Truly independent web browser
LibWeb: Keep a fetch's algorithms on its fetch controller
Luke Wilde5756cb4cc170
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex 7829d50a610..287fc080bf3 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -1121,8 +1121,9 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const// 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process response// end-of-body given response.- if (fetch_params.algorithms()->process_response_end_of_body())- (fetch_params.algorithms()->process_response_end_of_body())(response_view);+ auto algorithms = fetch_params.controller()->algorithms();+ if (algorithms->process_response_end_of_body())+ (algorithms->process_response_end_of_body())(response_view);report_timing_if_appropriate();});@@ -1133,9 +1134,9 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const// 5. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s process response// given response, with fetchParams’s task destination.- if (fetch_params.algorithms()->process_response()) {+ if (fetch_params.controller()->algorithms()->process_response()) {Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.task_destination(), GC::create_function(GC::Heap::the(), [&fetch_params, response_view]() {- fetch_params.algorithms()->process_response()(response_view);+ fetch_params.controller()->algorithms()->process_response()(response_view);}));}@@ -1165,7 +1166,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams constif (Core::StatsLog::the() && body_view)track_rendering_pending_stream(fetch_params.controller().ptr(), *body_view->stream());- auto algorithms = fetch_params.algorithms();+ auto algorithms = fetch_params.controller()->algorithms();auto body_intent = fetch_params.body_intent();@@ -2976,9 +2977,9 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(// 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.algorithms()->process_request_end_of_body()) {+ if (fetch_params.controller()->algorithms()->process_request_end_of_body()) {Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.task_destination(), GC::create_function(GC::Heap::the(), [&fetch_params]() {- fetch_params.algorithms()->process_request_end_of_body()();+ fetch_params.controller()->algorithms()->process_request_end_of_body()();}));}}@@ -2996,8 +2997,8 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(// 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 (fetch_params.algorithms()->process_request_body_chunk_length())- fetch_params.algorithms()->process_request_body_chunk_length()(length);+ if (fetch_params.controller()->algorithms()->process_request_body_chunk_length())+ fetch_params.controller()->algorithms()->process_request_body_chunk_length()(length);};// 2. Let processEndOfBody be these steps:@@ -3008,8 +3009,8 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(// 2. If fetchParams’s process request end-of-body is non-null, then run fetchParams’s process request// end-of-body.- if (fetch_params.algorithms()->process_request_end_of_body())- fetch_params.algorithms()->process_request_end_of_body()();+ if (fetch_params.controller()->algorithms()->process_request_end_of_body())+ fetch_params.controller()->algorithms()->process_request_end_of_body()();});// 3. Let processBodyError given e be these steps:@@ -3039,7 +3040,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(}));}Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.task_destination(), process_end_of_body);- } else if (auto const& request_body_reader = fetch_params.algorithms()->request_body_reader(); request_body_reader.has_value()) {+ } 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(), [process_body_chunk](ByteBuffer bytes) {process_body_chunk(bytes.size());diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cppindex 8c158a178f0..8a1ead5a3f1 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp@@ -45,11 +45,18 @@ void FetchController::visit_edges(JS::Cell::Visitor& visitor)visitor.visit(m_awaited_network_completion->steps);visitor.visit(m_next_manual_redirect_steps);visitor.visit(m_fetch_params);+ visitor.visit(m_algorithms);visitor.visit(m_pending_preloaded_response);visitor.visit(m_stop_steps);visitor.visit(m_pending_responses);}+GC::Ref<FetchAlgorithms const> FetchController::algorithms() const+{+ VERIFY(m_algorithms);+ return *m_algorithms;+}+void FetchController::set_network_transport(Engine::NetworkTransportHandle& network_transport){set_body_transport(network_transport);@@ -191,12 +198,11 @@ void FetchController::stop_fetch()});});- if (m_fetch_params) {- // NB: Nobody reads a stopped fetch's body.+ // NB: Nobody reads a stopped fetch's body.+ if (m_fetch_params)m_fetch_params->set_body_intent(Engine::BodyIntent::DrainAndDiscard);- auto fetch_algorithms = FetchAlgorithms::create(FetchAlgorithms::Input { m_fetch_params->body_intent() });- m_fetch_params->set_algorithms(fetch_algorithms);- }+ if (m_algorithms)+ m_algorithms = FetchAlgorithms::create(FetchAlgorithms::Input { Engine::BodyIntent::DrainAndDiscard });stop_request();diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.hindex 605996372db..9558a462d39 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h@@ -67,6 +67,9 @@ public:void set_fetch_params(Badge<FetchParams>, GC::Ref<FetchParams> fetch_params) { m_fetch_params = fetch_params; }[[nodiscard]] GC::Ptr<FetchParams> fetch_params() const { return m_fetch_params; }+ void set_algorithms(Badge<FetchParams>, GC::Ref<FetchAlgorithms const> algorithms) { m_algorithms = algorithms; }+ [[nodiscard]] GC::Ref<FetchAlgorithms const> algorithms() const;+// AD-HOC: Whether this fetch's response has arrived: as headers from the network, or at main fetch. From then on,// its body delivery is queued as event-loop tasks, and its response processing captures its task// destination as it was then — so re-targeting the fetch no longer reaches either.@@ -133,6 +136,23 @@ private:GC::Ptr<GC::Function<void()>> m_next_manual_redirect_steps;GC::Ptr<FetchParams> m_fetch_params;++ // AD-HOC: The fetch params' algorithms are kept on their controller, which every copy of the fetch params shares.+ // https://fetch.spec.whatwg.org/#fetch-params-process-request-body+ // process request body chunk length (default null)+ // https://fetch.spec.whatwg.org/#fetch-params-process-request-end-of-body+ // process request end-of-body (default null)+ // https://fetch.spec.whatwg.org/#fetch-params-process-early-hints-response+ // process early hints response (default null)+ // https://fetch.spec.whatwg.org/#fetch-params-process-response+ // process response (default null)+ // https://fetch.spec.whatwg.org/#fetch-params-process-response-end-of-body+ // process response end-of-body (default null)+ // https://fetch.spec.whatwg.org/#fetch-params-process-response-consume-body+ // process response consume body (default null)+ // Null or an algorithm.+ GC::Ptr<FetchAlgorithms const> m_algorithms;+bool m_response_arrived { false };// NB: Assumes one waiting consumer for a pending preloaded response.// Widen this if preload handoff ever supports multiple consumers.diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cppindex d9ae0411a14..35a70e57fbb 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp@@ -15,18 +15,17 @@ GC_DEFINE_ALLOCATOR(FetchParams);FetchParams::FetchParams(NonnullRefPtr<Request> request, GC::Ref<FetchAlgorithms const> algorithms, GC::Ref<FetchController> controller, NonnullRefPtr<FetchTimingInfo> timing_info, NonnullRefPtr<LoaderConfigSnapshot const> loader_config): m_request(move(request))- , m_algorithms(algorithms), m_body_intent(algorithms->body_intent()), m_controller(controller), m_timing_info(move(timing_info)), m_loader_config(move(loader_config)){m_controller->set_fetch_params({}, *this);+ m_controller->set_algorithms({}, algorithms);}FetchParams::FetchParams(FetchParams const& params): m_request(params.m_request)- , m_algorithms(params.m_algorithms), m_body_intent(params.m_body_intent), m_task_destination(params.m_task_destination), m_cross_origin_isolated_capability(params.m_cross_origin_isolated_capability)@@ -53,7 +52,6 @@ GC::Ref<FetchParams> FetchParams::copy(FetchParams const& params)void FetchParams::visit_edges(JS::Cell::Visitor& visitor){Base::visit_edges(visitor);- visitor.visit(m_algorithms);visitor.visit(m_controller);visitor.visit(m_task_destination);}diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.hindex 8c93f172eb6..01a2a21fd97 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h@@ -41,9 +41,6 @@ public:[[nodiscard]] LoaderConfig const& loader_config() const { return m_loader_config->config; }[[nodiscard]] NonnullRefPtr<LoaderConfigSnapshot const> const& loader_config_snapshot() const { return m_loader_config; }- [[nodiscard]] GC::Ref<FetchAlgorithms const> algorithms() const { return m_algorithms; }- void set_algorithms(GC::Ref<FetchAlgorithms const> algorithms) { m_algorithms = algorithms; }-[[nodiscard]] Engine::BodyIntent body_intent() const { return m_body_intent; }void set_body_intent(Engine::BodyIntent body_intent) { m_body_intent = body_intent; }@@ -81,21 +78,6 @@ private:// A request.NonnullRefPtr<Request> m_request;- // https://fetch.spec.whatwg.org/#fetch-params-process-request-body- // process request body chunk length (default null)- // https://fetch.spec.whatwg.org/#fetch-params-process-request-end-of-body- // process request end-of-body (default null)- // https://fetch.spec.whatwg.org/#fetch-params-process-early-hints-response- // process early hints response (default null)- // https://fetch.spec.whatwg.org/#fetch-params-process-response- // process response (default null)- // https://fetch.spec.whatwg.org/#fetch-params-process-response-end-of-body- // process response end-of-body (default null)- // https://fetch.spec.whatwg.org/#fetch-params-process-response-consume-body- // process response consume body (default null)- // Null or an algorithm.- GC::Ref<FetchAlgorithms const> m_algorithms;-Engine::BodyIntent m_body_intent;// https://fetch.spec.whatwg.org/#fetch-params-task-destinationdiff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txtindex e3fc7354949..99ed60fcd3b 100644--- a/Tests/LibWeb/CMakeLists.txt+++ b/Tests/LibWeb/CMakeLists.txt@@ -26,6 +26,7 @@ set(TEST_SOURCESTestDump.cppTestEventLoop.cppTestFaviconDecoding.cpp+ TestFetchAlgorithms.cppTestFetchBodyDeliveryGate.cppTestFetchBodyStream.cppTestFetchByteChannel.cpp@@ -92,6 +93,7 @@ if (NOT WIN32)endif()target_link_libraries(TestDownloadReader PRIVATE LibGC LibJS LibURL)target_link_libraries(TestFaviconDecoding PRIVATE LibCore LibGC LibGfx LibJS)+target_link_libraries(TestFetchAlgorithms PRIVATE LibCore LibGC LibJS LibURL)target_link_libraries(TestFetchBodyDeliveryGate PRIVATE LibCore LibThreading)target_link_libraries(TestFetchBodyStream PRIVATE LibCore LibGC LibJS)target_link_libraries(TestFetchByteChannel PRIVATE LibThreading)diff --git a/Tests/LibWeb/TestFetchAlgorithms.cpp b/Tests/LibWeb/TestFetchAlgorithms.cppnew file mode 100644index 00000000000..b0aad63add2--- /dev/null+++ b/Tests/LibWeb/TestFetchAlgorithms.cpp@@ -0,0 +1,195 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include "FetchTestDocument.h"+#include <LibCore/EventLoop.h>+#include <LibCore/Timer.h>+#include <LibGC/RootVector.h>+#include <LibTest/TestCase.h>+#include <LibURL/Parser.h>+#include <LibWeb/Fetch/Fetching/Fetching.h>+#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>+#include <LibWeb/Fetch/Infrastructure/FetchController.h>+#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>+#include <LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h>+#include <LibWeb/HTML/EventLoop/EventLoop.h>+#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>++using Web::Fetch::Infrastructure::FetchAlgorithms;+using Web::Fetch::Infrastructure::Request;+using Web::Fetch::Infrastructure::ResponseView;++namespace {++struct FetchHarness {+ FetchHarness()+ : document(create_test_document())+ , realm(document->relevant_settings_object().realm())+ {+ }++ // An unknown scheme: scheme fetch returns a network error, which has no body.+ NonnullRefPtr<Request> create_request() const+ {+ return create_request_for("unknown-scheme:network-error"sv);+ }++ NonnullRefPtr<Request> create_request_for(StringView url_string) const+ {+ auto url = URL::Parser::basic_parse(url_string);+ VERIFY(url.has_value());++ auto request = Request::create();+ request->set_url_list({ url.release_value() });+ request->set_client(document->relevant_settings_object().address());+ return request;+ }++ GC::Ref<Web::Fetch::Infrastructure::FetchController> fetch(Request& request, FetchAlgorithms::Input input) const+ {+ return fetch_with(request, FetchAlgorithms::create(move(input)));+ }++ GC::Ref<Web::Fetch::Infrastructure::FetchController> fetch_with(Request& request, FetchAlgorithms const& algorithms) const+ {+ Web::HTML::TemporaryExecutionContext execution_context { *realm, Web::HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };+ return Web::Fetch::Fetching::fetch(*realm, request, algorithms);+ }++ // Runs the fetch's steps and the tasks they queue until the condition holds, or for ten seconds.+ void run_tasks_until(ESCAPING Function<bool()> condition) const+ {+ auto deadline = Core::Timer::create_single_shot(AK::Duration::from_seconds(10), [] { });+ deadline->start();+ Web::HTML::main_thread_event_loop().spin_until(GC::create_function(realm->heap(), [condition = move(condition), deadline] {+ return condition() || !deadline->is_active();+ }));+ }++ GC::Ref<Web::DOM::Document> document;+ GC::Ref<JS::Realm> realm;+};++}++TEST_CASE(each_algorithm_gets_the_same_response_in_order)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;++ IGNORE_USE_IN_ESCAPING_LAMBDA Vector<StringView> calls;+ GC::RootVector<GC::Ref<ResponseView>> responses;+ FetchAlgorithms::Input input { Web::Fetch::Engine::BodyIntent::ConsumeForCallback };+ input.process_response = [&](GC::Ref<ResponseView> response) {+ calls.append("process response"sv);+ responses.append(response);+ };+ input.process_response_end_of_body = [&](GC::Ref<ResponseView> response) {+ calls.append("process response end-of-body"sv);+ responses.append(response);+ };+ input.process_response_consume_body = [&](GC::Ref<ResponseView> response, FetchAlgorithms::BodyBytes body) {+ calls.append("process response consume body"sv);+ responses.append(response);+ EXPECT(body.has<Empty>());+ };++ auto request = harness.create_request();+ (void)harness.fetch(request, move(input));+ harness.run_tasks_until([&] { return calls.size() == 3; });++ EXPECT_EQ(calls, (Vector<StringView> { "process response"sv, "process response end-of-body"sv, "process response consume body"sv }));+ VERIFY(responses.size() == 3);+ EXPECT(responses[0]->is_network_error());+ EXPECT_EQ(responses[1].ptr(), responses[0].ptr());+ EXPECT_EQ(responses[2].ptr(), responses[0].ptr());+}++TEST_CASE(each_algorithm_gets_the_same_response_with_a_body_in_order)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;++ IGNORE_USE_IN_ESCAPING_LAMBDA Vector<StringView> calls;+ GC::RootVector<GC::Ref<ResponseView>> responses;+ Optional<ByteBuffer> consumed_bytes;+ FetchAlgorithms::Input input { Web::Fetch::Engine::BodyIntent::ConsumeForCallback };+ input.process_response = [&](GC::Ref<ResponseView> response) {+ calls.append("process response"sv);+ responses.append(response);+ };+ input.process_response_end_of_body = [&](GC::Ref<ResponseView> response) {+ calls.append("process response end-of-body"sv);+ responses.append(response);+ };+ input.process_response_consume_body = [&](GC::Ref<ResponseView> response, FetchAlgorithms::BodyBytes body) {+ calls.append("process response consume body"sv);+ responses.append(response);+ if (auto const* bytes = body.get_pointer<Core::ImmutableBytes>())+ consumed_bytes = MUST(ByteBuffer::copy(bytes->bytes()));+ };++ auto request = harness.create_request_for("data:text/plain,hello"sv);+ (void)harness.fetch(request, move(input));+ harness.run_tasks_until([&] { return calls.size() == 3; });++ EXPECT_EQ(calls, (Vector<StringView> { "process response"sv, "process response end-of-body"sv, "process response consume body"sv }));+ VERIFY(responses.size() == 3);+ EXPECT(!responses[0]->is_network_error());+ EXPECT_EQ(responses[1].ptr(), responses[0].ptr());+ EXPECT_EQ(responses[2].ptr(), responses[0].ptr());+ VERIFY(consumed_bytes.has_value());+ EXPECT_EQ(*consumed_bytes, MUST(ByteBuffer::copy("hello"sv.bytes())));+}++TEST_CASE(a_stopped_fetch_runs_no_algorithm_but_its_request_is_done)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;++ size_t call_count = 0;+ FetchAlgorithms::Input input { Web::Fetch::Engine::BodyIntent::ConsumeForCallback };+ input.process_response = [&](GC::Ref<ResponseView>) { ++call_count; };+ input.process_response_end_of_body = [&](GC::Ref<ResponseView>) { ++call_count; };+ input.process_response_consume_body = [&](GC::Ref<ResponseView>, FetchAlgorithms::BodyBytes) { ++call_count; };++ IGNORE_USE_IN_ESCAPING_LAMBDA auto request = harness.create_request();+ auto controller = harness.fetch(request, move(input));+ controller->stop_fetch();+ harness.run_tasks_until([&] { return request->done(); });++ EXPECT_EQ(call_count, 0u);+ EXPECT(request->done());+}++TEST_CASE(a_stop_leaves_the_algorithms_for_the_next_fetch)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;++ IGNORE_USE_IN_ESCAPING_LAMBDA size_t call_count = 0;+ FetchAlgorithms::Input input { Web::Fetch::Engine::BodyIntent::ConsumeForCallback };+ input.process_response = [&](GC::Ref<ResponseView>) { ++call_count; };+ input.process_response_end_of_body = [&](GC::Ref<ResponseView>) { ++call_count; };+ input.process_response_consume_body = [&](GC::Ref<ResponseView>, FetchAlgorithms::BodyBytes) { ++call_count; };+ auto algorithms = FetchAlgorithms::create(move(input));++ IGNORE_USE_IN_ESCAPING_LAMBDA auto stopped_request = harness.create_request();+ harness.fetch_with(stopped_request, algorithms)->stop_fetch();+ harness.run_tasks_until([&] { return stopped_request->done(); });+ EXPECT_EQ(call_count, 0u);++ // A stop empties the stopped fetch's algorithms, not the caller's.+ auto request = harness.create_request();+ (void)harness.fetch_with(request, algorithms);+ harness.run_tasks_until([&] { return call_count == 3; });+ EXPECT_EQ(call_count, 3u);+}