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