Goal: A heapify priority queue that is regularly polled for message objects to send. Whenever the queue is polled, it should peek at the queue to see if there's any messages. If so, it should attempt to send the message.
On success, remove that message from the queue.
I'm worried about dropped messages, so if the message fails then it should remain in the queue to be sent on the next invocation. And the user will need to be alerted (but I will handle that part myself).
What I have so far:
import { Heap } from 'heap-js';
function coroutine(f) {
var o = f(); // instantiate the coroutine
o.next(); // execute until the first yield
return function(x) {
o.next(x);
};
}
socket.messageQueue = new Heap(100);
var messageBox = coroutine(async function*() {
while (true) {
yield;
if (typeof socket.messageQueue.peek() === 'undefined') {
continue;
}
let message = socket.messageQueue.peek();
let response = await sendMessage(socket, message);
if (response.success) {
socket.messageQueue.pop();
// the message was sent
// reset warnings if they exist
} else {
// warn user that the message send failed
// it will retry in 3 seconds
}
}
});
socket.messageBox = setInterval(messageBox, 3000);
And messages are added to the queue like so:
let priority = // the largest priority + 1
socket.messageQueue.push(message, priority);
The socket is from socket.io. I'm instantiating the process on a server-side socket because I'm going to tear it down when the user disconnects. And the queue is FIFO so the priority should just be set to the last priority. Unfortunately it doesn't look like heapify has a built-in method to get the largest priority from a heap.
Any suggestions on making this efficient and eloquent would be appreciated.