Truly independent web browser
LibWeb: Gate fetch end-of-body per body intent
Luke Wildef47907809399
diff --git a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cppindex e02afc60fe9..0f3eb5d64e9 100644--- a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp@@ -202,7 +202,7 @@ void BodyStreamPullSource::settle_stream(Engine::FetchByteChannel::TakeResult co// AD-HOC: A sync XHR send() pauses the HTML event loop while it waits for exactly these bytes, and a stream set up// under that pause never starts pulling: the start promise's reaction is a microtask. So while the loop is// paused, bytes are pushed into the stream as they arrive, the way the specification's in-parallel steps-// would deliver them (see the parallel-queue path in fetch_response_handover()).+// would deliver them (see the sync XHR body path in fetch_response_handover()).void BodyStreamPullSource::deliver_while_paused(){// A pending pull's wake carries these bytes to run_pull_task() itself.diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex 81b2deee857..5059b8d6f7e 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -292,7 +292,7 @@ GC::Ref<Infrastructure::FetchController> fetch(JS::Realm& realm, Infrastructure:request.credentials_mode(),request.integrity_metadata(),on_preloaded_response_available,- fetch_params->task_destination(),+ fetch_params->algorithms()->body_intent(),preload_reports_timing);fetch_params->set_preload_reports_timing(preload_reports_timing);@@ -963,9 +963,11 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams constauto algorithms = fetch_params.algorithms();- // AD-HOC: A parallel-queue task destination with a process-response-consume-body algorithm is a sync XHR send()+ auto body_intent = algorithms->body_intent();++ // AD-HOC: A fetch whose body intent is SyncAccumulate is a sync XHR send()// (https://xhr.spec.whatwg.org/#the-send()-method, step 12) — or a preload fetch that "consume a preloaded- // resource" re-targeted onto a parallel queue for one. While that send() is blocked, the HTML event loop is+ // resource" re-targeted for one. While that send() is blocked, the HTML event loop is// paused (https://html.spec.whatwg.org/multipage/#pause): It runs no tasks and performs no microtask// checkpoints. But the identity-TransformStream pipe in step 7 and Body::fully_read() in step 8.4 progress// only thru promise-reaction microtasks — so they'd never complete. Nor could they when send() was invoked@@ -974,7 +976,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const// delivery and stream close fulfill pending read requests synchronously), and once the read completes, run// processResponseEndOfBody — which the pipe's flush algorithm would otherwise have — and then processBody,// in the order the parallel queue would have run them.- bool read_body_in_parallel = fetch_params.task_destination().has<NonnullRefPtr<HTML::ParallelQueue>>() && algorithms->process_response_consume_body();+ bool read_body_in_parallel = body_intent == Engine::BodyIntent::SyncAccumulate;// AD-HOC: That direct read runs processResponseEndOfBody and processBody itself. processResponse (step 4 above)// and processResponseEndOfBody's task (step 3) are queued either way — onto a parallel queue backed by the@@ -982,6 +984,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const// and run after the body they precede was consumed. No caller sets either; assert it, so that adding one// fails here instead of silently reordering the algorithms.if (read_body_in_parallel) {+ VERIFY(algorithms->process_response_consume_body());VERIFY(!algorithms->process_response());VERIFY(!algorithms->process_response_end_of_body());}@@ -991,32 +994,53 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams constprocess_response_end_of_body();}// 7. Otherwise:- // AD-HOC: Not when the body is read in parallel (see read_body_in_parallel above): processResponseEndOfBody then- // runs once the direct read of the stream below completes.- else if (!read_body_in_parallel) {- HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };+ else {+ switch (body_intent) {+ case Engine::BodyIntent::DeliverStreamToConsumerAgent:+ case Engine::BodyIntent::ConsumeForCallback: {+ HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- // 1. Let transformStream be a new TransformStream.- auto transform_stream = Streams::TransformStream::create(realm);+ // 1. Let transformStream be a new TransformStream.+ auto transform_stream = Streams::TransformStream::create(realm);- // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream.- auto identity_transform_algorithm = GC::create_function(GC::Heap::the(), [&realm, transform_stream](JS::Value chunk) -> GC::Ref<WebIDL::Promise> {- if (auto result = transform_stream->enqueue(chunk); result.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, result.release_error());+ // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream.+ auto identity_transform_algorithm = GC::create_function(GC::Heap::the(), [&realm, transform_stream](JS::Value chunk) -> GC::Ref<WebIDL::Promise> {+ if (auto result = transform_stream->enqueue(chunk); result.is_error())+ return WebIDL::create_rejected_promise_from_exception(realm, result.release_error());- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });+ return WebIDL::create_resolved_promise(realm, JS::js_undefined());+ });- // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm set- // to processResponseEndOfBody.- auto flush_algorithm = GC::create_function(GC::Heap::the(), [&realm, process_response_end_of_body]() -> GC::Ref<WebIDL::Promise> {- process_response_end_of_body();- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });- transform_stream->set_up(realm, identity_transform_algorithm, flush_algorithm);+ // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm set+ // to processResponseEndOfBody.+ auto flush_algorithm = GC::create_function(GC::Heap::the(), [&realm, process_response_end_of_body]() -> GC::Ref<WebIDL::Promise> {+ process_response_end_of_body();+ return WebIDL::create_resolved_promise(realm, JS::js_undefined());+ });+ transform_stream->set_up(realm, identity_transform_algorithm, flush_algorithm);- // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream.- internal_response->body()->set_stream(internal_response->body()->stream()->piped_through(transform_stream));+ // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream.+ internal_response->body()->set_stream(internal_response->body()->stream()->piped_through(transform_stream));+ break;+ }+ case Engine::BodyIntent::DrainAndDiscard: {+ // AD-HOC: No algorithm reads this body, so the pipe above would never flush, and a body larger than the+ // transport's credit would stall its transfer. Read the body to its end and drop it, then run+ // processResponseEndOfBody as the flush would have.+ VERIFY(!algorithms->process_response_consume_body());+ auto discard_chunk = GC::create_function(GC::Heap::the(), [](ByteBuffer) { });+ auto end_of_body = GC::create_function(GC::Heap::the(), [process_response_end_of_body] {+ process_response_end_of_body();+ });+ auto discard_error = GC::create_function(GC::Heap::the(), [](JS::Value) { });+ internal_response->body()->incrementally_read(realm, discard_chunk, end_of_body, discard_error, fetch_params.task_destination());+ break;+ }+ case Engine::BodyIntent::SyncAccumulate:+ // AD-HOC: processResponseEndOfBody runs once the direct read of the stream below completes (see+ // read_body_in_parallel above).+ break;+ }}// 8. If fetchParams’s process response consume body is non-null, then:@@ -1046,7 +1070,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const// 3. If internalResponse's body is null, then queue a fetch task to run processBody given null, with// fetchParams’s task destination.if (!internal_response->body()) {- // AD-HOC: On a parallel-queue task destination, run processBody directly (see read_body_in_parallel above;+ // AD-HOC: For a sync XHR's body, run processBody directly (see read_body_in_parallel above;// processResponseEndOfBody already ran, right after it).if (read_body_in_parallel) {(algorithms->process_response_consume_body())(response, Empty {});@@ -1060,8 +1084,8 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const}// 4. Otherwise, fully read internalResponse body given processBody, processBodyError, and fetchParams’s task// destination.- // AD-HOC: On a parallel-queue task destination, read the stream directly, without the event loop (see the- // comment at read_body_in_parallel above).+ // AD-HOC: For a sync XHR's body, read the stream directly, without the event loop (see the comment at+ // read_body_in_parallel above).else if (read_body_in_parallel) {HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cppindex 94b4c83be03..d74ce3d6443 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cpp@@ -30,6 +30,18 @@ GC::Ref<FetchAlgorithms> FetchAlgorithms::create(Input input)process_response_consume_body);}+GC::Ref<FetchAlgorithms> FetchAlgorithms::with_body_intent(Engine::BodyIntent body_intent) const+{+ return GC::Heap::the().allocate<FetchAlgorithms>(+ body_intent,+ m_process_request_body_chunk_length,+ m_process_request_end_of_body,+ m_process_early_hints_response,+ m_process_response,+ m_process_response_end_of_body,+ m_process_response_consume_body);+}+FetchAlgorithms::FetchAlgorithms(Engine::BodyIntent body_intent,ProcessRequestBodyChunkLengthHeapFunction process_request_body_chunk_length,diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.hindex d4dcf5e2113..329145477de 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.h@@ -56,6 +56,7 @@ public:};[[nodiscard]] static GC::Ref<FetchAlgorithms> create(Input);+ [[nodiscard]] GC::Ref<FetchAlgorithms> with_body_intent(Engine::BodyIntent) const;Engine::BodyIntent body_intent() const { return m_body_intent; }ProcessRequestBodyChunkLengthFunction const& process_request_body_chunk_length() const { return m_process_request_body_chunk_length->function(); }diff --git a/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cppindex fe591bd8560..619bab21c3e 100644--- a/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp+++ b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp@@ -233,7 +233,7 @@ void issue_speculative_module_fetch(DOM::Document& document, URL::URL const& urlFetch::Infrastructure::Request::Destination::SharedWorker,Fetch::Infrastructure::Request::Destination::ServiceWorker))request->set_mode(Fetch::Infrastructure::Request::Mode::SameOrigin);- request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Script);+ // NB: The request has no initiator type: only the fetch that uses the response reports its timing.set_up_module_script_request(request, options);Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::DrainAndDiscard };diff --git a/Libraries/LibWeb/HTML/PreloadEntry.cpp b/Libraries/LibWeb/HTML/PreloadEntry.cppindex 70ae87531a9..e01ca2b10bf 100644--- a/Libraries/LibWeb/HTML/PreloadEntry.cpp+++ b/Libraries/LibWeb/HTML/PreloadEntry.cpp@@ -62,7 +62,7 @@ bool consume_a_preloaded_resource(Fetch::Infrastructure::Request::CredentialsMode credentials_mode,Utf16View integrity_metadata,GC::Ref<GC::Function<void(GC::Ref<Fetch::Infrastructure::Response>)>> on_response_available,- Fetch::Infrastructure::TaskDestination const& consumer_task_destination,+ Fetch::Engine::BodyIntent consumer_body_intent,bool& preload_reports_timing){// 1. Let key be a preload key whose URL is url, destination is destination, mode is mode, and credentials mode is@@ -93,12 +93,12 @@ bool consume_a_preloaded_resource(// then return false.(void)integrity_metadata;- // AD-HOC: A consumer on a parallel queue (a sync XHR send(), whose event loop is paused while it's blocked) can't- // park on an in-flight entry whose fetch's response has already arrived: Its delivery and processing are- // already queued against the event loop, beyond the reach of step 9's re-targeting — so they can't hand- // the response over. Return false, so the consumer fetches on its own (as Blink/WebKit have every sync- // request do; see step 9), and leave the entry in the map: The preload completes once the loop resumes.- if (!entry->response && consumer_task_destination.has<NonnullRefPtr<ParallelQueue>>() && entry->controller+ // AD-HOC: A sync XHR consumer, whose event loop is paused while it's blocked, can't park on an in-flight entry whose+ // fetch's response has already arrived: Its delivery and processing are already queued against the event+ // loop, beyond the reach of step 9's re-targeting, so they can't hand the response over. Return false, so+ // the consumer fetches on its own (as Blink/WebKit have every sync request do; see step 9), and leave the+ // entry in the map: The preload completes once the loop resumes.+ if (!entry->response && consumer_body_intent == Fetch::Engine::BodyIntent::SyncAccumulate && entry->controller&& entry->controller->response_arrived()) {return false;}@@ -120,16 +120,18 @@ bool consume_a_preloaded_resource(if (!entry->response) {entry->on_response_available = on_response_available;- // AD-HOC: A consumer on a parallel queue has its event loop paused while it waits (sync XHR send()) — so the- // preload's fetch, whose response is otherwise handed over thru event-loop tasks, could never deliver.- // Move it onto a parallel queue of its own: fetch response handover then reads its body and runs its+ // AD-HOC: A sync XHR consumer has its event loop paused while it waits, so the preload's fetch, whose response+ // is otherwise handed over thru event-loop tasks, could never deliver. Move it onto a parallel queue of+ // its own, with the consumer's body intent: fetch response handover then reads its body and runs its// algorithms without the event loop, as it does for the consumer. Gecko too lets a sync XHR consume an// in-flight preload (XMLHttpRequestMainThread::FindPreload, FetchPreloader::AsyncConsume); Blink never// reuses a resource for a sync request (Resource::CanReuse), and WebKit's sync load bypasses its cache// and preloads (DocumentThreadableLoader::loadRequest).- if (consumer_task_destination.has<NonnullRefPtr<ParallelQueue>>() && entry->controller) {- if (auto fetch_params = entry->controller->fetch_params())+ if (consumer_body_intent == Fetch::Engine::BodyIntent::SyncAccumulate && entry->controller) {+ if (auto fetch_params = entry->controller->fetch_params()) {fetch_params->set_task_destination(ParallelQueue::create());+ fetch_params->set_algorithms(fetch_params->algorithms()->with_body_intent(consumer_body_intent));+ }}}// 10. Otherwise, call onResponseAvailable with entry's response.diff --git a/Libraries/LibWeb/HTML/PreloadEntry.h b/Libraries/LibWeb/HTML/PreloadEntry.hindex 8ebc0f07bda..5cd745b6006 100644--- a/Libraries/LibWeb/HTML/PreloadEntry.h+++ b/Libraries/LibWeb/HTML/PreloadEntry.h@@ -13,8 +13,8 @@#include <LibGC/Ptr.h>#include <LibJS/Heap/Cell.h>#include <LibURL/URL.h>+#include <LibWeb/Fetch/Engine/BodyIntent.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>-#include <LibWeb/Fetch/Infrastructure/Task.h>#include <LibWeb/Forward.h>namespace Web::HTML {@@ -70,9 +70,9 @@ public:// or the response delivered by the preload's fetch.GC::Ptr<GC::Function<void(GC::Ref<Fetch::Infrastructure::Response>)>> on_response_available;- // AD-HOC: The controller of the fetch loading this entry. A consumer whose own fetch runs on a parallel queue (a- // sync XHR send(), whose event loop is paused while it's blocked) re-targets that fetch thru this, so it- // delivers its response without the event loop as well; see consume_a_preloaded_resource().+ // AD-HOC: The controller of the fetch loading this entry. A sync XHR consumer, whose event loop is paused while it's+ // blocked, re-targets that fetch thru this, so it delivers its response without the event loop as well; see+ // consume_a_preloaded_resource().GC::Ptr<Fetch::Infrastructure::FetchController> controller;// AD-HOC: Whether this entry offers a speculative fetch's response to the normal parser's fetch.@@ -88,7 +88,7 @@ bool consume_a_preloaded_resource(Fetch::Infrastructure::Request::CredentialsMode credentials_mode,Utf16View integrity_metadata,GC::Ref<GC::Function<void(GC::Ref<Fetch::Infrastructure::Response>)>> on_response_available,- Fetch::Infrastructure::TaskDestination const& consumer_task_destination,+ Fetch::Engine::BodyIntent consumer_body_intent,bool& preload_reports_timing);// AD-HOC: Speculative fetches' responses that the normal parser didn't use must not be handed to a later fetch.diff --git a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp b/Libraries/LibWeb/XHR/XMLHttpRequest.cppindex 89fd3031731..1156a6558d5 100644--- a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp+++ b/Libraries/LibWeb/XHR/XMLHttpRequest.cpp@@ -1101,7 +1101,7 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(NullableDocumentOrXMLHttpRequestB// (https://html.spec.whatwg.org/multipage/webappapis.html#pause). The fetch above runs on a parallel// queue, and progresses on the platform event loop (deferred invocations, IPC, timers) — all that's// pumped here. So, the response arrives and is read to completion while the HTML event loop stays- // paused; see the parallel-queue path in fetch_response_handover(), and the direct delivery in+ // paused; see the sync XHR body path in fetch_response_handover(), and the direct delivery in// BodyStreamPullSource::deliver_while_paused(). Blink/WebKit block the thread outright for a sync load:// Blink on a WaitableEvent (ResourceRequestSender::SendSync), WebKit on a sync IPC reply// (WebLoaderStrategy::loadResourceSynchronously). Gecko instead spins a nested event loopdiff --git a/Tests/LibWeb/Text/expected/Fetch/sendbeacon-large-response-completes.txt b/Tests/LibWeb/Text/expected/Fetch/sendbeacon-large-response-completes.txtnew file mode 100644index 00000000000..8976a88d209--- /dev/null+++ b/Tests/LibWeb/Text/expected/Fetch/sendbeacon-large-response-completes.txt@@ -0,0 +1,2 @@+beacon queued: true+initiator type: beacondiff --git a/Tests/LibWeb/Text/input/Fetch/sendbeacon-large-response-completes.html b/Tests/LibWeb/Text/input/Fetch/sendbeacon-large-response-completes.htmlnew file mode 100644index 00000000000..229db94ce36--- /dev/null+++ b/Tests/LibWeb/Text/input/Fetch/sendbeacon-large-response-completes.html@@ -0,0 +1,31 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A response no algorithm reads is still read to its end: a beacon whose response is larger than the+ // transport's credit completes and records its timing.+ asyncTest(async done => {+ const httpServer = httpTestServer();+ const size = 2 * 1024 * 1024;+ const url = await httpServer.createEcho("POST", `/beacon-${crypto.randomUUID()}`, {+ status: 200,+ headers: { "Content-Type": "application/octet-stream" },+ body: "x".repeat(size),+ });++ const timingEntry = new Promise(resolve => {+ new PerformanceObserver((list, observer) => {+ for (const entry of list.getEntries()) {+ if (entry.name === url) {+ observer.disconnect();+ resolve(entry);+ }+ }+ }).observe({ type: "resource", buffered: true });+ });++ println(`beacon queued: ${navigator.sendBeacon(url, "ping")}`);+ const entry = await timingEntry;+ println(`initiator type: ${entry.initiatorType}`);+ done();+ });+</script>