Premise
In this challenge, we are going to tackle a common but often overlooked scenario: Resolving the ordering of websocket messages that arrive jumbled up. Think of a chat application where several people are typing in their messages and the backing web server is using multiple processes (or even multiple servers) to process the form submissions. There’s no guarantee whatsoever that messages arrive in the correct order at each of the participants, yet it’s crucial to understanding the conversation. We are going to take a look at how to resolve that.
Challenge
First up, let’s assume that each message has a timestamp of when it arrived at the server and that this timestamp is correct (i.e., can be used to sort the messages). To simulate the out-of-order arrival I’ve set up a procedure that slices a random element out of the messages
array and transports them as Turbo Stream broadcasts over the websocket:
These messages are appended to a <ul>
on the index page, where a sort
Stimulus controller is already connected:
https://stackblitz.com/edit/stimulus-auto-sort?file=index.html%3AL42
To visualize this a bit, I’ve used the simple but effictive auto-animate Javascript library.
Your task is to conceive a Stimulus controller that handles the ordering of the messages as they come in:
Here’s a peek at the end result:
Caveats
You will need a MutationObserver
, but be mindful of infinite loops. Think carefully of when to start, stop, and restart observing.
Teaser
Can you think of other ways to insert messages at the correct spot right before they are appended to the DOM?