nodejs/stdlib/timers.rs
1//! Node `timers` and `timers/promises` modules.
2//!
3//! `require('timers')` re-exports the SAME timer primitives that already exist as
4//! globals (`setTimeout`/`setInterval`/`setImmediate` + their `clear*`), so this
5//! module owns NO queue of its own: every method delegates straight to
6//! `builtins::call_builtin_function`, which schedules onto the single shared
7//! `JsHost.macrotasks` queue. `timers.foo(...)` is therefore observably identical
8//! to the global `foo(...)`.
9//!
10//! `require('timers/promises')` returns the promise-based variants: `setTimeout`
11//! and `setImmediate` resolve a Promise after the delay instead of invoking a
12//! callback. They are built on the SAME two substrates — the global timer
13//! scheduler and the `@@presolve:<id>` native-continuation convention that
14//! `builtins.rs` uses for Promise resolve reactions — so no new mechanism is
15//! introduced: a timer is scheduled whose callback is the promise's resolver.
16
17use super::arg_num;
18use crate::host::{with_host, JsObj};
19use fusevm::Value;
20use indexmap::IndexMap;
21
22// ── timer handle objects (`Timeout` / `Immediate`) ───────────────────────────
23
24/// Methods on a `Timeout` (returned by `setTimeout`/`setInterval`). Node's
25/// prototype carries exactly `refresh`, `unref`, `ref`, `hasRef`, `close`;
26/// `valueOf`/`toString` back the primitive coercion described on
27/// [`new_handle`].
28pub const TIMEOUT_METHODS: &[&str] = &[
29 "ref",
30 "unref",
31 "hasRef",
32 "refresh",
33 "close",
34 "toString",
35 // A `Timeout` coerces to its own id, which is how the handle can be passed
36 // straight back to `clearTimeout` in code that stored `Number(t)`. The
37 // symbol form was missing, so `t[Symbol.toPrimitive]` was not a function.
38 "@@toPrimitive",
39];
40
41/// Methods on an `Immediate` (returned by `setImmediate`). Node's `Immediate`
42/// prototype has no `refresh` — there is no countdown to restart.
43pub const IMMEDIATE_METHODS: &[&str] = &["ref", "unref", "hasRef", "close", "valueOf", "toString"];
44
45/// Build the handle object a `set*` call returns: an `@@native`-tagged object
46/// (`"Timeout"` or `"Immediate"`) carrying the scheduler's timer id in a hidden
47/// `@@timerId` slot.
48///
49/// Node's handles coerce to their integer id (`String(t)` is `"2"`), which is
50/// what keeps `clearTimeout` working for code that stashed the return value in a
51/// number. `valueOf`/`toString` reproduce that for both ToPrimitive hints —
52/// Node reaches it via an own `Symbol.toPrimitive`, which this does not model.
53pub fn new_handle(id: u64, tag: &'static str) -> Value {
54 with_host(|h| {
55 let mut m = IndexMap::new();
56 m.insert("@@native".into(), h.new_str(tag));
57 m.insert("@@timerId".into(), Value::Float(id as f64));
58 h.new_object(m)
59 })
60}
61
62/// The timer id behind a handle object, or `None` for anything else.
63///
64/// Read straight off the heap slot rather than through `ToPrimitive`: the
65/// `clear*` builtins run inside a `with_host` borrow, and coercing via a
66/// `valueOf` call would re-enter `with_host` and panic on the `RefCell`.
67pub fn handle_id(v: &Value) -> Option<u64> {
68 with_host(|h| match h.get(v) {
69 Some(JsObj::Object(p)) => p.get("@@timerId").map(|n| h.to_number(n) as u64),
70 _ => None,
71 })
72}
73
74thread_local! {
75 /// node's `knownTimersById`: the `Timeout`s whose id has been taken as a
76 /// primitive, which are the only ones `clearTimeout` will find by id.
77 static KNOWN_IDS: std::cell::RefCell<std::collections::HashSet<u64>> =
78 std::cell::RefCell::new(std::collections::HashSet::new());
79}
80
81fn note_known_id(id: u64) {
82 KNOWN_IDS.with(|k| k.borrow_mut().insert(id));
83}
84
85/// `clearTimeout`/`clearInterval` (`lib/timers.js`): a `Timeout` handle is
86/// cleared; a number or string clears the `Timeout` that coerced to it, if
87/// any. Anything else — an `Immediate` among them — is ignored.
88pub fn clear_timeout(v: &Value) {
89 if native_tag(v).as_deref() == Some("Timeout") {
90 if let Some(id) = handle_id(v) {
91 with_host(|h| h.cancel_timer(id));
92 }
93 return;
94 }
95 let key = with_host(|h| {
96 if matches!(v, Value::Int(_) | Value::Float(_)) || h.as_str(v).is_some() {
97 Some(h.to_number(v))
98 } else {
99 None
100 }
101 });
102 if let Some(n) = key.filter(|n| n.fract() == 0.0 && *n >= 0.0) {
103 let id = n as u64;
104 if KNOWN_IDS.with(|k| k.borrow().contains(&id)) {
105 with_host(|h| h.cancel_timer(id));
106 }
107 }
108}
109
110/// `clearImmediate`: only an `Immediate` handle is cleared.
111pub fn clear_immediate(v: &Value) {
112 if native_tag(v).as_deref() == Some("Immediate") {
113 if let Some(id) = handle_id(v) {
114 with_host(|h| h.cancel_timer(id));
115 }
116 }
117}
118
119fn native_tag(v: &Value) -> Option<String> {
120 super::native_tag(v)
121}
122
123/// Dispatch a method on a `Timeout`/`Immediate` handle.
124///
125/// `ref`/`unref`/`refresh` return the handle itself (Node chains them); they are
126/// inert once the timer has fired or been cleared, since the scheduler entry is
127/// gone. `close` is Node's alias for clearing the timer.
128pub fn instance_call(recv: &Value, method: &str, _args: &[Value]) -> Result<Value, String> {
129 let id = handle_id(recv).unwrap_or(0);
130 match method {
131 "ref" => {
132 with_host(|h| h.set_timer_refed(id, true));
133 Ok(recv.clone())
134 }
135 "unref" => {
136 with_host(|h| h.set_timer_refed(id, false));
137 Ok(recv.clone())
138 }
139 "hasRef" => Ok(Value::Bool(with_host(|h| h.timer_has_ref(id)))),
140 "refresh" => {
141 with_host(|h| h.refresh_timer(id));
142 Ok(recv.clone())
143 }
144 "close" => {
145 with_host(|h| h.cancel_timer(id));
146 Ok(recv.clone())
147 }
148 // Only the SYMBOL form yields the id. `valueOf` is the inherited
149 // `Object.prototype.valueOf`, which returns the receiver — node's
150 // `Timeout` does not override it, and reporting the id there made
151 // `t.valueOf() === t` false.
152 "@@toPrimitive" => {
153 note_known_id(id);
154 Ok(Value::Float(id as f64))
155 }
156 "toString" => {
157 note_known_id(id);
158 Ok(with_host(|h| h.new_str(id.to_string())))
159 }
160 _ => Err(crate::host::type_error(&format!(
161 "timeout.{method} is not a function"
162 ))),
163 }
164}
165
166// ── timers (callback API) ────────────────────────────────────────────────────
167
168/// Methods of the `timers` module. Each name is also a global; `call` forwards to
169/// the identical global implementation, so there is one timer queue, not two.
170pub const METHODS: &[&str] = &[
171 "setTimeout",
172 "setInterval",
173 "setImmediate",
174 "clearTimeout",
175 "clearInterval",
176 "clearImmediate",
177];
178
179/// Dispatch a `timers.<method>` call by delegating to the matching global timer
180/// builtin.
181pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
182 let global = match method {
183 "setTimeout" | "setInterval" | "setImmediate" | "clearTimeout" | "clearInterval"
184 | "clearImmediate" => method,
185 _ => return None,
186 };
187 Some(crate::builtins::call_builtin_function(
188 global,
189 args.to_vec(),
190 ))
191}
192
193// ── timers/promises (Promise API) ────────────────────────────────────────────
194
195/// Methods of the `timers/promises` module (its namespace name carries no `.`, so
196/// `stdlib::is_method` treats the whole `"timers/promises"` as the namespace).
197///
198/// `setInterval(delay[, value])` (an async iterator) is NOT implemented: the
199/// `for await` machinery finds a native object's async iterator only via
200/// `host::user_async_iterator_fn`, which needs a *callable* `@@asyncIterator`
201/// stored property discoverable by `lookup_chain` — native-tagged objects
202/// dispatch methods through the parent `instance_call` table, not stored
203/// properties, so there is no way to expose it without editing `builtins.rs`/
204/// `host.rs` (out of scope here).
205pub const PROMISES_METHODS: &[&str] = &["setTimeout", "setImmediate", "setInterval"];
206
207/// The async-iterator surface `timers/promises.setInterval` returns.
208pub const INTERVAL_METHODS: &[&str] = &["next", "return", "@@asyncIterator"];
209
210/// Dispatch a `timers/promises.<method>` call.
211///
212/// `setTimeout(delay[, value])` → a Promise that fulfills with `value` (undefined
213/// if absent) after `delay` ms. `setImmediate([value])` → a Promise that fulfills
214/// with `value` on the next loop turn. Any trailing `options` argument (Node's
215/// `{ signal, ref }`) is accepted and ignored — abort/unref are not modeled.
216pub fn promises_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
217 match method {
218 "setTimeout" => {
219 let delay = arg_num(args, 0);
220 let value = args.get(1).cloned().unwrap_or(Value::Undef);
221 Some(Ok(schedule_promise("setTimeout", Some(delay), value)))
222 }
223 "setImmediate" => {
224 let value = args.first().cloned().unwrap_or(Value::Undef);
225 Some(Ok(schedule_promise("setImmediate", None, value)))
226 }
227 // `setInterval(delay, value)` is an ASYNC ITERABLE, not a promise: it
228 // yields `value` every `delay` for as long as it is iterated. It was
229 // missing, so `for await (const v of setInterval(...))` had nothing to
230 // call.
231 "setInterval" => {
232 let delay = arg_num(args, 0);
233 let value = args.get(1).cloned().unwrap_or(Value::Undef);
234 Some(Ok(interval_iterator(delay, value)))
235 }
236 _ => None,
237 }
238}
239
240/// The object `timers/promises.setInterval` hands back: an async iterator that
241/// resolves one `{ value, done: false }` per `delay`, and reports `done` once
242/// `return()` has been called (which is what `break` inside `for await` does).
243fn interval_iterator(delay: f64, value: Value) -> Value {
244 with_host(|h| {
245 let mut m = IndexMap::new();
246 m.insert("@@native".into(), h.new_str("IntervalIterator"));
247 m.insert("@@delay".into(), Value::Float(delay));
248 m.insert("@@value".into(), value);
249 m.insert("@@stopped".into(), Value::Bool(false));
250 h.new_object(m)
251 })
252}
253
254pub fn interval_call(recv: &Value, method: &str, _args: &[Value]) -> Result<Value, String> {
255 let slot = |k: &str| {
256 with_host(|h| match h.get(recv) {
257 Some(JsObj::Object(p)) => p.get(k).cloned(),
258 _ => None,
259 })
260 };
261 match method {
262 // An async iterable is its own iterator here, as node's is.
263 "@@asyncIterator" => Ok(recv.clone()),
264 "next" => {
265 let stopped = slot("@@stopped").is_some_and(|v| with_host(|h| h.truthy(&v)));
266 let value = slot("@@value").unwrap_or(Value::Undef);
267 if stopped {
268 let done = iter_result(Value::Undef, true);
269 return Ok(resolved_promise(done));
270 }
271 let delay = slot("@@delay")
272 .map(|v| with_host(|h| h.to_number(&v)))
273 .unwrap_or(0.0);
274 let result = iter_result(value, false);
275 Ok(schedule_promise("setTimeout", Some(delay), result))
276 }
277 "return" => {
278 with_host(|h| {
279 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
280 p.insert("@@stopped".into(), Value::Bool(true));
281 }
282 });
283 let done = iter_result(Value::Undef, true);
284 Ok(resolved_promise(done))
285 }
286 _ => Err(crate::host::type_error(&format!(
287 "intervalIterator.{method} is not a function"
288 ))),
289 }
290}
291
292/// `{ value, done }` — the iterator-result shape both arms return.
293fn iter_result(value: Value, done: bool) -> Value {
294 with_host(|h| {
295 let mut m = IndexMap::new();
296 m.insert("value".into(), value);
297 m.insert("done".into(), Value::Bool(done));
298 h.new_object(m)
299 })
300}
301
302/// A promise already fulfilled with `v`.
303fn resolved_promise(v: Value) -> Value {
304 let (promise, id) = with_host(|h| {
305 let p = h.new_promise();
306 let id = h.promise_id(&p).unwrap_or(0);
307 (p, id)
308 });
309 crate::host::resolve_promise_val(id, v);
310 promise
311}
312
313/// Allocate a pending Promise and schedule its resolution with `value` via the
314/// existing global timer scheduler. The scheduled callback is a
315/// `Builtin("@@presolve:<id>")` value — the same native continuation
316/// `builtins.rs` invokes to fulfill a Promise — so when the timer fires it
317/// resolves the Promise with the timer's extra argument (`value`).
318fn schedule_promise(kind: &str, delay: Option<f64>, value: Value) -> Value {
319 // Create the promise and grab its id for the resolver continuation.
320 let (promise, id) = with_host(|h| {
321 let p = h.new_promise();
322 let id = h.promise_id(&p).unwrap_or(0);
323 (p, id)
324 });
325 // The resolver: invoked with `[value]` when the timer fires.
326 let resolver = with_host(|h| h.alloc(JsObj::Builtin(format!("@@presolve:{id}"))));
327 // Route through the exact global scheduler. `setTimeout(cb, delay, value)`
328 // and `setImmediate(cb, value)` pass `value` on to the callback as its first
329 // argument, which `@@presolve:<id>` resolves the promise with.
330 let timer_args = match delay {
331 Some(d) => vec![resolver, Value::Float(d), value],
332 None => vec![resolver, value],
333 };
334 // Ignore the returned timer id; the promise is the module's return value.
335 let _ = crate::builtins::call_builtin_function(kind, timer_args);
336 promise
337}