Truly independent web browser
LibWeb: Clamp timers that a timer’s promise reactions schedule
sideshowbarker23be19ed9c8d
diff --git a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cppindex af55716aad8..bebad027c6a 100644--- a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp+++ b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp@@ -314,6 +314,8 @@ bool EventLoop::run_one_turn_of_the_processing_model()// 5. Set the event loop's currently running task to oldestTask.m_currently_running_task = oldest_task.ptr();+ // NB: A task that spins the event loop runs other tasks in the middle of its own, so each restores what it found.+ TemporaryChange timer_nesting_level_for_microtasks { m_timer_nesting_level_for_microtasks, oldest_task->timer_nesting_level() };// 6. Perform oldestTask's steps.oldest_task->execute();@@ -1883,6 +1885,12 @@ void EventLoop::perform_a_microtask_checkpoint()// 2. Set the event loop's currently running task to oldestMicrotask.m_currently_running_task = oldest_microtask;+ // AD-HOC: The spec gives a microtask no timer nesting level, so a timer it schedules starts over at 0 — even+ // in the checkpoint that ends a deeply-nested timer callback. A page that re-arms a 0ms timer from a+ // promise reaction then never reaches the 4ms clamp, and spins. Instead, a microtask carries the+ // nesting level of the task whose checkpoint runs it, just as the timer callback itself would have.+ oldest_microtask->set_timer_nesting_level(m_timer_nesting_level_for_microtasks);+// 3. Run oldestMicrotask.oldest_microtask->execute();diff --git a/Libraries/LibWeb/HTML/EventLoop/EventLoop.h b/Libraries/LibWeb/HTML/EventLoop/EventLoop.hindex 42cc62c6605..b673b4eb2ba 100644--- a/Libraries/LibWeb/HTML/EventLoop/EventLoop.h+++ b/Libraries/LibWeb/HTML/EventLoop/EventLoop.h@@ -283,6 +283,7 @@ private:// https://html.spec.whatwg.org/multipage/webappapis.html#currently-running-taskGC::Ptr<Task> m_currently_running_task { nullptr };+ u32 m_timer_nesting_level_for_microtasks { 0 };u64 m_task_generation { 0 };diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cppindex 8354f121438..4dda6a67216 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp@@ -898,9 +898,8 @@ WebIDL::ExceptionOr<i32> WindowOrWorkerGlobalScopeMixin::run_timer_initializatio// 4. If the surrounding agent's event loop's currently running task is a task that was created by this algorithm,// then let nesting level be the task's timer nesting level. Otherwise, let nesting level be 0.- // NB: Only a task created by this algorithm carries a nonzero timer nesting level — so reading the level of- // whatever task is running covers both cases. A microtask counts as its own task here — so a timer scheduled- // from one starts over at 0 even when the checkpoint follows a deeply-nested timer callback.+ // NB: Only a task created by this algorithm, or a microtask run in such a task's checkpoint, carries a nonzero+ // timer nesting level — so reading the level of whatever task is running covers both cases.u32 nesting_level = 0;if (auto currently_running_task = relevant_agent(relevant_global_object(*this)).event_loop->currently_running_task())nesting_level = currently_running_task->timer_nesting_level();diff --git a/Tests/LibWeb/Text/expected/HTML/timer-nesting-level-settimeout-chain.txt b/Tests/LibWeb/Text/expected/HTML/timer-nesting-level-settimeout-chain.txtindex 5efd2f1de7e..835d87c1bd8 100644--- a/Tests/LibWeb/Text/expected/HTML/timer-nesting-level-settimeout-chain.txt+++ b/Tests/LibWeb/Text/expected/HTML/timer-nesting-level-settimeout-chain.txt@@ -1,2 +1,3 @@A chain of 30 nested setTimeout(f, 0) calls takes at least 90ms: true-Timers fired in the order: unclamped timer from the microtask, clamped timer from the callback+A chain of 30 setTimeout(f, 0) calls made from promise reactions takes at least 90ms: true+Timers fired in the order: clamped timer from the callback, clamped timer from the microtaskdiff --git a/Tests/LibWeb/Text/input/HTML/timer-nesting-level-settimeout-chain.html b/Tests/LibWeb/Text/input/HTML/timer-nesting-level-settimeout-chain.htmlindex 089a5edd42a..7d7f5cbf4fe 100644--- a/Tests/LibWeb/Text/input/HTML/timer-nesting-level-settimeout-chain.html+++ b/Tests/LibWeb/Text/input/HTML/timer-nesting-level-settimeout-chain.html@@ -15,13 +15,30 @@}const elapsed = performance.now() - start;println(`A chain of 30 nested setTimeout(f, 0) calls takes at least 90ms: ${elapsed >= 90}`);- testTimerScheduledFromMicrotask();+ testChainThroughPromiseReactions();};setTimeout(step, 0);- // A microtask isn't a task created by the timer initialization steps, so a setTimeout() call made during the- // microtask checkpoint after a deeply-nested timer callback starts over at nesting level 0: its 0ms timer fires- // before the clamped 4ms one that the callback itself scheduled a moment earlier.+ // A chain whose every hop schedules the next one from a promise reaction, as an "await" on a promise that a+ // 0ms timer resolves does, is clamped the same way: a microtask run in a timer callback's checkpoint carries+ // the callback's nesting level.+ function testChainThroughPromiseReactions() {+ const start = performance.now();+ let hop = 0;+ const step = () => {+ if (++hop < 30) {+ Promise.resolve().then(() => setTimeout(step, 0));+ return;+ }+ const elapsed = performance.now() - start;+ println(`A chain of 30 setTimeout(f, 0) calls made from promise reactions takes at least 90ms: ${elapsed >= 90}`);+ testTimerScheduledFromMicrotask();+ };+ setTimeout(step, 0);+ }++ // A setTimeout() call made during the microtask checkpoint after a deeply-nested timer callback is clamped+ // like one the callback makes itself, so the two 0ms timers fire in the order they were scheduled.function testTimerScheduledFromMicrotask() {const order = [];const record = name => {@@ -38,7 +55,7 @@return;}setTimeout(() => record("clamped timer from the callback"), 0);- queueMicrotask(() => setTimeout(() => record("unclamped timer from the microtask"), 0));+ queueMicrotask(() => setTimeout(() => record("clamped timer from the microtask"), 0));};setTimeout(nest, 0);}diff --git a/Tests/LibWeb/Text/input/HTML/timer-throttling-hidden-document-intensive.html b/Tests/LibWeb/Text/input/HTML/timer-throttling-hidden-document-intensive.htmlindex 4747d642914..93d12ecae87 100644--- a/Tests/LibWeb/Text/input/HTML/timer-throttling-hidden-document-intensive.html+++ b/Tests/LibWeb/Text/input/HTML/timer-throttling-hidden-document-intensive.html@@ -50,6 +50,11 @@};nest(6);});+ const nextTask = () => new Promise(resolve => {+ const { port1, port2 } = new MessageChannel();+ port1.onmessage = resolve;+ port2.postMessage(null);+ });const report = (what, ok, details) => {println(`${what}: ${ok}`);if (!ok)@@ -91,9 +96,13 @@{ armedAt, baseWakeUp, delayed });lastChainedWakeUp = Math.max(chainedAgain, nested.firedAt);- // Let an intensive interval pass with no chained timer running.- while (performance.now() < lastChainedWakeUp + intensiveWakeUpInterval + 60)+ // Let an intensive interval pass with no chained timer running. Each wait starts from a message task: a+ // timeout() awaited right after another one is scheduled from that timer's promise reaction, so it nests+ // one level deeper, and past level 5 it would count as chained itself.+ while (performance.now() < lastChainedWakeUp + intensiveWakeUpInterval + 60) {+ await nextTask();await timeout(50);+ }armedAt = performance.now();wakeUp = wakeUpAtOrAfter(armedAt + 10, wakeUpInterval);chained = await chainedFireTime(10);