Skip to main content

quickjs_jit_stdlib/llrt/llrt_timers/
lib.rs

1// Vendored from LLRT d9fd873e793c (modules/llrt_timers/src/lib.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0
5use std::{
6    pin::{pin, Pin},
7    ptr::NonNull,
8    rc::Rc,
9    sync::{
10        atomic::{AtomicUsize, Ordering},
11        Mutex, MutexGuard,
12    },
13    time::Duration,
14};
15
16use crate::context::CtxExtension;
17pub use crate::hooking::{invoke_async_hook, register_finalization_registry, HookType};
18use crate::utils::{
19    module::{export_default, ModuleInfo},
20    provider::ProviderType,
21};
22use once_cell::sync::Lazy;
23use rquickjs::{
24    module::{Declarations, Exports, ModuleDef},
25    prelude::{Func, Opt},
26    qjs, Ctx, Exception, Function, Persistent, Result, Value,
27};
28use tokio::{
29    select,
30    sync::Notify,
31    time::{Instant, Sleep},
32};
33
34static TIMER_ID: AtomicUsize = AtomicUsize::new(0);
35static RT_TIMER_STATE: Lazy<Mutex<Vec<RuntimeTimerState>>> = Lazy::new(|| Mutex::new(Vec::new()));
36
37pub struct RuntimeTimerState {
38    timers: Vec<Timeout>,
39    rt: *mut qjs::JSRuntime,
40    running: bool,
41    deadline: Instant,
42    notify: Rc<Notify>,
43}
44impl RuntimeTimerState {
45    fn new(rt: *mut qjs::JSRuntime) -> Self {
46        let deadline = Instant::now() + Duration::from_secs(86400 * 365 * 30);
47        Self {
48            timers: Default::default(),
49            rt,
50            deadline,
51            running: false,
52            notify: Default::default(),
53        }
54    }
55}
56
57unsafe impl Send for RuntimeTimerState {}
58
59#[derive(Clone)]
60pub struct Timeout {
61    callback: Option<Persistent<Function<'static>>>,
62    deadline: Instant,
63    raw_ctx: NonNull<qjs::JSContext>,
64    id: usize,
65    repeating: bool,
66    interval: u64,
67}
68
69impl Default for Timeout {
70    fn default() -> Self {
71        Self {
72            callback: None,
73            deadline: Instant::now(),
74            raw_ctx: NonNull::dangling(),
75            id: 0,
76            repeating: false,
77            interval: 0,
78        }
79    }
80}
81
82fn queue_microtask<'js>(_ctx: Ctx<'js>, cb: Function<'js>) -> Result<()> {
83    // SAFETY: Since it checks in advance whether it is an Function type, we can always get a pointer to the Function.
84    let uid = unsafe { qjs::JS_VALUE_GET_PTR(cb.as_raw()) } as usize;
85    register_finalization_registry(&_ctx, cb.clone().into_value(), uid)?;
86    invoke_async_hook(&_ctx, HookType::Init, ProviderType::Microtask, uid)?;
87    // NOTE: Defer simply registers a task in a microtask queue
88    // and is separate from the timing of when the actual callback runs.
89    // Therefore, asynchronous before/after hooks are not meaningful and will not be implemented.
90
91    cb.defer::<()>(())?;
92    Ok(())
93}
94
95pub fn set_timeout_interval<'js>(
96    ctx: &Ctx<'js>,
97    cb: Function<'js>,
98    delay: u64,
99    provider_type: ProviderType,
100) -> Result<usize> {
101    // SAFETY: Since it checks in advance whether it is an Function type, we can always get a pointer to the Function.
102    let uid = unsafe { qjs::JS_VALUE_GET_PTR(cb.as_raw()) } as usize;
103
104    // NOTE: https://noncodersuccess.medium.com/understanding-setimmediate-vs-settimeout-in-node-js-6a3ef8fc02d4
105    // If `setImmediate(fn)` and `setTimeout(fn, 0) are queued at the exact same time,
106    // `setImmediate(fn) takes precedence in Node.js, regardless of their execution order.
107    // This is due to the specifications of the Node.js event loop.
108    // The event loop specifications of LLRT are completely different from those of Node.js,
109    // but to make them the same, `setImmedaite()` is executed before any delay setting of `setTimeout()`.
110    let (repeating, deadline) = match provider_type {
111        ProviderType::Immediate => (false, Instant::now() - Duration::from_secs(600)), // before any setTimeout(fn, delay)
112        ProviderType::Timeout => (false, Instant::now() + Duration::from_millis(delay)),
113        ProviderType::Interval => (true, Instant::now() + Duration::from_millis(delay)),
114        _ => {
115            return Err(Exception::throw_type(
116                ctx,
117                "The specified provider type is not supported.",
118            ))
119        }
120    };
121
122    register_finalization_registry(ctx, cb.clone().into_value(), uid)?;
123    invoke_async_hook(ctx, HookType::Init, provider_type, uid)?;
124
125    let id = TIMER_ID.fetch_add(1, Ordering::Relaxed);
126
127    let callback = Persistent::<Function>::save(ctx, cb);
128
129    let timeout = Timeout {
130        deadline,
131        callback: Some(callback),
132        raw_ctx: ctx.as_raw(),
133        id,
134        repeating,
135        interval: delay,
136    };
137
138    let rt_ptr = unsafe { qjs::JS_GetRuntime(ctx.as_raw().as_ptr()) };
139
140    let mut rt_timer = RT_TIMER_STATE.lock().unwrap();
141    let state = get_timer_state(&mut rt_timer, rt_ptr);
142    state.timers.push(timeout);
143    let task_running = state.running;
144    if task_running {
145        if deadline < state.deadline {
146            state.deadline = deadline;
147            state.notify.notify_one();
148        }
149    } else {
150        state.running = true;
151        let timer_abort = state.notify.clone();
152        drop(rt_timer);
153        create_spawn_loop(rt_ptr, ctx, timer_abort, deadline)?;
154    }
155
156    Ok(id)
157}
158
159fn get_timer_state<'a>(
160    state_ref: &'a mut MutexGuard<Vec<RuntimeTimerState>>,
161    rt: *mut qjs::JSRuntime,
162) -> &'a mut RuntimeTimerState {
163    let rt_timers = state_ref.iter_mut().find(|state| state.rt == rt);
164
165    //save a branch
166    unsafe { rt_timers.unwrap_unchecked() }
167}
168
169fn clear_timeout_interval(ctx: Ctx<'_>, id: Opt<Value>) -> Result<()> {
170    if let Some(id) = id.0.and_then(|v| v.as_number()) {
171        let id = id as usize;
172        let rt = unsafe { qjs::JS_GetRuntime(ctx.as_raw().as_ptr()) };
173        let mut rt_timers = RT_TIMER_STATE.lock().unwrap();
174
175        let state = get_timer_state(&mut rt_timers, rt);
176        if let Some(timeout) = state.timers.iter_mut().find(|t| t.id == id) {
177            let _ = timeout.callback.take();
178            timeout.repeating = false;
179            timeout.deadline = Instant::now() - Duration::from_secs(1);
180            state.notify.notify_one()
181        }
182    }
183
184    Ok(())
185}
186
187pub struct TimersModule;
188
189impl ModuleDef for TimersModule {
190    fn declare(declare: &Declarations) -> Result<()> {
191        declare.declare("setTimeout")?;
192        declare.declare("clearTimeout")?;
193        declare.declare("setInterval")?;
194        declare.declare("setImmediate")?;
195        declare.declare("clearInterval")?;
196        declare.declare("queueMicrotask")?;
197        declare.declare("default")?;
198        Ok(())
199    }
200
201    fn evaluate<'js>(ctx: &Ctx<'js>, exports: &Exports<'js>) -> Result<()> {
202        let globals = ctx.globals();
203
204        export_default(ctx, exports, |default| {
205            let functions = [
206                "setTimeout",
207                "clearTimeout",
208                "setInterval",
209                "clearInterval",
210                "setImmediate",
211                "queueMicrotask",
212            ];
213            for func_name in functions {
214                let function: Function = globals.get(func_name)?;
215                default.set(func_name, function)?;
216            }
217            Ok(())
218        })?;
219
220        Ok(())
221    }
222}
223
224impl From<TimersModule> for ModuleInfo<TimersModule> {
225    fn from(val: TimersModule) -> Self {
226        ModuleInfo {
227            name: "timers",
228            module: val,
229        }
230    }
231}
232
233pub fn init(ctx: &Ctx<'_>) -> Result<()> {
234    let rt_ptr = unsafe { qjs::JS_GetRuntime(ctx.as_raw().as_ptr()) };
235
236    let mut rt_timers = RT_TIMER_STATE.lock().unwrap();
237    rt_timers.push(RuntimeTimerState::new(rt_ptr));
238
239    let globals = ctx.globals();
240
241    globals.set(
242        "setTimeout",
243        Func::from(move |ctx, cb, delay: Opt<f64>| {
244            let delay = delay.unwrap_or(0.).max(0.) as u64;
245            set_timeout_interval(&ctx, cb, delay, ProviderType::Timeout)
246        }),
247    )?;
248
249    globals.set(
250        "setInterval",
251        Func::from(move |ctx, cb, delay: Opt<f64>| {
252            let delay = delay.unwrap_or(0.).max(0.) as u64;
253            set_timeout_interval(&ctx, cb, delay, ProviderType::Interval)
254        }),
255    )?;
256
257    globals.set("clearTimeout", Func::from(clear_timeout_interval))?;
258
259    globals.set("clearInterval", Func::from(clear_timeout_interval))?;
260
261    globals.set(
262        "setImmediate",
263        Func::from(move |ctx, cb| set_timeout_interval(&ctx, cb, 0, ProviderType::Immediate)),
264    )?;
265
266    globals.set("queueMicrotask", Func::from(queue_microtask))?;
267
268    Ok(())
269}
270
271#[inline(always)]
272fn create_spawn_loop(
273    rt: *mut qjs::JSRuntime,
274    ctx: &Ctx<'_>,
275    timer_abort: Rc<Notify>,
276    deadline: Instant,
277) -> Result<()> {
278    ctx.spawn_exit_simple(async move {
279        let mut sleep = pin!(tokio::time::sleep_until(deadline));
280
281        let mut executing_timers: Vec<Option<ExecutingTimer>> = Default::default();
282
283        loop {
284            select! {
285                _ = timer_abort.notified() => {}
286                _ = sleep.as_mut() => {}
287            }
288
289            if !poll_timers(rt, &mut executing_timers, Some(&mut sleep), None)? {
290                break;
291            }
292        }
293        Ok(())
294    });
295
296    Ok(())
297}
298
299pub struct ExecutingTimer(
300    Instant,
301    NonNull<qjs::JSContext>,
302    Persistent<Function<'static>>,
303);
304
305unsafe impl Send for ExecutingTimer {}
306
307pub fn poll_timers(
308    rt: *mut qjs::JSRuntime,
309    call_vec: &mut Vec<Option<ExecutingTimer>>,
310    sleep: Option<&mut Pin<&mut Sleep>>,
311    deadline: Option<&mut Instant>,
312) -> Result<bool> {
313    static MIN_SLEEP: Duration = Duration::from_millis(4);
314    static FAR_FUTURE: Duration = Duration::from_secs(84200 * 365 * 30);
315
316    let mut rt_timers = RT_TIMER_STATE.lock().unwrap();
317    let state = get_timer_state(&mut rt_timers, rt);
318    let now = Instant::now();
319
320    let mut had_items = false;
321    let mut lowest = now + FAR_FUTURE;
322    state.timers.retain_mut(|timeout| {
323        had_items = true;
324        if timeout.deadline < now {
325            let ctx = timeout.raw_ctx;
326            if let Some(cb) = timeout.callback.take() {
327                if !timeout.repeating {
328                    call_vec.push(Some(ExecutingTimer(timeout.deadline, ctx, cb)));
329                    return false;
330                }
331                timeout.deadline = now + Duration::from_millis(timeout.interval);
332                if timeout.deadline < lowest {
333                    lowest = timeout.deadline;
334                }
335                call_vec.push(Some(ExecutingTimer(timeout.deadline, ctx, cb.clone())));
336                timeout.callback.replace(cb);
337            } else {
338                return false;
339            }
340        } else if timeout.deadline < lowest {
341            lowest = timeout.deadline;
342        }
343        true
344    });
345
346    let has_items = !state.timers.is_empty();
347
348    if had_items {
349        if lowest - now < MIN_SLEEP {
350            lowest = now + MIN_SLEEP;
351        }
352        if let Some(sleep) = sleep {
353            sleep.as_mut().reset(lowest);
354        }
355        if let Some(deadline) = deadline {
356            *deadline = lowest;
357        }
358        state.deadline = lowest;
359    }
360
361    drop(rt_timers);
362
363    call_vec.sort_unstable_by_key(|v| v.as_ref().map(|v| v.0));
364
365    let mut is_first_time = true;
366    for item in call_vec.iter_mut() {
367        if let Some(ExecutingTimer(_, ctx, timeout)) = item.take() {
368            let ctx2 = unsafe { Ctx::from_raw(ctx) };
369
370            if is_first_time {
371                while ctx2.execute_pending_job() {}
372                is_first_time = false;
373            }
374
375            if let Ok(timeout) = timeout.restore(&ctx2) {
376                // SAFETY: Since it checks in advance whether it is an Function type, we can always get a pointer to the Function.
377                let uid: usize = unsafe { qjs::JS_VALUE_GET_PTR(timeout.as_raw()) } as usize;
378
379                invoke_async_hook(&ctx2, HookType::Before, ProviderType::None, uid)?;
380
381                timeout.call::<_, ()>(())?;
382
383                invoke_async_hook(&ctx2, HookType::After, ProviderType::None, uid)?;
384            }
385
386            while ctx2.execute_pending_job() {}
387        }
388    }
389    call_vec.clear();
390
391    if !has_items {
392        let mut rt_timers = RT_TIMER_STATE.lock().unwrap();
393        let state = get_timer_state(&mut rt_timers, rt);
394        let is_empty = state.timers.is_empty();
395        state.running = !is_empty;
396
397        return Ok(!is_empty);
398    }
399    Ok(true)
400}
401
402#[cfg(test)]
403mod tests {
404    use crate::test_support::{call_test, test_async_with, ModuleEvaluator};
405
406    use super::*;
407
408    #[tokio::test]
409    async fn test_timers() {
410        test_async_with(|ctx| {
411            Box::pin(async move {
412                init(&ctx).unwrap();
413
414                // Assume we have a TimersModule that provides setTimeout, setImmediate, and setInterval
415                ModuleEvaluator::eval_rust::<TimersModule>(ctx.clone(), "timers")
416                    .await
417                    .unwrap();
418
419                // Test setTimeout
420                let module = ModuleEvaluator::eval_js(
421                    ctx.clone(),
422                    "test_setTimeout",
423                    r#"
424                        import { setTimeout } from 'timers';
425                        export async function test() {
426                            return new Promise((resolve) => {
427                                setTimeout(() => resolve('timeout'), 100);
428                            });
429                        }
430                    "#,
431                )
432                .await
433                .unwrap();
434                let result = call_test::<String, _>(&ctx, &module, ()).await;
435                assert_eq!(result, "timeout");
436
437                // Test setImmediate
438                let module = ModuleEvaluator::eval_js(
439                    ctx.clone(),
440                    "test_setImmediate",
441                    r#"
442                        import { setImmediate } from 'timers';
443                        export async function test() {
444                            return new Promise((resolve) => {
445                                setImmediate(() => resolve('immediate'));
446                            });
447                        }
448                    "#,
449                )
450                .await
451                .unwrap();
452                let result = call_test::<String, _>(&ctx, &module, ()).await;
453                assert_eq!(result, "immediate");
454
455                // Test setInterval
456                let module = ModuleEvaluator::eval_js(
457                    ctx.clone(),
458                    "test_setInterval",
459                    r#"
460                        import { setInterval, clearInterval } from 'timers';
461                        export async function test() {
462                            return new Promise((resolve) => {
463                                let count = 0;
464                                const intervalId = setInterval(() => {
465                                    count++;
466                                    if (count === 3) {
467                                        clearInterval(intervalId);
468                                        resolve(count);
469                                    }
470                                }, 10);
471                            });
472                        }
473                    "#,
474                )
475                .await
476                .unwrap();
477                let result = call_test::<i32, _>(&ctx, &module, ()).await;
478                assert_eq!(result, 3);
479
480                // Test nested timers
481                let module = ModuleEvaluator::eval_js(
482                    ctx.clone(),
483                    "test_nestedTimers",
484                    r#"
485                        import { setTimeout, setImmediate } from 'timers';
486                        export async function test() {
487                            return new Promise((resolve) => {
488                                setTimeout(() => {
489                                    setImmediate(() => {
490                                        setTimeout(() => {
491                                            resolve('nested');
492                                        }, 10);
493                                    });
494                                }, 10);
495                            });
496                        }
497                    "#,
498                )
499                .await
500                .unwrap();
501                let result = call_test::<String, _>(&ctx, &module, ()).await;
502                assert_eq!(result, "nested");
503
504                // Test canceling timeout
505                let module = ModuleEvaluator::eval_js(
506                    ctx.clone(),
507                    "test_cancelTimeout",
508                    r#"
509                        import { setTimeout, clearTimeout } from 'timers';
510                        export async function test() {
511                            return new Promise((resolve) => {
512                                const timeoutId = setTimeout(() => {
513                                    resolve('should not happen');
514                                }, 10);
515                                clearTimeout(timeoutId);
516                                setTimeout(() => resolve('canceled'), 20);
517                            });
518                        }
519                    "#,
520                )
521                .await
522                .unwrap();
523                let result = call_test::<String, _>(&ctx, &module, ()).await;
524                assert_eq!(result, "canceled");
525
526                // Test multiple intervals
527                let module = ModuleEvaluator::eval_js(
528                    ctx.clone(),
529                    "test_multipleIntervals",
530                    r#"
531                        import { setInterval, clearInterval } from 'timers';
532                        export async function test() {
533                            return new Promise((resolve) => {
534                                let count1 = 0, count2 = 0;
535                                const id1 = setInterval(() => {
536                                    count1++;
537                                    if (count1 === 2) clearInterval(id1);
538                                }, 10);
539                                const id2 = setInterval(() => {
540                                    count2++;
541                                    if (count2 === 3) {
542                                        clearInterval(id2);
543                                        resolve([count1, count2]);
544                                    }
545                                }, 20);
546                            });
547                        }
548                    "#,
549                )
550                .await
551                .unwrap();
552                let result = call_test::<Vec<i32>, _>(&ctx, &module, ()).await;
553                assert_eq!(result, vec![2, 3]);
554            })
555        })
556        .await;
557    }
558}