use std::cell::Cell;
use std::cmp::{Ord, Ordering};
use std::collections::VecDeque;
use std::default::Default;
use std::rc::Rc;
use std::time::{Duration, Instant};
use deny_public_fields::DenyPublicFields;
use js::context::JSContext;
use js::jsapi::Heap;
use js::jsval::{JSVal, UndefinedValue};
use js::rust::wrappers2::JS_GetScriptedCallerPrivate;
use js::rust::{HandleValue, IntoHandle};
use net_traits::request::ParserMetadata;
use rustc_hash::FxHashMap;
use script_bindings::cell::DomRefCell;
use serde::{Deserialize, Serialize};
use servo_base::id::PipelineId;
use servo_config::pref;
use servo_url::ServoUrl;
use timers::{BoxedTimerCallback, TimerEventRequest};
use crate::dom::bindings::callback::ExceptionHandling::Report;
use crate::dom::bindings::codegen::Bindings::FunctionBinding::Function;
use crate::dom::bindings::codegen::UnionTypes::TrustedScriptOrString;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::root::{AsHandleValue, Dom};
use crate::dom::bindings::str::DOMString;
use crate::dom::csp::CspReporting;
use crate::dom::document::RefreshRedirectDue;
use crate::dom::eventsource::EventSourceTimeoutCallback;
use crate::dom::globalscope::GlobalScope;
use crate::dom::globalscope::script_execution::RethrowErrors;
use crate::dom::script_execution::ScriptOptions;
#[cfg(feature = "testbinding")]
use crate::dom::testbinding::TestBindingCallback;
use crate::dom::trustedtypes::trustedscript::TrustedScript;
use crate::dom::types::{Window, WorkerGlobalScope};
use crate::dom::xmlhttprequest::XHRTimeoutCallback;
use crate::event_loop::script_thread::ScriptThread;
use crate::modules::script_module::{ScriptFetchOptions, module_script_from_reference_private};
use crate::runtime::script_runtime::IntroductionType;
use crate::tasks::task_source::SendableTaskSource;
type TimerKey = i32;
type RunStepsDeadline = Instant;
type CompletionStep = Box<dyn FnOnce(&mut JSContext, &GlobalScope) + 'static>;
type OrderingIdentifier = DOMString;
#[derive(JSTraceable, MallocSizeOf)]
struct OrderingEntry {
milliseconds: u64,
start_seq: u64,
handle: OneshotTimerHandle,
}
type OrderingQueues = FxHashMap<OrderingIdentifier, Vec<OrderingEntry>>;
type RunStepsActiveMap = FxHashMap<TimerKey, RunStepsDeadline>;
#[derive(Clone, Copy, Debug, Eq, Hash, JSTraceable, MallocSizeOf, Ord, PartialEq, PartialOrd)]
pub(crate) struct OneshotTimerHandle(i32);
#[derive(DenyPublicFields, JSTraceable, MallocSizeOf)]
#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
pub(crate) struct OneshotTimers {
global_scope: Dom<GlobalScope>,
js_timers: JsTimers,
next_timer_handle: Cell<OneshotTimerHandle>,
timers: DomRefCell<VecDeque<OneshotTimer>>,
suspended_since: Cell<Option<Instant>>,
suspension_offset: Cell<Duration>,
#[no_trace]
expected_event_id: Cell<TimerEventId>,
map_of_active_timers: DomRefCell<RunStepsActiveMap>,
runsteps_queues: DomRefCell<OrderingQueues>,
next_runsteps_key: Cell<TimerKey>,
runsteps_start_seq: Cell<u64>,
}
#[derive(DenyPublicFields, JSTraceable, MallocSizeOf)]
struct OneshotTimer {
handle: OneshotTimerHandle,
#[no_trace]
source: TimerSource,
callback: OneshotTimerCallback,
scheduled_for: Instant,
}
#[derive(JSTraceable, MallocSizeOf)]
pub(crate) enum OneshotTimerCallback {
XhrTimeout(XHRTimeoutCallback),
EventSourceTimeout(EventSourceTimeoutCallback),
JsTimer(JsTimerTask),
#[cfg(feature = "testbinding")]
TestBindingCallback(TestBindingCallback),
RefreshRedirectDue(RefreshRedirectDue),
RunStepsAfterTimeout {
timer_key: i32,
ordering_id: DOMString,
milliseconds: u64,
#[no_trace]
#[ignore_malloc_size_of = "Closure"]
completion: CompletionStep,
},
}
impl OneshotTimerCallback {
fn invoke(self, cx: &mut JSContext, global: &GlobalScope, js_timers: &JsTimers) {
match self {
OneshotTimerCallback::XhrTimeout(callback) => callback.invoke(cx),
OneshotTimerCallback::EventSourceTimeout(callback) => callback.invoke(),
OneshotTimerCallback::JsTimer(task) => task.invoke(cx, global, js_timers),
#[cfg(feature = "testbinding")]
OneshotTimerCallback::TestBindingCallback(callback) => callback.invoke(cx),
OneshotTimerCallback::RefreshRedirectDue(callback) => callback.invoke(cx, global),
OneshotTimerCallback::RunStepsAfterTimeout { completion, .. } => {
completion(cx, global);
},
}
}
}
impl Ord for OneshotTimer {
fn cmp(&self, other: &OneshotTimer) -> Ordering {
match self.scheduled_for.cmp(&other.scheduled_for).reverse() {
Ordering::Equal => self.handle.cmp(&other.handle).reverse(),
res => res,
}
}
}
impl PartialOrd for OneshotTimer {
fn partial_cmp(&self, other: &OneshotTimer) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Eq for OneshotTimer {}
impl PartialEq for OneshotTimer {
fn eq(&self, other: &OneshotTimer) -> bool {
std::ptr::eq(self, other)
}
}
impl OneshotTimers {
pub(crate) fn new(global_scope: &GlobalScope) -> OneshotTimers {
OneshotTimers {
global_scope: Dom::from_ref(global_scope),
js_timers: JsTimers::default(),
next_timer_handle: Cell::new(OneshotTimerHandle(1)),
timers: DomRefCell::new(VecDeque::new()),
suspended_since: Cell::new(None),
suspension_offset: Cell::new(Duration::ZERO),
expected_event_id: Cell::new(TimerEventId(0)),
map_of_active_timers: Default::default(),
runsteps_queues: Default::default(),
next_runsteps_key: Cell::new(1),
runsteps_start_seq: Cell::new(0),
}
}
#[inline]
pub(crate) fn now_for_runsteps(&self) -> Instant {
self.base_time()
}
pub(crate) fn fresh_runsteps_key(&self) -> TimerKey {
let k = self.next_runsteps_key.get();
self.next_runsteps_key.set(k + 1);
k
}
pub(crate) fn runsteps_set_active(&self, timer_key: TimerKey, deadline: RunStepsDeadline) {
self.map_of_active_timers
.borrow_mut()
.insert(timer_key, deadline);
}
fn runsteps_enqueue_sorted(
&self,
ordering_id: &DOMString,
handle: OneshotTimerHandle,
milliseconds: u64,
) {
let mut map = self.runsteps_queues.borrow_mut();
let q = map.entry(ordering_id.clone()).or_default();
let seq = {
let cur = self.runsteps_start_seq.get();
self.runsteps_start_seq.set(cur + 1);
cur
};
let key = OrderingEntry {
milliseconds,
start_seq: seq,
handle,
};
let idx = q
.binary_search_by(|ordering_entry| {
match ordering_entry.milliseconds.cmp(&milliseconds) {
Ordering::Less => Ordering::Less,
Ordering::Greater => Ordering::Greater,
Ordering::Equal => ordering_entry.start_seq.cmp(&seq),
}
})
.unwrap_or_else(|i| i);
q.insert(idx, key);
}
pub(crate) fn schedule_callback(
&self,
callback: OneshotTimerCallback,
duration: Duration,
source: TimerSource,
) -> OneshotTimerHandle {
let new_handle = self.next_timer_handle.get();
self.next_timer_handle
.set(OneshotTimerHandle(new_handle.0 + 1));
let timer = OneshotTimer {
handle: new_handle,
source,
callback,
scheduled_for: self.base_time() + duration,
};
if let OneshotTimerCallback::RunStepsAfterTimeout {
ordering_id,
milliseconds,
..
} = &timer.callback
{
self.runsteps_enqueue_sorted(ordering_id, new_handle, *milliseconds);
}
{
let mut timers = self.timers.borrow_mut();
let insertion_index = timers.binary_search(&timer).err().unwrap();
timers.insert(insertion_index, timer);
}
if self.is_next_timer(new_handle) {
self.schedule_timer_call();
}
new_handle
}
pub(crate) fn unschedule_callback(&self, handle: OneshotTimerHandle) {
let was_next = self.is_next_timer(handle);
self.timers.borrow_mut().retain(|t| t.handle != handle);
if was_next {
self.invalidate_expected_event_id();
self.schedule_timer_call();
}
}
fn is_next_timer(&self, handle: OneshotTimerHandle) -> bool {
match self.timers.borrow().back() {
None => false,
Some(max_timer) => max_timer.handle == handle,
}
}
pub(crate) fn fire_timer(&self, id: TimerEventId, cx: &mut JSContext) {
let expected_id = self.expected_event_id.get();
if expected_id != id {
debug!(
"ignoring timer fire event {:?} (expected {:?})",
id, expected_id
);
return;
}
assert!(self.suspended_since.get().is_none());
let base_time = self.base_time();
if base_time < self.timers.borrow().back().unwrap().scheduled_for {
warn!("Unexpected timing!");
return;
}
let mut timers_to_run = Vec::new();
loop {
let mut timers = self.timers.borrow_mut();
if timers.is_empty() || timers.back().unwrap().scheduled_for > base_time {
break;
}
timers_to_run.push(timers.pop_back().unwrap());
}
for timer in timers_to_run {
if !self.global_scope.can_continue_running() {
return;
}
match &timer.callback {
OneshotTimerCallback::RunStepsAfterTimeout { ordering_id, .. } => {
let head_handle_opt = {
let queues_ref = self.runsteps_queues.borrow();
queues_ref
.get(ordering_id)
.and_then(|v| v.first().map(|t| t.handle))
};
let is_head = head_handle_opt.is_none_or(|head| head == timer.handle);
if !is_head {
let rein = OneshotTimer {
handle: timer.handle,
source: timer.source,
callback: timer.callback,
scheduled_for: self.base_time(),
};
let mut timers = self.timers.borrow_mut();
let idx = timers.binary_search(&rein).err().unwrap();
timers.insert(idx, rein);
continue;
}
let (timer_key, ordering_id_owned, completion) = match timer.callback {
OneshotTimerCallback::RunStepsAfterTimeout {
timer_key,
ordering_id,
milliseconds: _,
completion,
} => (timer_key, ordering_id, completion),
_ => unreachable!(),
};
(completion)(cx, &self.global_scope);
self.map_of_active_timers.borrow_mut().remove(&timer_key);
{
let mut queues_mut = self.runsteps_queues.borrow_mut();
if let Some(q) = queues_mut.get_mut(&ordering_id_owned) {
if !q.is_empty() {
q.remove(0);
}
if q.is_empty() {
queues_mut.remove(&ordering_id_owned);
}
}
}
},
_ => {
let cb = timer.callback;
cb.invoke(cx, &self.global_scope, &self.js_timers);
},
}
}
self.schedule_timer_call();
}
fn base_time(&self) -> Instant {
let offset = self.suspension_offset.get();
match self.suspended_since.get() {
Some(suspend_time) => suspend_time - offset,
None => Instant::now() - offset,
}
}
pub(crate) fn slow_down(&self) {
let min_duration_ms = pref!(js_timers_minimum_duration) as u64;
self.js_timers
.set_min_duration(Duration::from_millis(min_duration_ms));
}
pub(crate) fn speed_up(&self) {
self.js_timers.remove_min_duration();
}
pub(crate) fn suspend(&self) {
if self.suspended_since.get().is_some() {
return warn!("Suspending an already suspended timer.");
}
debug!("Suspending timers.");
self.suspended_since.set(Some(Instant::now()));
self.invalidate_expected_event_id();
}
pub(crate) fn resume(&self) {
let additional_offset = match self.suspended_since.get() {
Some(suspended_since) => Instant::now() - suspended_since,
None => return warn!("Resuming an already resumed timer."),
};
debug!("Resuming timers.");
self.suspension_offset
.set(self.suspension_offset.get() + additional_offset);
self.suspended_since.set(None);
self.schedule_timer_call();
}
fn schedule_timer_call(&self) {
if self.suspended_since.get().is_some() {
return;
}
let timers = self.timers.borrow();
let Some(timer) = timers.back() else {
return;
};
let expected_event_id = self.invalidate_expected_event_id();
let callback = TimerListener {
context: Trusted::new(&*self.global_scope),
task_source: self
.global_scope
.task_manager()
.timer_task_source()
.to_sendable(),
source: timer.source,
id: expected_event_id,
}
.into_callback();
let event_request = TimerEventRequest {
callback,
duration: timer.scheduled_for - self.base_time(),
};
self.global_scope.schedule_timer(event_request);
}
fn invalidate_expected_event_id(&self) -> TimerEventId {
let TimerEventId(currently_expected) = self.expected_event_id.get();
let next_id = TimerEventId(currently_expected + 1);
debug!(
"invalidating expected timer (was {:?}, now {:?}",
currently_expected, next_id
);
self.expected_event_id.set(next_id);
next_id
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn set_timeout_or_interval(
&self,
cx: &mut JSContext,
global: &GlobalScope,
callback: TimerCallback,
arguments: Vec<HandleValue>,
timeout: Duration,
is_interval: IsInterval,
source: TimerSource,
) -> Fallible<i32> {
self.js_timers.set_timeout_or_interval(
cx,
global,
callback,
arguments,
timeout,
is_interval,
source,
)
}
pub(crate) fn clear_timeout_or_interval(&self, global: &GlobalScope, handle: i32) {
self.js_timers.clear_timeout_or_interval(global, handle)
}
}
#[derive(Clone, Copy, Eq, Hash, JSTraceable, MallocSizeOf, Ord, PartialEq, PartialOrd)]
pub(crate) struct JsTimerHandle(i32);
#[derive(DenyPublicFields, JSTraceable, MallocSizeOf)]
pub(crate) struct JsTimers {
next_timer_handle: Cell<JsTimerHandle>,
active_timers: DomRefCell<FxHashMap<JsTimerHandle, JsTimerEntry>>,
nesting_level: Cell<u32>,
min_duration: Cell<Option<Duration>>,
}
#[derive(JSTraceable, MallocSizeOf)]
struct JsTimerEntry {
oneshot_handle: OneshotTimerHandle,
}
#[derive(JSTraceable, MallocSizeOf)]
pub(crate) struct JsTimerTask {
handle: JsTimerHandle,
#[no_trace]
source: TimerSource,
callback: InternalTimerCallback,
is_interval: IsInterval,
nesting_level: u32,
duration: Duration,
is_user_interacting: bool,
}
#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
pub(crate) enum IsInterval {
Interval,
NonInterval,
}
pub(crate) enum TimerCallback {
StringTimerCallback(TrustedScriptOrString),
FunctionTimerCallback(Rc<Function>),
}
#[derive(Clone, JSTraceable, MallocSizeOf)]
#[cfg_attr(crown, expect(crown::unrooted_must_root))]
enum InternalTimerCallback {
StringTimerCallback(DOMString, InitiatingScriptFetchInfo),
FunctionTimerCallback(
#[conditional_malloc_size_of] Rc<Function>,
#[ignore_malloc_size_of = "mozjs"] Rc<Box<[Heap<JSVal>]>>,
),
}
impl Default for JsTimers {
fn default() -> Self {
JsTimers {
next_timer_handle: Cell::new(JsTimerHandle(1)),
active_timers: DomRefCell::new(FxHashMap::default()),
nesting_level: Cell::new(0),
min_duration: Cell::new(None),
}
}
}
impl JsTimers {
#[allow(clippy::too_many_arguments)]
#[cfg_attr(crown, expect(crown::unrooted_must_root))]
pub(crate) fn set_timeout_or_interval(
&self,
cx: &mut JSContext,
global: &GlobalScope,
callback: TimerCallback,
arguments: Vec<HandleValue>,
timeout: Duration,
is_interval: IsInterval,
source: TimerSource,
) -> Fallible<i32> {
let callback = match callback {
TimerCallback::StringTimerCallback(trusted_script_or_string) => {
let global_name = if global.is::<Window>() {
"Window"
} else {
"WorkerGlobalScope"
};
let method_name = if is_interval == IsInterval::Interval {
"setInterval"
} else {
"setTimeout"
};
let sink = format!("{} {}", global_name, method_name);
let code_str = TrustedScript::get_trusted_type_compliant_string(
cx,
global,
trusted_script_or_string,
&sink,
)?;
let initiating_script_fetch_info = active_script_fetch_info(cx, global);
if global
.get_csp_list()
.is_js_evaluation_allowed(cx, global, &code_str.str())
{
InternalTimerCallback::StringTimerCallback(
code_str,
initiating_script_fetch_info,
)
} else {
return Ok(0);
}
},
TimerCallback::FunctionTimerCallback(function) => {
let mut args = Vec::with_capacity(arguments.len());
for _ in 0..arguments.len() {
args.push(Heap::default());
}
for (i, item) in arguments.iter().enumerate() {
args.get_mut(i).unwrap().set(item.get());
}
InternalTimerCallback::FunctionTimerCallback(
function,
Rc::new(args.into_boxed_slice()),
)
},
};
let JsTimerHandle(new_handle) = self.next_timer_handle.get();
self.next_timer_handle.set(JsTimerHandle(new_handle + 1));
let mut task = JsTimerTask {
handle: JsTimerHandle(new_handle),
source,
callback,
is_interval,
is_user_interacting: ScriptThread::is_user_interacting(),
nesting_level: 0,
duration: Duration::ZERO,
};
task.duration = timeout.max(Duration::ZERO);
self.initialize_and_schedule(global, task);
Ok(new_handle)
}
pub(crate) fn clear_timeout_or_interval(&self, global: &GlobalScope, handle: i32) {
let mut active_timers = self.active_timers.borrow_mut();
if let Some(entry) = active_timers.remove(&JsTimerHandle(handle)) {
global.unschedule_callback(entry.oneshot_handle);
}
}
pub(crate) fn set_min_duration(&self, duration: Duration) {
self.min_duration.set(Some(duration));
}
pub(crate) fn remove_min_duration(&self) {
self.min_duration.set(None);
}
fn user_agent_pad(&self, current_duration: Duration) -> Duration {
match self.min_duration.get() {
Some(min_duration) => min_duration.max(current_duration),
None => current_duration,
}
}
fn initialize_and_schedule(&self, global: &GlobalScope, mut task: JsTimerTask) {
let handle = task.handle;
let mut active_timers = self.active_timers.borrow_mut();
let nesting_level = self.nesting_level.get();
let duration = self.user_agent_pad(clamp_duration(nesting_level, task.duration));
task.nesting_level = nesting_level + 1;
let callback = OneshotTimerCallback::JsTimer(task);
let oneshot_handle = global.schedule_callback(callback, duration);
let entry = active_timers
.entry(handle)
.or_insert(JsTimerEntry { oneshot_handle });
entry.oneshot_handle = oneshot_handle;
}
}
fn clamp_duration(nesting_level: u32, unclamped: Duration) -> Duration {
let lower_bound_ms = if nesting_level > 5 { 4 } else { 0 };
let lower_bound = Duration::from_millis(lower_bound_ms);
lower_bound.max(unclamped)
}
impl JsTimerTask {
fn invoke(self, cx: &mut JSContext, global: &GlobalScope, timers: &JsTimers) {
timers.nesting_level.set(self.nesting_level);
let _guard = ScriptThread::user_interacting_guard();
match self.callback {
InternalTimerCallback::StringTimerCallback(ref code_str, ref fetch_info) => {
let InitiatingScriptFetchInfo {
fetch_options,
base_url,
} = fetch_info.clone();
let script = global.create_a_classic_script(
cx,
(*code_str.str()).into(),
base_url,
ScriptOptions::empty(),
fetch_options,
Some(IntroductionType::DOM_TIMER),
1,
);
_ = global.run_a_classic_script(
cx,
script,
RethrowErrors::No,
None, );
},
InternalTimerCallback::FunctionTimerCallback(ref function, ref arguments) => {
let arguments = self.collect_heap_args(arguments);
rooted!(&in(cx) let mut value: JSVal);
let _ = function.Call_(cx, global, arguments, value.handle_mut(), Report);
},
};
timers.nesting_level.set(0);
if self.is_interval == IsInterval::Interval &&
timers.active_timers.borrow().contains_key(&self.handle)
{
timers.initialize_and_schedule(global, self);
}
}
fn collect_heap_args<'b>(&self, args: &'b [Heap<JSVal>]) -> Vec<HandleValue<'b>> {
args.iter().map(|arg| arg.as_handle_value()).collect()
}
}
#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, Serialize)]
pub enum TimerSource {
FromWindow(PipelineId),
FromWorker,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub struct TimerEventId(pub u32);
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct TimerEvent(pub TimerSource, pub TimerEventId);
#[derive(Clone)]
struct TimerListener {
task_source: SendableTaskSource,
context: Trusted<GlobalScope>,
source: TimerSource,
id: TimerEventId,
}
impl TimerListener {
fn handle(&self, event: TimerEvent) {
let context = self.context.clone();
self.task_source.queue(task!(timer_event: move |cx| {
let global = context.root();
let TimerEvent(source, id) = event;
match source {
TimerSource::FromWorker => {
global.downcast::<WorkerGlobalScope>().expect("Window timer delivered to worker");
},
TimerSource::FromWindow(pipeline) => {
assert_eq!(pipeline, global.pipeline_id());
global.downcast::<Window>().expect("Worker timer delivered to window");
},
};
global.fire_timer(id, cx);
})
);
}
fn into_callback(self) -> BoxedTimerCallback {
let timer_event = TimerEvent(self.source, self.id);
Box::new(move || self.handle(timer_event))
}
}
#[derive(Clone, JSTraceable, MallocSizeOf)]
struct InitiatingScriptFetchInfo {
fetch_options: ScriptFetchOptions,
#[no_trace]
base_url: ServoUrl,
}
#[expect(unsafe_code)]
fn active_script_fetch_info(cx: &mut JSContext, global: &GlobalScope) -> InitiatingScriptFetchInfo {
rooted!(&in(cx) let mut value = UndefinedValue());
unsafe { JS_GetScriptedCallerPrivate(cx, value.handle_mut()) };
let reference_private = value.handle().into_handle();
let initiating_script = unsafe { module_script_from_reference_private(&reference_private) };
let (fetch_options, base_url) = match initiating_script {
Some(script) => (
ScriptFetchOptions {
cryptographic_nonce: script.options.cryptographic_nonce.clone(),
integrity_metadata: String::new(),
parser_metadata: ParserMetadata::NotParserInserted,
credentials_mode: script.options.credentials_mode,
referrer_policy: script.options.referrer_policy,
render_blocking: false,
},
script.base_url.clone(),
),
None => (
ScriptFetchOptions::default_classic_script(),
global.api_base_url(),
),
};
InitiatingScriptFetchInfo {
fetch_options,
base_url,
}
}