Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Possible race condition with EventSource?

I am using Server Sent Events (SSE) and my code to connect to my SSE backend looks like this:

function sseSubscribe() {
  events = new EventSource("/v1/sse/" + sseID + "/" + lastEventId);

  events.addEventListener("message", sseHeartbeat);
  events.addEventListener("error", sseError);
  events.addEventListener("reply", sseReply);
  events.addEventListener("refresh", sseRefresh);
}

This function is called to setup the initial SSE connection, but also when a reconnection is desired (because the connection broke for whatever reason).

On the server, if the lastEventId is greater than 0, it will stream any missing messages to the client.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So, hypothetically, if doing new EventSource() blocked, this wouldn’t work, because the events would be streamed back to the browser before the corresponding event handlers (reply, refresh, etc.) were registered.

However, to my knowledge, this is not the case (I believe calling new EventSource is a non-blocking operation? Not sure though). However, I suppose it’s possible if the user’s computer was slow enough, and their connection was fast enough, that maybe missing messages could be streamed back before the listeners were registered.

Is this a reasonable fear, or should I feel relatively safe with the above code?

To reiterate, this code seems to work, but my fear is that messages may be streamed back from the new EventSource connection before the corresponding handlers are added. Is this reasonable, or does it have a 0% chance of happening?

>Solution :

The connection occurs after the current Javascript execution has completed. I believe this would be safe to assume for all browsers, though I don’t have a definitive reference.

For example, Chrome starts the connection from a timer, which probably ties into the same event loop as, for example, setTimeout: https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/modules/eventsource/event_source.cc;l=99?q=EventSource&ss=chromium

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading