Skip to main content

script/
timers.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6use std::cmp::{Ord, Ordering};
7use std::collections::VecDeque;
8use std::default::Default;
9use std::rc::Rc;
10use std::time::{Duration, Instant};
11
12use deny_public_fields::DenyPublicFields;
13use js::context::JSContext;
14use js::jsapi::Heap;
15use js::jsval::{JSVal, UndefinedValue};
16use js::rust::wrappers2::JS_GetScriptedCallerPrivate;
17use js::rust::{HandleValue, IntoHandle};
18use net_traits::request::ParserMetadata;
19use rustc_hash::FxHashMap;
20use script_bindings::cell::DomRefCell;
21use serde::{Deserialize, Serialize};
22use servo_base::id::PipelineId;
23use servo_config::pref;
24use servo_url::ServoUrl;
25use timers::{BoxedTimerCallback, TimerEventRequest};
26
27use crate::dom::bindings::callback::ExceptionHandling::Report;
28use crate::dom::bindings::codegen::Bindings::FunctionBinding::Function;
29use crate::dom::bindings::codegen::UnionTypes::TrustedScriptOrString;
30use crate::dom::bindings::error::Fallible;
31use crate::dom::bindings::inheritance::Castable;
32use crate::dom::bindings::refcounted::Trusted;
33use crate::dom::bindings::root::{AsHandleValue, Dom};
34use crate::dom::bindings::str::DOMString;
35use crate::dom::csp::CspReporting;
36use crate::dom::document::RefreshRedirectDue;
37use crate::dom::eventsource::EventSourceTimeoutCallback;
38use crate::dom::globalscope::GlobalScope;
39use crate::dom::globalscope::script_execution::{ErrorReporting, RethrowErrors};
40#[cfg(feature = "testbinding")]
41use crate::dom::testbinding::TestBindingCallback;
42use crate::dom::trustedtypes::trustedscript::TrustedScript;
43use crate::dom::types::{Window, WorkerGlobalScope};
44use crate::dom::xmlhttprequest::XHRTimeoutCallback;
45use crate::script_module::{ScriptFetchOptions, module_script_from_reference_private};
46use crate::script_runtime::IntroductionType;
47use crate::script_thread::ScriptThread;
48use crate::task_source::SendableTaskSource;
49
50type TimerKey = i32;
51type RunStepsDeadline = Instant;
52type CompletionStep = Box<dyn FnOnce(&mut JSContext, &GlobalScope) + 'static>;
53
54/// <https://html.spec.whatwg.org/multipage/#run-steps-after-a-timeout>
55/// OrderingIdentifier per spec ("orderingIdentifier")
56type OrderingIdentifier = DOMString;
57
58#[derive(JSTraceable, MallocSizeOf)]
59struct OrderingEntry {
60    milliseconds: u64,
61    start_seq: u64,
62    handle: OneshotTimerHandle,
63}
64
65// Per-ordering queues map
66type OrderingQueues = FxHashMap<OrderingIdentifier, Vec<OrderingEntry>>;
67
68// Active timers map for Run Steps After A Timeout
69type RunStepsActiveMap = FxHashMap<TimerKey, RunStepsDeadline>;
70
71#[derive(Clone, Copy, Debug, Eq, Hash, JSTraceable, MallocSizeOf, Ord, PartialEq, PartialOrd)]
72pub(crate) struct OneshotTimerHandle(i32);
73
74#[derive(DenyPublicFields, JSTraceable, MallocSizeOf)]
75#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
76pub(crate) struct OneshotTimers {
77    global_scope: Dom<GlobalScope>,
78    js_timers: JsTimers,
79    next_timer_handle: Cell<OneshotTimerHandle>,
80    timers: DomRefCell<VecDeque<OneshotTimer>>,
81    suspended_since: Cell<Option<Instant>>,
82    /// Initially 0, increased whenever the associated document is reactivated
83    /// by the amount of ms the document was inactive. The current time can be
84    /// offset back by this amount for a coherent time across document
85    /// activations.
86    suspension_offset: Cell<Duration>,
87    /// Calls to `fire_timer` with a different argument than this get ignored.
88    /// They were previously scheduled and got invalidated when
89    ///  - timers were suspended,
90    ///  - the timer it was scheduled for got canceled or
91    ///  - a timer was added with an earlier callback time. In this case the
92    ///    original timer is rescheduled when it is the next one to get called.
93    #[no_trace]
94    expected_event_id: Cell<TimerEventId>,
95    /// <https://html.spec.whatwg.org/multipage/#map-of-active-timers>
96    /// TODO this should also be used for the other timers
97    /// as per <html.spec.whatwg.org/multipage/#map-of-settimeout-and-setinterval-ids>Z.
98    map_of_active_timers: DomRefCell<RunStepsActiveMap>,
99
100    /// <https://html.spec.whatwg.org/multipage/#run-steps-after-a-timeout>
101    /// Step 4.2 Wait until any invocations of this algorithm that had the same global and orderingIdentifier,
102    /// that started before this one, and whose milliseconds is less than or equal to this one's, have completed.
103    runsteps_queues: DomRefCell<OrderingQueues>,
104
105    /// <html.spec.whatwg.org/multipage/#timers:unique-internal-value-5>
106    next_runsteps_key: Cell<TimerKey>,
107
108    /// <https://html.spec.whatwg.org/multipage/#run-steps-after-a-timeout>
109    /// Start order sequence to break ties for Step 4.2.
110    runsteps_start_seq: Cell<u64>,
111}
112
113#[derive(DenyPublicFields, JSTraceable, MallocSizeOf)]
114struct OneshotTimer {
115    handle: OneshotTimerHandle,
116    #[no_trace]
117    source: TimerSource,
118    callback: OneshotTimerCallback,
119    scheduled_for: Instant,
120}
121
122// This enum is required to work around the fact that trait objects do not support generic methods.
123// A replacement trait would have a method such as
124//     `invoke<T: DomObject>(self: Box<Self>, this: &T, js_timers: &JsTimers);`.
125#[derive(JSTraceable, MallocSizeOf)]
126pub(crate) enum OneshotTimerCallback {
127    XhrTimeout(XHRTimeoutCallback),
128    EventSourceTimeout(EventSourceTimeoutCallback),
129    JsTimer(JsTimerTask),
130    #[cfg(feature = "testbinding")]
131    TestBindingCallback(TestBindingCallback),
132    RefreshRedirectDue(RefreshRedirectDue),
133    /// <https://html.spec.whatwg.org/multipage/#run-steps-after-a-timeout>
134    RunStepsAfterTimeout {
135        /// Step 1. timerKey
136        timer_key: i32,
137        /// Step 4. orderingIdentifier
138        ordering_id: DOMString,
139        /// Spec: milliseconds (the algorithm input)
140        milliseconds: u64,
141        /// Perform completionSteps.
142        #[no_trace]
143        #[ignore_malloc_size_of = "Closure"]
144        completion: CompletionStep,
145    },
146}
147
148impl OneshotTimerCallback {
149    fn invoke(self, cx: &mut JSContext, global: &GlobalScope, js_timers: &JsTimers) {
150        match self {
151            OneshotTimerCallback::XhrTimeout(callback) => callback.invoke(cx),
152            OneshotTimerCallback::EventSourceTimeout(callback) => callback.invoke(),
153            OneshotTimerCallback::JsTimer(task) => task.invoke(cx, global, js_timers),
154            #[cfg(feature = "testbinding")]
155            OneshotTimerCallback::TestBindingCallback(callback) => callback.invoke(cx),
156            OneshotTimerCallback::RefreshRedirectDue(callback) => callback.invoke(cx, global),
157            OneshotTimerCallback::RunStepsAfterTimeout { completion, .. } => {
158                // <https://html.spec.whatwg.org/multipage/#run-steps-after-a-timeout>
159                // Step 4.4 Perform completionSteps.
160                completion(cx, global);
161            },
162        }
163    }
164}
165
166impl Ord for OneshotTimer {
167    fn cmp(&self, other: &OneshotTimer) -> Ordering {
168        match self.scheduled_for.cmp(&other.scheduled_for).reverse() {
169            Ordering::Equal => self.handle.cmp(&other.handle).reverse(),
170            res => res,
171        }
172    }
173}
174
175impl PartialOrd for OneshotTimer {
176    fn partial_cmp(&self, other: &OneshotTimer) -> Option<Ordering> {
177        Some(self.cmp(other))
178    }
179}
180
181impl Eq for OneshotTimer {}
182impl PartialEq for OneshotTimer {
183    fn eq(&self, other: &OneshotTimer) -> bool {
184        std::ptr::eq(self, other)
185    }
186}
187
188impl OneshotTimers {
189    pub(crate) fn new(global_scope: &GlobalScope) -> OneshotTimers {
190        OneshotTimers {
191            global_scope: Dom::from_ref(global_scope),
192            js_timers: JsTimers::default(),
193            next_timer_handle: Cell::new(OneshotTimerHandle(1)),
194            timers: DomRefCell::new(VecDeque::new()),
195            suspended_since: Cell::new(None),
196            suspension_offset: Cell::new(Duration::ZERO),
197            expected_event_id: Cell::new(TimerEventId(0)),
198            map_of_active_timers: Default::default(),
199            runsteps_queues: Default::default(),
200            next_runsteps_key: Cell::new(1),
201            runsteps_start_seq: Cell::new(0),
202        }
203    }
204
205    /// <https://html.spec.whatwg.org/multipage/#run-steps-after-a-timeout>
206    #[inline]
207    pub(crate) fn now_for_runsteps(&self) -> Instant {
208        // Step 2. Let startTime be the current high resolution time given global.
209        self.base_time()
210    }
211
212    /// <https://html.spec.whatwg.org/multipage/#run-steps-after-a-timeout>
213    /// Step 1. Let timerKey be a new unique internal value.
214    pub(crate) fn fresh_runsteps_key(&self) -> TimerKey {
215        let k = self.next_runsteps_key.get();
216        self.next_runsteps_key.set(k + 1);
217        k
218    }
219
220    /// <https://html.spec.whatwg.org/multipage/#run-steps-after-a-timeout>
221    /// Step 3. Set global's map of active timers[timerKey] to startTime plus milliseconds.
222    pub(crate) fn runsteps_set_active(&self, timer_key: TimerKey, deadline: RunStepsDeadline) {
223        self.map_of_active_timers
224            .borrow_mut()
225            .insert(timer_key, deadline);
226    }
227
228    /// <https://html.spec.whatwg.org/multipage/#run-steps-after-a-timeout>
229    /// Helper for Step 4.2: maintain per-ordering sorted queue by (milliseconds, startSeq, handle).
230    fn runsteps_enqueue_sorted(
231        &self,
232        ordering_id: &DOMString,
233        handle: OneshotTimerHandle,
234        milliseconds: u64,
235    ) {
236        let mut map = self.runsteps_queues.borrow_mut();
237        let q = map.entry(ordering_id.clone()).or_default();
238
239        let seq = {
240            let cur = self.runsteps_start_seq.get();
241            self.runsteps_start_seq.set(cur + 1);
242            cur
243        };
244
245        let key = OrderingEntry {
246            milliseconds,
247            start_seq: seq,
248            handle,
249        };
250
251        let idx = q
252            .binary_search_by(|ordering_entry| {
253                match ordering_entry.milliseconds.cmp(&milliseconds) {
254                    Ordering::Less => Ordering::Less,
255                    Ordering::Greater => Ordering::Greater,
256                    Ordering::Equal => ordering_entry.start_seq.cmp(&seq),
257                }
258            })
259            .unwrap_or_else(|i| i);
260
261        q.insert(idx, key);
262    }
263
264    pub(crate) fn schedule_callback(
265        &self,
266        callback: OneshotTimerCallback,
267        duration: Duration,
268        source: TimerSource,
269    ) -> OneshotTimerHandle {
270        let new_handle = self.next_timer_handle.get();
271        self.next_timer_handle
272            .set(OneshotTimerHandle(new_handle.0 + 1));
273
274        let timer = OneshotTimer {
275            handle: new_handle,
276            source,
277            callback,
278            scheduled_for: self.base_time() + duration,
279        };
280
281        // https://html.spec.whatwg.org/multipage/#run-steps-after-a-timeout
282        // Step 4.2: maintain per-orderingIdentifier order by milliseconds (and start order for ties).
283        if let OneshotTimerCallback::RunStepsAfterTimeout {
284            ordering_id,
285            milliseconds,
286            ..
287        } = &timer.callback
288        {
289            self.runsteps_enqueue_sorted(ordering_id, new_handle, *milliseconds);
290        }
291
292        {
293            let mut timers = self.timers.borrow_mut();
294            let insertion_index = timers.binary_search(&timer).err().unwrap();
295            timers.insert(insertion_index, timer);
296        }
297
298        if self.is_next_timer(new_handle) {
299            self.schedule_timer_call();
300        }
301
302        new_handle
303    }
304
305    pub(crate) fn unschedule_callback(&self, handle: OneshotTimerHandle) {
306        let was_next = self.is_next_timer(handle);
307
308        self.timers.borrow_mut().retain(|t| t.handle != handle);
309
310        if was_next {
311            self.invalidate_expected_event_id();
312            self.schedule_timer_call();
313        }
314    }
315
316    fn is_next_timer(&self, handle: OneshotTimerHandle) -> bool {
317        match self.timers.borrow().back() {
318            None => false,
319            Some(max_timer) => max_timer.handle == handle,
320        }
321    }
322
323    /// <https://html.spec.whatwg.org/multipage/#timer-initialisation-steps>
324    pub(crate) fn fire_timer(&self, id: TimerEventId, cx: &mut JSContext) {
325        // Step 9.2. If id does not exist in global's map of setTimeout and setInterval IDs, then abort these steps.
326        let expected_id = self.expected_event_id.get();
327        if expected_id != id {
328            debug!(
329                "ignoring timer fire event {:?} (expected {:?})",
330                id, expected_id
331            );
332            return;
333        }
334
335        assert!(self.suspended_since.get().is_none());
336
337        let base_time = self.base_time();
338
339        // Since the event id was the expected one, at least one timer should be due.
340        if base_time < self.timers.borrow().back().unwrap().scheduled_for {
341            warn!("Unexpected timing!");
342            return;
343        }
344
345        // select timers to run to prevent firing timers
346        // that were installed during fire of another timer
347        let mut timers_to_run = Vec::new();
348
349        loop {
350            let mut timers = self.timers.borrow_mut();
351
352            if timers.is_empty() || timers.back().unwrap().scheduled_for > base_time {
353                break;
354            }
355
356            timers_to_run.push(timers.pop_back().unwrap());
357        }
358
359        for timer in timers_to_run {
360            // Since timers can be coalesced together inside a task,
361            // this loop can keep running, including after an interrupt of the JS,
362            // and prevent a clean-shutdown of a JS-running thread.
363            // This check prevents such a situation.
364            if !self.global_scope.can_continue_running() {
365                return;
366            }
367            match &timer.callback {
368                // TODO: https://github.com/servo/servo/issues/40060
369                OneshotTimerCallback::RunStepsAfterTimeout { ordering_id, .. } => {
370                    // Step 4.2 Wait until any invocations of this algorithm that had the same global and orderingIdentifier,
371                    // that started before this one, and whose milliseconds is less than or equal to this one's, have completed.
372                    let head_handle_opt = {
373                        let queues_ref = self.runsteps_queues.borrow();
374                        queues_ref
375                            .get(ordering_id)
376                            .and_then(|v| v.first().map(|t| t.handle))
377                    };
378                    let is_head = head_handle_opt.is_none_or(|head| head == timer.handle);
379
380                    if !is_head {
381                        // TODO: this re queuing would go away when we revisit timers implementation.
382                        let rein = OneshotTimer {
383                            handle: timer.handle,
384                            source: timer.source,
385                            callback: timer.callback,
386                            scheduled_for: self.base_time(),
387                        };
388                        let mut timers = self.timers.borrow_mut();
389                        let idx = timers.binary_search(&rein).err().unwrap();
390                        timers.insert(idx, rein);
391                        continue;
392                    }
393
394                    let (timer_key, ordering_id_owned, completion) = match timer.callback {
395                        OneshotTimerCallback::RunStepsAfterTimeout {
396                            timer_key,
397                            ordering_id,
398                            milliseconds: _,
399                            completion,
400                        } => (timer_key, ordering_id, completion),
401                        _ => unreachable!(),
402                    };
403
404                    // Step 4.3 Optionally, wait a further implementation-defined length of time.
405                    // (No additional delay applied.)
406
407                    // Step 4.4 Perform completionSteps.
408                    (completion)(cx, &self.global_scope);
409
410                    // Step 4.5 Remove global's map of active timers[timerKey].
411                    self.map_of_active_timers.borrow_mut().remove(&timer_key);
412
413                    {
414                        let mut queues_mut = self.runsteps_queues.borrow_mut();
415                        if let Some(q) = queues_mut.get_mut(&ordering_id_owned) {
416                            if !q.is_empty() {
417                                q.remove(0);
418                            }
419                            if q.is_empty() {
420                                queues_mut.remove(&ordering_id_owned);
421                            }
422                        }
423                    }
424                },
425                _ => {
426                    let cb = timer.callback;
427                    cb.invoke(cx, &self.global_scope, &self.js_timers);
428                },
429            }
430        }
431
432        self.schedule_timer_call();
433    }
434
435    fn base_time(&self) -> Instant {
436        let offset = self.suspension_offset.get();
437        match self.suspended_since.get() {
438            Some(suspend_time) => suspend_time - offset,
439            None => Instant::now() - offset,
440        }
441    }
442
443    pub(crate) fn slow_down(&self) {
444        let min_duration_ms = pref!(js_timers_minimum_duration) as u64;
445        self.js_timers
446            .set_min_duration(Duration::from_millis(min_duration_ms));
447    }
448
449    pub(crate) fn speed_up(&self) {
450        self.js_timers.remove_min_duration();
451    }
452
453    pub(crate) fn suspend(&self) {
454        // Suspend is idempotent: do nothing if the timers are already suspended.
455        if self.suspended_since.get().is_some() {
456            return warn!("Suspending an already suspended timer.");
457        }
458
459        debug!("Suspending timers.");
460        self.suspended_since.set(Some(Instant::now()));
461        self.invalidate_expected_event_id();
462    }
463
464    pub(crate) fn resume(&self) {
465        // Resume is idempotent: do nothing if the timers are already resumed.
466        let additional_offset = match self.suspended_since.get() {
467            Some(suspended_since) => Instant::now() - suspended_since,
468            None => return warn!("Resuming an already resumed timer."),
469        };
470
471        debug!("Resuming timers.");
472        self.suspension_offset
473            .set(self.suspension_offset.get() + additional_offset);
474        self.suspended_since.set(None);
475
476        self.schedule_timer_call();
477    }
478
479    /// <https://html.spec.whatwg.org/multipage/#timer-initialisation-steps>
480    fn schedule_timer_call(&self) {
481        if self.suspended_since.get().is_some() {
482            // The timer will be scheduled when the pipeline is fully activated.
483            return;
484        }
485
486        let timers = self.timers.borrow();
487        let Some(timer) = timers.back() else {
488            return;
489        };
490
491        let expected_event_id = self.invalidate_expected_event_id();
492        // Step 12. Let completionStep be an algorithm step which queues a global
493        // task on the timer task source given global to run task.
494        let callback = TimerListener {
495            context: Trusted::new(&*self.global_scope),
496            task_source: self
497                .global_scope
498                .task_manager()
499                .timer_task_source()
500                .to_sendable(),
501            source: timer.source,
502            id: expected_event_id,
503        }
504        .into_callback();
505
506        let event_request = TimerEventRequest {
507            callback,
508            duration: timer.scheduled_for - self.base_time(),
509        };
510
511        self.global_scope.schedule_timer(event_request);
512    }
513
514    fn invalidate_expected_event_id(&self) -> TimerEventId {
515        let TimerEventId(currently_expected) = self.expected_event_id.get();
516        let next_id = TimerEventId(currently_expected + 1);
517        debug!(
518            "invalidating expected timer (was {:?}, now {:?}",
519            currently_expected, next_id
520        );
521        self.expected_event_id.set(next_id);
522        next_id
523    }
524
525    #[allow(clippy::too_many_arguments)]
526    pub(crate) fn set_timeout_or_interval(
527        &self,
528        cx: &mut JSContext,
529        global: &GlobalScope,
530        callback: TimerCallback,
531        arguments: Vec<HandleValue>,
532        timeout: Duration,
533        is_interval: IsInterval,
534        source: TimerSource,
535    ) -> Fallible<i32> {
536        self.js_timers.set_timeout_or_interval(
537            cx,
538            global,
539            callback,
540            arguments,
541            timeout,
542            is_interval,
543            source,
544        )
545    }
546
547    pub(crate) fn clear_timeout_or_interval(&self, global: &GlobalScope, handle: i32) {
548        self.js_timers.clear_timeout_or_interval(global, handle)
549    }
550}
551
552#[derive(Clone, Copy, Eq, Hash, JSTraceable, MallocSizeOf, Ord, PartialEq, PartialOrd)]
553pub(crate) struct JsTimerHandle(i32);
554
555#[derive(DenyPublicFields, JSTraceable, MallocSizeOf)]
556pub(crate) struct JsTimers {
557    next_timer_handle: Cell<JsTimerHandle>,
558    /// <https://html.spec.whatwg.org/multipage/#list-of-active-timers>
559    active_timers: DomRefCell<FxHashMap<JsTimerHandle, JsTimerEntry>>,
560    /// The nesting level of the currently executing timer task or 0.
561    nesting_level: Cell<u32>,
562    /// Used to introduce a minimum delay in event intervals
563    min_duration: Cell<Option<Duration>>,
564}
565
566#[derive(JSTraceable, MallocSizeOf)]
567struct JsTimerEntry {
568    oneshot_handle: OneshotTimerHandle,
569}
570
571// Holder for the various JS values associated with setTimeout
572// (ie. function value to invoke and all arguments to pass
573//      to the function when calling it)
574// TODO: Handle rooting during invocation when movable GC is turned on
575#[derive(JSTraceable, MallocSizeOf)]
576pub(crate) struct JsTimerTask {
577    handle: JsTimerHandle,
578    #[no_trace]
579    source: TimerSource,
580    callback: InternalTimerCallback,
581    is_interval: IsInterval,
582    nesting_level: u32,
583    duration: Duration,
584    is_user_interacting: bool,
585}
586
587// Enum allowing more descriptive values for the is_interval field
588#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
589pub(crate) enum IsInterval {
590    Interval,
591    NonInterval,
592}
593
594pub(crate) enum TimerCallback {
595    StringTimerCallback(TrustedScriptOrString),
596    FunctionTimerCallback(Rc<Function>),
597}
598
599#[derive(Clone, JSTraceable, MallocSizeOf)]
600#[cfg_attr(crown, expect(crown::unrooted_must_root))]
601enum InternalTimerCallback {
602    StringTimerCallback(DOMString, InitiatingScriptFetchInfo),
603    FunctionTimerCallback(
604        #[conditional_malloc_size_of] Rc<Function>,
605        #[ignore_malloc_size_of = "mozjs"] Rc<Box<[Heap<JSVal>]>>,
606    ),
607}
608
609impl Default for JsTimers {
610    fn default() -> Self {
611        JsTimers {
612            next_timer_handle: Cell::new(JsTimerHandle(1)),
613            active_timers: DomRefCell::new(FxHashMap::default()),
614            nesting_level: Cell::new(0),
615            min_duration: Cell::new(None),
616        }
617    }
618}
619
620impl JsTimers {
621    /// <https://html.spec.whatwg.org/multipage/#timer-initialisation-steps>
622    #[allow(clippy::too_many_arguments)]
623    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
624    pub(crate) fn set_timeout_or_interval(
625        &self,
626        cx: &mut JSContext,
627        global: &GlobalScope,
628        callback: TimerCallback,
629        arguments: Vec<HandleValue>,
630        timeout: Duration,
631        is_interval: IsInterval,
632        source: TimerSource,
633    ) -> Fallible<i32> {
634        let callback = match callback {
635            TimerCallback::StringTimerCallback(trusted_script_or_string) => {
636                // Step 9.6.1.1. Let globalName be "Window" if global is a Window object; "WorkerGlobalScope" otherwise.
637                let global_name = if global.is::<Window>() {
638                    "Window"
639                } else {
640                    "WorkerGlobalScope"
641                };
642                // Step 9.6.1.2. Let methodName be "setInterval" if repeat is true; "setTimeout" otherwise.
643                let method_name = if is_interval == IsInterval::Interval {
644                    "setInterval"
645                } else {
646                    "setTimeout"
647                };
648                // Step 9.6.1.3. Let sink be a concatenation of globalName, U+0020 SPACE, and methodName.
649                let sink = format!("{} {}", global_name, method_name);
650                // Step 9.6.1.4. Set handler to the result of invoking the
651                // Get Trusted Type compliant string algorithm with TrustedScript, global, handler, sink, and "script".
652                let code_str = TrustedScript::get_trusted_type_compliant_string(
653                    cx,
654                    global,
655                    trusted_script_or_string,
656                    &sink,
657                )?;
658
659                let initiating_script_fetch_info = active_script_fetch_info(cx, global);
660
661                // Step 9.6.3. Perform EnsureCSPDoesNotBlockStringCompilation(realm, « », handler, handler, timer, « », handler).
662                // If this throws an exception, catch it, report it for global, and abort these steps.
663                if global
664                    .get_csp_list()
665                    .is_js_evaluation_allowed(cx, global, &code_str.str())
666                {
667                    // Step 9.6.2. Assert: handler is a string.
668                    InternalTimerCallback::StringTimerCallback(
669                        code_str,
670                        initiating_script_fetch_info,
671                    )
672                } else {
673                    return Ok(0);
674                }
675            },
676            TimerCallback::FunctionTimerCallback(function) => {
677                // This is a bit complicated, but this ensures that the vector's
678                // buffer isn't reallocated (and moved) after setting the Heap values
679                let mut args = Vec::with_capacity(arguments.len());
680                for _ in 0..arguments.len() {
681                    args.push(Heap::default());
682                }
683                for (i, item) in arguments.iter().enumerate() {
684                    args.get_mut(i).unwrap().set(item.get());
685                }
686                // Step 9.5. If handler is a Function, then invoke handler given arguments and "report",
687                // and with callback this value set to thisArg.
688                InternalTimerCallback::FunctionTimerCallback(
689                    function,
690                    Rc::new(args.into_boxed_slice()),
691                )
692            },
693        };
694
695        // Step 2. If previousId was given, let id be previousId; otherwise,
696        // let id be an implementation-defined integer that is greater than zero
697        // and does not already exist in global's map of setTimeout and setInterval IDs.
698        let JsTimerHandle(new_handle) = self.next_timer_handle.get();
699        self.next_timer_handle.set(JsTimerHandle(new_handle + 1));
700
701        // Step 3. If the surrounding agent's event loop's currently running task
702        // is a task that was created by this algorithm, then let nesting level
703        // be the task's timer nesting level. Otherwise, let nesting level be 0.
704        let mut task = JsTimerTask {
705            handle: JsTimerHandle(new_handle),
706            source,
707            callback,
708            is_interval,
709            is_user_interacting: ScriptThread::is_user_interacting(),
710            nesting_level: 0,
711            duration: Duration::ZERO,
712        };
713
714        // Step 4. If timeout is less than 0, then set timeout to 0.
715        task.duration = timeout.max(Duration::ZERO);
716
717        self.initialize_and_schedule(global, task);
718
719        // Step 15. Return id.
720        Ok(new_handle)
721    }
722
723    pub(crate) fn clear_timeout_or_interval(&self, global: &GlobalScope, handle: i32) {
724        let mut active_timers = self.active_timers.borrow_mut();
725
726        if let Some(entry) = active_timers.remove(&JsTimerHandle(handle)) {
727            global.unschedule_callback(entry.oneshot_handle);
728        }
729    }
730
731    pub(crate) fn set_min_duration(&self, duration: Duration) {
732        self.min_duration.set(Some(duration));
733    }
734
735    pub(crate) fn remove_min_duration(&self) {
736        self.min_duration.set(None);
737    }
738
739    // see step 13 of https://html.spec.whatwg.org/multipage/#timer-initialisation-steps
740    fn user_agent_pad(&self, current_duration: Duration) -> Duration {
741        match self.min_duration.get() {
742            Some(min_duration) => min_duration.max(current_duration),
743            None => current_duration,
744        }
745    }
746
747    /// <https://html.spec.whatwg.org/multipage/#timer-initialisation-steps>
748    fn initialize_and_schedule(&self, global: &GlobalScope, mut task: JsTimerTask) {
749        let handle = task.handle;
750        let mut active_timers = self.active_timers.borrow_mut();
751
752        // Step 3. If the surrounding agent's event loop's currently running task
753        // is a task that was created by this algorithm, then let nesting level be
754        // the task's timer nesting level. Otherwise, let nesting level be 0.
755        let nesting_level = self.nesting_level.get();
756
757        let duration = self.user_agent_pad(clamp_duration(nesting_level, task.duration));
758        // Step 10. Increment nesting level by one.
759        // Step 11. Set task's timer nesting level to nesting level.
760        task.nesting_level = nesting_level + 1;
761
762        // Step 13. Set uniqueHandle to the result of running steps after a timeout given global,
763        // "setTimeout/setInterval", timeout, and completionStep.
764        let callback = OneshotTimerCallback::JsTimer(task);
765        let oneshot_handle = global.schedule_callback(callback, duration);
766
767        // Step 14. Set global's map of setTimeout and setInterval IDs[id] to uniqueHandle.
768        let entry = active_timers
769            .entry(handle)
770            .or_insert(JsTimerEntry { oneshot_handle });
771        entry.oneshot_handle = oneshot_handle;
772    }
773}
774
775/// Step 5 of <https://html.spec.whatwg.org/multipage/#timer-initialisation-steps>
776fn clamp_duration(nesting_level: u32, unclamped: Duration) -> Duration {
777    // Step 5. If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.
778    let lower_bound_ms = if nesting_level > 5 { 4 } else { 0 };
779    let lower_bound = Duration::from_millis(lower_bound_ms);
780    lower_bound.max(unclamped)
781}
782
783impl JsTimerTask {
784    // see https://html.spec.whatwg.org/multipage/#timer-initialisation-steps
785    fn invoke(self, cx: &mut JSContext, global: &GlobalScope, timers: &JsTimers) {
786        // step 9.2 can be ignored, because we proactively prevent execution
787        // of this task when its scheduled execution is canceled.
788
789        // prep for step ? in nested set_timeout_or_interval calls
790        timers.nesting_level.set(self.nesting_level);
791
792        let _guard = ScriptThread::user_interacting_guard();
793        match self.callback {
794            InternalTimerCallback::StringTimerCallback(ref code_str, ref fetch_info) => {
795                // Step 6.4. Let settings object be global's relevant settings object.
796                // Step 6. Let realm be global's relevant realm.
797
798                // Note: the steps to retrieve *fetch options* and *base URL* are performed in
799                // `active_script_fetch_info`.
800                let InitiatingScriptFetchInfo {
801                    fetch_options,
802                    base_url,
803                } = fetch_info.clone();
804
805                // Step 9.6.8. Let script be the result of creating a classic script given handler,
806                // settings object, base URL, and fetch options.
807                let script = global.create_a_classic_script(
808                    cx,
809                    (*code_str.str()).into(),
810                    base_url,
811                    fetch_options,
812                    ErrorReporting::Unmuted,
813                    Some(IntroductionType::DOM_TIMER),
814                    1,
815                    false,
816                );
817
818                // Step 9.6.9. Run the classic script script.
819                _ = global.run_a_classic_script(cx, script, RethrowErrors::No);
820            },
821            // Step 9.5. If handler is a Function, then invoke handler given arguments and
822            // "report", and with callback this value set to thisArg.
823            InternalTimerCallback::FunctionTimerCallback(ref function, ref arguments) => {
824                let arguments = self.collect_heap_args(arguments);
825                rooted!(&in(cx) let mut value: JSVal);
826                let _ = function.Call_(cx, global, arguments, value.handle_mut(), Report);
827            },
828        };
829
830        // reset nesting level (see above)
831        timers.nesting_level.set(0);
832
833        // Step 9.9. If repeat is true, then perform the timer initialization steps again,
834        // given global, handler, timeout, arguments, true, and id.
835        //
836        // Since we choose proactively prevent execution (see 4.1 above), we must only
837        // reschedule repeating timers when they were not canceled as part of step 4.2.
838        if self.is_interval == IsInterval::Interval &&
839            timers.active_timers.borrow().contains_key(&self.handle)
840        {
841            timers.initialize_and_schedule(global, self);
842        }
843    }
844
845    fn collect_heap_args<'b>(&self, args: &'b [Heap<JSVal>]) -> Vec<HandleValue<'b>> {
846        args.iter().map(|arg| arg.as_handle_value()).collect()
847    }
848}
849
850/// Describes the source that requested the [`TimerEvent`].
851#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, Serialize)]
852pub enum TimerSource {
853    /// The event was requested from a window (`ScriptThread`).
854    FromWindow(PipelineId),
855    /// The event was requested from a worker (`DedicatedGlobalWorkerScope`).
856    FromWorker,
857}
858
859/// The id to be used for a [`TimerEvent`] is defined by the corresponding [`TimerEventRequest`].
860#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
861pub struct TimerEventId(pub u32);
862
863/// A notification that a timer has fired. [`TimerSource`] must be `FromWindow` when
864/// dispatched to `ScriptThread` and must be `FromWorker` when dispatched to a
865/// `DedicatedGlobalWorkerScope`
866#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
867pub struct TimerEvent(pub TimerSource, pub TimerEventId);
868
869/// A wrapper between timer events coming in over IPC, and the event-loop.
870#[derive(Clone)]
871struct TimerListener {
872    task_source: SendableTaskSource,
873    context: Trusted<GlobalScope>,
874    source: TimerSource,
875    id: TimerEventId,
876}
877
878impl TimerListener {
879    /// Handle a timer-event coming from the [`timers::TimerScheduler`]
880    /// by queuing the appropriate task on the relevant event-loop.
881    /// <https://html.spec.whatwg.org/multipage/#timer-initialisation-steps>
882    fn handle(&self, event: TimerEvent) {
883        let context = self.context.clone();
884        // Step 9. Let task be a task that runs the following substeps:
885        self.task_source.queue(task!(timer_event: move |cx| {
886                let global = context.root();
887                let TimerEvent(source, id) = event;
888                match source {
889                    TimerSource::FromWorker => {
890                        global.downcast::<WorkerGlobalScope>().expect("Window timer delivered to worker");
891                    },
892                    TimerSource::FromWindow(pipeline) => {
893                        assert_eq!(pipeline, global.pipeline_id());
894                        global.downcast::<Window>().expect("Worker timer delivered to window");
895                    },
896                };
897                global.fire_timer(id, cx);
898            })
899        );
900    }
901
902    fn into_callback(self) -> BoxedTimerCallback {
903        let timer_event = TimerEvent(self.source, self.id);
904        Box::new(move || self.handle(timer_event))
905    }
906}
907
908#[derive(Clone, JSTraceable, MallocSizeOf)]
909struct InitiatingScriptFetchInfo {
910    fetch_options: ScriptFetchOptions,
911    #[no_trace]
912    base_url: ServoUrl,
913}
914
915#[expect(unsafe_code)]
916/// <https://html.spec.whatwg.org/multipage/#timer-initialisation-steps>
917fn active_script_fetch_info(cx: &mut JSContext, global: &GlobalScope) -> InitiatingScriptFetchInfo {
918    rooted!(&in(cx) let mut value = UndefinedValue());
919    unsafe { JS_GetScriptedCallerPrivate(cx, value.handle_mut()) };
920
921    let reference_private = value.handle().into_handle();
922
923    // Step 7. Let initiating script be the active script.
924    let initiating_script = unsafe { module_script_from_reference_private(&reference_private) };
925
926    let (fetch_options, base_url) = match initiating_script {
927        // Step 9.6.7. If initiating script is not null, then:
928        Some(script) => (
929            // Step 9.6.7.1. Set fetch options to a script fetch options whose
930            ScriptFetchOptions {
931                // cryptographic nonce is initiating script's fetch options's cryptographic nonce,
932                cryptographic_nonce: script.options.cryptographic_nonce.clone(),
933                // integrity metadata is the empty string,
934                integrity_metadata: String::new(),
935                // parser metadata is "not-parser-inserted",
936                parser_metadata: ParserMetadata::NotParserInserted,
937                // credentials mode is initiating script's fetch options's credentials mode,
938                credentials_mode: script.options.credentials_mode,
939                // referrer policy is initiating script's fetch options's referrer policy,
940                referrer_policy: script.options.referrer_policy,
941                // TODO and fetch priority is "auto".
942                render_blocking: false,
943            },
944            // Step 9.6.7.2. Set base URL to initiating script's base URL.
945            script.base_url.clone(),
946        ),
947        None => (
948            // Step 9.6.5. Let fetch options be the default script fetch options.
949            ScriptFetchOptions::default_classic_script(),
950            // Step 9.6.6. Let base URL be settings object's API base URL.
951            global.api_base_url(),
952        ),
953    };
954
955    InitiatingScriptFetchInfo {
956        fetch_options,
957        base_url,
958    }
959}