Skip to main content

nodejs/stdlib/
worker_threads.rs

1//! Node `worker_threads`: real OS-thread workers with fully isolated heaps.
2//!
3//! # Model (matches Node: workers do NOT share the JS heap)
4//!
5//! node-js's entire runtime — the `JsHost` heap, the module cache, the event
6//! loop channel — lives in `thread_local!`s (`host::HOST`, `module`'s statics).
7//! So spawning a fresh OS thread automatically gives that thread its OWN
8//! isolated interpreter and heap. A `Worker` here is therefore a real
9//! `std::thread` that calls `crate::eval_file`/`eval_str` on the worker file,
10//! running it against that thread's own clean `thread_local` host. Nothing on
11//! the JS heap is shared between the main thread and a worker, or between two
12//! workers — exactly Node's isolation guarantee.
13//!
14//! # Why messages cross as JSON strings, never `Value`s
15//!
16//! `fusevm::Value` is a per-thread heap handle (`Value::Obj(u32)` indexes the
17//! calling thread's `JsHost.heap`); it is neither `Send` nor meaningful on
18//! another thread. So a message can NEVER be a `Value`. Every message crosses
19//! the thread boundary as a plain `String` of JSON:
20//!
21//! ```text
22//!   sender thread:   value ─JSON.stringify([value])→ String  (on sender's heap)
23//!   channel:         String  (Send)
24//!   receiver thread: String ─JSON.parse(s)[0]→ value        (on receiver's heap)
25//! ```
26//!
27//! The value is wrapped in a one-element array before `JSON.stringify` so that
28//! top-level primitives AND `undefined` round-trip through a single always-valid
29//! JSON document (`JSON.stringify(undefined)` is itself `undefined`, not a
30//! string — the array wrapper avoids that). Deserialization unwraps `[0]` on the
31//! receiving thread's own heap.
32//!
33//! ## Serialization is a JSON subset of structured clone (documented limitation)
34//!
35//! Only JSON-serializable data transfers: objects, arrays, strings, numbers,
36//! booleans, null. `undefined` becomes `null` (JSON semantics), and functions,
37//! symbols, `Map`/`Set`, cycles, `BigInt`, and `ArrayBuffer` transfers are NOT
38//! supported (a `BigInt` makes `JSON.stringify` throw, surfaced as a thrown
39//! error from `postMessage`, matching Node's `DataCloneError` in spirit). This
40//! is an honest subset, never a silent fake.
41//!
42//! # Bidirectional message flow (both directions are real)
43//!
44//! * worker → main (`parentPort.postMessage`): the worker serializes on its own
45//!   heap and posts an `IoTask` onto the MAIN loop's `io_sender` (captured at
46//!   construction). The task runs on the main thread, deserializes into a fresh
47//!   `Value` on the main heap, and emits `'message'` on the `Worker` object.
48//! * main → worker (`worker.postMessage`): the main thread serializes and sends
49//!   the JSON string over an `mpsc` channel to the worker. A per-worker "bridge"
50//!   thread (started when the worker adds a `parentPort` `'message'` listener)
51//!   forwards each string as an `IoTask` onto the WORKER loop's `io_sender`; the
52//!   task runs on the worker thread, deserializes on the worker heap, and emits
53//!   `'message'` on `parentPort`. The bridge is required because the worker's
54//!   event loop (`host::run_event_loop`) blocks only on its own I/O channel and
55//!   this module cannot modify it — same pattern `net` uses for socket reads.
56//!
57//! # Liveness
58//!
59//! `new Worker` `incr_handle`s the MAIN loop so the process stays alive while the
60//! worker runs; the worker's `'exit'` `decr_handle`s it. On the worker side,
61//! registering a `parentPort` `'message'` listener `incr_handle`s the WORKER loop
62//! (keeping the worker alive to receive messages); `terminate` or
63//! `parentPort.close()` releases it. `process.exit(code)` on a worker ends that
64//! worker with `code` (`exit_if_worker`), and one that completes leaves with
65//! its `process.exitCode`.
66//!
67//! # terminate is cooperative (documented limitation)
68//!
69//! Rust has no safe thread cancellation, so `terminate` signals the worker (via
70//! the bridge) to `decr_handle` and let its event loop unwind; a worker parked in
71//! its message loop exits promptly. A worker spinning in a tight *synchronous* JS
72//! loop is not force-killed — there is no safe preemption point. `terminate`
73//! returns `undefined` (awaiting it resolves to `undefined`).
74
75use crate::host::{with_host, IoTask, JsObj};
76use fusevm::Value;
77use indexmap::IndexMap;
78use std::cell::RefCell;
79use std::collections::{HashMap, HashSet, VecDeque};
80use std::sync::atomic::{AtomicU64, Ordering};
81use std::sync::mpsc::{Receiver, Sender};
82use std::sync::{Mutex, OnceLock};
83
84/// Module-level `worker_threads` functions. NOTE: these route only if the parent
85/// adds a `"worker_threads"` arm to `stdlib::is_method` and `stdlib::call` (the
86/// module previously had no callable methods) — see the report.
87pub const METHODS: &[&str] = &[
88    "getEnvironmentData",
89    "setEnvironmentData",
90    "receiveMessageOnPort",
91    "markAsUntransferable",
92    "isMarkedAsUntransferable",
93    "markAsUncloneable",
94    "moveMessagePortToContext",
95];
96
97/// Instance methods on a `BroadcastChannel` object.
98pub const BROADCAST_CHANNEL_METHODS: &[&str] = &[
99    "postMessage",
100    "close",
101    "ref",
102    "unref",
103    "addEventListener",
104    "removeEventListener",
105];
106
107/// Instance methods on a `Worker` (main-side handle), beyond the shared
108/// EventEmitter surface (`on`/`once`/`emit`/…).
109pub const WORKER_METHODS: &[&str] = &["postMessage", "terminate", "ref", "unref"];
110
111/// Instance methods on a `MessagePort` (the worker-side `parentPort`), beyond the
112/// shared EventEmitter surface.
113pub const PORT_METHODS: &[&str] = &["postMessage", "close", "start", "ref", "unref"];
114
115/// Global, cross-thread thread-id source. The main thread is id 0; each `Worker`
116/// (including nested workers spawned from a worker) gets a fresh positive id.
117static NEXT_THREAD_ID: AtomicU64 = AtomicU64::new(1);
118
119/// A message crossing the main→worker `mpsc` channel. Both variants are `Send`
120/// (a JSON `String` / unit) — never a `Value`.
121enum WorkerMsg {
122    Data(String),
123    Terminate,
124}
125
126/// An event to raise on a `Worker` object, produced by the worker thread and run
127/// as an `IoTask` on the MAIN thread. All fields are `Send` plain data.
128enum MainEvent {
129    Online,
130    Message(String),
131    Error(String),
132    Exit(i32),
133}
134
135/// Main-thread registry entry for a live worker (keyed by thread id).
136struct WorkerRec {
137    /// The `Worker` EventEmitter object (lives on the main heap).
138    emitter: Value,
139    /// Sends main→worker messages / the terminate signal.
140    to_worker: Sender<WorkerMsg>,
141}
142
143thread_local! {
144    /// Live workers owned by THIS thread (the main thread, or a worker that
145    /// itself spawned sub-workers). Only ever touched on the owning thread.
146    static WORKERS: RefCell<HashMap<u64, WorkerRec>> = RefCell::new(HashMap::new());
147}
148
149/// Per-worker-thread context, set once when the worker thread starts, read while
150/// its file runs. Absent (`None`) on the main thread — that is how `isMainThread`
151/// is computed.
152struct WorkerCtx {
153    thread_id: u64,
154    /// `workerData` serialized as JSON on the spawning (main) thread; deserialized
155    /// lazily on this thread when `workerData` is read.
156    worker_data_json: String,
157    /// The MAIN loop's `io_sender`, to post worker→main events.
158    main_tx: Sender<IoTask>,
159    /// This worker's id (registry key on the main side).
160    self_id: u64,
161    /// Receives main→worker messages; taken out when the bridge thread starts.
162    rx: Option<Receiver<WorkerMsg>>,
163    /// Whether the forwarding bridge thread has been started.
164    bridge_started: bool,
165    /// Whether the bridge's hold on this worker's loop has been released, by
166    /// `terminate` or by `parentPort.close()` — whichever comes first.
167    port_released: bool,
168    /// `parentPort.close()` was called: later `postMessage`s are dropped.
169    port_closed: bool,
170    /// The port's `'close'` has been emitted: later deliveries are dropped.
171    port_close_emitted: bool,
172}
173
174thread_local! {
175    static WORKER_CTX: RefCell<Option<WorkerCtx>> = const { RefCell::new(None) };
176    /// The worker-side `parentPort` object, created lazily on first access and
177    /// cached (so both the JS file and the delivery `IoTask` share one object).
178    static PARENT_PORT: RefCell<Option<Value>> = const { RefCell::new(None) };
179
180    // ── MessageChannel state (both ports live on ONE thread) ──────────────────
181    /// port id → the `MessagePort` object.
182    static CHANNEL_PORTS: RefCell<HashMap<u64, Value>> = RefCell::new(HashMap::new());
183    /// port id → its peer's port id (posting to one enqueues on the other).
184    static CH_PEER: RefCell<HashMap<u64, u64>> = RefCell::new(HashMap::new());
185    /// port id → JSON messages queued FOR that port (drained by
186    /// `receiveMessageOnPort` or async `'message'` delivery once started).
187    static CH_QUEUE: RefCell<HashMap<u64, VecDeque<String>>> = RefCell::new(HashMap::new());
188    /// port ids whose async `'message'` delivery is active (a listener was added
189    /// or `start()` was called).
190    static CH_STARTED: RefCell<HashSet<u64>> = RefCell::new(HashSet::new());
191
192    // ── BroadcastChannel state (in-process, SAME-thread only) ─────────────────
193    /// channel name → the live `BroadcastChannel` objects on this thread.
194    static BCAST: RefCell<HashMap<String, Vec<(u64, Value)>>> = RefCell::new(HashMap::new());
195
196    // ── markAsUntransferable / markAsUncloneable flags (heap ids) ─────────────
197    static UNTRANSFERABLE: RefCell<HashSet<u32>> = RefCell::new(HashSet::new());
198    static UNCLONEABLE: RefCell<HashSet<u32>> = RefCell::new(HashSet::new());
199}
200
201/// Process-global `environmentData` map (shared across threads, so a value set on
202/// the main thread is visible via `getEnvironmentData` on a worker). Values cross
203/// as JSON strings because `fusevm::Value` is not `Send`.
204fn env_data() -> &'static Mutex<HashMap<String, String>> {
205    static ENV_DATA: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
206    ENV_DATA.get_or_init(|| Mutex::new(HashMap::new()))
207}
208
209/// A fresh unique port / broadcast-channel id (shares the thread-id counter's
210/// space is unnecessary — its own counter keeps ids distinct within a thread).
211static NEXT_PORT_ID: AtomicU64 = AtomicU64::new(1);
212
213// ── serialization (JSON subset of structured clone) ──────────────────────────
214
215/// Serialize a value to a JSON string on the CURRENT thread's heap. Wrapped in a
216/// one-element array so primitives and `undefined` round-trip through one always-
217/// valid JSON document. Errors (e.g. a `BigInt`) propagate as a thrown error.
218fn serialize(v: &Value) -> Result<String, String> {
219    let arr = with_host(|h| h.new_array(vec![v.clone()]));
220    let json = crate::builtins::call_builtin_function("JSON.stringify", vec![arr])?;
221    Ok(with_host(|h| h.str_of(&json)))
222}
223
224/// Deserialize a JSON string produced by `serialize` into a fresh value on the
225/// CURRENT thread's heap (unwrapping the array wrapper).
226fn deserialize(json: &str) -> Result<Value, String> {
227    let sv = with_host(|h| h.new_str(json.to_string()));
228    let arr = crate::builtins::call_builtin_function("JSON.parse", vec![sv])?;
229    Ok(with_host(|h| match h.get(&arr) {
230        Some(JsObj::Array(items)) => items.first().cloned().unwrap_or(Value::Undef),
231        _ => Value::Undef,
232    }))
233}
234
235// ── small heap helpers ───────────────────────────────────────────────────────
236
237fn arg0(args: &[Value]) -> Value {
238    args.first().cloned().unwrap_or(Value::Undef)
239}
240
241fn get_prop(recv: &Value, key: &str) -> Option<Value> {
242    with_host(|h| match h.get(recv) {
243        Some(JsObj::Object(p)) => p.get(key).cloned(),
244        _ => None,
245    })
246}
247
248fn u64_prop(recv: &Value, key: &str) -> Option<u64> {
249    get_prop(recv, key).map(|v| with_host(|h| h.to_number(&v)) as u64)
250}
251
252/// Emit `name` (with `args`) on an emitter object, releasing the host borrow
253/// before dispatch (listeners re-enter the host).
254fn emit_event(emitter: &Value, name: &str, mut args: Vec<Value>) -> Result<(), String> {
255    let mut a = vec![with_host(|h| h.new_str(name))];
256    a.append(&mut args);
257    super::events::instance_call(emitter, "emit", a).map(|_| ())
258}
259
260// ── thread-context queries (drive the module constants) ──────────────────────
261
262fn is_worker_thread() -> bool {
263    WORKER_CTX.with(|c| c.borrow().is_some())
264}
265
266fn current_thread_id() -> u64 {
267    WORKER_CTX.with(|c| c.borrow().as_ref().map(|x| x.thread_id).unwrap_or(0))
268}
269
270/// `workerData` for this thread: the deserialized options payload on a worker,
271/// `undefined` on the main thread.
272fn current_worker_data() -> Value {
273    let json = WORKER_CTX.with(|c| c.borrow().as_ref().map(|x| x.worker_data_json.clone()));
274    match json {
275        Some(j) => deserialize(&j).unwrap_or(Value::Undef),
276        None => Value::Undef,
277    }
278}
279
280/// The worker-side `parentPort` (a `MessagePort` emitter), created once per worker
281/// thread and cached. Only meaningful on a worker thread.
282fn ensure_parent_port() -> Value {
283    if let Some(p) = PARENT_PORT.with(|p| p.borrow().clone()) {
284        return p;
285    }
286    let port = super::net::new_emitter_object("MessagePort", IndexMap::new());
287    PARENT_PORT.with(|p| *p.borrow_mut() = Some(port.clone()));
288    port
289}
290
291// ── module constants (reached via `stdlib::constant("worker_threads", name)`) ─
292
293/// Non-function members of the `worker_threads` namespace:
294/// `isMainThread`/`threadId`/`parentPort`/`workerData`, and the `Worker`
295/// constructor (as a `Builtin("Worker")` so `new Worker(...)` reaches
296/// `construct_worker`).
297pub fn constant(name: &str) -> Option<Value> {
298    match name {
299        "isMainThread" => Some(Value::Bool(!is_worker_thread())),
300        "threadId" => Some(Value::Float(current_thread_id() as f64)),
301        "parentPort" => Some(if is_worker_thread() {
302            ensure_parent_port()
303        } else {
304            // On the main thread `parentPort` is `null` (Node parity).
305            with_host(|h| h.null())
306        }),
307        "workerData" => Some(current_worker_data()),
308        "Worker" | "MessageChannel" | "BroadcastChannel" => {
309            Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
310        }
311        _ => None,
312    }
313}
314
315/// Module-level dispatch. Routes only if the parent adds a `"worker_threads"` arm
316/// to `stdlib::call` (see the report).
317pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
318    Some(match method {
319        "setEnvironmentData" => {
320            let key = super::arg_str(args, 0);
321            match args.get(1) {
322                // An `undefined` value deletes the key (Node behavior).
323                Some(v) if !matches!(v, Value::Undef) => match serialize(v) {
324                    Ok(json) => {
325                        if let Ok(mut m) = env_data().lock() {
326                            m.insert(key, json);
327                        }
328                        Ok(Value::Undef)
329                    }
330                    Err(e) => Err(e),
331                },
332                _ => {
333                    if let Ok(mut m) = env_data().lock() {
334                        m.remove(&key);
335                    }
336                    Ok(Value::Undef)
337                }
338            }
339        }
340        "getEnvironmentData" => {
341            let key = super::arg_str(args, 0);
342            let json = env_data().lock().ok().and_then(|m| m.get(&key).cloned());
343            match json {
344                Some(j) => deserialize(&j),
345                None => Ok(Value::Undef),
346            }
347        }
348        "receiveMessageOnPort" => Ok(receive_message_on_port(args.first())),
349        // Best-effort transfer/clone flags: node-js clones every message as a JSON
350        // subset (see module docs), so these flags do not alter serialization —
351        // they are recorded and reflected by the `is*` query for API fidelity.
352        "markAsUntransferable" => {
353            if let Some(Value::Obj(id)) = args.first() {
354                UNTRANSFERABLE.with(|s| s.borrow_mut().insert(*id));
355            }
356            Ok(Value::Undef)
357        }
358        "isMarkedAsUntransferable" => Ok(Value::Bool(matches!(
359            args.first(),
360            Some(Value::Obj(id)) if UNTRANSFERABLE.with(|s| s.borrow().contains(id))
361        ))),
362        "markAsUncloneable" => {
363            if let Some(Value::Obj(id)) = args.first() {
364                UNCLONEABLE.with(|s| s.borrow_mut().insert(*id));
365            }
366            Ok(Value::Undef)
367        }
368        // node-js has one context, so there is nothing to move the port into;
369        // return the port unchanged.
370        "moveMessagePortToContext" => Ok(arg0(args)),
371        _ => return None,
372    })
373}
374
375// ── construction: `new Worker(filename[, options])` ──────────────────────────
376
377/// Build a `Worker` and spawn its OS thread (runs on the MAIN thread). The worker
378/// thread runs `filename` (a file path, or the code itself when `options.eval` is
379/// truthy) against its own fresh `thread_local` host.
380pub fn construct_worker(args: &[Value]) -> Result<Value, String> {
381    let filename = with_host(|h| h.str_of(&arg0(args)));
382    let opts = args.get(1).cloned();
383    let is_eval = opts
384        .as_ref()
385        .and_then(|o| get_prop(o, "eval"))
386        .map(|v| with_host(|h| h.truthy(&v)))
387        .unwrap_or(false);
388    // Serialize workerData NOW, on the main heap, into a Send JSON string.
389    let worker_data_json = match opts.as_ref().and_then(|o| get_prop(o, "workerData")) {
390        Some(v) => serialize(&v)?,
391        None => serialize(&Value::Undef)?, // "[null]"
392    };
393
394    let id = NEXT_THREAD_ID.fetch_add(1, Ordering::SeqCst);
395    let (to_worker_tx, to_worker_rx) = std::sync::mpsc::channel::<WorkerMsg>();
396    let main_tx = with_host(|h| h.io_sender());
397
398    let mut extra = IndexMap::new();
399    extra.insert("@@wtid".into(), Value::Float(id as f64));
400    extra.insert("threadId".into(), Value::Float(id as f64));
401    let emitter = super::net::new_emitter_object("Worker", extra);
402
403    WORKERS.with(|w| {
404        w.borrow_mut().insert(
405            id,
406            WorkerRec {
407                emitter: emitter.clone(),
408                to_worker: to_worker_tx,
409            },
410        );
411    });
412    // Keep the MAIN loop alive while the worker runs.
413    with_host(|h| h.incr_handle());
414
415    let spawn_tx = main_tx.clone();
416    std::thread::spawn(move || {
417        worker_thread_main(
418            id,
419            filename,
420            is_eval,
421            worker_data_json,
422            spawn_tx,
423            to_worker_rx,
424        );
425    });
426
427    Ok(emitter)
428}
429
430/// The worker thread's entry point. Runs on a brand-new OS thread whose
431/// `thread_local` host/module state is clean and isolated.
432fn worker_thread_main(
433    id: u64,
434    filename: String,
435    is_eval: bool,
436    worker_data_json: String,
437    main_tx: Sender<IoTask>,
438    rx: Receiver<WorkerMsg>,
439) {
440    WORKER_CTX.with(|c| {
441        *c.borrow_mut() = Some(WorkerCtx {
442            thread_id: id,
443            worker_data_json,
444            main_tx: main_tx.clone(),
445            self_id: id,
446            rx: Some(rx),
447            bridge_started: false,
448            port_released: false,
449            port_closed: false,
450            port_close_emitted: false,
451        });
452    });
453
454    // `'online'` fires once the worker thread has begun executing.
455    post_to_main(&main_tx, id, MainEvent::Online);
456
457    // Run the worker's code on this thread's own isolated host. `eval_file` /
458    // `eval_str` call `reset_host()` (fresh heap) and drain the worker's event
459    // loop — which, if the worker added a `parentPort` 'message' listener, stays
460    // alive processing bridged messages until `terminate`.
461    let outcome = if is_eval {
462        crate::eval_str(&filename)
463    } else {
464        crate::eval_file(&filename)
465    };
466
467    match outcome {
468        // A worker that ran to completion leaves with its `process.exitCode`.
469        Ok(_) => {
470            let code = with_host(|h| h.exit_code).unwrap_or(0);
471            post_to_main(&main_tx, id, MainEvent::Exit(code));
472        }
473        Err(e) => {
474            post_to_main(&main_tx, id, MainEvent::Error(e));
475            post_to_main(&main_tx, id, MainEvent::Exit(1));
476        }
477    }
478}
479
480/// Post a worker→main event as an `IoTask` onto the main loop. The closure is
481/// `Send` (captures only `id` + plain data) and runs `dispatch_main` on the main
482/// thread, where the `Worker` object and main heap live.
483fn post_to_main(main_tx: &Sender<IoTask>, id: u64, ev: MainEvent) {
484    let _ = main_tx.send(Box::new(move || dispatch_main(id, ev)));
485}
486
487/// Run a worker→main event on the MAIN thread.
488fn dispatch_main(id: u64, ev: MainEvent) -> Result<(), String> {
489    let emitter = WORKERS.with(|w| w.borrow().get(&id).map(|r| r.emitter.clone()));
490    let Some(emitter) = emitter else {
491        return Ok(());
492    };
493    match ev {
494        MainEvent::Online => emit_event(&emitter, "online", vec![]),
495        MainEvent::Message(json) => {
496            let v = deserialize(&json)?;
497            emit_event(&emitter, "message", vec![v])
498        }
499        MainEvent::Error(msg) => {
500            let err =
501                crate::builtins::construct_builtin("Error", vec![with_host(|h| h.new_str(msg))])?;
502            emit_event(&emitter, "error", vec![err])
503        }
504        MainEvent::Exit(code) => {
505            emit_event(&emitter, "exit", vec![Value::Float(code as f64)])?;
506            WORKERS.with(|w| {
507                w.borrow_mut().remove(&id);
508            });
509            with_host(|h| h.decr_handle());
510            // Wake the loop so a now-idle process can exit.
511            let _ = with_host(|h| h.io_sender()).send(Box::new(|| Ok(())));
512            Ok(())
513        }
514    }
515}
516
517// ── worker-side bridge: main→worker message delivery ─────────────────────────
518
519/// Start the forwarding thread that drains the main→worker `mpsc` channel and
520/// posts each message as an `IoTask` onto THIS worker's event loop. Idempotent;
521/// called when the worker adds a `parentPort` 'message' listener (or `start()`s
522/// the port). Also `incr_handle`s the worker loop so it stays alive to receive.
523fn start_parent_bridge() {
524    // Take the receiver + capture the worker loop's sender while we hold the ctx.
525    let worker_io: Option<Sender<IoTask>> = WORKER_CTX.with(|c| {
526        let mut cb = c.borrow_mut();
527        let ctx = cb.as_mut()?;
528        if ctx.bridge_started {
529            return None;
530        }
531        let rx = ctx.rx.take()?;
532        ctx.bridge_started = true;
533        let io = with_host(|h| h.io_sender());
534        with_host(|h| h.incr_handle());
535        // Spawn the forwarder; it owns `rx` and a clone of the worker io sender.
536        let io_for_thread = io.clone();
537        std::thread::spawn(move || {
538            while let Ok(msg) = rx.recv() {
539                match msg {
540                    WorkerMsg::Data(json) => {
541                        let _ = io_for_thread.send(Box::new(move || parent_deliver(json)));
542                    }
543                    WorkerMsg::Terminate => {
544                        // Release the worker loop so it can unwind and exit.
545                        let _ = io_for_thread.send(Box::new(|| {
546                            release_parent_port();
547                            Ok(())
548                        }));
549                        break;
550                    }
551                }
552            }
553        });
554        Some(io)
555    });
556    let _ = worker_io;
557}
558
559/// Drop the bridge's hold on this worker's event loop, once: what lets a
560/// worker whose only remaining handle was its `parentPort` end.
561fn release_parent_port() {
562    let release = WORKER_CTX.with(|c| {
563        let mut cb = c.borrow_mut();
564        match cb.as_mut() {
565            Some(ctx) if ctx.bridge_started && !ctx.port_released => {
566                ctx.port_released = true;
567                true
568            }
569            _ => false,
570        }
571    });
572    if release {
573        with_host(|h| h.decr_handle());
574    }
575}
576
577/// `parentPort.close()` (`MessagePort.prototype.close`): the port stops
578/// sending at once, and — after the messages already queued for it — emits
579/// `'close'` and stops holding the worker open, so a worker with nothing else
580/// to do ends.
581fn close_parent_port() {
582    let first = WORKER_CTX.with(|c| {
583        let mut cb = c.borrow_mut();
584        match cb.as_mut() {
585            Some(ctx) if !ctx.port_closed => {
586                ctx.port_closed = true;
587                true
588            }
589            _ => false,
590        }
591    });
592    if !first {
593        return;
594    }
595    // Queued on this worker's own loop, behind whatever the bridge has already
596    // forwarded; the loop is held until it runs.
597    with_host(|h| h.incr_handle());
598    let task: IoTask = Box::new(|| {
599        WORKER_CTX.with(|c| {
600            if let Some(ctx) = c.borrow_mut().as_mut() {
601                ctx.port_close_emitted = true;
602            }
603        });
604        release_parent_port();
605        with_host(|h| h.decr_handle());
606        emit_event(&ensure_parent_port(), "close", vec![])
607    });
608    let _ = with_host(|h| h.io_sender()).send(task);
609}
610
611/// `process.exit(code)` on a worker thread ends the WORKER, not the process
612/// (node's `process.exit` in a worker stops its isolate): the `Worker`'s
613/// `'exit'` fires on the spawning thread with `code`, and nothing after the
614/// call runs on this one. A thread cannot be stopped from inside its own JS
615/// stack, so it is parked for good once the event is posted. Returns on the
616/// main thread.
617pub fn exit_if_worker(code: i32) {
618    let target = WORKER_CTX.with(|c| c.borrow().as_ref().map(|x| (x.main_tx.clone(), x.self_id)));
619    let Some((main_tx, id)) = target else {
620        return;
621    };
622    post_to_main(&main_tx, id, MainEvent::Exit(code));
623    loop {
624        std::thread::park();
625    }
626}
627
628/// Deliver a main→worker message on the WORKER thread (runs inside the worker
629/// event loop): deserialize on the worker heap and emit `'message'` on
630/// `parentPort`.
631fn parent_deliver(json: String) -> Result<(), String> {
632    if WORKER_CTX.with(|c| c.borrow().as_ref().is_some_and(|x| x.port_close_emitted)) {
633        return Ok(());
634    }
635    let port = ensure_parent_port();
636    let v = deserialize(&json)?;
637    emit_event(&port, "message", vec![v])
638}
639
640// ── instance dispatch (from `stdlib::instance_call`) ─────────────────────────
641
642/// The shared EventEmitter method names delegated to `events` — the one
643/// definition, so this dispatcher cannot drift from the emitter surface.
644const EMITTER_METHODS: &[&str] = super::events::METHODS;
645
646pub fn instance_call(
647    tag: &str,
648    recv: &Value,
649    method: &str,
650    args: Vec<Value>,
651) -> Result<Value, String> {
652    match tag {
653        "Worker" => worker_call(recv, method, args),
654        "MessagePort" => port_call(recv, method, args),
655        "BroadcastChannel" => broadcast_call(recv, method, args),
656        _ => Err(crate::host::type_error(&format!(
657            "{method} is not a function"
658        ))),
659    }
660}
661
662/// Methods on the main-side `Worker` handle.
663fn worker_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
664    if EMITTER_METHODS.contains(&method) {
665        return super::events::instance_call(recv, method, args);
666    }
667    match method {
668        "postMessage" => {
669            let json = serialize(&arg0(&args))?;
670            if let Some(id) = u64_prop(recv, "@@wtid") {
671                WORKERS.with(|w| {
672                    if let Some(r) = w.borrow().get(&id) {
673                        let _ = r.to_worker.send(WorkerMsg::Data(json));
674                    }
675                });
676            }
677            Ok(Value::Undef)
678        }
679        "terminate" => {
680            // Signal the worker; its normal completion emits `'exit'`. Cooperative
681            // (see module docs) — returns `undefined`.
682            if let Some(id) = u64_prop(recv, "@@wtid") {
683                WORKERS.with(|w| {
684                    if let Some(r) = w.borrow().get(&id) {
685                        let _ = r.to_worker.send(WorkerMsg::Terminate);
686                    }
687                });
688            }
689            Ok(Value::Undef)
690        }
691        "ref" | "unref" => Ok(recv.clone()),
692        _ => Err(crate::host::type_error(&format!(
693            "worker.{method} is not a function"
694        ))),
695    }
696}
697
698/// Methods on the worker-side `parentPort` (`MessagePort`).
699fn port_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
700    // A `MessageChannel` port carries a `@@portid` and is handled separately from
701    // the worker `parentPort` (which posts to the spawning thread).
702    if let Some(pid) = u64_prop(recv, "@@portid") {
703        return channel_port_call(recv, pid, method, args);
704    }
705    if EMITTER_METHODS.contains(&method) {
706        let r = super::events::instance_call(recv, method, args.clone());
707        // Adding a 'message' listener implicitly starts message delivery.
708        if matches!(
709            method,
710            "on" | "addListener" | "prependListener" | "once" | "prependOnceListener"
711        ) {
712            let ev = with_host(|h| args.first().map(|v| h.str_of(v)).unwrap_or_default());
713            if ev == "message" {
714                start_parent_bridge();
715            }
716        }
717        return r;
718    }
719    match method {
720        "postMessage" => {
721            let json = serialize(&arg0(&args))?;
722            WORKER_CTX.with(|c| {
723                if let Some(ctx) = c.borrow().as_ref().filter(|x| !x.port_closed) {
724                    post_to_main(&ctx.main_tx, ctx.self_id, MainEvent::Message(json));
725                }
726            });
727            Ok(Value::Undef)
728        }
729        "start" => {
730            start_parent_bridge();
731            Ok(Value::Undef)
732        }
733        "close" => {
734            close_parent_port();
735            Ok(Value::Undef)
736        }
737        "ref" | "unref" => Ok(recv.clone()),
738        _ => Err(crate::host::type_error(&format!(
739            "port.{method} is not a function"
740        ))),
741    }
742}
743
744// ── MessageChannel (a pair of linked in-process ports) ───────────────────────
745
746/// `new MessageChannel()` → `{ port1, port2 }`, two `MessagePort` objects linked
747/// so that `port1.postMessage(v)` is delivered to `port2` (and vice versa). Both
748/// ports live on the calling thread and share its heap; messages are cloned
749/// through the JSON subset (`serialize`/`deserialize`) so a posted object is a
750/// copy, not a shared reference — matching structured clone's copy semantics.
751/// Requires the parent to wire `MessageChannel` construction (see the report).
752pub fn construct_message_channel(_args: &[Value]) -> Result<Value, String> {
753    let id1 = NEXT_PORT_ID.fetch_add(1, Ordering::SeqCst);
754    let id2 = NEXT_PORT_ID.fetch_add(1, Ordering::SeqCst);
755    let mut e1 = IndexMap::new();
756    e1.insert("@@portid".into(), Value::Float(id1 as f64));
757    let port1 = super::net::new_emitter_object("MessagePort", e1);
758    let mut e2 = IndexMap::new();
759    e2.insert("@@portid".into(), Value::Float(id2 as f64));
760    let port2 = super::net::new_emitter_object("MessagePort", e2);
761
762    CHANNEL_PORTS.with(|m| {
763        let mut m = m.borrow_mut();
764        m.insert(id1, port1.clone());
765        m.insert(id2, port2.clone());
766    });
767    CH_PEER.with(|m| {
768        let mut m = m.borrow_mut();
769        m.insert(id1, id2);
770        m.insert(id2, id1);
771    });
772
773    Ok(with_host(|h| {
774        let mut m = IndexMap::new();
775        m.insert("port1".into(), port1);
776        m.insert("port2".into(), port2);
777        h.new_object(m)
778    }))
779}
780
781/// Method dispatch for a `MessageChannel` port (identified by its `@@portid`).
782fn channel_port_call(
783    recv: &Value,
784    pid: u64,
785    method: &str,
786    args: Vec<Value>,
787) -> Result<Value, String> {
788    if EMITTER_METHODS.contains(&method) {
789        let r = super::events::instance_call(recv, method, args.clone());
790        // Adding a 'message' listener starts async delivery for this port.
791        if matches!(
792            method,
793            "on" | "addListener" | "prependListener" | "once" | "prependOnceListener"
794        ) {
795            let ev = with_host(|h| args.first().map(|v| h.str_of(v)).unwrap_or_default());
796            if ev == "message" {
797                start_channel_port(pid);
798            }
799        }
800        return r;
801    }
802    match method {
803        "postMessage" => {
804            let json = serialize(&arg0(&args))?;
805            channel_post(pid, json);
806            Ok(Value::Undef)
807        }
808        "start" => {
809            start_channel_port(pid);
810            Ok(Value::Undef)
811        }
812        "close" => {
813            CH_STARTED.with(|s| {
814                s.borrow_mut().remove(&pid);
815            });
816            Ok(Value::Undef)
817        }
818        "ref" | "unref" => Ok(recv.clone()),
819        _ => Err(crate::host::type_error(&format!(
820            "port.{method} is not a function"
821        ))),
822    }
823}
824
825/// Enqueue a JSON message on `from`'s peer, and schedule async delivery if the
826/// peer has started listening.
827fn channel_post(from: u64, json: String) {
828    let Some(peer) = CH_PEER.with(|m| m.borrow().get(&from).copied()) else {
829        return;
830    };
831    CH_QUEUE.with(|q| q.borrow_mut().entry(peer).or_default().push_back(json));
832    if CH_STARTED.with(|s| s.borrow().contains(&peer)) {
833        schedule_channel_delivery(peer);
834    }
835}
836
837/// Mark a port started and flush anything already queued to it.
838fn start_channel_port(pid: u64) {
839    let newly = CH_STARTED.with(|s| s.borrow_mut().insert(pid));
840    if !newly {
841        return;
842    }
843    let pending = CH_QUEUE.with(|q| q.borrow().get(&pid).map_or(0, |d| d.len()));
844    for _ in 0..pending {
845        schedule_channel_delivery(pid);
846    }
847}
848
849/// Post one delivery `IoTask` onto THIS thread's loop; keep the loop alive until
850/// it runs.
851fn schedule_channel_delivery(pid: u64) {
852    with_host(|h| h.incr_handle());
853    let io = with_host(|h| h.io_sender());
854    let _ = io.send(Box::new(move || channel_deliver(pid)));
855}
856
857/// Deliver (at most) one queued message to port `pid` by emitting `'message'`.
858/// Always `Ok(())`: a listener error is caught, never `?`-propagated (that would
859/// unwind the whole event loop — see the module docs).
860fn channel_deliver(pid: u64) -> Result<(), String> {
861    let json = CH_QUEUE.with(|q| q.borrow_mut().get_mut(&pid).and_then(|d| d.pop_front()));
862    if let Some(json) = json {
863        if let Some(port) = CHANNEL_PORTS.with(|m| m.borrow().get(&pid).cloned()) {
864            match deserialize(&json) {
865                Ok(v) => {
866                    if let Err(e) = emit_event(&port, "message", vec![v]) {
867                        eprintln!("{e}");
868                    }
869                }
870                Err(e) => eprintln!("{e}"),
871            }
872        }
873    }
874    with_host(|h| h.decr_handle());
875    Ok(())
876}
877
878/// `worker.receiveMessageOnPort(port)` → `{ message }` draining one queued message
879/// from `port`, or `undefined` if none is queued.
880fn receive_message_on_port(port: Option<&Value>) -> Value {
881    let Some(port) = port else {
882        return Value::Undef;
883    };
884    let Some(pid) = u64_prop(port, "@@portid") else {
885        return Value::Undef;
886    };
887    let json = CH_QUEUE.with(|q| q.borrow_mut().get_mut(&pid).and_then(|d| d.pop_front()));
888    match json {
889        Some(j) => match deserialize(&j) {
890            Ok(v) => with_host(|h| {
891                let mut m = IndexMap::new();
892                m.insert("message".into(), v);
893                h.new_object(m)
894            }),
895            Err(_) => Value::Undef,
896        },
897        None => Value::Undef,
898    }
899}
900
901// ── BroadcastChannel (in-process, SAME-thread pub/sub by name) ────────────────
902
903/// `new BroadcastChannel(name)` → an object that broadcasts `postMessage` data to
904/// every OTHER `BroadcastChannel` of the same name.
905///
906/// LIMITATION (documented, never faked): this is SAME-THREAD only. Node's
907/// BroadcastChannel spans worker threads; node-js delivers only to channels on
908/// the constructing thread (cross-thread delivery would need the worker bridge and
909/// is out of scope here). Like Node, a channel keeps the event loop alive (refs a
910/// handle) until `close()` / `unref()`.
911pub fn construct_broadcast_channel(args: &[Value]) -> Result<Value, String> {
912    let name = with_host(|h| h.str_of(&arg0(args)));
913    let id = NEXT_PORT_ID.fetch_add(1, Ordering::SeqCst);
914    let obj = with_host(|h| {
915        let listeners = h.new_array(Vec::new());
916        let mut m = IndexMap::new();
917        m.insert("@@native".into(), h.new_str("BroadcastChannel"));
918        m.insert("@@bcid".into(), Value::Float(id as f64));
919        m.insert("@@bcname".into(), h.new_str(name.clone()));
920        m.insert("@@listeners".into(), listeners);
921        m.insert("@@refed".into(), Value::Bool(true));
922        m.insert("name".into(), h.new_str(name.clone()));
923        m.insert("onmessage".into(), h.null());
924        m.insert("onmessageerror".into(), h.null());
925        h.new_object(m)
926    });
927    BCAST.with(|b| {
928        b.borrow_mut()
929            .entry(name)
930            .or_default()
931            .push((id, obj.clone()))
932    });
933    with_host(|h| h.incr_handle());
934    Ok(obj)
935}
936
937/// Method dispatch for a `BroadcastChannel` object.
938fn broadcast_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
939    match method {
940        "postMessage" => {
941            let json = serialize(&arg0(&args))?;
942            let name = str_prop(recv, "@@bcname");
943            let self_id = u64_prop(recv, "@@bcid");
944            let targets: Vec<Value> = BCAST.with(|b| match b.borrow().get(&name) {
945                Some(list) => list
946                    .iter()
947                    .filter(|(id, _)| Some(*id) != self_id)
948                    .map(|(_, v)| v.clone())
949                    .collect(),
950                None => Vec::new(),
951            });
952            for t in targets {
953                schedule_broadcast_delivery(t, json.clone());
954            }
955            Ok(Value::Undef)
956        }
957        "close" => {
958            let name = str_prop(recv, "@@bcname");
959            let self_id = u64_prop(recv, "@@bcid");
960            BCAST.with(|b| {
961                if let Some(list) = b.borrow_mut().get_mut(&name) {
962                    list.retain(|(id, _)| Some(*id) != self_id);
963                }
964            });
965            release_broadcast_ref(recv);
966            Ok(Value::Undef)
967        }
968        "addEventListener" => {
969            // Only 'message' is meaningful here; store the callback.
970            let ev = with_host(|h| args.first().map(|v| h.str_of(v)).unwrap_or_default());
971            if ev == "message" {
972                if let Some(cb) = args.get(1) {
973                    if let Some(arr) = get_prop(recv, "@@listeners") {
974                        with_host(|h| {
975                            if let Some(JsObj::Array(items)) = h.get_mut(&arr) {
976                                items.push(cb.clone());
977                            }
978                        });
979                    }
980                }
981            }
982            Ok(Value::Undef)
983        }
984        "removeEventListener" => Ok(Value::Undef),
985        "ref" => {
986            let refed = matches!(get_prop(recv, "@@refed"), Some(Value::Bool(true)));
987            if !refed {
988                with_host(|h| h.incr_handle());
989                set_bool(recv, "@@refed", true);
990            }
991            Ok(recv.clone())
992        }
993        "unref" => {
994            release_broadcast_ref(recv);
995            Ok(recv.clone())
996        }
997        _ => Err(crate::host::type_error(&format!(
998            "BroadcastChannel.{method} is not a function"
999        ))),
1000    }
1001}
1002
1003/// Drop the channel's event-loop handle if it currently holds one.
1004fn release_broadcast_ref(recv: &Value) {
1005    if matches!(get_prop(recv, "@@refed"), Some(Value::Bool(true))) {
1006        with_host(|h| h.decr_handle());
1007        set_bool(recv, "@@refed", false);
1008    }
1009}
1010
1011/// Schedule delivery of a broadcast message to one target channel.
1012fn schedule_broadcast_delivery(target: Value, json: String) {
1013    with_host(|h| h.incr_handle());
1014    let io = with_host(|h| h.io_sender());
1015    let _ = io.send(Box::new(move || broadcast_deliver(target, json)));
1016}
1017
1018/// Deliver a broadcast message: build a `MessageEvent`-like `{ data, type }` and
1019/// invoke the target's `onmessage` plus any `addEventListener('message')` handlers.
1020/// Always `Ok(())` — handler errors are caught, never `?`-propagated.
1021fn broadcast_deliver(target: Value, json: String) -> Result<(), String> {
1022    let value = match deserialize(&json) {
1023        Ok(v) => v,
1024        Err(e) => {
1025            eprintln!("{e}");
1026            with_host(|h| h.decr_handle());
1027            return Ok(());
1028        }
1029    };
1030    let event = with_host(|h| {
1031        let mut m = IndexMap::new();
1032        m.insert("data".into(), value);
1033        m.insert("type".into(), h.new_str("message"));
1034        h.new_object(m)
1035    });
1036    let onmessage = get_prop(&target, "onmessage");
1037    let mut handlers: Vec<Value> = Vec::new();
1038    if let Some(cb) = onmessage {
1039        if with_host(|h| crate::host::is_callable(h, &cb)) {
1040            handlers.push(cb);
1041        }
1042    }
1043    if let Some(arr) = get_prop(&target, "@@listeners") {
1044        let listeners: Vec<Value> = with_host(|h| match h.get(&arr) {
1045            Some(JsObj::Array(items)) => items.clone(),
1046            _ => Vec::new(),
1047        });
1048        handlers.extend(listeners);
1049    }
1050    for cb in handlers {
1051        if let Err(e) = crate::host::invoke(&cb, vec![event.clone()], None) {
1052            eprintln!("{e}");
1053        }
1054    }
1055    with_host(|h| h.decr_handle());
1056    Ok(())
1057}
1058
1059/// The string value of a hidden own property of `recv`.
1060fn str_prop(recv: &Value, key: &str) -> String {
1061    get_prop(recv, key)
1062        .map(|v| with_host(|h| h.str_of(&v)))
1063        .unwrap_or_default()
1064}
1065
1066/// Set a boolean own property on `recv`.
1067fn set_bool(recv: &Value, key: &str, val: bool) {
1068    with_host(|h| {
1069        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
1070            p.insert(key.to_string(), Value::Bool(val));
1071        }
1072    });
1073}