mirror of
https://github.com/lexmount/moli.git
synced 2026-11-22 16:02:34 +00:00
fix(timers): suspend timer nesting during microtasks
Timers queued from microtasks inherited the surrounding timer task's nesting level and were clamped to 4ms after six callbacks. Suspend that metadata for the microtask checkpoint and restore it for the outer task and interval rearm. Cover the existing worker import, module and error checkpoint entry points. Correct the old native expectation that required microtask inheritance and add queueMicrotask/Promise, interval and worker-owner restoration regressions. The tests inspect scheduled delays without relying on elapsed wall time.
This commit is contained in:
@@ -229,6 +229,7 @@ pub(crate) fn dispatch_worker_error_event_with_kind<'s>(
|
||||
|
||||
fn worker_error_microtask_checkpoint(scope: &mut v8::PinScope<'_, '_>) {
|
||||
// Blink observes cancellation after microtasks queued by error listeners.
|
||||
let _checkpoint_scope = crate::script_cleanup::MicrotaskCheckpointScope::enter(scope);
|
||||
scope.perform_microtask_checkpoint();
|
||||
crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope);
|
||||
}
|
||||
|
||||
@@ -39,7 +39,10 @@ struct MicrotaskCheckpointState(Rc<Cell<bool>>);
|
||||
|
||||
/// HTML's performing-a-microtask-checkpoint flag also covers rejection
|
||||
/// notification and checkpoint-end cleanup after V8 finishes draining jobs.
|
||||
pub(crate) struct MicrotaskCheckpointScope(Rc<Cell<bool>>);
|
||||
pub(crate) struct MicrotaskCheckpointScope {
|
||||
active: Rc<Cell<bool>>,
|
||||
_timer_nesting: Option<crate::timer_nesting::TimerNestingScope>,
|
||||
}
|
||||
|
||||
impl MicrotaskCheckpointScope {
|
||||
pub(crate) fn enter(scope: &mut v8::PinScope<'_, '_>) -> Option<Self> {
|
||||
@@ -61,13 +64,17 @@ impl MicrotaskCheckpointScope {
|
||||
if active.replace(true) {
|
||||
return None;
|
||||
}
|
||||
Some(Self(active))
|
||||
Some(Self {
|
||||
active,
|
||||
_timer_nesting:
|
||||
crate::timer_nesting::TimerNestingScope::suspend_for_microtask_checkpoint(scope),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MicrotaskCheckpointScope {
|
||||
fn drop(&mut self) {
|
||||
self.0.set(false);
|
||||
self.active.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ fn timer_nesting_clamps_string_chains_after_six_callbacks() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timer_nesting_survives_the_callback_microtask_checkpoint() {
|
||||
fn timer_nesting_resets_inside_callback_microtask_checkpoint() {
|
||||
let mut vm = new_storage_test_vm("https://timer-nesting.test/");
|
||||
vm.eval(
|
||||
"globalThis.fired = 0; function step() { ++fired; queueMicrotask(() => setTimeout(step, 0)); } setTimeout(step, 0)",
|
||||
@@ -99,7 +99,105 @@ fn timer_nesting_survives_the_callback_microtask_checkpoint() {
|
||||
run_first_six_callbacks(&mut vm);
|
||||
assert_eq!(
|
||||
vm.document_runtime.take_next_timeout_delay_for_test(),
|
||||
Some(4)
|
||||
Some(0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timer_microtask_timeout_keeps_requested_delay_after_a_nested_callback() {
|
||||
for schedule in [
|
||||
"queueMicrotask",
|
||||
"callback => Promise.resolve().then(callback)",
|
||||
] {
|
||||
let mut vm = new_storage_test_vm("https://timer-microtask.test/");
|
||||
vm.eval(&format!(
|
||||
r#"
|
||||
globalThis.fired = 0;
|
||||
const scheduleMicrotask = {schedule};
|
||||
function step() {{
|
||||
if (++fired < 6) {{
|
||||
setTimeout(step, 0);
|
||||
return;
|
||||
}}
|
||||
setTimeout(() => {{}}, 1);
|
||||
scheduleMicrotask(() => setTimeout(() => {{}}, 1));
|
||||
}}
|
||||
setTimeout(step, 0);
|
||||
"#,
|
||||
))
|
||||
.unwrap();
|
||||
run_first_six_callbacks(&mut vm);
|
||||
let mut delays = [
|
||||
vm.document_runtime.take_next_timeout_delay_for_test(),
|
||||
vm.document_runtime.take_next_timeout_delay_for_test(),
|
||||
];
|
||||
delays.sort();
|
||||
assert_eq!(delays, [Some(1), Some(4)], "{schedule}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timer_microtask_timeout_does_not_reset_the_interval_rearm_level() {
|
||||
let mut vm = new_storage_test_vm("https://timer-microtask-interval.test/");
|
||||
vm.eval(
|
||||
r#"
|
||||
globalThis.fired = 0;
|
||||
setInterval(() => {
|
||||
if (++fired === 6) queueMicrotask(() => setTimeout(() => {}, 1));
|
||||
}, 0);
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
run_first_six_callbacks(&mut vm);
|
||||
let mut delays = [
|
||||
vm.document_runtime.take_next_timeout_delay_for_test(),
|
||||
vm.document_runtime.take_next_timeout_delay_for_test(),
|
||||
];
|
||||
delays.sort();
|
||||
assert_eq!(delays, [Some(1), Some(4)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timer_microtask_checkpoint_suspends_worker_level_and_restores_outer_task() {
|
||||
use crate::timer_nesting::{TimerNestingLevel, TimerNestingOwner, TimerNestingScope};
|
||||
|
||||
crate::ensure_v8_for_test();
|
||||
let mut isolate = v8::Isolate::new(Default::default());
|
||||
let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));
|
||||
let scope = &mut scope.init();
|
||||
let context = v8::Context::new(scope, Default::default());
|
||||
let scope = &mut v8::ContextScope::new(scope, context);
|
||||
let task = TimerNestingScope::enter(scope.as_mut());
|
||||
let owner = TimerNestingOwner::Worker;
|
||||
let mut level = TimerNestingLevel::default();
|
||||
for _ in 0..6 {
|
||||
level = level.next();
|
||||
}
|
||||
level.activate(scope, owner);
|
||||
assert_eq!(
|
||||
TimerNestingLevel::for_new_timer(scope, owner).clamp_delay_ms(1),
|
||||
4
|
||||
);
|
||||
let checkpoint = crate::script_cleanup::MicrotaskCheckpointScope::enter(scope)
|
||||
.expect("the agent checkpoint should start");
|
||||
assert_eq!(
|
||||
TimerNestingLevel::for_new_timer(scope, owner).clamp_delay_ms(1),
|
||||
1
|
||||
);
|
||||
assert!(crate::script_cleanup::MicrotaskCheckpointScope::enter(scope).is_none());
|
||||
assert_eq!(
|
||||
TimerNestingLevel::for_new_timer(scope, owner).clamp_delay_ms(1),
|
||||
1
|
||||
);
|
||||
drop(checkpoint);
|
||||
assert_eq!(
|
||||
TimerNestingLevel::for_new_timer(scope, owner).clamp_delay_ms(1),
|
||||
4
|
||||
);
|
||||
drop(task);
|
||||
assert_eq!(
|
||||
TimerNestingLevel::for_new_timer(scope, owner).clamp_delay_ms(1),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -66,9 +66,9 @@ struct TimerNestingState {
|
||||
scope_depth: Cell<usize>,
|
||||
}
|
||||
|
||||
/// Keep an ExecutionContext's timer level through its callback checkpoint.
|
||||
/// Consume this guard after the checkpoint, before asynchronous runtime
|
||||
/// follow-up. Drop also restores it when a callback or checkpoint fails.
|
||||
/// Preserve a timer task's level until its callback turn is finished.
|
||||
/// Microtask checkpoints temporarily suspend this state because their jobs
|
||||
/// are separate tasks. Drop also restores it on callback or checkpoint failure.
|
||||
pub(crate) struct TimerNestingScope {
|
||||
state: Rc<TimerNestingState>,
|
||||
previous: TimerLevels,
|
||||
@@ -99,6 +99,24 @@ impl TimerNestingScope {
|
||||
}
|
||||
}
|
||||
|
||||
/// A microtask is the currently running task while its checkpoint drains.
|
||||
/// Preserve the outer task's metadata for reentry and interval bookkeeping,
|
||||
/// without letting newly scheduled timers inherit it from microtasks.
|
||||
pub(crate) fn suspend_for_microtask_checkpoint(isolate: &v8::Isolate) -> Option<Self> {
|
||||
let state = isolate.get_slot::<Rc<TimerNestingState>>()?.clone();
|
||||
if state.levels.borrow().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let previous = std::mem::take(&mut *state.levels.borrow_mut());
|
||||
let previous_depth = state.scope_depth.get();
|
||||
state.scope_depth.set(previous_depth + 1);
|
||||
Some(Self {
|
||||
state,
|
||||
previous,
|
||||
previous_depth,
|
||||
})
|
||||
}
|
||||
|
||||
/// Body-only execution has no checkpoint. Complete-task entrypoints keep
|
||||
/// an outer scope through the checkpoint as well.
|
||||
pub(crate) fn enter_if_absent(isolate: &mut v8::Isolate) -> Option<Self> {
|
||||
|
||||
@@ -584,8 +584,11 @@ fn evaluate_worker_script(
|
||||
});
|
||||
return Err(error);
|
||||
}
|
||||
scope.perform_microtask_checkpoint();
|
||||
crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(&mut scope);
|
||||
{
|
||||
let _checkpoint_scope = crate::script_cleanup::MicrotaskCheckpointScope::enter(&mut scope);
|
||||
scope.perform_microtask_checkpoint();
|
||||
crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(&mut scope);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -699,8 +699,11 @@ fn finish_worker_module_bootstrap(
|
||||
// The host reports evaluation failures as errors, not unhandled rejections.
|
||||
promise.mark_as_handled();
|
||||
}
|
||||
scope.perform_microtask_checkpoint();
|
||||
crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope);
|
||||
{
|
||||
let _checkpoint_scope = crate::script_cleanup::MicrotaskCheckpointScope::enter(scope);
|
||||
scope.perform_microtask_checkpoint();
|
||||
crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope);
|
||||
}
|
||||
if root_module.get_status() == v8::ModuleStatus::Errored {
|
||||
return Err(WorkerModuleBootstrapFailure::evaluation(
|
||||
worker_bootstrap_value_error(
|
||||
@@ -1382,8 +1385,11 @@ fn finish_worker_dynamic_module_import_evaluation(
|
||||
if let Some(promise) = evaluation_promise {
|
||||
promise.mark_as_handled();
|
||||
}
|
||||
scope.perform_microtask_checkpoint();
|
||||
crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope);
|
||||
{
|
||||
let _checkpoint_scope = crate::script_cleanup::MicrotaskCheckpointScope::enter(scope);
|
||||
scope.perform_microtask_checkpoint();
|
||||
crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope);
|
||||
}
|
||||
if root_module.get_status() == v8::ModuleStatus::Errored {
|
||||
return Err(WorkerDynamicModuleImportError::evaluation_rejection_value(
|
||||
scope,
|
||||
@@ -1504,8 +1510,11 @@ fn resolve_single_worker_dynamic_module_import(
|
||||
return;
|
||||
};
|
||||
let _ = resolver.resolve(scope, resolved_value);
|
||||
scope.perform_microtask_checkpoint();
|
||||
crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope);
|
||||
{
|
||||
let _checkpoint_scope = crate::script_cleanup::MicrotaskCheckpointScope::enter(scope);
|
||||
scope.perform_microtask_checkpoint();
|
||||
crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope);
|
||||
}
|
||||
}
|
||||
|
||||
fn take_worker_dynamic_module_imports_joined_to_root(
|
||||
@@ -1546,8 +1555,11 @@ fn reject_worker_dynamic_module_import(
|
||||
.unwrap_or_else(|| v8::undefined(scope).into()),
|
||||
};
|
||||
let _ = resolver.reject(scope, rejection);
|
||||
scope.perform_microtask_checkpoint();
|
||||
crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope);
|
||||
{
|
||||
let _checkpoint_scope = crate::script_cleanup::MicrotaskCheckpointScope::enter(scope);
|
||||
scope.perform_microtask_checkpoint();
|
||||
crate::context_bootstrap::run_end_of_microtask_checkpoint_tasks(scope);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_failed_worker_dynamic_module_import(
|
||||
|
||||
Reference in New Issue
Block a user