Skip to main content

nodejs/stdlib/
async_hooks.rs

1//! Node `async_hooks` module — honest minimal implementation.
2//!
3//! There IS a real async-resource id graph, but only over the resources this
4//! module itself creates:
5//!
6//!   - Every `new AsyncResource(type)` takes the next monotonically increasing
7//!     `asyncId` (from 2; Node reserves 1 for the root context) and records the
8//!     creating context's id as its `triggerAsyncId`.
9//!   - `runInAsyncScope` makes that pair the current execution context for the
10//!     duration of the call, so `executionAsyncId()` inside reports the
11//!     resource and a resource constructed there inherits it as its parent.
12//!     Nesting `runInAsyncScope` therefore builds a real parent chain.
13//!
14//! What is NOT modeled: node-js does not instrument timers, promises, sockets
15//! or any other engine-level async resource, so `executionAsyncId()` inside a
16//! `setTimeout`/`.then` callback reports the ROOT context (1) rather than a
17//! per-callback id, and `triggerAsyncId()` there reports 0. Only the
18//! `AsyncResource` graph above is real. Consequently:
19//!
20//!   - `createHook({ init, before, after, destroy })` returns a hook object with
21//!     chainable `enable()`/`disable()`. The registered callbacks are stored
22//!     nowhere and NEVER FIRE — node-js does not instrument async resource
23//!     lifetimes. This is intentional; do not treat it as a gap to "fill" by
24//!     faking hook invocations.
25//!
26//! `AsyncLocalStorage` is real across async boundaries: stores live in the
27//! host's ASYNC CONTEXT FRAME (node's `AsyncContextFrame`), which every queued
28//! task, timer and promise reaction captures when it is scheduled (a reaction:
29//! when `.then`/`await` registers it) and restores while it runs. `run(store,
30//! cb)` runs `cb` in a frame with the store set, `exit` in one without it,
31//! `enterWith` replaces the current frame, and `AsyncLocalStorage.snapshot()` /
32//! `bind()` and `AsyncResource` hold the frame they were made in.
33//!
34//! Instances are `@@native`-tagged objects (`AsyncLocalStorage` / `AsyncHook`)
35//! dispatched through `instance_call`; the parent wires `construct`,
36//! `native_tag`, `instance_has_method`, and `instance_call` (see the report).
37
38use crate::host::{invoke, with_host};
39use fusevm::Value;
40use indexmap::IndexMap;
41use std::cell::RefCell;
42
43thread_local! {
44
45    /// Monotonic async-id source. Node reserves 1 for the root execution
46    /// context, so fresh resources start at 2.
47    static NEXT_ASYNC_ID: RefCell<f64> = const { RefCell::new(2.0) };
48
49    /// The execution-context stack as `(asyncId, triggerAsyncId)` pairs, rooted
50    /// at Node's `(1, 0)`. `runInAsyncScope` pushes the resource's pair for the
51    /// duration of the call, which is what makes `executionAsyncId()` inside the
52    /// scope report the resource and a resource *created* in that scope inherit
53    /// it as its `triggerAsyncId`.
54    static EXEC_STACK: RefCell<Vec<(f64, f64)>> = const { RefCell::new(Vec::new()) };
55}
56
57/// The id of the currently-executing async context (Node's `executionAsyncId`).
58pub fn execution_async_id() -> f64 {
59    EXEC_STACK.with(|s| s.borrow().last().map(|p| p.0).unwrap_or(1.0))
60}
61
62/// The id of the context that *created* the currently-executing one.
63pub fn trigger_async_id() -> f64 {
64    EXEC_STACK.with(|s| s.borrow().last().map(|p| p.1).unwrap_or(0.0))
65}
66
67/// Take the next async id.
68fn fresh_async_id() -> f64 {
69    NEXT_ASYNC_ID.with(|n| {
70        let mut n = n.borrow_mut();
71        let id = *n;
72        *n += 1.0;
73        id
74    })
75}
76
77/// Run `f` with `(async_id, trigger_id)` as the current execution context,
78/// restoring the previous context even if `f` fails.
79fn in_async_scope<T>(async_id: f64, trigger_id: f64, f: impl FnOnce() -> T) -> T {
80    EXEC_STACK.with(|s| s.borrow_mut().push((async_id, trigger_id)));
81    let r = f();
82    EXEC_STACK.with(|s| {
83        s.borrow_mut().pop();
84    });
85    r
86}
87
88/// Module-level callable members.
89pub const METHODS: &[&str] = &["executionAsyncId", "triggerAsyncId", "createHook"];
90
91/// Instance method names by native tag — for the parent's `instance_has_method`
92/// so a method *read* (`als.run.bind(...)`) resolves before it is invoked.
93pub const ALS_METHODS: &[&str] = &["getStore", "run", "enterWith", "exit", "disable"];
94pub const HOOK_METHODS: &[&str] = &["enable", "disable"];
95pub const RESOURCE_METHODS: &[&str] = &[
96    "runInAsyncScope",
97    "emitDestroy",
98    "asyncId",
99    "triggerAsyncId",
100    "bind",
101];
102
103/// Static members on the `AsyncResource` constructor itself.
104pub const RESOURCE_STATIC_METHODS: &[&str] = &["bind"];
105
106/// `AsyncResource.bind(fn[, type[, thisArg]])` — with no async-context graph to
107/// capture there is nothing to restore, so the bound function IS `fn` (bound to
108/// `thisArg` when one is given). Node's own semantics reduce to this whenever no
109/// context is active.
110pub fn static_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
111    match method {
112        "bind" => {
113            let f = args.first().cloned().unwrap_or(Value::Undef);
114            let bound = bind_to(f, args.get(2).cloned());
115            let frame = with_host(|h| h.async_frame.clone());
116            Some(frame_runner(frame, Some(bound)))
117        }
118        _ => None,
119    }
120}
121
122/// `fn` itself, or a `fn.bind(thisArg)` when a non-nullish receiver is supplied.
123fn bind_to(f: Value, this: Option<Value>) -> Value {
124    match this.filter(|t| !with_host(|h| h.is_nullish(t))) {
125        Some(t) => with_host(|h| {
126            h.alloc(crate::host::JsObj::BoundFunc {
127                target: f,
128                this: t,
129                args: Vec::new(),
130            })
131        }),
132        None => f,
133    }
134}
135
136pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
137    Some(match method {
138        "@@runInFrame" => run_in_frame(args),
139        "executionAsyncId" => Ok(Value::Float(execution_async_id())),
140        "triggerAsyncId" => Ok(Value::Float(trigger_async_id())),
141        // The hook object; its callbacks never fire (see module docs).
142        "createHook" => Ok(new_hook()),
143        _ => return None,
144    })
145}
146
147/// Construct a stdlib class instance (`new AsyncLocalStorage()`). `None` for any
148/// other name so the parent's `construct` can fall through.
149pub fn construct(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
150    match name {
151        "AsyncLocalStorage" => Some(Ok(new_native("AsyncLocalStorage"))),
152        // `new AsyncResource(type[, options])` takes the next monotonic async id
153        // and records the creating context as its `triggerAsyncId`, so a graph
154        // built by nesting `runInAsyncScope` calls has real parent links.
155        // `options.triggerAsyncId` overrides the inherited parent, as in Node.
156        "AsyncResource" => {
157            let r = new_native("AsyncResource");
158            let frame_id = hold_frame(with_host(|h| h.async_frame.clone()));
159            let trigger = args
160                .get(1)
161                .and_then(|o| {
162                    with_host(|h| match h.get(o) {
163                        Some(crate::host::JsObj::Object(p)) => p
164                            .get("triggerAsyncId")
165                            .filter(|v| !matches!(v, Value::Undef))
166                            .map(|v| h.to_number(v)),
167                        _ => None,
168                    })
169                })
170                .unwrap_or_else(execution_async_id);
171            with_host(|h| {
172                if let Some(crate::host::JsObj::Object(p)) = h.get_mut(&r) {
173                    p.insert("@@asyncId".into(), Value::Float(fresh_async_id()));
174                    p.insert("@@triggerAsyncId".into(), Value::Float(trigger));
175                    // The async context frame the resource was created in;
176                    // `runInAsyncScope` and `bind` run in it.
177                    p.insert("@@frame".into(), Value::Float(frame_id));
178                }
179            });
180            Some(Ok(r))
181        }
182        _ => None,
183    }
184}
185
186/// A fresh `@@native`-tagged object carrying `tag`.
187fn new_native(tag: &'static str) -> Value {
188    with_host(|h| {
189        let mut m = IndexMap::new();
190        m.insert("@@native".into(), h.new_str(tag));
191        h.new_object(m)
192    })
193}
194
195/// A hidden numeric slot on a native instance (`@@asyncId`), or `fallback`.
196fn hidden_num(recv: &Value, key: &str, fallback: f64) -> f64 {
197    with_host(|h| match h.get(recv) {
198        Some(crate::host::JsObj::Object(p)) => {
199            p.get(key).map(|v| h.to_number(v)).unwrap_or(fallback)
200        }
201        _ => fallback,
202    })
203}
204
205/// The object returned by `createHook`. Its `enable`/`disable` are no-ops that
206/// return the hook itself (Node's chainable API); no callbacks are ever invoked.
207fn new_hook() -> Value {
208    new_native("AsyncHook")
209}
210
211/// Dispatch a method on a native `async_hooks` instance.
212pub fn instance_call(
213    tag: &str,
214    recv: &Value,
215    method: &str,
216    args: Vec<Value>,
217) -> Result<Value, String> {
218    match tag {
219        // A createHook() result: enable/disable are no-ops returning `this` so
220        // `createHook(...).enable()` chains work. No hook callbacks fire.
221        "AsyncHook" => match method {
222            "enable" | "disable" => Ok(recv.clone()),
223            _ => Err(crate::host::type_error(&format!(
224                "{method} is not a function"
225            ))),
226        },
227        "AsyncLocalStorage" => als_call(recv, method, args),
228        "AsyncResource" => resource_call(recv, method, args),
229        _ => Err(crate::host::type_error(&format!(
230            "{method} is not a function"
231        ))),
232    }
233}
234
235/// An `AsyncResource` instance. Each carries a real monotonic `asyncId` and the
236/// `triggerAsyncId` of the context that created it, and `runInAsyncScope` makes
237/// that pair the current execution context for the duration of the call — so
238/// `executionAsyncId()` inside the callback reports the resource, and a resource
239/// constructed there records this one as its parent. `emitDestroy` still has
240/// nothing to destroy (no `destroy` hooks fire; see the module docs).
241fn resource_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
242    match method {
243        // runInAsyncScope(fn[, thisArg[, ...args]]) === fn.apply(thisArg, args),
244        // run under this resource's async context.
245        "runInAsyncScope" => {
246            let f = args.first().cloned().unwrap_or(Value::Undef);
247            // Pass the receiver through verbatim (Node uses `ReflectApply`), so
248            // an explicit `null` gets the same sloppy-mode coercion `fn.call(null)`
249            // already applies rather than silently becoming "no receiver".
250            let this = args.get(1).cloned();
251            let rest = args.get(2..).map(|s| s.to_vec()).unwrap_or_default();
252            let id = hidden_num(recv, "@@asyncId", 1.0);
253            let trigger = hidden_num(recv, "@@triggerAsyncId", 0.0);
254            let frame = resource_frame(recv);
255            in_async_scope(id, trigger, || {
256                crate::host::in_frame(frame, || invoke(&f, rest, this))
257            })
258        }
259        "bind" => {
260            let f = args.first().cloned().unwrap_or(Value::Undef);
261            let bound = bind_to(f, args.get(1).cloned());
262            frame_runner(resource_frame(recv), Some(bound))
263        }
264        "emitDestroy" => Ok(recv.clone()),
265        "asyncId" => Ok(Value::Float(hidden_num(recv, "@@asyncId", 1.0))),
266        "triggerAsyncId" => Ok(Value::Float(hidden_num(recv, "@@triggerAsyncId", 0.0))),
267        _ => Err(crate::host::type_error(&format!(
268            "{method} is not a function"
269        ))),
270    }
271}
272
273/// The instance's heap index (its store-stack key), or `0` for a non-heap value.
274fn key(recv: &Value) -> u32 {
275    match recv {
276        Value::Obj(i) => *i,
277        _ => 0,
278    }
279}
280
281fn als_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
282    let id = key(recv);
283    match method {
284        // The store this instance has in the current async context frame.
285        "getStore" => Ok(with_host(|h| {
286            h.async_frame
287                .iter()
288                .find(|(k, _)| *k == id)
289                .map(|(_, v)| v.clone())
290                .unwrap_or(Value::Undef)
291        })),
292        // run(store, callback, ...args): set the store, call the callback with the
293        // remaining args, restore the previous store, return the callback result.
294        "run" => {
295            let store = args.first().cloned().unwrap_or(Value::Undef);
296            let cb = args.get(1).cloned().unwrap_or(Value::Undef);
297            let rest = args.get(2..).map(|s| s.to_vec()).unwrap_or_default();
298            let frame = crate::host::frame_with(id, Some(store));
299            crate::host::in_frame(frame, || invoke(&cb, rest, None))
300        }
301        // exit(callback, ...args): the callback runs with no store.
302        "exit" => {
303            let cb = args.first().cloned().unwrap_or(Value::Undef);
304            let rest = args.get(1..).map(|s| s.to_vec()).unwrap_or_default();
305            let frame = crate::host::frame_with(id, None);
306            crate::host::in_frame(frame, || invoke(&cb, rest, None))
307        }
308        // enterWith(store): the store for the rest of the current execution and
309        // everything it schedules.
310        "enterWith" | "disable" => {
311            let store =
312                (method == "enterWith").then(|| args.first().cloned().unwrap_or(Value::Undef));
313            let frame = crate::host::frame_with(id, store);
314            with_host(|h| h.async_frame = frame);
315            Ok(Value::Undef)
316        }
317        _ => Err(crate::host::type_error(&format!(
318            "{method} is not a function"
319        ))),
320    }
321}
322
323/// The frame an `AsyncResource` was created in.
324fn resource_frame(recv: &Value) -> crate::host::AsyncFrame {
325    let id = hidden_num(recv, "@@frame", -1.0);
326    if id < 0.0 {
327        return with_host(|h| h.async_frame.clone());
328    }
329    HELD_FRAMES
330        .with(|f| f.borrow().get(id as usize).cloned())
331        .unwrap_or_default()
332}
333
334/// Static members on the `AsyncLocalStorage` constructor.
335pub const ALS_STATIC_METHODS: &[&str] = &["bind", "snapshot"];
336
337/// `AsyncLocalStorage.snapshot()` — a function that runs its argument in the
338/// frame current now — and `AsyncLocalStorage.bind(fn)` — `fn`, run in the
339/// frame current now.
340pub fn als_static_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
341    let frame = with_host(|h| h.async_frame.clone());
342    Some(match method {
343        "snapshot" => frame_runner(frame, None),
344        "bind" => frame_runner(frame, Some(args.first().cloned().unwrap_or(Value::Undef))),
345        _ => return None,
346    })
347}
348
349thread_local! {
350    /// Frames handed out to `snapshot`/`bind`/`AsyncResource`, by handle.
351    static HELD_FRAMES: RefCell<Vec<crate::host::AsyncFrame>> = const { RefCell::new(Vec::new()) };
352}
353
354fn hold_frame(frame: crate::host::AsyncFrame) -> f64 {
355    HELD_FRAMES.with(|f| {
356        let mut f = f.borrow_mut();
357        f.push(frame);
358        (f.len() - 1) as f64
359    })
360}
361
362/// A JS function over a held frame: with `target`, `target` bound to it (its
363/// `this` and arguments passed through); without, node's snapshot runner
364/// `(fn, ...args) => fn(...args)` in that frame.
365fn frame_runner(frame: crate::host::AsyncFrame, target: Option<Value>) -> Result<Value, String> {
366    thread_local! {
367        static FACTORY: RefCell<Option<Value>> = const { RefCell::new(None) };
368    }
369    let factory = match FACTORY.with(|f| f.borrow().clone()) {
370        Some(f) => f,
371        None => {
372            let f = crate::eval_internal(
373                "(function (runner, id, target) {\n\
374                   if (target === undefined) return function runInAsyncScope(fn, ...args) { return runner(id, fn, undefined, ...args); };\n\
375                   return function (...args) { return runner(id, target, this, ...args); };\n\
376                 })",
377            )?;
378            FACTORY.with(|c| *c.borrow_mut() = Some(f.clone()));
379            f
380        }
381    };
382    let id = Value::Float(hold_frame(frame));
383    let runner = with_host(|h| {
384        h.alloc(crate::host::JsObj::Builtin(
385            "async_hooks.@@runInFrame".into(),
386        ))
387    });
388    invoke(
389        &factory,
390        vec![runner, id, target.unwrap_or(Value::Undef)],
391        None,
392    )
393}
394
395/// `async_hooks.@@runInFrame(id, fn, this, ...args)`: `fn` called in held frame `id`.
396pub fn run_in_frame(args: &[Value]) -> Result<Value, String> {
397    let id = with_host(|h| h.to_number(args.first().unwrap_or(&Value::Undef))) as usize;
398    let frame = HELD_FRAMES
399        .with(|f| f.borrow().get(id).cloned())
400        .unwrap_or_default();
401    let f = args.get(1).cloned().unwrap_or(Value::Undef);
402    let this = args.get(2).cloned().filter(|t| !matches!(t, Value::Undef));
403    let rest = args.get(3..).map(|s| s.to_vec()).unwrap_or_default();
404    crate::host::in_frame(frame, || invoke(&f, rest, this))
405}