Phase 19: Web Workers#
Expose the Worker interface on the main thread so JS code can spawn and communicate with workers.
What to implement#
Add crates/js/src/worker.rs:
-
Workerconstructor —new Worker(url, options?):- Resolve
urlrelative to the document base URL - Fetch the worker script (off main thread is fine, or synchronously for simplicity initially)
- Spawn the worker thread (using the infrastructure from the first issue)
- Store a
WorkerHandleinternally
- Resolve
-
worker.postMessage(message, transfer?):- Serialize
messageusing Structured Clone - Enqueue the serialized message to the worker thread's inbound channel
transferarray: mark ArrayBuffers as transferred (zero out the source)
- Serialize
-
worker.terminate(): close the channel and join the thread -
worker.onmessage/worker.addEventListener('message', fn):- The main thread event loop polls worker outbound channels (alongside timer callbacks and rAF)
- When a message arrives, deserialize it, wrap in a
MessageEvent, and dispatch to listeners
-
worker.onerror: fires anErrorEventwhen the worker thread propagates an unhandled error -
MessageEventinterface:data,origin,source,portsproperties
Acceptance criteria#
- JS on the main thread can do:
andconst w = new Worker('/worker.js'); w.onmessage = e => console.log(e.data); w.postMessage({ n: 40 });worker.jscan respond withself.postMessage(result). worker.terminate()stops the thread without deadlock.cargo test -p we-jspasses.