1use 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
54type OrderingIdentifier = DOMString;
57
58#[derive(JSTraceable, MallocSizeOf)]
59struct OrderingEntry {
60 milliseconds: u64,
61 start_seq: u64,
62 handle: OneshotTimerHandle,
63}
64
65type OrderingQueues = FxHashMap<OrderingIdentifier, Vec<OrderingEntry>>;
67
68type 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 suspension_offset: Cell<Duration>,
87 #[no_trace]
94 expected_event_id: Cell<TimerEventId>,
95 map_of_active_timers: DomRefCell<RunStepsActiveMap>,
99
100 runsteps_queues: DomRefCell<OrderingQueues>,
104
105 next_runsteps_key: Cell<TimerKey>,
107
108 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#[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 RunStepsAfterTimeout {
135 timer_key: i32,
137 ordering_id: DOMString,
139 milliseconds: u64,
141 #[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 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 #[inline]
207 pub(crate) fn now_for_runsteps(&self) -> Instant {
208 self.base_time()
210 }
211
212 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 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 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 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 pub(crate) fn fire_timer(&self, id: TimerEventId, cx: &mut JSContext) {
325 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 if base_time < self.timers.borrow().back().unwrap().scheduled_for {
341 warn!("Unexpected timing!");
342 return;
343 }
344
345 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 if !self.global_scope.can_continue_running() {
365 return;
366 }
367 match &timer.callback {
368 OneshotTimerCallback::RunStepsAfterTimeout { ordering_id, .. } => {
370 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 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 (completion)(cx, &self.global_scope);
409
410 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 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 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 fn schedule_timer_call(&self) {
481 if self.suspended_since.get().is_some() {
482 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 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 active_timers: DomRefCell<FxHashMap<JsTimerHandle, JsTimerEntry>>,
560 nesting_level: Cell<u32>,
562 min_duration: Cell<Option<Duration>>,
564}
565
566#[derive(JSTraceable, MallocSizeOf)]
567struct JsTimerEntry {
568 oneshot_handle: OneshotTimerHandle,
569}
570
571#[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#[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 #[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 let global_name = if global.is::<Window>() {
638 "Window"
639 } else {
640 "WorkerGlobalScope"
641 };
642 let method_name = if is_interval == IsInterval::Interval {
644 "setInterval"
645 } else {
646 "setTimeout"
647 };
648 let sink = format!("{} {}", global_name, method_name);
650 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 if global
664 .get_csp_list()
665 .is_js_evaluation_allowed(cx, global, &code_str.str())
666 {
667 InternalTimerCallback::StringTimerCallback(
669 code_str,
670 initiating_script_fetch_info,
671 )
672 } else {
673 return Ok(0);
674 }
675 },
676 TimerCallback::FunctionTimerCallback(function) => {
677 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 InternalTimerCallback::FunctionTimerCallback(
689 function,
690 Rc::new(args.into_boxed_slice()),
691 )
692 },
693 };
694
695 let JsTimerHandle(new_handle) = self.next_timer_handle.get();
699 self.next_timer_handle.set(JsTimerHandle(new_handle + 1));
700
701 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 task.duration = timeout.max(Duration::ZERO);
716
717 self.initialize_and_schedule(global, task);
718
719 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 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 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 let nesting_level = self.nesting_level.get();
756
757 let duration = self.user_agent_pad(clamp_duration(nesting_level, task.duration));
758 task.nesting_level = nesting_level + 1;
761
762 let callback = OneshotTimerCallback::JsTimer(task);
765 let oneshot_handle = global.schedule_callback(callback, duration);
766
767 let entry = active_timers
769 .entry(handle)
770 .or_insert(JsTimerEntry { oneshot_handle });
771 entry.oneshot_handle = oneshot_handle;
772 }
773}
774
775fn clamp_duration(nesting_level: u32, unclamped: Duration) -> Duration {
777 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 fn invoke(self, cx: &mut JSContext, global: &GlobalScope, timers: &JsTimers) {
786 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 let InitiatingScriptFetchInfo {
801 fetch_options,
802 base_url,
803 } = fetch_info.clone();
804
805 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 _ = global.run_a_classic_script(cx, script, RethrowErrors::No);
820 },
821 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 timers.nesting_level.set(0);
832
833 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#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, Serialize)]
852pub enum TimerSource {
853 FromWindow(PipelineId),
855 FromWorker,
857}
858
859#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
861pub struct TimerEventId(pub u32);
862
863#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
867pub struct TimerEvent(pub TimerSource, pub TimerEventId);
868
869#[derive(Clone)]
871struct TimerListener {
872 task_source: SendableTaskSource,
873 context: Trusted<GlobalScope>,
874 source: TimerSource,
875 id: TimerEventId,
876}
877
878impl TimerListener {
879 fn handle(&self, event: TimerEvent) {
883 let context = self.context.clone();
884 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)]
916fn 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 let initiating_script = unsafe { module_script_from_reference_private(&reference_private) };
925
926 let (fetch_options, base_url) = match initiating_script {
927 Some(script) => (
929 ScriptFetchOptions {
931 cryptographic_nonce: script.options.cryptographic_nonce.clone(),
933 integrity_metadata: String::new(),
935 parser_metadata: ParserMetadata::NotParserInserted,
937 credentials_mode: script.options.credentials_mode,
939 referrer_policy: script.options.referrer_policy,
941 render_blocking: false,
943 },
944 script.base_url.clone(),
946 ),
947 None => (
948 ScriptFetchOptions::default_classic_script(),
950 global.api_base_url(),
952 ),
953 };
954
955 InitiatingScriptFetchInfo {
956 fetch_options,
957 base_url,
958 }
959}