Phase 19: Web Workers#
Complete the Web Workers implementation with script importing and shared memory primitives.
Part 1: importScripts()#
Implement importScripts(...urls) on DedicatedWorkerGlobalScope:
- Accept one or more URL strings (resolved relative to the worker script URL)
- Fetch each script synchronously (blocking the worker thread — this is spec-correct for
importScripts) - Parse and execute each script in the current worker
JsContextin order - Throw a
NetworkErrorDOMException if any fetch fails; stop execution at that point
Part 2: SharedArrayBuffer#
- Add
SharedArrayBufferto the JS built-ins incrates/js/src/builtins.rs - Backed by
Arc<Vec<u8>>(shared ownership, no copy on postMessage) new SharedArrayBuffer(length)— allocates zeroed bytesbyteLengthproperty- Structured Clone serializes it by cloning the
Arc(not the bytes), so both threads see the same memory
Part 3: Atomics#
Add an Atomics built-in object (non-constructable) with methods operating on integer TypedArray views over a SharedArrayBuffer:
Atomics.load(typedArray, index)Atomics.store(typedArray, index, value)Atomics.add,sub,and,or,xor,exchange,compareExchangeAtomics.wait(typedArray, index, value, timeout?)— block the calling thread (only valid in workers)Atomics.notify(typedArray, index, count?)— wake waiting threads- Implement using
std::sync::atomic(Ordering::SeqCst for correctness)
Test milestone#
A worker script uses importScripts('/lib.js') to load a utility library, then uses SharedArrayBuffer + Atomics to synchronize with the main thread. A unit test verifies that a counter incremented from a worker thread is visible on the main thread.
Acceptance criteria#
importScriptsloads and executes external scripts in the worker contextSharedArrayBufferis correctly transferred (Arc-cloned) via postMessageAtomics.load/store/addproduce correct results under concurrent accessAtomics.wait/Atomics.notifysynchronize two threads correctlycargo test -p we-jspasses.