we (web engine): Experimental web browser project to understand the limits of Claude
2
fork

Configure Feed

Select the types of activity you want to include in your feed.

Main-thread Worker API: constructor, postMessage, terminate, events #180

open opened by pierrelf.com

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:

  • Worker constructornew Worker(url, options?):

    • Resolve url relative 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 WorkerHandle internally
  • worker.postMessage(message, transfer?):

    • Serialize message using Structured Clone
    • Enqueue the serialized message to the worker thread's inbound channel
    • transfer array: mark ArrayBuffers as transferred (zero out the source)
  • 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 an ErrorEvent when the worker thread propagates an unhandled error

  • MessageEvent interface: data, origin, source, ports properties

Acceptance criteria#

  • JS on the main thread can do:
    const w = new Worker('/worker.js');
    w.onmessage = e => console.log(e.data);
    w.postMessage({ n: 40 });
    
    and worker.js can respond with self.postMessage(result).
  • worker.terminate() stops the thread without deadlock.
  • cargo test -p we-js passes.
sign up or login to add to the discussion
Labels

None yet.

assignee

None yet.

Participants 1
AT URI
at://did:plc:meotu43t6usg4qdwzenk4s2t/sh.tangled.repo.issue/3mlxpoquxys22