blazeds how to understand if the session is timed out - apache-flex

Hi my aim is to catch when the session is invalidated and send message to all destination that the FlexClient subscribed that the client wiht id .... has disconnected.
I implemented a service which listens for sessionCretaed,sessionDestroyed,clientCreated,clientDestroyed,messageClientCreated,messageClientDestroyed.
Problem is that i want to catch messageClientDestroyed and send to that destination a message that the user has disconnected.But blazeds destroys messageClient when you add a subtopic.So how to understand that if session is invalidated and all messageClient are being destroyed or the user just enter another place and add a subtopic to his consumer.
I'am also open for other solutions to implement that mechanism.When user disconnected by session timeout or closed the site browser etc. i wanna catch it and send a message to subscribed destinations.
thank you.

I am not a master on this topic but I believe you have to tune into the Flex session lifecycle event, FlexSessionListener after a d/c.
If your client is leaving because they want to, on the flex side you invoke disconnectAll() on the ChanelSet so that Blaze DS will clean up resources explicitly.
If your client is leaving because of timing out, you can configure the channel definition to use invalidate-session-on-disconnect = true
These two should trigger the FlexSessionListner.sessionDestroyed(). The parameter for this method is a FlexSession object where you can extrapolate what you need.

Related

Does Signalr change connectionId OnReconnected method?

I was wondering if signalr changes the connectionId on OnReconnected method? as I'm mapping a list of users to their connection ids so if the reconneced event raised on the server due to slow connection for example will the connectionId will be changed ?
No. The connectionId does not change in an OnReconnected event.
The OnReconnected fires automatically(if you're using a signalR client) within the disconnect timeout in case there is a network issue and a keep alive is missed.
If the network is disrupted or the server is unable to process the OnReconnected event for longer than the disconnect timeout, the connection will be disconnected on the server and a new connection will need to be made. This making a new connection is not automatic. The client code will have to call a connection.Start() to create a new connection.
If the client comes back with the old connectionId, it will not go through as that connection would be in a disconnected state.
So if you are mapping connectionIDs with Users then you need to make sure that the connection Id is updated with the new connectionId in every OnConnected event and deleted in every OnDisconnected event on the server .
I don't believe the OnReconnect will change the connectionID. However, that depends on what the cause of the problem is.
If the client dropped it's internet connection for example and then picked back up, OnReconnect fires and the user should have the same connectionID.
If the server rebooted or IIS restarted, then you have a different situation and when your clients refresh it will appear as a OnConnect and get a new connectionID.

SignalR - Sending from server-to-client from latest Hub context

I have a simple demo with only 1 client and the server. I can send messages back and forth, very trivial stuff.
The server Hub has a timer which sends a message to the client(s) every 1000 milliseconds. Now I have a button, where when clicked, sends a message to the server (via signalR).
Problem:
When the button is clicked (and the message sent to the server), the Hub is instantiated each time (I read about the SignalR lifecycle here).
Of course, when the Hub is instantiated the Timer is also instantiated. So the side effect (ie. bug) that I am seeing is that messages are being send to the client from multiple Hub instances.
What I would like:
I would like the client to receive messages (from the Timer that is running on the Hub), but only 1 set of messages from a single Hub (latest Hub instance?). I do not want simultaneous/multiple messages that were spawned from each Hub that was instantiated.
But perhaps I am doing something drastically wrong in design here.
You shouldn´t set the timer in the hub instance because they are re-created on every request.
Just create a Singleton class to handle the timer and actions. Then access that singleton from your hub instance.
The singleton instance will persist during the whole live cycle of your application, thus you will create only one timer.
To avoid concurrency problems, your singleton should be Lazy

How to Intercept ScaleoutMessage Broadcast: (Edited: How to send message directly to ServiceBus SignalR Backplane)

I have following scenario:
User request for certain resource on server, This request is long running task and very like 2~3 seconds to 10 seconds. We issue a JobTicket to user, As our user want to wait.
On receiving request we store that request in persistence storage and issue a token to user as JobTicket (GUID).
User make connection with Hub to get information about that GUID.
In Background:
We have WAS Hosted as well as Windows Service to perform some operation on that request.
On complete, WAS Hosted/Windows Service call our Web Application that job has been completed.
From there based on job Ticket we identify which user and on its connection we let user know its job has been completed.
Now we have farm of servers, we are using Windows Server On Prem ServiceBus 1.1 which is working fine, But challenge we have is that we are not able to intercept ServiceBus based backplane message broadcast and message is going to all the client. As we have farm, user intermediately may have drop connection and connected to other server based on load balancer so we need to have scale out using Service Bus as its kind of seamless to integrate and we are also using for our internal purpose in our application so we don't want to user any other mix in complex solution.
I have tried using IHubPipelineModule but still Scale out message broadcast not passing thru that, I tried to hookup SignalR code directly and debug thru it but its taking long. I don't want to mess-up something arbitrary in actual code. As I can see that in OnReceive I can see message are coming, but not able to follow further. I just need small mechanism that I can intercept broadcast message and make sure that it goes to client it intended and not all the client by wasting resources, and security concern as well.
Please help me on this issue, it's kind of stuck from last 4 days and not able to come to any solution and same time I want to go with establish pattern and don't want to fork any special build for this kind of small issues which I am sure one of you expert knows how I can do that seamlessly.
Thanks,
Shrenik
After lots of struggling and not finding straight forward way, I have found the way as below for someone else in future it might help.
Scenario:
1. Web Farm: Host External User facing Web Pages
2. Backend Process: Which is mix of WebApi, SharePoint, Windows Service etc.
User from Web Page submit some request and get a unique id as return back. Internally on receiving request, we queue that request to Service Bus using TopicClient for processing.
There are pool of Windows Service watching on Message on Service Bus using SubscriptionClient and process that message. On completion of process which can run from 5 seconds to 30 seconds and some cases even more. We need to inform client that its job done if its waiting on web page or waiting for completion notification.
In this story, We are using SignalR to push job completion notification to client.
Now my earlier problem is How I let know from windows service to web application that job is done so send notification to client who submitted request.
One way is we hosted another hub internally in web application, Windows service act as client and call web application hosted hub, and in that hub method it will call external facing hub method to propagate message to specific client who submitted request, for which we are using Single user Group.
And as we have register service bus as backplane it will propagate to other servers and then appropriate client will get notification. So this is ideal solution and should work in most cases.
In above approach we have one limitation that, how Windows Service connect to Web Client, as we donot have windows auth, but we have openid based auth with ADFS. Now in such case Web Application required special code in which provide separate userid or password for windows service to communicate or have windows authentication also allowed for that hub for service account of windows service.
I was trying and trying how to remove all this hopes between interserver communication and again management of extra security.
So I did below with simplicity, though it tooks me whole night to find our internal of SignalR. But it works:
Approach is to send message directly to ServiceBus Backplane, and as all Web Server already hooked-up with ServiceBus backplane then they will get message.
Unfortunately SignalR doesn't provide such mechanism to send message directly to Backplane. I think its on pub/sub model so they don't want somebody to hack in their system :). or its violation of their pattern, but its make sense, in my case because of different roles and security, I have simplify code as below:
Create a ServiceBusMessageBus instance in my code, Same way as Below: Though I have created separate instance and store till lifetime of Windows Service, so I don't create instance every time:
ServiceBusMessageBus serviceBusBackplane = new ServiceBusMessageBus(new DefaultDependencyResolver(), new ServiceBusScaleoutConfiguration(connectionString, appName));
Create a ClientHubInvocation Object: This is a message which actually get created in SignalR infrastructure when Backplane based message broadcast:
ClientHubInvocation hubData = new ClientHubInvocation
{
Args = new object[] { msg },
Hub = "JobStatusHub",
Method = "onJobStatus",
State = null,
};
Create a Message object which accept by ServiceBusMessageBus.Publish, Yes, so this is a method which actually get called on base class ScaleoutMessageBus.Publish. This class is actually responsible for sending message to topic and other subscribers on other server nodes. Why not use that directly. Now to create Message Object, You need following code:
Message backplaneMessage = new Message(
sourceId,
"hg-JobStatusHub." + name,
new ArraySegment(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(hubData))));
In above second parameter is something interesting,
In case if you want to publish to all the client then syntax is "h-", in my case specific group user, so syntax is "hg-.. You can check the code here: https://github.com/SignalR/SignalR/blob/bc9412bcab0f5ef097c7dc919e3ea1b37fc8718c/src/Microsoft.AspNet.SignalR.Core/Infrastructure/PrefixHelper.cs
Publish your message to backplane directly as below:
await serviceBusBackplane.Publish(backplaneMessage);
I wish this PrefixHelper class have been public.
Remember: This is not recommended way and doent insulate from future upgrade for SignalR, as its internal they may change so any upgrade might come with small hazale to change this code. But in summary this works. Hope SignalR Team provide some mechanisam out of box to send message directly to backplane instead.
Thanks

Reusing same connection in signalR while navigating through different pages

I have an MVC project, with multiple pages.
I have a long running process, which updates the client on its progress. However, this update is sent only to a single client, instead of broadcasting to all.
Clients.Client(ConnectionId).sendMessage(msg);
In my layout.cshtml, this is how I connect to the hub
var serverHub = $.connection.notifier;
window.hubReady = $.connection.hub.start(function () { });
The problem is, when I navigate to another page, I no longer receive the messages from signalr, because the connection id has changed.
How should I workaround this issue, such that my signalr hub can still send messages to a single client, while the client navigates from page to page.
You will want to create a server mapping of users to connection id's. See: SignalR 1.0 beta connection factory.
You will want to let your users persist past an OnDisconnected event and when they connect with a different connection Id you can continue pumping data down to them.
So the thought process could be as follows:
Page loads, SignalR connection is instantiated
Once connection is fully started call => TryCreateUser (returns a user, whether it existed or it was created).
Long Running process Starts
Client changes pages -> SignalR connection stops
New Page loads, new SignalR connection is instantiated
Once connection is fully started see if you have a cookie, session, or some type of data representing who you are => TryCreateUser(userData) (returns the user you created on the last page).
Data continues pumping down to user.
Note: if you take an authentication approach you will have to be authenticated prior to starting a connection and that data cannot change during the lifetime of a SignalR connection, it can only be created/modified while the connection is in the disconnected state.

Managing state server side to be requested by a hub client

I have created a really basic hub that I get the IHubContext and call the my javascript client side method via a group so I can always push the data to the same user no matter how many diffrent connections they are on, which i pass some text to and that text is appended in a multiline textbox in the browser.
It all works really nicely. The thread will typically run long operations, often appending text reporting on the status of the operation using the hub context to call the client.
However, I wish to cater for the situation where someone would close their browser then return later the page with the textbox.
Now at the moment they would just start reciving the text from the point in the operation they connect on. How can I send a request from the client to the server to retrive all the text back from the begining of the operation?
My idea was to have a StringBuilder object that i append each line identically as the text I send to the client hub.
Then on connect of the hub call a server side function from the client which asks for the full text which can be taken from the StringBuilder object ToString();
But how can the hub know where to get the StringBuilder object from in the still executing thread?
OR
If there is a way to push it to the client instead, how can I know in the executing thread that the user has connected and send the StringBuilder ToString() to the user?
NB. I do not want to resend the full string appened every time! Only when the user has just connected and needs to catch up.
I think understanding how to do this would help understand how to deal with signalR and state on the server outside of the hub. Thank you.
Well, for starters, you should probably store this data in some kind of persistent storage (not just in an in-memory StringBuilder). Regardless of that though, what you really need to do is store the individual strings with timestamps. Then just remember the last time you saw the logical user and dump all entries since that time when they are first connecting to your Hub.
JabbR, the flagship, test bed application for SignalR, does something just like this except it just does it using message ids and asks for all message ids since the last message id the client received. Check out the Chat Hub's GetPreviousMessages for details.

Resources