Skip to main content

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