jcayzac
jcayzac8mo ago

Most efficient way to broadcast messages globally across main script and workers?

I basically want a simple message bus that is global to all my workers + the main script, without relying on any dependency. Is there something more efficient, maybe using MessageChannel, than using postMessage() in workers to send things to the main script and iterate through all workers in the main script to postMessage() again on each worker?
11 Replies
Andreu Botella (they/them)
BroadcastChannel could work
jcayzac
jcayzac8mo ago
Thanks @Andreu Botella (they/them) ! I didn't know that API, it looks like it's exactly what I want.
> const bc = new BroadcastChannel("test_channel");
Uncaught ReferenceError: BroadcastChannel is not defined
at <anonymous>:2:12
> const bc = new BroadcastChannel("test_channel");
Uncaught ReferenceError: BroadcastChannel is not defined
at <anonymous>:2:12
Hmm 😕
Andreu Botella (they/them)
--unstable
jcayzac
jcayzac8mo ago
Oh… it works, yay! How do you pass the broadcast channel to each worker? Is it a transferable object? type Transferable doesn't list it
Andreu Botella (they/them)
no, if you create multiple broadcastchannels with the same string passed to the constructor, they get linked together
jcayzac
jcayzac8mo ago
I see. Thank you very much!
Andreu Botella (they/them)
even if they're created from different workers
NDH
NDH8mo ago
BroadcastChannel works great for me.
Kofi GOLO
Kofi GOLO8mo ago
How does that work exactly? What are the use cases?
Andreu Botella (they/them)
the initial use case in the browser was to let every tab from a same origin do multiple publisher multiple consumer communication like, you log in on one tab and it notifies every other tab so it shows you as logged in without having to refresh and you might want multiple different channels, for different things, so you give them different names technically it works much like postMessage and MessagePort, except deno knows all of the BroadcastChannels in existence I think
jcayzac
jcayzac8mo ago
I think BroadcastChannel works best for my use case but, for reference, let me also mention Deno Queues if you want at-least-once delivery guarantees, persistance, and communication across deno instances when using the new denokv service. https://deno.com/blog/queues
Deno Blog
Announcing Deno Queues
Introducing Deno Queues - zero config, scalable messaging with a guaranteed at-least-once delivery. This new primitive builds on the foundation set by Deno KV, and is available today in the Deno JavaScript runtime and Deno Deploy.