Home > Software design >  Possible race condition with EventSource?
Possible race condition with EventSource?

Time:03-12

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.

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?

CodePudding user response:

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

  • Related