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::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
55type OrderingIdentifier = DOMString;
58
59#[derive(JSTraceable, MallocSizeOf)]
60struct OrderingEntry {
61 milliseconds: u64,
62 start_seq: u64,
63 handle: OneshotTimerHandle,
64}
65
66type OrderingQueues = FxHashMap<OrderingIdentifier, Vec<OrderingEntry>>;
68
69type 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 suspension_offset: Cell<Duration>,
88 #[no_trace]
95 expected_event_id: Cell<TimerEventId>,
96 map_of_active_timers: DomRefCell<RunStepsActiveMap>,
100
101 runsteps_queues: DomRefCell<OrderingQueues>,
105
106 next_runsteps_key: Cell<TimerKey>,
108
109 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#[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 RunStepsAfterTimeout {
136 timer_key: i32,
138 ordering_id: DOMString,
140 milliseconds: u64,
142 #[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 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 #[inline]
208 pub(crate) fn now_for_runsteps(&self) -> Instant {
209 self.base_time()
211 }
212
213 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 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 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 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 pub(crate) fn fire_timer(&self, id: TimerEventId, cx: &mut JSContext) {
326 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 if base_time < self.timers.borrow().back().unwrap().scheduled_for {
342 warn!("Unexpected timing!");
343 return;
344 }
345
346 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 if !self.global_scope.can_continue_running() {
366 return;
367 }
368 match &timer.callback {
369 OneshotTimerCallback::RunStepsAfterTimeout { ordering_id, .. } => {
371 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 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 (completion)(cx, &self.global_scope);
410
411 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 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 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 fn schedule_timer_call(&self) {
482 if self.suspended_since.get().is_some() {
483 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 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 active_timers: DomRefCell<FxHashMap<JsTimerHandle, JsTimerEntry>>,
561 nesting_level: Cell<u32>,
563 min_duration: Cell<Option<Duration>>,
565}
566
567#[derive(JSTraceable, MallocSizeOf)]
568struct JsTimerEntry {
569 oneshot_handle: OneshotTimerHandle,
570}
571
572#[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#[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 #[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 let global_name = if global.is::<Window>() {
639 "Window"
640 } else {
641 "WorkerGlobalScope"
642 };
643 let method_name = if is_interval == IsInterval::Interval {
645 "setInterval"
646 } else {
647 "setTimeout"
648 };
649 let sink = format!("{} {}", global_name, method_name);
651 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 if global
665 .get_csp_list()
666 .is_js_evaluation_allowed(cx, global, &code_str.str())
667 {
668 InternalTimerCallback::StringTimerCallback(
670 code_str,
671 initiating_script_fetch_info,
672 )
673 } else {
674 return Ok(0);
675 }
676 },
677 TimerCallback::FunctionTimerCallback(function) => {
678 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 InternalTimerCallback::FunctionTimerCallback(
690 function,
691 Rc::new(args.into_boxed_slice()),
692 )
693 },
694 };
695
696 let JsTimerHandle(new_handle) = self.next_timer_handle.get();
700 self.next_timer_handle.set(JsTimerHandle(new_handle + 1));
701
702 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 task.duration = timeout.max(Duration::ZERO);
717
718 self.initialize_and_schedule(global, task);
719
720 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 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 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 let nesting_level = self.nesting_level.get();
757
758 let duration = self.user_agent_pad(clamp_duration(nesting_level, task.duration));
759 task.nesting_level = nesting_level + 1;
762
763 let callback = OneshotTimerCallback::JsTimer(task);
766 let oneshot_handle = global.schedule_callback(callback, duration);
767
768 let entry = active_timers
770 .entry(handle)
771 .or_insert(JsTimerEntry { oneshot_handle });
772 entry.oneshot_handle = oneshot_handle;
773 }
774}
775
776fn clamp_duration(nesting_level: u32, unclamped: Duration) -> Duration {
778 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 fn invoke(self, cx: &mut JSContext, global: &GlobalScope, timers: &JsTimers) {
787 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 let InitiatingScriptFetchInfo {
802 fetch_options,
803 base_url,
804 } = fetch_info.clone();
805
806 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 _ = global.run_a_classic_script(
820 cx,
821 script,
822 RethrowErrors::No,
823 None, );
825 },
826 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 timers.nesting_level.set(0);
837
838 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#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, Serialize)]
857pub enum TimerSource {
858 FromWindow(PipelineId),
860 FromWorker,
862}
863
864#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
866pub struct TimerEventId(pub u32);
867
868#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
872pub struct TimerEvent(pub TimerSource, pub TimerEventId);
873
874#[derive(Clone)]
876struct TimerListener {
877 task_source: SendableTaskSource,
878 context: Trusted<GlobalScope>,
879 source: TimerSource,
880 id: TimerEventId,
881}
882
883impl TimerListener {
884 fn handle(&self, event: TimerEvent) {
888 let context = self.context.clone();
889 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)]
921fn 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 let initiating_script = unsafe { module_script_from_reference_private(&reference_private) };
930
931 let (fetch_options, base_url) = match initiating_script {
932 Some(script) => (
934 ScriptFetchOptions {
936 cryptographic_nonce: script.options.cryptographic_nonce.clone(),
938 integrity_metadata: String::new(),
940 parser_metadata: ParserMetadata::NotParserInserted,
942 credentials_mode: script.options.credentials_mode,
944 referrer_policy: script.options.referrer_policy,
946 render_blocking: false,
948 },
949 script.base_url.clone(),
951 ),
952 None => (
953 ScriptFetchOptions::default_classic_script(),
955 global.api_base_url(),
957 ),
958 };
959
960 InitiatingScriptFetchInfo {
961 fetch_options,
962 base_url,
963 }
964}