Truly independent web browser
LibWeb: Pause the event loop while `importScripts()` fetches a script
Tim Ledbetterdc532237a6f3
diff --git a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp b/Libraries/LibWeb/HTML/Scripting/Fetching.cppindex af22ad90687..00d6b89c16e 100644--- a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp+++ b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp@@ -46,6 +46,7 @@#include <LibWeb/HTML/Window.h>#include <LibWeb/Infra/SerializedURL.h>#include <LibWeb/Loader/ResourceLoader.h>+#include <LibWeb/Platform/EventLoopPlugin.h>#include <LibWeb/ReferrerPolicy/AbstractOperations.h>#include <LibWebCommon/Fetch/Infrastructure/URL.h>#include <LibWebCommon/Infra/Strings.h>@@ -927,18 +928,26 @@ WebIDL::ExceptionOr<GC::Ref<ClassicScript>> fetch_a_classic_worker_imported_scriTRY(perform_fetch->function()(request, TopLevelModule::Yes, move(process_response_consume_body)));}// Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.+ // AD-HOC: The fetch runs on a parallel queue, since the event loop it would otherwise queue tasks on is paused below.else {- Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };+ Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::SyncAccumulate };fetch_algorithms_input.process_response_consume_body = move(process_response_consume_body);- Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));+ Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)), Fetch::Fetching::UseParallelQueue::Yes);}// 5. Pause until response is not null.// FIXME: Consider using a "response holder" to avoid needing to annotate response as IGNORE_USE_IN_ESCAPING_LAMBDA.auto& event_loop = settings_object.responsible_event_loop();- event_loop.spin_until(GC::create_function(GC::Heap::the(), [&]() -> bool {+ auto response_is_not_null = GC::create_function(GC::Heap::the(), [&]() -> bool {return !!response;- }));+ });+ if (perform_fetch) {+ // AD-HOC: The event loop is spun rather than paused, since a perform the fetch hook may queue tasks on it.+ event_loop.spin_until(response_is_not_null);+ } else {+ auto pause_handle = event_loop.pause(EventLoop::UpdateTheRendering::No);+ Platform::EventLoopPlugin::the().spin_until(response_is_not_null);+ }// NB: Whether response was CORS-cross-origin must be determined before unwrapping it, since the internal// response of an opaque filtered response is never CORS-cross-origin itself.diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex 61bb1a2a942..bae572a489f 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -621,6 +621,9 @@ Text/input/Worker/Worker-close-after-postMessage.htmlText/input/Worker/Worker-crypto.htmlText/input/Worker/Worker-echo.htmlText/input/Worker/Worker-importScripts.html+Text/input/Worker/Worker-importScripts-concurrent-async-fetch.html+Text/input/Worker/Worker-importScripts-in-microtask.html+Text/input/Worker/Worker-importScripts-pauses-other-tasks.htmlText/input/Worker/Worker-location.htmlText/input/Worker/Worker-module.htmlText/input/Worker/Worker-performance.htmldiff --git a/Tests/LibWeb/Text/expected/Worker/Worker-importScripts-concurrent-async-fetch.txt b/Tests/LibWeb/Text/expected/Worker/Worker-importScripts-concurrent-async-fetch.txtnew file mode 100644index 00000000000..2d517855986--- /dev/null+++ b/Tests/LibWeb/Text/expected/Worker/Worker-importScripts-concurrent-async-fetch.txt@@ -0,0 +1,3 @@+The imported script ran: true+The fetch() completed after importScripts() returned, with body: fetched body+The fetch() promise reactions ran while importScripts() was blocked: falsediff --git a/Tests/LibWeb/Text/expected/Worker/Worker-importScripts-in-microtask.txt b/Tests/LibWeb/Text/expected/Worker/Worker-importScripts-in-microtask.txtnew file mode 100644index 00000000000..5e2ab6a669e--- /dev/null+++ b/Tests/LibWeb/Text/expected/Worker/Worker-importScripts-in-microtask.txt@@ -0,0 +1,2 @@+importScripts() called from a promise reaction: the imported script ran+importScripts() called from a queueMicrotask() callback: the imported script randiff --git a/Tests/LibWeb/Text/expected/Worker/Worker-importScripts-pauses-other-tasks.txt b/Tests/LibWeb/Text/expected/Worker/Worker-importScripts-pauses-other-tasks.txtnew file mode 100644index 00000000000..b40a2773a23--- /dev/null+++ b/Tests/LibWeb/Text/expected/Worker/Worker-importScripts-pauses-other-tasks.txt@@ -0,0 +1,6 @@+The imported script ran: true+Ran while importScripts() was blocked: (nothing)+Never ran after importScripts() returned: (none)+Ran more than once: (none)+The microtasks ran before the tasks: true+The microtasks ran in the order they were queued: truediff --git a/Tests/LibWeb/Text/input/Worker/Worker-importScripts-concurrent-async-fetch.html b/Tests/LibWeb/Text/input/Worker/Worker-importScripts-concurrent-async-fetch.htmlnew file mode 100644index 00000000000..73d08f488d1--- /dev/null+++ b/Tests/LibWeb/Text/input/Worker/Worker-importScripts-concurrent-async-fetch.html@@ -0,0 +1,35 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A fetch() in flight while importScripts() blocks completes once the call returns, and none of its promise+ // reactions run during the call.+ promiseTest(async () => {+ const server = httpTestServer();+ const fetchToken = crypto.randomUUID();+ const fetchURL = await server.createEcho("GET", "/worker-importScripts-concurrent-async-fetch-fetched", {+ status: 200,+ headers: { "Access-Control-Allow-Origin": "*", "Content-Type": "text/plain" },+ body: "fetched body",+ wait_for_unblock: fetchToken,+ });+ const importToken = crypto.randomUUID();+ const importURL = await server.createEcho("GET", "/worker-importScripts-concurrent-async-fetch-imported", {+ status: 200,+ headers: { "Access-Control-Allow-Origin": "*", "Content-Type": "text/javascript" },+ body: "self.importedScriptRan = true;",+ wait_for_unblock: importToken,+ });++ const worker = new Worker("worker-importScripts-concurrent-async-fetch.js");+ const results = new Promise(resolve => (worker.onmessage = event => resolve(event.data)));+ worker.postMessage({ fetchURL, importURL });++ await server.waitForRequest(fetchURL);+ await server.waitForRequest(importURL);+ await fetch(`${server.baseURL}/unblock/${fetchToken}`);+ await fetch(`${server.baseURL}/unblock/${importToken}`);++ for (const line of await results)+ println(line);+ });+</script>diff --git a/Tests/LibWeb/Text/input/Worker/Worker-importScripts-in-microtask.html b/Tests/LibWeb/Text/input/Worker/Worker-importScripts-in-microtask.htmlnew file mode 100644index 00000000000..066bdf9962c--- /dev/null+++ b/Tests/LibWeb/Text/input/Worker/Worker-importScripts-in-microtask.html@@ -0,0 +1,13 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // importScripts() fetches and runs its script when it is called from a microtask.+ asyncTest(done => {+ const worker = new Worker("worker-importScripts-in-microtask.js");+ worker.onmessage = event => {+ println(`importScripts() called from a promise reaction: ${event.data.fromPromiseReaction}`);+ println(`importScripts() called from a queueMicrotask() callback: ${event.data.fromQueueMicrotask}`);+ done();+ };+ });+</script>diff --git a/Tests/LibWeb/Text/input/Worker/Worker-importScripts-pauses-other-tasks.html b/Tests/LibWeb/Text/input/Worker/Worker-importScripts-pauses-other-tasks.htmlnew file mode 100644index 00000000000..df6f64a4e40--- /dev/null+++ b/Tests/LibWeb/Text/input/Worker/Worker-importScripts-pauses-other-tasks.html@@ -0,0 +1,33 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // While importScripts() blocks, no task, animation frame callback or microtask may run. Each runs once afterwards,+ // microtasks first.+ promiseTest(async () => {+ const server = httpTestServer();+ const token = crypto.randomUUID();+ const url = await server.createEcho("GET", "/worker-importScripts-pauses-other-tasks", {+ status: 200,+ headers: { "Access-Control-Allow-Origin": "*", "Content-Type": "text/javascript" },+ body: "self.importedScriptRan = true;",+ wait_for_unblock: token,+ });++ const frameWorkerSource = "onmessage = () => requestAnimationFrame(() => postMessage(null));";+ const frameWorker = new Worker(URL.createObjectURL(new Blob([frameWorkerSource], { type: "text/javascript" })));+ const worker = new Worker("worker-importScripts-pauses-other-tasks.js");+ const results = new Promise(resolve => (worker.onmessage = event => resolve(event.data)));+ worker.postMessage(url);++ // A frame of another worker shows that the animation frame the blocked worker requested is due.+ await server.waitForRequest(url);+ await new Promise(resolve => {+ frameWorker.onmessage = resolve;+ frameWorker.postMessage(null);+ });+ await fetch(`${server.baseURL}/unblock/${token}`);++ for (const line of await results)+ println(line);+ });+</script>diff --git a/Tests/LibWeb/Text/input/Worker/worker-importScripts-concurrent-async-fetch.js b/Tests/LibWeb/Text/input/Worker/worker-importScripts-concurrent-async-fetch.jsnew file mode 100644index 00000000000..fc4f32d3b25--- /dev/null+++ b/Tests/LibWeb/Text/input/Worker/worker-importScripts-concurrent-async-fetch.js@@ -0,0 +1,26 @@+self.onmessage = event => {+ const { fetchURL, importURL } = event.data;+ let importScriptsReturned = false;+ let fetchReactionsRanWhileBlocked = false;++ const fetched = fetch(fetchURL)+ .then(response => response.text())+ .then(text => {+ fetchReactionsRanWhileBlocked = !importScriptsReturned;+ return text;+ });++ importScripts(importURL);+ importScriptsReturned = true;++ fetched.then(+ text => {+ self.postMessage([+ `The imported script ran: ${self.importedScriptRan === true}`,+ `The fetch() completed after importScripts() returned, with body: ${text}`,+ `The fetch() promise reactions ran while importScripts() was blocked: ${fetchReactionsRanWhileBlocked}`,+ ]);+ },+ error => self.postMessage([`The fetch() failed: ${error.name}`])+ );+};diff --git a/Tests/LibWeb/Text/input/Worker/worker-importScripts-in-microtask-imported.js b/Tests/LibWeb/Text/input/Worker/worker-importScripts-in-microtask-imported.jsnew file mode 100644index 00000000000..204614e68a3--- /dev/null+++ b/Tests/LibWeb/Text/input/Worker/worker-importScripts-in-microtask-imported.js@@ -0,0 +1 @@+self.importedScriptRuns = (self.importedScriptRuns ?? 0) + 1;diff --git a/Tests/LibWeb/Text/input/Worker/worker-importScripts-in-microtask.js b/Tests/LibWeb/Text/input/Worker/worker-importScripts-in-microtask.jsnew file mode 100644index 00000000000..ca20d9fefec--- /dev/null+++ b/Tests/LibWeb/Text/input/Worker/worker-importScripts-in-microtask.js@@ -0,0 +1,16 @@+const importScriptsAndCheck = () => {+ const runsBefore = self.importedScriptRuns ?? 0;+ try {+ importScripts("worker-importScripts-in-microtask-imported.js");+ } catch (error) {+ return `threw ${error.name}`;+ }+ return self.importedScriptRuns === runsBefore + 1 ? "the imported script ran" : "the imported script did not run";+};++Promise.resolve().then(() => {+ const fromPromiseReaction = importScriptsAndCheck();+ queueMicrotask(() => {+ self.postMessage({ fromPromiseReaction, fromQueueMicrotask: importScriptsAndCheck() });+ });+});diff --git a/Tests/LibWeb/Text/input/Worker/worker-importScripts-pauses-other-tasks.js b/Tests/LibWeb/Text/input/Worker/worker-importScripts-pauses-other-tasks.jsnew file mode 100644index 00000000000..09c90e46148--- /dev/null+++ b/Tests/LibWeb/Text/input/Worker/worker-importScripts-pauses-other-tasks.js@@ -0,0 +1,43 @@+self.onmessage = event => {+ const log = [];+ const note = entry => log.push(entry);+ const armed = [+ "timer",+ "posted message",+ "animation frame callback",+ "promise reaction",+ "queueMicrotask() callback",+ ];++ setTimeout(() => note("timer"), 0);+ const channel = new MessageChannel();+ channel.port1.onmessage = () => note("posted message");+ channel.port2.postMessage("x");+ requestAnimationFrame(() => note("animation frame callback"));+ Promise.resolve().then(() => note("promise reaction"));+ queueMicrotask(() => note("queueMicrotask() callback"));++ importScripts(event.data);++ const results = [+ `The imported script ran: ${self.importedScriptRan === true}`,+ `Ran while importScripts() was blocked: ${log.join(", ") || "(nothing)"}`,+ ];++ const report = () => {+ const missing = armed.filter(entry => !log.includes(entry));+ const duplicated = armed.filter(entry => log.filter(logged => logged === entry).length > 1);+ const firstTask = Math.min(log.indexOf("timer"), log.indexOf("posted message"));+ const promiseReaction = log.indexOf("promise reaction");+ const queuedMicrotask = log.indexOf("queueMicrotask() callback");+ results.push(`Never ran after importScripts() returned: ${missing.join(", ") || "(none)"}`);+ results.push(`Ran more than once: ${duplicated.join(", ") || "(none)"}`);+ results.push(+ `The microtasks ran before the tasks: ${promiseReaction < firstTask && queuedMicrotask < firstTask}`+ );+ results.push(`The microtasks ran in the order they were queued: ${promiseReaction < queuedMicrotask}`);+ self.postMessage(results);+ };++ requestAnimationFrame(() => setTimeout(report, 0));+};