UNPKG

@evolu/web

Version:
105 lines (104 loc) 3.92 kB
/** * SharedWebWorker (WebWorker + BroadcastChannel + Web Locks) * * A SharedWebWorker is a Web Worker that is shared across multiple browser * tabs. This implementation provides a shared worker-like experience even in * browsers that do not support the native SharedWorker API. * * Unlike a true SharedWorker (which uses MessagePorts for direct, tab-specific * communication), this approach uses BroadcastChannel for cross-tab messaging * and Web Locks to ensure only one tab owns and runs the actual Worker * instance. * * All tabs communicate via BroadcastChannel, so every message is broadcast to * all tabs, and each tab must filter/process only relevant messages. This is * less efficient than MessagePorts, but it works everywhere and is "good * enough" for most use cases. * * See the protocol and coordination logic below for details. * * @module SharedWebWorker */ import { constVoid } from "@evolu/common"; /** * Creates a shared Web Worker using BroadcastChannel and Web Locks. This allows * multiple tabs to share a single Web Worker instance. The first tab to acquire * the lock becomes the owner and runs the worker. Other tabs act as proxies, * forwarding messages to the owner. */ export const createSharedWebWorker = (name, createWebWorker) => { // Server. if (typeof document === "undefined") return { postMessage: constVoid, onMessage: constVoid, }; const namespacedName = `evolu-sharedwebworker-${name}`; const channel = new BroadcastChannel(namespacedName); let worker; let onMessageCallback; let ownerReady = false; const pendingMessages = []; // Listen for owner-ready and worker responses channel.onmessage = (event) => { const data = event.data; if (data.type === "owner-ready") { ownerReady = true; // Flush pending messages to the new owner for (const message of pendingMessages) { channel.postMessage({ type: "to-worker", message }); } pendingMessages.length = 0; } else if (!worker && data.type === "from-worker") { onMessageCallback?.(data.message); } }; // Request owner-ready when not the owner channel.postMessage({ type: "request-owner-ready" }); // Try to acquire the lock and become the owner void navigator.locks.request(namespacedName, async () => { worker = createWebWorker(); // Flush pending messages to the worker for (const message of pendingMessages) { worker.postMessage(message); } pendingMessages.length = 0; // Forward messages from channel to worker channel.onmessage = (event) => { const data = event.data; if (data.type === "to-worker") { worker.postMessage(data.message); } else if (data.type === "request-owner-ready") { // Respond to request channel.postMessage({ type: "owner-ready" }); } }; // Forward messages from worker to channel worker.onmessage = (event) => { channel.postMessage({ type: "from-worker", message: event.data }); onMessageCallback?.(event.data); }; // Announce ownership channel.postMessage({ type: "owner-ready" }); // Hold the lock forever await new Promise(constVoid); }); return { postMessage: (message) => { if (worker) { worker.postMessage(message); } else if (ownerReady) { channel.postMessage({ type: "to-worker", message }); } else { pendingMessages.push(message); } }, onMessage: (callback) => { onMessageCallback = callback; }, }; };