Truly independent web browser
LibWeb: Report a fetch's request body progress to its agent as events
Luke Wilde9e59b68c7229
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex f6743a28824..7f6abe21f1b 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -307,6 +307,7 @@ set(SOURCESFetch/Fetching/ClientContextSnapshots.cppFetch/Fetching/NetworkBodyPump.cppFetch/Fetching/FetchEngine.cpp+ Fetch/Fetching/FetchEventSink.cppFetch/Fetching/Fetching.cppFetch/Fetching/PendingResponse.cppFetch/Fetching/RefCountedFlag.cppdiff --git a/Libraries/LibWeb/Fetch/Engine/EngineEvent.h b/Libraries/LibWeb/Fetch/Engine/EngineEvent.hindex f56c32024bf..4b47c50a5e1 100644--- a/Libraries/LibWeb/Fetch/Engine/EngineEvent.h+++ b/Libraries/LibWeb/Fetch/Engine/EngineEvent.h@@ -71,6 +71,22 @@ struct RequestTransmissionEnded {RequestEnd request_end;};+// The length of one more chunk of a request's body.+struct RequestBodyProgress {+ u64 length { 0 };+};++// The end of a request's body after its last chunk, or the end of a null body.+struct RequestBodyEndOfBody {+ bool body_is_null { false };+};++// Asks the fetch's agent to read a request's body from its stream, the only place its bytes are.+struct ReadRequestBodyStream { };++// A request's body is sent from its source.+struct RequestBodySentFromSource { };+}namespace Web::Fetch::Engine {@@ -82,6 +98,10 @@ using EngineEvent = Variant<Event::BodyChannelReadable,Event::DeliveryEnd,Event::RequestTransmissionStarted,- Event::RequestTransmissionEnded>;+ Event::RequestTransmissionEnded,+ Event::RequestBodyProgress,+ Event::RequestBodyEndOfBody,+ Event::ReadRequestBodyStream,+ Event::RequestBodySentFromSource>;}diff --git a/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.h b/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.hnew file mode 100644index 00000000000..ef89cb8d72b--- /dev/null+++ b/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.h@@ -0,0 +1,35 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/NonnullOwnPtr.h>+#include <AK/NonnullRefPtr.h>+#include <AK/RefCounted.h>+#include <LibWeb/Fetch/Engine/EngineEventSink.h>++namespace Web::Fetch::Engine {++// What the fetch engine keeps of a fetch it has started.+class FetchEngineRecord final : public RefCounted<FetchEngineRecord> {+public:+ [[nodiscard]] static NonnullRefPtr<FetchEngineRecord> create(NonnullOwnPtr<EngineEventSink> event_sink)+ {+ return adopt_ref(*new FetchEngineRecord(move(event_sink)));+ }++ [[nodiscard]] EngineEventSink& event_sink() { return *m_event_sink; }++private:+ explicit FetchEngineRecord(NonnullOwnPtr<EngineEventSink> event_sink)+ : m_event_sink(move(event_sink))+ {+ }++ NonnullOwnPtr<EngineEventSink> m_event_sink;+};++}diff --git a/Libraries/LibWeb/Fetch/Engine/StartFetchInput.h b/Libraries/LibWeb/Fetch/Engine/StartFetchInput.hindex d19c18ebb89..f14e351dcc4 100644--- a/Libraries/LibWeb/Fetch/Engine/StartFetchInput.h+++ b/Libraries/LibWeb/Fetch/Engine/StartFetchInput.h@@ -7,8 +7,10 @@#pragma once#include <AK/Badge.h>+#include <AK/NonnullOwnPtr.h>#include <AK/Optional.h>#include <LibWeb/Fetch/Engine/BodyIntent.h>+#include <LibWeb/Fetch/Engine/EngineEventSink.h>#include <LibWeb/Fetch/Engine/Ids.h>#include <LibWebCommon/FileAPI/SerializedBlobURLEntry.h>@@ -21,10 +23,11 @@ class FetchParams;namespace Web::Fetch::Engine {struct StartFetchInput {- StartFetchInput(Badge<Infrastructure::FetchParams>, FetchId fetch_id, BodyIntent body_intent, Optional<FileAPI::SerializedBlobURLEntry> blob_url_entry)+ StartFetchInput(Badge<Infrastructure::FetchParams>, FetchId fetch_id, BodyIntent body_intent, Optional<FileAPI::SerializedBlobURLEntry> blob_url_entry, NonnullOwnPtr<EngineEventSink> event_sink): fetch_id(fetch_id), body_intent(body_intent), blob_url_entry(move(blob_url_entry))+ , event_sink(move(event_sink)){}@@ -33,6 +36,8 @@ struct StartFetchInput {// Resolved by the agent that starts the fetch, at fetch start.Optional<FileAPI::SerializedBlobURLEntry> blob_url_entry;++ NonnullOwnPtr<EngineEventSink> event_sink;};}diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchEngine.cpp b/Libraries/LibWeb/Fetch/Fetching/FetchEngine.cppindex 0b6c8d3cd3f..aa424f7630b 100644--- a/Libraries/LibWeb/Fetch/Fetching/FetchEngine.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/FetchEngine.cpp@@ -5,6 +5,7 @@*/#include <LibCore/EventLoop.h>+#include <LibWeb/Fetch/Engine/FetchEngineRecord.h>#include <LibWeb/Fetch/Engine/InlineFetchExecutor.h>#include <LibWeb/Fetch/Fetching/FetchEngine.h>#include <LibWeb/Fetch/Fetching/Fetching.h>@@ -14,8 +15,9 @@ namespace Web::Fetch::Fetching {void FetchEngine::handle_command(Engine::EngineCommand command){command.visit(- [](Engine::Command::StartFetch const& start_fetch) {- run_deferred_main_fetch_steps(start_fetch.input.fetch_id);+ [](Engine::Command::StartFetch& start_fetch) {+ auto record = Engine::FetchEngineRecord::create(move(start_fetch.input.event_sink));+ run_deferred_main_fetch_steps(start_fetch.input.fetch_id, move(record));},[](Engine::Command::Abort const&) { VERIFY_NOT_REACHED(); },[](Engine::Command::Terminate const&) { VERIFY_NOT_REACHED(); },diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.cpp b/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.cppnew file mode 100644index 00000000000..cced6b276c1--- /dev/null+++ b/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.cpp@@ -0,0 +1,178 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibGC/Function.h>+#include <LibGC/Heap.h>+#include <LibWeb/Fetch/Fetching/FetchEventSink.h>+#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>+#include <LibWeb/Fetch/Infrastructure/FetchController.h>+#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>+#include <LibWeb/Fetch/Infrastructure/Task.h>+#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>+#include <LibWeb/WebIDL/DOMException.h>++namespace Web::Fetch::Fetching {++FetchEventSink::FetchEventSink(Infrastructure::FetchController const& controller)+ : m_controller_token(controller.token())+ , m_controller_registry(controller.registry())+{+}++GC::Ref<Infrastructure::FetchController> FetchEventSink::controller() const+{+ VERIFY(m_controller_registry);+ auto controller = m_controller_registry->find(m_controller_token);+ VERIFY(controller);+ return *controller;+}++// https://fetch.spec.whatwg.org/#fetch-params-canceled+static bool is_canceled(Infrastructure::FetchController const& controller)+{+ // A fetch params fetchParams is canceled if its controller’s state is "aborted" or "terminated".+ auto state = controller.state();+ return state == Infrastructure::FetchController::State::Aborted || state == Infrastructure::FetchController::State::Terminated;+}++// https://fetch.spec.whatwg.org/#concept-http-network-fetch+// The processBodyChunk steps of transmitting request's body.+// NB: The steps read only bytes's length, so they are given it.+static void process_body_chunk(Infrastructure::FetchController& controller, u64 length)+{+ // 1. If fetchParams is canceled, then abort these steps.+ if (is_canceled(controller))+ return;++ // 2. Run this step in parallel: transmit bytes.+ // NB: The fetch engine loads a body's source whole, with its request.++ // 3. If fetchParams’s process request body chunk length is non-null, then run fetchParams’s process request body+ // chunk length given bytes’s length.+ if (controller.algorithms()->process_request_body_chunk_length())+ controller.algorithms()->process_request_body_chunk_length()->function()(length);+}++// https://fetch.spec.whatwg.org/#concept-http-network-fetch+// The processEndOfBody steps of transmitting request's body.+static void process_end_of_body(Infrastructure::FetchController& controller)+{+ // 1. If fetchParams is canceled, then abort these steps.+ if (is_canceled(controller))+ return;++ // 2. If fetchParams’s process request end-of-body is non-null, then run fetchParams’s process request+ // end-of-body.+ if (controller.algorithms()->process_request_end_of_body())+ controller.algorithms()->process_request_end_of_body()->function()();+}++// https://fetch.spec.whatwg.org/#concept-http-network-fetch+// The step of transmitting request's body for a null body.+static void transmit_null_request_body(GC::Ref<Infrastructure::FetchController> controller)+{+ // 1. If body is null and fetchParams’s process request end-of-body is non-null, then queue a fetch task given+ // fetchParams’s process request end-of-body and fetchParams’s task destination.+ if (!controller->algorithms()->process_request_end_of_body())+ return;+ Infrastructure::queue_fetch_task(controller, controller->task_destination(), GC::create_function(GC::Heap::the(), GC::captures(controller), [](auto& controller) {+ controller->algorithms()->process_request_end_of_body()->function()();+ }));+}++// https://fetch.spec.whatwg.org/#concept-http-network-fetch+// The steps of transmitting request's body that read a body without a source from its stream.+static void read_request_body_stream(GC::Ref<Infrastructure::FetchController> controller)+{+ auto const& request_body_reader = controller->algorithms()->request_body_reader();+ if (!request_body_reader.has_value())+ return;++ auto const& task_destination = controller->task_destination();+ auto& realm = HTML::relevant_realm(*task_destination.get<GC::Ref<JS::Object>>());++ // 3. Let processBodyError given e be these steps:+ auto process_body_error = GC::create_function(GC::Heap::the(), GC::captures(realm, controller), [](auto& realm, auto& controller, JS::Value error) {+ // 1. If fetchParams is canceled, then abort these steps.+ if (is_canceled(controller))+ return;++ // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.+ auto const* exception = error.is_object() ? Bindings::dom_exception_from_object(error.as_object()) : nullptr;+ if (exception && exception->name() == "AbortError"_utf16_fly_string)+ controller->abort(realm, {});+ // 3. Otherwise, terminate fetchParams’s controller.+ else+ controller->terminate();+ });++ // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, processBodyError, and+ // fetchParams’s task destination.+ // FIXME: Send the bytes read here to RequestServer, which only receives a body's source.+ auto process_body_chunk_steps = GC::create_function(GC::Heap::the(), GC::captures(controller), [](auto& controller, ByteBuffer bytes) {+ process_body_chunk(controller, bytes.size());+ });+ auto process_end_of_body_steps = GC::create_function(GC::Heap::the(), GC::captures(controller), [](auto& controller) {+ process_end_of_body(controller);+ });+ HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };+ request_body_reader->body->incrementally_read_loop(request_body_reader->reader, task_destination, process_body_chunk_steps, process_end_of_body_steps, process_body_error);+}++// AD-HOC: A body with a source is sent from its source, but its stream has to be read all the same: Canceling a stream+// teed from it (that of a clone of the Request, e.g.) waits until it is read to its end, or canceled.+static void drain_request_body_stream(GC::Ref<Infrastructure::FetchController> controller)+{+ auto const& request_body_reader = controller->algorithms()->request_body_reader();+ if (!request_body_reader.has_value())+ return;++ auto const& task_destination = controller->task_destination();+ auto& realm = HTML::relevant_realm(*task_destination.get<GC::Ref<JS::Object>>());+ auto ignore_chunk = GC::create_function(GC::Heap::the(), [](ByteBuffer) { });+ auto ignore_end_of_body = GC::create_function(GC::Heap::the(), [] { });+ auto ignore_error = GC::create_function(GC::Heap::the(), [](JS::Value) { });+ HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };+ request_body_reader->body->incrementally_read_loop(request_body_reader->reader, task_destination, ignore_chunk, ignore_end_of_body, ignore_error);+}++void FetchEventSink::handle_event(Engine::EngineEvent event)+{+ VERIFY(m_agent_thread_id.is_current_thread());+ auto controller = this->controller();++ event.visit(+ [&](Engine::Event::RequestBodyProgress const& progress) {+ Infrastructure::queue_fetch_task(controller, controller->task_destination(), GC::create_function(GC::Heap::the(), GC::captures(controller, progress.length), [](auto& controller, auto& length) {+ process_body_chunk(controller, length);+ }));+ },+ [&](Engine::Event::RequestBodyEndOfBody const& end_of_body) {+ if (end_of_body.body_is_null) {+ transmit_null_request_body(controller);+ return;+ }+ Infrastructure::queue_fetch_task(controller, controller->task_destination(), GC::create_function(GC::Heap::the(), GC::captures(controller), [](auto& controller) {+ process_end_of_body(controller);+ }));+ },+ [&](Engine::Event::ReadRequestBodyStream const&) {+ read_request_body_stream(controller);+ },+ [&](Engine::Event::RequestBodySentFromSource const&) {+ drain_request_body_stream(controller);+ },+ [](Engine::Event::ResponseDelivery const&) { VERIFY_NOT_REACHED(); },+ [](Engine::Event::EndOfBody const&) { VERIFY_NOT_REACHED(); },+ [](Engine::Event::ConsumeBodyResult const&) { VERIFY_NOT_REACHED(); },+ [](Engine::Event::BodyChannelReadable const&) { VERIFY_NOT_REACHED(); },+ [](Engine::Event::DeliveryEnd const&) { VERIFY_NOT_REACHED(); },+ [](Engine::Event::RequestTransmissionStarted const&) { VERIFY_NOT_REACHED(); },+ [](Engine::Event::RequestTransmissionEnded const&) { VERIFY_NOT_REACHED(); });+}++}diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.h b/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.hnew file mode 100644index 00000000000..b728fd1f5e9--- /dev/null+++ b/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.h@@ -0,0 +1,35 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/ThreadID.h>+#include <AK/WeakPtr.h>+#include <LibGC/Ptr.h>+#include <LibWeb/Export.h>+#include <LibWeb/Fetch/Engine/EngineEventSink.h>+#include <LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h>+#include <LibWeb/Fetch/Infrastructure/FetchControllerToken.h>+#include <LibWeb/Forward.h>++namespace Web::Fetch::Fetching {++// Receives a fetch's events on the agent that started the fetch, without keeping the fetch's controller alive.+class WEB_API FetchEventSink final : public Engine::EngineEventSink {+public:+ explicit FetchEventSink(Infrastructure::FetchController const&);++ virtual void handle_event(Engine::EngineEvent) override;++private:+ [[nodiscard]] GC::Ref<Infrastructure::FetchController> controller() const;++ Infrastructure::FetchControllerToken m_controller_token;+ WeakPtr<Infrastructure::FetchControllerRegistry> m_controller_registry;+ AK::ThreadID m_agent_thread_id { AK::ThreadID::current() };+};++}diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex ef49444f383..40cd7541086 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -35,6 +35,7 @@#include <LibWeb/Fetch/Fetching/BodyStreamPullSource.h>#include <LibWeb/Fetch/Fetching/Checks.h>#include <LibWeb/Fetch/Fetching/ClientContextSnapshots.h>+#include <LibWeb/Fetch/Fetching/FetchEventSink.h>#include <LibWeb/Fetch/Fetching/Fetching.h>#include <LibWeb/Fetch/Fetching/NetworkBodyPump.h>#include <LibWeb/Fetch/Fetching/PendingResponse.h>@@ -83,7 +84,6 @@#include <LibWeb/Streams/TransformStream.h>#include <LibWeb/UpgradeInsecureRequests/AbstractOperations.h>#include <LibWeb/WebDriver/BiDi/Network.h>-#include <LibWeb/WebIDL/DOMException.h>#include <LibWeb/WebIDL/ExceptionOrUtils.h>#include <LibWebCommon/Fetch/Infrastructure/DataURL.h>#include <LibWebCommon/Fetch/Infrastructure/HTTP/Statuses.h>@@ -833,7 +833,9 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam}// 11. If recursive is false, then run the remaining steps in parallel.- auto in_parallel_steps = GC::create_function<void()>(GC::Heap::the(), GC::captures(realm, NonnullRefPtr { fetch_params }, fetch_params.controller(), request, response, get_response), [](auto& realm, NonnullRefPtr<Infrastructure::FetchParams const>& fetch_params, GC::Ref<Infrastructure::FetchController>& controller, NonnullRefPtr<Infrastructure::Request>& request, RefPtr<Infrastructure::Response>& response, GC::Ref<GC::Function<GC::Ref<PendingResponse>()>>& get_response) {+ auto in_parallel_steps = GC::create_function<void(NonnullRefPtr<Engine::FetchEngineRecord>)>(GC::Heap::the(), GC::captures(realm, NonnullRefPtr { fetch_params }, fetch_params.controller(), request, response, get_response), [](auto& realm, NonnullRefPtr<Infrastructure::FetchParams const>& fetch_params, GC::Ref<Infrastructure::FetchController>& controller, NonnullRefPtr<Infrastructure::Request>& request, RefPtr<Infrastructure::Response>& response, GC::Ref<GC::Function<GC::Ref<PendingResponse>()>>& get_response, NonnullRefPtr<Engine::FetchEngineRecord> engine_record) {+ fetch_params->set_engine_record(move(engine_record));+// 12. If response is null, then set response to the result of running the steps corresponding to the first// matching statement:auto pending_response = PendingResponse::create(controller, Infrastructure::Response::create());@@ -998,17 +1000,18 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam});auto& agent = HTML::relevant_agent(realm.global_object());auto fetch_id = agent.fetch_controller_registry.defer_main_fetch_steps(in_parallel_steps);- auto start_fetch_input = fetch_params.start_fetch_input(fetch_id);+ auto event_sink = make<FetchEventSink>(*fetch_params.controller());+ auto start_fetch_input = fetch_params.start_fetch_input(fetch_id, move(event_sink));agent.fetch_executor->post(Engine::Command::StartFetch { move(start_fetch_input) });return GC::Ptr<PendingResponse> {};}-void run_deferred_main_fetch_steps(Engine::FetchId fetch_id)+void run_deferred_main_fetch_steps(Engine::FetchId fetch_id, NonnullRefPtr<Engine::FetchEngineRecord> engine_record){// An agent's fetch engine runs on the agent's thread.auto steps = HTML::surrounding_agent().fetch_controller_registry.take_deferred_main_fetch_steps(fetch_id);- steps->function()();+ steps->function()(move(engine_record));}using RequestEnvironment = Variant<Empty, NonnullRefPtr<Infrastructure::ReservedClientContextSnapshot const>, NonnullRefPtr<Infrastructure::ClientContextSnapshot const>>;@@ -3065,106 +3068,50 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(}// To transmit request’s body body, run these steps:- // 1. If body is null and fetchParams’s process request end-of-body is non-null, then queue a fetch task given- // fetchParams’s process request end-of-body and fetchParams’s task destination.- if (request->body().has<Empty>()) {- if (fetch_params.controller()->algorithms()->process_request_end_of_body()) {- Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.controller()->task_destination(), GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { fetch_params }), [](auto& fetch_params) {- fetch_params->controller()->algorithms()->process_request_end_of_body()->function()();- }));- }- }- // 2. Otherwise, if body is non-null:- else if (auto const* body = request->body().get_pointer<Infrastructure::FetchBody>()) {- // 1. Let processBodyChunk given bytes be these steps:- // NB: The steps read only bytes's length, so they are given it.- auto process_body_chunk = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { fetch_params }, fetch_params.controller()), [](auto& fetch_params, auto& controller, u64 length) {- // 1. If fetchParams is canceled, then abort these steps.- if (fetch_params->is_canceled())- return;-- // 2. Run this step in parallel: transmit bytes.- // NB: A body's source was handed to RequestServer above.-- // 3. If fetchParams’s process request body chunk length is non-null, then run fetchParams’s process- // request body chunk length given bytes’s length.- if (controller->algorithms()->process_request_body_chunk_length())- controller->algorithms()->process_request_body_chunk_length()->function()(length);- });-- // 2. Let processEndOfBody be these steps:- auto process_end_of_body = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { fetch_params }, fetch_params.controller()), [](auto& fetch_params, auto& controller) {- // 1. If fetchParams is canceled, then abort these steps.- if (fetch_params->is_canceled())- return;-- // 2. If fetchParams’s process request end-of-body is non-null, then run fetchParams’s process request- // end-of-body.- if (controller->algorithms()->process_request_end_of_body())- controller->algorithms()->process_request_end_of_body()->function()();- });-- // 3. Let processBodyError given e be these steps:- auto process_body_error = GC::create_function(GC::Heap::the(), GC::captures(realm, NonnullRefPtr { fetch_params }, fetch_params.controller()), [](auto& realm, auto& fetch_params, auto& controller, JS::Value error) {- // 1. If fetchParams is canceled, then abort these steps.- if (fetch_params->is_canceled())- return;-- // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.- auto const* exception = error.is_object() ? Bindings::dom_exception_from_object(error.as_object()) : nullptr;- if (exception && exception->name() == "AbortError"_utf16_fly_string)- controller->abort(realm, {});- // 3. Otherwise, terminate fetchParams’s controller.- else- controller->terminate();- });-- // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, processBodyError, and- // fetchParams’s task destination.- // AD-HOC: A request holds its body's source and length but not its stream. A body with a source is read in the- // chunks RequestServer reports sending it in, when it goes over the network, and otherwise as one- // chunk of the whole source. A body without a source is read through the reader fetch() acquired for- // its stream.- auto const& source = body->source();- if (source.has_value() && source->size() > 0 && network_transport) {- network_transport->set_on_upload_progress([fetch_params = NonnullRefPtr { fetch_params }, process_body_chunk = GC::Root { process_body_chunk }, process_end_of_body = GC::Root { process_end_of_body }, length = source->size(), bytes_read = u64 { 0 }](u64 bytes_sent) mutable {- bytes_sent = min(bytes_sent, length);- if (bytes_sent <= bytes_read)- return;- auto chunk_length = bytes_sent - bytes_read;- bytes_read = bytes_sent;+ // NB: Only a CORS preflight's fetch params lack an engine record, and a preflight has no request body algorithms.+ if (auto* engine_record = fetch_params.engine_record()) {+ auto& event_sink = engine_record->event_sink();++ // 1. If body is null and fetchParams’s process request end-of-body is non-null, then queue a fetch task given+ // fetchParams’s process request end-of-body and fetchParams’s task destination.+ // NB: The fetch's event sink checks for process request end-of-body and queues the task, on the fetch's agent.+ if (request->body().has<Empty>()) {+ event_sink.handle_event(Engine::Event::RequestBodyEndOfBody { .body_is_null = true });+ }+ // 2. Otherwise, if body is non-null:+ // NB: The fetch's event sink defines processBodyChunk, processEndOfBody and processBodyError (steps 1 to 3),+ // and runs them on the fetch's agent.+ else if (auto const* body = request->body().get_pointer<Infrastructure::FetchBody>()) {+ // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, processBodyError, and+ // fetchParams’s task destination.+ // AD-HOC: A request holds its body's source and length but not its stream. A body with a source is read in+ // the chunks RequestServer reports sending it in, when it goes over the network, and otherwise as+ // one chunk of the whole source. A body without a source is read through the reader fetch()+ // acquired for its stream. If fetch() also acquired a reader for the stream of a body with a+ // source, the stream is read to its end through it, and what is read is ignored.+ auto const& source = body->source();+ if (source.has_value() && source->size() > 0 && network_transport) {+ network_transport->set_on_upload_progress([engine_record = NonnullRefPtr { *engine_record }, length = source->size(), bytes_read = u64 { 0 }](u64 bytes_sent) mutable {+ bytes_sent = min(bytes_sent, length);+ if (bytes_sent <= bytes_read)+ return;+ auto chunk_length = bytes_sent - bytes_read;+ bytes_read = bytes_sent;- auto controller = fetch_params->controller();- Infrastructure::queue_fetch_task(controller, controller->task_destination(), GC::create_function(GC::Heap::the(), GC::captures(process_body_chunk, chunk_length), [](auto& process_body_chunk, auto& chunk_length) {- process_body_chunk->function()(chunk_length);- }));- if (bytes_read == length)- Infrastructure::queue_fetch_task(controller, controller->task_destination(), GC::Ref { *process_end_of_body });- });- } else if (source.has_value()) {- if (auto length = source->size(); length > 0) {- Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.controller()->task_destination(), GC::create_function(GC::Heap::the(), GC::captures(process_body_chunk, length), [](auto& process_body_chunk, auto& length) {- process_body_chunk->function()(length);- }));+ engine_record->event_sink().handle_event(Engine::Event::RequestBodyProgress { chunk_length });+ if (bytes_read == length)+ engine_record->event_sink().handle_event(Engine::Event::RequestBodyEndOfBody {});+ });+ } else if (source.has_value()) {+ if (auto length = source->size(); length > 0)+ event_sink.handle_event(Engine::Event::RequestBodyProgress { length });+ event_sink.handle_event(Engine::Event::RequestBodyEndOfBody {});+ } else {+ event_sink.handle_event(Engine::Event::ReadRequestBodyStream {});}- Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.controller()->task_destination(), process_end_of_body);- } else if (auto const& request_body_reader = fetch_params.controller()->algorithms()->request_body_reader(); request_body_reader.has_value()) {- // FIXME: Send the bytes read here to RequestServer, which only receives a body's source.- auto process_body_chunk_bytes = GC::create_function(GC::Heap::the(), GC::captures(process_body_chunk), [](auto& process_body_chunk, ByteBuffer bytes) {- process_body_chunk->function()(bytes.size());- });- HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- request_body_reader->body->incrementally_read_loop(request_body_reader->reader, fetch_params.controller()->task_destination(), process_body_chunk_bytes, process_end_of_body, process_body_error);- }- // AD-HOC: A body with a source is sent from its source, but its stream has to be read all the same: A stream- // teed from it (that of a clone of the Request, e.g.) can't finish, or be canceled, until it is.- if (auto const& request_body_reader = fetch_params.controller()->algorithms()->request_body_reader(); source.has_value() && request_body_reader.has_value()) {- auto ignore_chunk = GC::create_function(GC::Heap::the(), [](ByteBuffer) { });- auto ignore_end_of_body = GC::create_function(GC::Heap::the(), [] { });- auto ignore_error = GC::create_function(GC::Heap::the(), [](JS::Value) { });- HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- request_body_reader->body->incrementally_read_loop(request_body_reader->reader, fetch_params.controller()->task_destination(), ignore_chunk, ignore_end_of_body, ignore_error);+ if (source.has_value())+ event_sink.handle_event(Engine::Event::RequestBodySentFromSource {});}}diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.h b/Libraries/LibWeb/Fetch/Fetching/Fetching.hindex 170b281f1dc..847fb0ea8ff 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.h+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.h@@ -18,6 +18,7 @@#include <LibRequests/RequestTransferLease.h>#include <LibURL/Forward.h>#include <LibWeb/Export.h>+#include <LibWeb/Fetch/Engine/FetchEngineRecord.h>#include <LibWeb/Fetch/Engine/Ids.h>#include <LibWeb/Fetch/Infrastructure/NetworkPartitionKey.h>#include <LibWeb/Forward.h>@@ -52,7 +53,7 @@ ENUMERATE_BOOL_PARAMSWEB_API GC::Ref<Infrastructure::FetchController> fetch(JS::Realm&, Infrastructure::Request&, Infrastructure::FetchAlgorithms const&, UseParallelQueue use_parallel_queue = UseParallelQueue::No, CreateResponseBodyTransferLease = CreateResponseBodyTransferLease::No);GC::Ptr<PendingResponse> main_fetch(JS::Realm&, Infrastructure::FetchParams const&, Recursive recursive = Recursive::No);// Runs the in-parallel steps that main fetch deferred under the id.-void run_deferred_main_fetch_steps(Engine::FetchId);+void run_deferred_main_fetch_steps(Engine::FetchId, NonnullRefPtr<Engine::FetchEngineRecord>);void populate_request_from_client(Infrastructure::Request&, Optional<HTML::FetchClient> const& client);void fetch_response_handover(JS::Realm&, Infrastructure::FetchParams const&, GC::Ref<Infrastructure::FetchController>, Infrastructure::Response&);GC::Ref<PendingResponse> scheme_fetch(JS::Realm&, Infrastructure::FetchParams const&);diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.cppindex 8446b74002f..15466ca1aea 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.cpp@@ -47,14 +47,14 @@ Vector<GC::Root<FetchController>> FetchControllerRegistry::controllers() constreturn controllers;}-Engine::FetchId FetchControllerRegistry::defer_main_fetch_steps(GC::Ref<GC::Function<void()>> steps)+Engine::FetchId FetchControllerRegistry::defer_main_fetch_steps(GC::Ref<DeferredMainFetchSteps> steps){Engine::FetchId fetch_id { s_next_fetch_id.fetch_add(1) };m_deferred_main_fetch_steps.set(fetch_id, GC::make_root(steps));return fetch_id;}-GC::Root<GC::Function<void()>> FetchControllerRegistry::take_deferred_main_fetch_steps(Engine::FetchId fetch_id)+GC::Root<FetchControllerRegistry::DeferredMainFetchSteps> FetchControllerRegistry::take_deferred_main_fetch_steps(Engine::FetchId fetch_id){return m_deferred_main_fetch_steps.take(fetch_id).release_value();}diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.hindex f72bdff5b45..438bb30ab8a 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h@@ -15,6 +15,7 @@#include <LibGC/Ptr.h>#include <LibGC/Root.h>#include <LibWeb/Export.h>+#include <LibWeb/Fetch/Engine/FetchEngineRecord.h>#include <LibWeb/Fetch/Engine/Ids.h>#include <LibWeb/Fetch/Infrastructure/FetchControllerToken.h>#include <LibWeb/Forward.h>@@ -27,6 +28,8 @@ class WEB_API FetchControllerRegistry : public Weakable<FetchControllerRegistry>AK_MAKE_NONMOVABLE(FetchControllerRegistry);public:+ using DeferredMainFetchSteps = GC::Function<void(NonnullRefPtr<Engine::FetchEngineRecord>)>;+FetchControllerRegistry();[[nodiscard]] FetchControllerToken add(Badge<FetchController>, FetchController&);@@ -37,13 +40,13 @@ public:[[nodiscard]] Vector<GC::Root<FetchController>> controllers() const;// Keeps main fetch's in-parallel steps alive while they wait to be taken.- [[nodiscard]] Engine::FetchId defer_main_fetch_steps(GC::Ref<GC::Function<void()>> steps);- [[nodiscard]] GC::Root<GC::Function<void()>> take_deferred_main_fetch_steps(Engine::FetchId);+ [[nodiscard]] Engine::FetchId defer_main_fetch_steps(GC::Ref<DeferredMainFetchSteps> steps);+ [[nodiscard]] GC::Root<DeferredMainFetchSteps> take_deferred_main_fetch_steps(Engine::FetchId);private:u64 m_id { 0 };HashMap<u64, GC::RawPtr<FetchController>> m_controllers;- HashMap<Engine::FetchId, GC::Root<GC::Function<void()>>> m_deferred_main_fetch_steps;+ HashMap<Engine::FetchId, GC::Root<DeferredMainFetchSteps>> m_deferred_main_fetch_steps;};}diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cppindex 6ceb40f4ef8..da918aafa72 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp@@ -33,6 +33,7 @@ FetchParams::FetchParams(FetchParams const& params), m_has_response_body_transfer_lease(params.m_has_response_body_transfer_lease), m_blob_url_entry(params.m_blob_url_entry), m_loader_config(params.m_loader_config)+ , m_engine_record(params.m_engine_record){}@@ -46,9 +47,9 @@ NonnullRefPtr<FetchParams> FetchParams::copy(FetchParams const& params)return adopt_ref(*new FetchParams(params));}-Engine::StartFetchInput FetchParams::start_fetch_input(Engine::FetchId fetch_id) const+Engine::StartFetchInput FetchParams::start_fetch_input(Engine::FetchId fetch_id, NonnullOwnPtr<Engine::EngineEventSink> event_sink) const{- return Engine::StartFetchInput { {}, fetch_id, m_control_block->body_intent(), m_blob_url_entry };+ return Engine::StartFetchInput { {}, fetch_id, m_control_block->body_intent(), m_blob_url_entry, move(event_sink) };}GC::Ref<FetchController> FetchParams::controller() constdiff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.hindex 11d27a28193..abd858f38bd 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h@@ -12,6 +12,7 @@#include <AK/Weakable.h>#include <LibGC/Ptr.h>#include <LibWeb/Export.h>+#include <LibWeb/Fetch/Engine/FetchEngineRecord.h>#include <LibWeb/Fetch/Engine/StartFetchInput.h>#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>#include <LibWeb/Fetch/Infrastructure/FetchController.h>@@ -63,7 +64,11 @@ public:[[nodiscard]] Optional<FileAPI::SerializedBlobURLEntry> const& blob_url_entry() const { return m_blob_url_entry; }void set_blob_url_entry(Optional<FileAPI::SerializedBlobURLEntry> blob_url_entry) { m_blob_url_entry = move(blob_url_entry); }- [[nodiscard]] Engine::StartFetchInput start_fetch_input(Engine::FetchId) const;+ [[nodiscard]] Engine::StartFetchInput start_fetch_input(Engine::FetchId, NonnullOwnPtr<Engine::EngineEventSink>) const;++ // Set by the fetch engine when it runs main fetch's in-parallel steps, and shared with copies made after that.+ [[nodiscard]] Engine::FetchEngineRecord* engine_record() const { return m_engine_record; }+ void set_engine_record(NonnullRefPtr<Engine::FetchEngineRecord> engine_record) const { m_engine_record = move(engine_record); }private:FetchParams(NonnullRefPtr<Request>, GC::Ref<FetchAlgorithms const>, FetchController&, NonnullRefPtr<FetchTimingInfo>, NonnullRefPtr<LoaderConfigSnapshot const>);@@ -107,6 +112,8 @@ private:// The loader configuration as it was when the fetch started.NonnullRefPtr<LoaderConfigSnapshot const> m_loader_config;++ mutable RefPtr<Engine::FetchEngineRecord> m_engine_record;};}diff --git a/Libraries/LibWeb/Fetch/Infrastructure/KeepaliveQuotaAccountant.h b/Libraries/LibWeb/Fetch/Infrastructure/KeepaliveQuotaAccountant.hindex f1c517408a8..f5e01c2cc94 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/KeepaliveQuotaAccountant.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/KeepaliveQuotaAccountant.h@@ -19,7 +19,7 @@ namespace Web::Fetch::Infrastructure {class WEB_API KeepaliveQuotaAccountant final : public AtomicRefCounted<KeepaliveQuotaAccountant> {public:// Keeps its byte count in the accountant's sum until it is destroyed.- class Reservation {+ class WEB_API Reservation {AK_MAKE_NONCOPYABLE(Reservation);public:diff --git a/Tests/LibWeb/TestFetchAlgorithms.cpp b/Tests/LibWeb/TestFetchAlgorithms.cppindex 23203e00177..0357a0366eb 100644--- a/Tests/LibWeb/TestFetchAlgorithms.cpp+++ b/Tests/LibWeb/TestFetchAlgorithms.cpp@@ -11,20 +11,35 @@#include <LibGC/Function.h>#include <LibGC/Root.h>#include <LibGC/Testing.h>+#include <LibJS/Runtime/Error.h>#include <LibTest/TestCase.h>#include <LibURL/Parser.h>+#include <LibWeb/Fetch/Engine/EngineEvent.h>#include <LibWeb/Fetch/Fetching/FetchEngine.h>+#include <LibWeb/Fetch/Fetching/FetchEventSink.h>#include <LibWeb/Fetch/Fetching/Fetching.h>#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>#include <LibWeb/Fetch/Infrastructure/FetchController.h>+#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>#include <LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h>+#include <LibWeb/Fetch/Infrastructure/Task.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/Scripting/Agent.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-+#include <LibWeb/Loader/ResourceLoader.h>+#include <LibWeb/Streams/ReadableStream.h>+#include <LibWeb/Streams/ReadableStreamDefaultReader.h>+#include <LibWeb/WebIDL/DOMException.h>++using Web::Fetch::Engine::Event::ReadRequestBodyStream;+using Web::Fetch::Engine::Event::RequestBodyEndOfBody;+using Web::Fetch::Engine::Event::RequestBodyProgress;+using Web::Fetch::Engine::Event::RequestBodySentFromSource;+using Web::Fetch::Fetching::FetchEventSink;using Web::Fetch::Infrastructure::FetchAlgorithms;+using Web::Fetch::Infrastructure::FetchController;using Web::Fetch::Infrastructure::Request;using Web::Fetch::Infrastructure::ResponseView;@@ -252,3 +267,282 @@ TEST_CASE(a_fetch_whose_controller_nothing_holds_still_runs_its_algorithms)GC::scrub_stack_for_testing();run_a_fetch_whose_controller_nothing_holds();}++namespace {++// What an upload's algorithms and tasks did, which the test reads once they have run.+struct UploadCalls : RefCounted<UploadCalls> {+ GC_HOLDS_NO_CELL_EDGES;++ Vector<ByteString> calls;+ bool later_task_ran { false };+};++}++// The algorithms of an upload, which record each call.+static FetchAlgorithms::Input upload_algorithms(GC::Heap& heap, NonnullRefPtr<UploadCalls> const& record)+{+ FetchAlgorithms::Input input { Web::Fetch::Engine::BodyIntent::DeliverStreamToConsumerAgent };+ input.process_request_body_chunk_length = GC::create_function(heap, GC::captures(record), [](auto& record, u64 length) { record->calls.append(ByteString::formatted("chunk {}", length)); });+ input.process_request_end_of_body = GC::create_function(heap, GC::captures(record), [](auto& record) { record->calls.append("end of body"); });+ return input;+}++// A request body that only its stream has, which the steps set up before the stream is read.+static FetchAlgorithms::RequestBodyReader create_request_body_reader(JS::Realm& realm, Function<void(Web::Streams::ReadableStream&)> set_up_stream)+{+ Web::HTML::TemporaryExecutionContext execution_context { realm, Web::HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };+ auto stream = Web::Streams::ReadableStream::create(realm);+ stream->set_up_with_byte_reading_support(realm);+ set_up_stream(stream);+ auto reader = MUST(stream->get_a_reader());+ return { Web::Fetch::Infrastructure::Body::create(stream), reader };+}++TEST_CASE(a_request_body_runs_its_algorithms_in_fetch_tasks_until_its_end)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;++ auto& heap = harness.realm->heap();+ auto record = make_ref_counted<UploadCalls>();+ auto request = harness.create_request();+ auto controller = harness.fetch(request, upload_algorithms(heap, record));++ FetchEventSink event_sink { controller };+ event_sink.handle_event(RequestBodyProgress { .length = 3 });+ event_sink.handle_event(RequestBodyProgress { .length = 4 });+ event_sink.handle_event(RequestBodyEndOfBody {});+ EXPECT(record->calls.is_empty());++ harness.run_tasks_until(GC::create_function(heap, GC::captures(record), [](auto& record) { return record->calls.size() == 3; }));+ EXPECT_EQ(record->calls, (Vector<ByteString> { "chunk 3", "chunk 4", "end of body" }));+}++TEST_CASE(a_canceled_fetch_runs_no_algorithm_of_a_non_null_request_body)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;++ auto& heap = harness.realm->heap();+ auto record = make_ref_counted<UploadCalls>();+ auto request = harness.create_request();+ auto controller = harness.fetch(request, upload_algorithms(heap, record));++ FetchEventSink event_sink { controller };+ event_sink.handle_event(RequestBodyProgress { .length = 3 });+ event_sink.handle_event(RequestBodyEndOfBody {});+ controller->terminate();++ // A task queued after the request body's tasks runs after them.+ Web::Fetch::Infrastructure::queue_fetch_task(controller, controller->task_destination(), GC::create_function(heap, GC::captures(record), [](auto& record) { record->later_task_ran = true; }));+ harness.run_tasks_until(GC::create_function(heap, GC::captures(record), [](auto& record) { return record->later_task_ran; }));++ EXPECT(record->later_task_ran);+ EXPECT(record->calls.is_empty());+}++TEST_CASE(the_end_of_a_null_request_body_runs_for_a_fetch_canceled_after_it_is_queued)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;++ auto& heap = harness.realm->heap();+ auto record = make_ref_counted<UploadCalls>();+ auto request = harness.create_request();+ auto controller = harness.fetch(request, upload_algorithms(heap, record));++ FetchEventSink event_sink { controller };+ event_sink.handle_event(RequestBodyEndOfBody { .body_is_null = true });+ controller->terminate();+ EXPECT(record->calls.is_empty());++ harness.run_tasks_until(GC::create_function(heap, GC::captures(record), [](auto& record) { return !record->calls.is_empty(); }));+ EXPECT_EQ(record->calls, (Vector<ByteString> { "end of body" }));+}++TEST_CASE(a_request_body_without_a_source_is_read_from_its_stream_until_its_end)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;++ auto& heap = harness.realm->heap();+ auto record = make_ref_counted<UploadCalls>();+ auto input = upload_algorithms(heap, record);+ input.request_body_reader = create_request_body_reader(*harness.realm, [](auto& stream) {+ MUST(stream.enqueue_bytes("hello"sv.bytes()));+ stream.close();+ });+ auto request = harness.create_request();+ auto controller = harness.fetch(request, move(input));++ FetchEventSink event_sink { controller };+ event_sink.handle_event(ReadRequestBodyStream {});++ harness.run_tasks_until(GC::create_function(heap, GC::captures(record), [](auto& record) { return record->calls.size() == 2; }));+ EXPECT_EQ(record->calls, (Vector<ByteString> { "chunk 5", "end of body" }));+}++TEST_CASE(an_error_from_a_request_body_stream_aborts_or_terminates_the_fetch)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;+ auto& realm = *harness.realm;++ JS::Value abort_error;+ JS::Value type_error;+ {+ Web::HTML::TemporaryExecutionContext execution_context { realm, Web::HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };+ abort_error = Web::throw_completion(realm, Web::WebIDL::AbortError::create("The body was aborted"_utf16)).value();+ type_error = JS::TypeError::create(realm, "The body failed"sv);+ }++ auto& heap = harness.realm->heap();+ auto record = make_ref_counted<UploadCalls>();+ auto fetch_with_a_body_stream_errored_with = [&](JS::Value error) {+ auto input = upload_algorithms(heap, record);+ input.request_body_reader = create_request_body_reader(realm, [error](auto& stream) { stream.error(error); });+ auto request = harness.create_request();+ auto controller = harness.fetch(request, move(input));+ FetchEventSink { controller }.handle_event(ReadRequestBodyStream {});+ return controller;+ };+ auto aborted = fetch_with_a_body_stream_errored_with(abort_error);+ auto terminated = fetch_with_a_body_stream_errored_with(type_error);++ harness.run_tasks_until(GC::create_function(heap, GC::captures(aborted, terminated), [](auto& aborted, auto& terminated) {+ return aborted->state() != FetchController::State::Ongoing && terminated->state() != FetchController::State::Ongoing;+ }));+ EXPECT_EQ(aborted->state(), FetchController::State::Aborted);+ EXPECT_EQ(terminated->state(), FetchController::State::Terminated);+ EXPECT(record->calls.is_empty());+}++TEST_CASE(the_stream_of_a_request_body_sent_from_its_source_is_read_to_its_end_and_runs_no_algorithm)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;++ auto& heap = harness.realm->heap();+ auto fetch_with_a_body_stream = [&](NonnullRefPtr<UploadCalls> const& record) {+ auto input = upload_algorithms(heap, record);+ input.request_body_reader = create_request_body_reader(*harness.realm, [](auto& stream) {+ MUST(stream.enqueue_bytes("hel"sv.bytes()));+ MUST(stream.enqueue_bytes("lo"sv.bytes()));+ stream.close();+ });+ auto request = harness.create_request();+ return harness.fetch(request, move(input));+ };+ auto drained = make_ref_counted<UploadCalls>();+ auto drained_controller = fetch_with_a_body_stream(drained);+ auto drained_stream = drained_controller->algorithms()->request_body_reader()->body->stream();+ FetchEventSink { drained_controller }.handle_event(RequestBodySentFromSource {});++ auto read = make_ref_counted<UploadCalls>();+ auto read_controller = fetch_with_a_body_stream(read);+ FetchEventSink { read_controller }.handle_event(ReadRequestBodyStream {});++ // The read stream's last task runs after every task of the drained stream.+ harness.run_tasks_until(GC::create_function(heap, GC::captures(read), [](auto& read) { return read->calls.size() == 3; }));+ EXPECT_EQ(read->calls, (Vector<ByteString> { "chunk 3", "chunk 2", "end of body" }));+ EXPECT(drained_stream->is_closed());+ EXPECT(drained->calls.is_empty());+}++namespace {++// A load over HTTP without a RequestServer fails as it starts, so the fetch sends no network request.+struct ResourceLoaderWithoutRequestServer {+ explicit ResourceLoaderWithoutRequestServer(GC::Heap& heap)+ {+ Web::ResourceLoader::initialize(heap);+ }++ ~ResourceLoaderWithoutRequestServer()+ {+ Web::ResourceLoader::shut_down();+ }+};++}++TEST_CASE(a_request_body_sent_without_a_network_request_is_one_chunk_before_the_response)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;+ ResourceLoaderWithoutRequestServer resource_loader { harness.realm->heap() };++ auto& heap = harness.realm->heap();+ auto record = make_ref_counted<UploadCalls>();+ auto input = upload_algorithms(heap, record);+ input.process_response = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView> response) {+ record->calls.append(response->is_network_error() ? "network error" : "response");+ });++ auto request = harness.create_request_for("http://127.0.0.1:8000/"sv);+ request->set_method("POST");+ request->set_body(MUST(ByteBuffer::copy("hello"sv.bytes())));+ (void)harness.fetch(request, move(input));++ harness.run_tasks_until(GC::create_function(heap, GC::captures(record), [](auto& record) { return record->calls.size() == 3; }));+ EXPECT_EQ(record->calls, (Vector<ByteString> { "chunk 5", "end of body", "network error" }));+}++TEST_CASE(a_request_body_sent_without_a_network_request_has_its_stream_read_to_its_end)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;+ ResourceLoaderWithoutRequestServer resource_loader { harness.realm->heap() };++ auto& heap = harness.realm->heap();+ auto record = make_ref_counted<UploadCalls>();+ auto input = upload_algorithms(heap, record);+ input.process_response = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView> response) {+ record->calls.append(response->is_network_error() ? "network error" : "response");+ });+ input.request_body_reader = create_request_body_reader(*harness.realm, [](auto& stream) {+ MUST(stream.enqueue_bytes("hello"sv.bytes()));+ stream.close();+ });+ auto stream = input.request_body_reader->body->stream();++ auto request = harness.create_request_for("http://127.0.0.1:8000/"sv);+ request->set_method("POST");+ request->set_body(MUST(ByteBuffer::copy("hello"sv.bytes())));+ (void)harness.fetch(request, move(input));++ harness.run_tasks_until(GC::create_function(heap, GC::captures(record), [](auto& record) { return record->calls.size() == 3; }));+ EXPECT_EQ(record->calls, (Vector<ByteString> { "chunk 5", "end of body", "network error" }));+ EXPECT(stream->is_closed());+}++TEST_CASE(a_null_request_body_ends_before_the_response)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;+ ResourceLoaderWithoutRequestServer resource_loader { harness.realm->heap() };++ auto& heap = harness.realm->heap();+ auto record = make_ref_counted<UploadCalls>();+ auto input = upload_algorithms(heap, record);+ input.process_response = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView> response) {+ record->calls.append(response->is_network_error() ? "network error" : "response");+ });++ auto request = harness.create_request_for("http://127.0.0.1:8000/"sv);+ (void)harness.fetch(request, move(input));++ harness.run_tasks_until(GC::create_function(heap, GC::captures(record), [](auto& record) { return record->calls.size() == 2; }));+ EXPECT_EQ(record->calls, (Vector<ByteString> { "end of body", "network error" }));+}diff --git a/Tests/LibWeb/TestFetchEngineMessages.cpp b/Tests/LibWeb/TestFetchEngineMessages.cppindex f2e19652f5d..63c06b97d44 100644--- a/Tests/LibWeb/TestFetchEngineMessages.cpp+++ b/Tests/LibWeb/TestFetchEngineMessages.cpp@@ -21,7 +21,7 @@ static_assert(!IsConstructible<Command::CompletedPreloadResponse::Completed, Nulstatic_assert(!IsConstructible<Delivered<NonNullLocalBodyHandle>, NullBody>);// Only fetch params build the input that starts a fetch.-static_assert(!IsConstructible<StartFetchInput, FetchId, BodyIntent, Optional<Web::FileAPI::SerializedBlobURLEntry>>);+static_assert(!IsConstructible<StartFetchInput, FetchId, BodyIntent, Optional<Web::FileAPI::SerializedBlobURLEntry>, NonnullOwnPtr<EngineEventSink>>);TEST_CASE(commands_round_trip_their_payloads){@@ -136,8 +136,13 @@ TEST_CASE(events_round_trip_their_payloads).outcome = RequestEnd::CommittedAttemptFailed { .attempt_id = AttemptId(4), .error = Requests::NetworkError::IncompleteContent, .encoded_body_size = 512 },},});+ events.append(Event::RequestBodyProgress { .length = 8 });+ events.append(Event::RequestBodyEndOfBody { .body_is_null = true });+ events.append(Event::ReadRequestBodyStream {});+ events.append(Event::RequestBodySentFromSource {});Vector<u64> seen_ids;+ Vector<StringView> seen_request_body_events;for (auto const& event : events) {event.visit([&](Event::ResponseDelivery const& delivery) {@@ -169,7 +174,18 @@ TEST_CASE(events_round_trip_their_payloads)EXPECT_EQ(failed.error, Requests::NetworkError::IncompleteContent);EXPECT_EQ(failed.encoded_body_size, 512u);seen_ids.append(ended.transmission_id.value());- });+ },+ [&](Event::RequestBodyProgress const& progress) {+ EXPECT_EQ(progress.length, 8u);+ seen_request_body_events.append("progress"sv);+ },+ [&](Event::RequestBodyEndOfBody const& end_of_body) {+ EXPECT(end_of_body.body_is_null);+ seen_request_body_events.append("end of body"sv);+ },+ [&](Event::ReadRequestBodyStream const&) { seen_request_body_events.append("read stream"sv); },+ [&](Event::RequestBodySentFromSource const&) { seen_request_body_events.append("sent from source"sv); });}EXPECT_EQ(seen_ids, (Vector<u64> { 1, 2, 3, 4, 5, 6, 7 }));+ EXPECT_EQ(seen_request_body_events, (Vector<StringView> { "progress"sv, "end of body"sv, "read stream"sv, "sent from source"sv }));}diff --git a/Tests/LibWebView/test-webdriver-bidi.py b/Tests/LibWebView/test-webdriver-bidi.pyindex ebe0a778f78..c1edddcedb3 100755--- a/Tests/LibWebView/test-webdriver-bidi.py+++ b/Tests/LibWebView/test-webdriver-bidi.py@@ -349,9 +349,14 @@ class ReloadHandler(http.server.BaseHTTPRequestHandler):def do_OPTIONS(self):server = self.serverassert isinstance(server, ReloadServer)+ body = self.rfile.read(int(self.headers.get("Content-Length", "0")))with server.interception_lock:server.preflight_requests.append(- {"path": self.path, "method": self.headers.get("Access-Control-Request-Method")}+ {+ "path": self.path,+ "method": self.headers.get("Access-Control-Request-Method"),+ "body": body.decode(),+ })server.preflight_received.set()if not server.release_preflight.wait(30):@@ -1210,6 +1215,39 @@ def check_network_continue_after_gc(bidi, context, server):bidi.command("session.unsubscribe", {"subscriptions": [subscription]})+def check_network_preflight_body(bidi, context, server):+ url = f"http://localhost:{server.server_port}/network-interception/cors/preflight-body"+ path = urllib.parse.urlsplit(url).path+ subscription = bidi.command("session.subscribe", {"events": ["network.beforeRequestSent"]})["subscription"]+ intercept = bidi.command(+ "network.addIntercept",+ {"phases": ["beforeRequestSent"], "urlPatterns": [{"type": "string", "pattern": url}]},+ )["intercept"]+ server.release_preflight.set()+ try:+ with server.interception_lock:+ server.interception_requests.clear()+ server.preflight_requests.clear()+ pending = send_fetch(bidi, context, url, {"headers": {"X-BiDi": "1"}})+ event = intercepted_event(bidi, "network.beforeRequestSent", url)+ assert event["request"]["method"] == "OPTIONS", event+ body = {"type": "string", "value": "preflight-body"}+ bidi.command("network.continueRequest", {"request": event["request"]["request"], "body": body})+ event = intercepted_event(bidi, "network.beforeRequestSent", url)+ assert event["request"]["method"] == "GET", event+ bidi.command("network.continueRequest", {"request": event["request"]["request"]})+ records = fetch_records(bidi, pending)+ received = [(record["path"], record["method"], record["body"]) for record in records]+ assert received == [(path, "GET", "")], records+ with server.interception_lock:+ preflights = list(server.preflight_requests)+ assert preflights == [{"path": path, "method": "GET", "body": "preflight-body"}], preflights+ finally:+ if sys.exc_info()[0] is None:+ bidi.command("network.removeIntercept", {"intercept": intercept})+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})++def check_network_intercepted_adopted_navigation(bidi, context, server, action):# A cross-site navigation blocked at responseStarted commits its document in another process once continued.terminal_methods = {"network.responseCompleted", "network.fetchError"}@@ -1492,6 +1530,8 @@ def check_network_interception(bidi, context, server, case="all"):check_network_stopped_fetch_reports_error(bidi, context, server)if case in ["all", "continue-after-gc"]:check_network_continue_after_gc(bidi, context, server)+ if case in ["all", "preflight-body"]:+ check_network_preflight_body(bidi, context, server)for action in ["continue", "fail", "provide"]:if case in ["all", f"adopted-navigation-{action}"]:check_network_intercepted_adopted_navigation(bidi, context, server, action)@@ -1841,7 +1881,8 @@ def check_network_subresource_events(bidi, context, server):# A preflight for this PUT reached the server.with server.interception_lock:preflights = list(server.preflight_requests)- assert {"path": urllib.parse.urlsplit(url).path, "method": "PUT"} in preflights, (host, preflights)+ preflight = {"path": urllib.parse.urlsplit(url).path, "method": "PUT", "body": ""}+ assert preflight in preflights, (host, preflights)finally:if sys.exc_info()[0] is None:bidi.command("session.unsubscribe", {"subscriptions": [subscription]})@@ -2734,6 +2775,7 @@ if __name__ == "__main__":"events-off-stop","events-on-stop","continue-after-gc",+ "preflight-body","adopted-navigation-continue","adopted-navigation-fail","adopted-navigation-provide",