MassTransit MessageRequestClient timeout issue - masstransit

We have two services which exchange messages via MassTransit on top of RabbitMQ.
The goal is to send a message in a request/response way. Here's the code of the service which listens for a message, let's call it Service1:
Bus.Factory.CreateUsingRabbitMq(
sbc =>
{
var host = sbc.Host(new Uri($"rabbitmq://{RabbitMqHost}"), h =>
{
h.ConfigureRabbitMq();//Custom extension to specify credentials
});
sbc.ReceiveEndpoint(host, "CUSTOM_QUEUE_NAME", ep =>
{
ep.Exclusive = false;
ep.AutoDelete = true;
ep.Durable = false;
ep.PrefetchCount = 1;
ep.Handler<EngineStartingMessage>(async context =>
{
//SourceAddress and ResponseAddress are auto generated queues
//Message processing is done here
context.Respond(response);
});
});
});
The code of the service which sends a message and process the result, let's call it Service2:
var requestClient =
new MessageRequestClient<EngineStartingMessage, EngineStartingResponse>(
EntityServiceBus,
new Uri("CUSTOM_QUEUE_NAME?durable=false&autodelete=true&exclusive=false"),
new TimeSpan(0, 0, 30));
var engineStartResponse = requestClient.Request(new EngineStartingMessage() { Version = SystemVersion }).Result;
When I run the above code I can see Service1 gets a request and calls context.Respond(response); but on the Service2 side I always get a Timeout exception. Since, a message can make it from Service2 to Service1 I assume there are no network related issues. The timeout is pretty high as well. The message processing on Service1 end takes less than a second. So I think a response message is just not routed properly and I don't understand why. What is suspicious to me is that SourceAddress and ResponseAddress contain auto generated values and not "CUSTOM_QUEUE_NAME?durable=false&autodelete=true&exclusive=false". Any ideas what I'm doing wrong?

You should start Bus, on your service start, like it shown here
await busControl.StartAsync(source.Token);

Related

AWS Websocket doesnt receive previous message until new message is sent

Most of the time the messages are passed normally, but a couple messages in particular arent recieved until the recieving client sends a message. This happens everytime for specific methods/messages, but not at all for others.
Example: user1 sends a message, user2 then sends a message to receive message from user1.
Related Material
Deleted question: websocket receives previous message only when new message is sent
Github issue: webSocket client does not receive messages before sending...
We ran into this issue and the solution had to do with how we wrote our promises. We initially used the sample code provided by Amazon
https://github.com/aws-samples/simple-websockets-chat-app/blob/master/sendmessage/app.js#L26
const postCalls = connectionData.Items.map(async ({ connectionId }) => {
try {
await apigwManagementApi.postToConnection({ ConnectionId: connectionId, Data: postData }).promise();
} catch (e) {
if (e.statusCode === 410) {
console.log(`Found stale connection, deleting ${connectionId}`);
await ddb.delete({ TableName: TABLE_NAME, Key: { connectionId } }).promise();
} else {
throw e;
}
}
});
And I'm pretty sure having an async function as a map function doesn't work properly or reliably (for whatever reason. maybe this is documented somewhere), so we changed it to a simple for loop and it fixed the issue.
for(const connection of connectionData.Items) {
const connectionId = connection.connectionId;
...same logic goes here
}

How to wait for WebSocket STOMP messages in Cypress.io

In one of my tests I want to wait for WebSocket STOMP messages. Is this possible with Cypress.io?
If the websocket you'd like to access is being established by your application, you could follow this basic process:
Obtain a reference to the WebSocket instance from inside your test.
Attach an event listener to the WebSocket.
Return a Cypress Promise that is resolved when your WebSocket receives the message.
This is a bit difficult for me to test out, absent a working application, but something like this should work:
In your application code:
// assuming you're using stomp-websocket: https://github.com/jmesnil/stomp-websocket
const Stomp = require('stompjs');
// bunch of app code here...
const client = Stomp.client(url);
if (window.Cypress) {
// running inside of a Cypress test, so expose this websocket globally
// so that the tests can access it
window.stompClient = client
}
In your Cypress test code:
cy.window() // yields Window of application under test
.its('stompClient') // will automatically retry until `window.stompClient` exists
.then(stompClient => {
// Cypress will wait for this Promise to resolve before continuing
return new Cypress.Promise(resolve => {
const onReceive = () => {
subscription.unsubscribe() // clean up our subscription
resolve() // resolve so Cypress continues
}
// create a new subscription on the stompClient
const subscription = stompClient.subscribe("/something/you're/waiting/for", onReceive)
})
})

MassTransit sends a durable message when a non durable one is configured

I'm trying to send a message to an queue. The queue exists already and is configured as non durable. Here's my code:
ServiceBus = Bus.Factory.CreateUsingRabbitMq(sbc =>
{
sbc.PurgeOnStartup = true;
sbc.Durable = false;
sbc.Exclusive = false;
sbc.Host(new Uri($"rabbitmq://{RabbitMqHost}"), cfg =>
{
cfg.ConfigureRabbitMq();
});
});
ServiceBus.Request(
new Uri(serviceUri),
new EngineStartingMessage() { Version = ApplicationConfig.SystemVersion },
rCfg =>
{
rCfg.Durable = false;
rCfg.Timeout = new TimeSpan(0, 0, 30);
rCfg.Handle<EngineStartingResponse>(async hContext =>
{
//Response handling
});
});
As you can see Durable is set to false. On ServiceBus.Request I get the following exception:
The AMQP operation was interrupted: AMQP close-reason, initiated by
Peer, code=406, text="PRECONDITION_FAILED - inequivalent arg 'durable'
for exchange 'QUEUENAMEHERE' in vhost '/': received 'true' but current
is 'false'", classId=40, methodId=10, cause=
Any ideas why the message is still sent as durable?
That Durable flag only specifies that the particular request message should not be persisted to disk.
If you want to fix this, add ?durable=false to the serviceUri, to match what's being specified at the receive endpoint which handles the request.

.Net Core SignalR - connection timeout - heartbeat timer - connection state change handling

just to be clear up-front, this questions is about .Net Core SignalR, not the previous version.
The new SignalR has an issue with WebSockets behind IIS (I can't get them to work on Chrome/Win7/IIS express). So instead I'm using Server Sent Events (SSE).
However, the problem is that those time out after about 2 minutes, the connection state goes from 2 to 3. Automatic reconnect has been removed (apparently it wasn't working really well anyway in previous versions).
I'd like to implement a heartbeat timer now to stop clients from timing out, a tick every 30 seconds may well do the job.
Update 10 November
I have now managed to implement the server side Heartbeat, essentially taken from Ricardo Peres' https://weblogs.asp.net/ricardoperes/signalr-in-asp-net-core
in startup.cs, add to public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
app.UseSignalR(routes =>
{
routes.MapHub<TheHubClass>("signalr");
});
TimerCallback SignalRHeartBeat = async (x) => {
await serviceProvider.GetService<IHubContext<TheHubClass>>().Clients.All.InvokeAsync("Heartbeat", DateTime.Now); };
var timer = new Timer(SignalRHeartBeat).Change(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(30));
HubClass
For the HubClass, I have added public async Task HeartBeat(DateTime now) => await Clients.All.InvokeAsync("Heartbeat", now);
Obviously, both the timer, the data being sent (I'm just sending a DateTime) and the client method name can be different.
Update .Net Core 2.1+
See the comment below; the timer callback should no longer be used. I've now implemented an IHostedService (or rather the abstract BackgroundService) to do that:
public class HeartBeat : BackgroundService
{
private readonly IHubContext<SignalRHub> _hubContext;
public HeartBeat(IHubContext<SignalRHub> hubContext)
{
_hubContext = hubContext;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await _hubContext.Clients.All.SendAsync("Heartbeat", DateTime.Now, stoppingToken);
await Task.Delay(30000, stoppingToken);
}
}
}
In your startup class, wire it in after services.AddSignalR();:
services.AddHostedService<HeartBeat>();
Client
var connection = new signalR.HubConnection("/signalr", { transport: signalR.TransportType.ServerSentEvents });
connection.on("Heartbeat", serverTime => { console.log(serverTime); });
Remaining pieces of the initial question
What is left is how to properly reconnect the client, e.g. after IO was suspended (the browser's computer went to sleep, lost connection, changed Wifis or whatever)
I have implemented a client side Heartbeat that is working properly, at least until the connection breaks:
Hub Class: public async Task HeartBeatTock() => await Task.CompletedTask;
Client:
var heartBeatTockTimer;
function sendHeartBeatTock() {
connection.invoke("HeartBeatTock");
}
connection.start().then(args => {
heartBeatTockTimer = setInterval(sendHeartBeatTock, 10000);
});
After the browser suspends IO for example, the invoke method would throw an exception - which cannot be caught by a simple try/catch because it is async.
What I tried to do for my HeartBeatTock was something like (pseudo-code):
function sendHeartBeatTock
try connection.invoke("HeartbeatTock)
catch exception
try connection.stop()
catch exception (and ignore it)
finally
connection = new HubConnection().start()
repeat try connection.invoke("HeartbeatTock")
catch exception
log("restart did not work")
clearInterval(heartBeatTockTimer)
informUserToRefreshBrowser()
Now, this does not work for a few reasons. invoke throws the exception after the code block executes due to being run asynchronous. It looks as though it exposes a .catch() method, but I'm not sure how to implement my thoughts there properly.
The other reason is that starting a new connection would require me to re-implement all server calls like "connection.on("send"...) - which appears silly.
Any hints as to how to properly implement a reconnecting client would be much appreciated.
This is an issue when running SignalR Core behind IIS. IIS will close idle connections after 2 minutes. The long term plan is to add keep alive messages which, as a side effect, will prevent IIS from closing the connection. To work around the problem for now you can:
send periodically a message to the clients
change the idle-timeout setting in IIS as described here
restart the connection on the client side if it gets closed
use a different transport (e.g. long polling since you cannot use webSockets on Win7/Win2008 R2 behind IIS)
I've got a working solution now (tested in Chrome and FF so far). In the hope to either motivate you to come up with something better, or to save you a little while coming up with something like this yourselves, I'm posting my solution here:
The Heartbeat-"Tick" message (the server routinely pinging the clients) is described in the question above.
The client ("Tock" part) now has:
a function to register the connection, so that the callback methods (connection.on()) can be repeated; they'd be lost after just restarting a "new HubConnection" otherwise
a function to register the TockTimer
and a function to actually send Tock pings
The tock method catches errors upon sending, and tries to initiate a new connection. Since the timer keeps running, I'm registering a new connection and then simply sit back and wait for the next invocation.
Putting the client together:
// keeps the connection object
var connection = null;
// stores the ID from SetInterval
var heartBeatTockTimer = 0;
// how often should I "tock" the server
var heartBeatTockTimerSeconds = 10;
// how often should I retry after connection loss?
var maxRetryAttempt = 5;
// the retry should wait less long then the TockTimer, or calls may overlap
var retryWaitSeconds = heartBeatTockTimerSeconds / 2;
// how many retry attempts did we have?
var currentRetryAttempt = 0;
// helper function to wait a few seconds
$.wait = function(miliseconds) {
var defer = $.Deferred();
setTimeout(function() { defer.resolve(); }, miliseconds);
return defer;
};
// first routine start of the connection
registerSignalRConnection();
function registerSignalRConnection() {
++currentRetryAttempt;
if (currentRetryAttempt > maxRetryAttempt) {
console.log("Clearing registerHeartBeatTockTimer");
clearInterval(heartBeatTockTimer);
heartBeatTockTimer = 0;
throw "Retry attempts exceeded.";
}
if (connection !== null) {
console.log("registerSignalRConnection was not null", connection);
connection.stop().catch(err => console.log(err));
}
console.log("Creating new connection");
connection = new signalR.HubConnection("/signalr", { transport: signalR.TransportType.ServerSentEvents });
connection.on("Heartbeat", serverTime => { console.log(serverTime); });
connection.start().then(() => {
console.log("Connection started, starting timer.");
registerHeartBeatTockTimer();
}).catch(exception => {
console.log("Error connecting", exception, connection);
});
}
function registerHeartBeatTockTimer() {
// make sure we're registered only once
if (heartBeatTockTimer !== 0) return;
console.log("Registering registerHeartBeatTockTimer");
if (connection !== null)
heartBeatTockTimer = setInterval(sendHeartBeatTock, heartBeatTockTimerSeconds * 1000);
else
console.log("Connection didn't allow registry");
}
function sendHeartBeatTock() {
console.log("Standard attempt HeartBeatTock");
connection.invoke("HeartBeatTock").then(() => {
console.log("HeartbeatTock worked.") })
.catch(err => {
console.log("HeartbeatTock Standard Error", err);
$.wait(retryWaitSeconds * 1000).then(function() {
console.log("executing attempt #" + currentRetryAttempt.toString());
registerSignalRConnection();
});
console.log("Current retry attempt: ", currentRetryAttempt);
});
}
Client version based on ExternalUse's answer...
import * as signalR from '#aspnet/signalr'
import _ from 'lodash'
var connection = null;
var sendHandlers = [];
var addListener = f => sendHandlers.push(f);
function registerSignalRConnection() {
if (connection !== null) {
connection.stop().catch(err => console.log(err));
}
connection = new signalR.HubConnectionBuilder()
.withUrl('myHub')
.build();
connection.on("Heartbeat", serverTime =>
console.log("Server heartbeat: " + serverTime));
connection.on("Send", data =>
_.each(sendHandlers, value => value(data)));
connection.start()
.catch(exception =>
console.log("Error connecting", exception, connection));
}
registerSignalRConnection();
setInterval(() =>
connection.invoke("HeartBeatTock")
.then(() => console.log("Client heatbeat."))
.catch(err => {
registerSignalRConnection();
}), 10 * 1000);
export { addListener };

NServiceBus Full duplex bus callback with Web API

Project Source: on github
Client is ASP.net Web API with OWIN and IIS host. Server is console.
I am having a scenario in which current thread has to wait till NSB completes its function. But my thread is waiting indefinitely from NSB reply.
var synchronousHandle = _bus.Send<MyCommand>(m => { m.TokenId = tokenId; })
.Register(r =>
{
var completionResult = r.AsyncState as CompletionResult;
if (completionResult == null || completionResult.Messages.Length <= 0) return;
// Always expecting one IMessage as reply
var response = completionResult.Messages[0];
}, null);
synchronousHandle.AsyncWaitHandle.WaitOne();
In my Handler:
Bus.Reply(new GenericResponseMessage { IsSuccess = true });
Problem:
Code run without any error and client message queue receives response from Bus.Reply. But callback does not receives response.
Will this doco help?
In your code it is commented out (https://github.com/sanelib/WebStarterKit/blob/da796e69826072ae78443c7952cf2669d74a9ee7/DotNetServer/src/NSBus.Server/CommandHandlers/UserGrantAccessHandler.cs#L70)
Another option is to use signalR (would be a more reliable option IMHO) Take a look at Roy's blog post

Resources