Skip to content

Truly independent web browser

LibWeb: Stop a fetch's transport through its fetch executor

Luke Wildec41f627d33b0
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 03757c6da65..520dc74168d 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -297,6 +297,7 @@ set(SOURCES
Fetch/BodyInit.cpp
Fetch/Engine/FetchBodyDeliveryGate.cpp
Fetch/Engine/FetchByteChannel.cpp
+ Fetch/Engine/FetchEngineRecord.cpp
Fetch/Engine/FetchExecutor.cpp
Fetch/Engine/InlineFetchExecutor.cpp
Fetch/Engine/NetworkTransportHandle.cpp
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.cpp b/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.cpp
new file mode 100644
index 00000000000..1e34df7b15e
--- /dev/null
+++ b/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.cpp
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Format.h>
+#include <LibWeb/Fetch/Engine/FetchEngineRecord.h>
+
+namespace Web::Fetch::Engine {
+
+FetchEngineRecord::FetchEngineRecord(FetchEngineRecords& records, FetchId fetch_id, NonnullOwnPtr<EngineEventSink> event_sink, NonnullRefPtr<NetworkActivityObservers const> network_activity_observers)
+ : m_records(records)
+ , m_fetch_id(fetch_id)
+ , m_event_sink(move(event_sink))
+ , m_network_activity_observers(move(network_activity_observers))
+{
+}
+
+FetchEngineRecord::~FetchEngineRecord()
+{
+ if (auto* records = m_records.ptr())
+ records->remove({}, m_fetch_id);
+}
+
+void FetchEngineRecord::set_body_transport(FetchBodyDeliveryGate::Transport& transport)
+{
+ m_body_transport = transport;
+}
+
+void FetchEngineRecord::stop_body_transport()
+{
+ if (auto transport = exchange(m_body_transport, nullptr).strong_ref())
+ transport->stop();
+}
+
+void FetchEngineRecord::set_cors_preflight_body_transport(FetchBodyDeliveryGate::Transport& transport)
+{
+ m_cors_preflight_body_transport = transport;
+}
+
+void FetchEngineRecord::stop_cors_preflight_body_transport()
+{
+ if (auto transport = exchange(m_cors_preflight_body_transport, nullptr).strong_ref())
+ transport->stop();
+}
+
+void FetchEngineRecords::Agent::misbehaved(StringView reason)
+{
+ dbgln("FetchEngineRecords: The agent misbehaved: {}", reason);
+ VERIFY_NOT_REACHED();
+}
+
+FetchEngineRecords::FetchEngineRecords(NonnullOwnPtr<Agent> agent)
+ : m_agent(move(agent))
+{
+}
+
+RefPtr<FetchEngineRecord> FetchEngineRecords::start(FetchId fetch_id, NonnullOwnPtr<EngineEventSink> event_sink, NonnullRefPtr<NetworkActivityObservers const> network_activity_observers)
+{
+ ASSERT(is_on_owner_thread());
+ if (fetch_id <= m_last_started_fetch_id) {
+ m_agent->misbehaved("The agent started a fetch out of fetch id order"sv);
+ return {};
+ }
+ m_last_started_fetch_id = fetch_id;
+
+ auto record = adopt_ref(*new FetchEngineRecord(*this, fetch_id, move(event_sink), move(network_activity_observers)));
+ m_records.set(fetch_id, record.ptr());
+ return record;
+}
+
+void FetchEngineRecords::stop_body_transport(FetchId fetch_id)
+{
+ ASSERT(is_on_owner_thread());
+ if (fetch_id > m_last_started_fetch_id) {
+ m_agent->misbehaved("The agent stopped a fetch it has not started"sv);
+ return;
+ }
+ if (auto record = m_records.get(fetch_id); record.has_value())
+ (*record)->stop_body_transport();
+}
+
+void FetchEngineRecords::remove(Badge<FetchEngineRecord>, FetchId fetch_id)
+{
+ ASSERT(is_on_owner_thread());
+ m_records.remove(fetch_id);
+}
+
+}
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.h b/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.h
index ba8425d3cf2..a618f630e6c 100644
--- a/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.h
+++ b/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.h
@@ -6,22 +6,34 @@
#pragma once
+#include <AK/Badge.h>
+#include <AK/HashMap.h>
+#include <AK/Noncopyable.h>
#include <AK/NonnullOwnPtr.h>
#include <AK/NonnullRefPtr.h>
#include <AK/RefCounted.h>
+#include <AK/RefPtr.h>
+#include <AK/StringView.h>
+#include <AK/ThreadID.h>
+#include <AK/WeakPtr.h>
+#include <AK/Weakable.h>
+#include <AK/kmalloc.h>
+#include <LibWeb/Export.h>
#include <LibWeb/Fetch/Engine/EngineEventSink.h>
+#include <LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h>
+#include <LibWeb/Fetch/Engine/Ids.h>
#include <LibWeb/Fetch/Engine/NetworkActivity.h>
#include <LibWeb/Fetch/Engine/NetworkActivityObservers.h>
namespace Web::Fetch::Engine {
-// What the fetch engine keeps of a fetch it has started.
-class FetchEngineRecord final : public RefCounted<FetchEngineRecord> {
+class FetchEngineRecords;
+
+// What the fetch engine keeps of a fetch it has started. Every method runs on the engine's loop, and so does the
+// record's destruction.
+class WEB_API FetchEngineRecord final : public RefCounted<FetchEngineRecord> {
public:
- [[nodiscard]] static NonnullRefPtr<FetchEngineRecord> create(NonnullOwnPtr<EngineEventSink> event_sink, NonnullRefPtr<NetworkActivityObservers const> network_activity_observers)
- {
- return adopt_ref(*new FetchEngineRecord(move(event_sink), move(network_activity_observers)));
- }
+ ~FetchEngineRecord();
[[nodiscard]] EngineEventSink& event_sink() { return *m_event_sink; }
@@ -34,15 +46,63 @@ public:
// Those of the agent that started the fetch.
[[nodiscard]] NetworkActivityObservers const& network_activity_observers() const { return m_network_activity_observers; }
+ // The transport of the response body the fetch receives, which stopping, aborting or terminating the fetch stops.
+ void set_body_transport(FetchBodyDeliveryGate::Transport&);
+ void stop_body_transport();
+
+ // The transport of the response body a CORS preflight for the fetch receives, which stopping, aborting or
+ // terminating the fetch leaves alone.
+ void set_cors_preflight_body_transport(FetchBodyDeliveryGate::Transport&);
+ void stop_cors_preflight_body_transport();
+
private:
- FetchEngineRecord(NonnullOwnPtr<EngineEventSink> event_sink, NonnullRefPtr<NetworkActivityObservers const> network_activity_observers)
- : m_event_sink(move(event_sink))
- , m_network_activity_observers(move(network_activity_observers))
- {
- }
+ friend class FetchEngineRecords;
+
+ FetchEngineRecord(FetchEngineRecords&, FetchId, NonnullOwnPtr<EngineEventSink>, NonnullRefPtr<NetworkActivityObservers const>);
+ WeakPtr<FetchEngineRecords> m_records;
+ FetchId m_fetch_id;
NonnullOwnPtr<EngineEventSink> m_event_sink;
NonnullRefPtr<NetworkActivityObservers const> m_network_activity_observers;
+ WeakPtr<FetchBodyDeliveryGate::Transport> m_body_transport;
+ WeakPtr<FetchBodyDeliveryGate::Transport> m_cors_preflight_body_transport;
+};
+
+// The records of the fetches an engine has started, by fetch id. A record stays only while something else holds it.
+// Every method, and each record's destruction, runs on the loop the records were created on.
+class WEB_API FetchEngineRecords : public Weakable<FetchEngineRecords> {
+ AK_MAKE_NONCOPYABLE(FetchEngineRecords);
+ AK_MAKE_NONMOVABLE(FetchEngineRecords);
+
+public:
+ // The agent whose commands start and stop the fetches.
+ class WEB_API Agent {
+ public:
+ AK_ALLOC_WITH_KMALLOC;
+
+ virtual ~Agent() = default;
+
+ // Called for a command no honest agent could have posted.
+ virtual void misbehaved(StringView reason);
+ };
+
+ explicit FetchEngineRecords(NonnullOwnPtr<Agent>);
+
+ // Reports to the agent a fetch id no higher than that of an earlier start, and returns null for it.
+ [[nodiscard]] RefPtr<FetchEngineRecord> start(FetchId, NonnullOwnPtr<EngineEventSink>, NonnullRefPtr<NetworkActivityObservers const>);
+
+ // Does nothing once the fetch's record is gone. Reports to the agent a fetch id above that of every started fetch.
+ void stop_body_transport(FetchId);
+
+ void remove(Badge<FetchEngineRecord>, FetchId);
+
+private:
+ [[nodiscard]] bool is_on_owner_thread() const { return m_owner_thread.is_current_thread(); }
+
+ NonnullOwnPtr<Agent> m_agent;
+ AK::ThreadID m_owner_thread { AK::ThreadID::current() };
+ FetchId m_last_started_fetch_id { 0 };
+ HashMap<FetchId, FetchEngineRecord*> m_records;
};
}
diff --git a/Libraries/LibWeb/Fetch/Engine/StartFetchInput.h b/Libraries/LibWeb/Fetch/Engine/StartFetchInput.h
index f14e351dcc4..4a34b5ec552 100644
--- a/Libraries/LibWeb/Fetch/Engine/StartFetchInput.h
+++ b/Libraries/LibWeb/Fetch/Engine/StartFetchInput.h
@@ -31,6 +31,7 @@ struct StartFetchInput {
{
}
+ // An agent's fetch ids rise in the order it posts their starts.
FetchId fetch_id;
BodyIntent body_intent;
diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchEngine.cpp b/Libraries/LibWeb/Fetch/Fetching/FetchEngine.cpp
index 32a83c99d40..6e7d0145097 100644
--- a/Libraries/LibWeb/Fetch/Fetching/FetchEngine.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/FetchEngine.cpp
@@ -12,8 +12,9 @@
namespace Web::Fetch::Fetching {
-FetchEngine::FetchEngine(NonnullRefPtr<Engine::NetworkActivityObservers const> network_activity_observers)
+FetchEngine::FetchEngine(NonnullRefPtr<Engine::NetworkActivityObservers const> network_activity_observers, NonnullOwnPtr<Engine::FetchEngineRecords::Agent> agent)
: m_network_activity_observers(move(network_activity_observers))
+ , m_records(move(agent))
{
}
@@ -21,12 +22,14 @@ void FetchEngine::handle_command(Engine::EngineCommand command)
{
command.visit(
[this](Engine::Command::StartFetch& start_fetch) {
- auto record = Engine::FetchEngineRecord::create(move(start_fetch.input.event_sink), m_network_activity_observers);
- run_deferred_main_fetch_steps(start_fetch.input.fetch_id, move(record));
+ auto record = m_records.start(start_fetch.input.fetch_id, move(start_fetch.input.event_sink), m_network_activity_observers);
+ if (!record)
+ return;
+ run_deferred_main_fetch_steps(start_fetch.input.fetch_id, record.release_nonnull());
},
- [](Engine::Command::Abort const&) { VERIFY_NOT_REACHED(); },
- [](Engine::Command::Terminate const&) { VERIFY_NOT_REACHED(); },
- [](Engine::Command::Stop const&) { VERIFY_NOT_REACHED(); },
+ [this](Engine::Command::Abort const& abort) { m_records.stop_body_transport(abort.fetch_id); },
+ [this](Engine::Command::Terminate const& terminate) { m_records.stop_body_transport(terminate.fetch_id); },
+ [this](Engine::Command::Stop const& stop) { m_records.stop_body_transport(stop.fetch_id); },
[](Engine::Command::ResolveRedirect const&) { VERIFY_NOT_REACHED(); },
[](Engine::Command::PreloadResponseResolved const&) { VERIFY_NOT_REACHED(); },
[](Engine::Command::TransportControl const&) { VERIFY_NOT_REACHED(); },
@@ -36,7 +39,7 @@ void FetchEngine::handle_command(Engine::EngineCommand command)
NonnullRefPtr<Engine::FetchExecutor> create_inline_fetch_executor(NonnullRefPtr<Engine::NetworkActivityObservers const> network_activity_observers)
{
Engine::FetchExecutorServices services { .event_loop = Core::EventLoop::current_weak() };
- return Engine::InlineFetchExecutor::create(move(services), make<FetchEngine>(move(network_activity_observers)));
+ return Engine::InlineFetchExecutor::create(move(services), make<FetchEngine>(move(network_activity_observers), make<Engine::FetchEngineRecords::Agent>()));
}
}
diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchEngine.h b/Libraries/LibWeb/Fetch/Fetching/FetchEngine.h
index b5483aac1cb..2f6f1653f14 100644
--- a/Libraries/LibWeb/Fetch/Fetching/FetchEngine.h
+++ b/Libraries/LibWeb/Fetch/Fetching/FetchEngine.h
@@ -9,6 +9,7 @@
#include <AK/NonnullRefPtr.h>
#include <LibWeb/Export.h>
#include <LibWeb/Fetch/Engine/EngineCommandSink.h>
+#include <LibWeb/Fetch/Engine/FetchEngineRecord.h>
#include <LibWeb/Fetch/Engine/FetchExecutor.h>
#include <LibWeb/Fetch/Engine/NetworkActivityObservers.h>
@@ -17,12 +18,13 @@ namespace Web::Fetch::Fetching {
// Handles the commands posted for the fetches of the agent on whose thread it runs.
class FetchEngine final : public Engine::EngineCommandSink {
public:
- explicit FetchEngine(NonnullRefPtr<Engine::NetworkActivityObservers const>);
+ FetchEngine(NonnullRefPtr<Engine::NetworkActivityObservers const>, NonnullOwnPtr<Engine::FetchEngineRecords::Agent>);
virtual void handle_command(Engine::EngineCommand) override;
private:
NonnullRefPtr<Engine::NetworkActivityObservers const> m_network_activity_observers;
+ Engine::FetchEngineRecords m_records;
};
// Creates an executor that runs a fetch engine on the current thread's event loop.
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 71c0ecbba09..c4ea0f3cf58 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -995,9 +995,12 @@ 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 event_sink = make<FetchEventSink>(*fetch_params.controller());
+ auto controller = fetch_params.controller();
+ auto& fetch_executor = *agent.fetch_executor;
+ controller->set_started_fetch(fetch_id, fetch_executor);
+ auto event_sink = make<FetchEventSink>(*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) });
+ fetch_executor.post(Engine::Command::StartFetch { move(start_fetch_input) });
return GC::Ptr<PendingResponse> {};
}
@@ -1424,7 +1427,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
if (internal_response->body()->source().has_value() || has_whole_body) {
// NB: process_body() reads the body's source itself and ignores the bytes passed here.
success_steps->function()({});
- fetch_params.controller()->stop_body_transport();
+ fetch_params.stop_body_transport();
} else {
auto reader = body_view->stream()->get_a_reader();
if (reader.is_exception()) {
@@ -2288,9 +2291,13 @@ static GC::Ref<PendingResponse> continue_http_network_or_cache_fetch(JS::Object&
pending_forward_response = PendingResponse::create(fetch_params, Infrastructure::Response::create());
}
- // AD-HOC: If the controller is already in the non-spec Stopped state, we should cancel the network request immediately.
- if (http_fetch_params->control_block().is_stopped())
- http_fetch_params->controller()->stop_fetch();
+ // AD-HOC: If the controller is already in the non-spec Stopped state, we should report the stop for this request and
+ // cancel the network request immediately.
+ if (http_fetch_params->control_block().is_stopped()) {
+ if (WebDriver::BiDi::network_events_enabled())
+ WebDriver::BiDi::network_fetch_error(fetch_params, "Fetch was stopped"sv);
+ http_fetch_params->stop_body_transport();
+ }
auto returned_pending_response = PendingResponse::create(fetch_params);
@@ -2891,6 +2898,12 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
auto whole_body_transport = create_whole_body_transport(*body_pump->delivery_gate(), *body_pump->channel());
auto on_headers_received = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { fetch_params }, NonnullRefPtr { *engine_record }, pending_response, request, body_pump, whole_body_transport, http_cache), [](auto& fetch_params, auto& engine_record, auto& pending_response, auto& request, auto& body_pump, auto& whole_body_transport, auto& http_cache, Engine::NetworkTransportHandle* network_transport, HTTP::HeaderList const& response_headers, Optional<u32> status_code, Optional<String> const& reason_phrase, Requests::CacheState cache_state) {
+ // 8. Run these steps, but abort when fetchParams is canceled:
+ // AD-HOC: A stopped fetch is not canceled, but takes no more headers either. A load without a RequestServer
+ // request takes its headers regardless.
+ if (network_transport && !fetch_params->control_block().is_ongoing())
+ return;
+
if (network_transport) {
Engine::Event::NetworkActivity::ResponseHeaders headers {
.status_code = status_code.value_or(0),
@@ -2977,8 +2990,8 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
body_pump->handle_network_data(move(data));
});
- auto on_data_received = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { *engine_record }, deliver_body_data, whole_body_transport), [](auto& engine_record, auto& deliver_body_data, auto& whole_body_transport, Engine::NetworkTransportHandle* network_transport, Requests::ResponseData data) {
- if (network_transport && engine_record->network_activity_observers().has_devtools_client()) {
+ auto on_data_received = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { fetch_params.control_block() }, NonnullRefPtr { *engine_record }, deliver_body_data, whole_body_transport), [](auto& control_block, auto& engine_record, auto& deliver_body_data, auto& whole_body_transport, Engine::NetworkTransportHandle* network_transport, Requests::ResponseData data) {
+ if (network_transport && control_block->is_ongoing() && engine_record->network_activity_observers().has_devtools_client()) {
Engine::Event::NetworkActivity::ResponseBodyBytes body_bytes { MUST(Core::ImmutableBytes::copy(data.bytes())) };
engine_record->report_network_activity(network_transport->request_id(), move(body_bytes));
}
@@ -3013,8 +3026,15 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
}
});
- auto on_complete = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { *engine_record }, complete_load, whole_body_transport), [](auto& engine_record, auto& complete_load, auto& whole_body_transport, bool success, Requests::RequestTimingInfo const& timing_info, Optional<StringView> error_message, Optional<ResourceLoader::NetworkRequestEnd> const& network_request_end) {
+ auto on_complete = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { fetch_params.control_block() }, NonnullRefPtr { *engine_record }, body_pump, complete_load, whole_body_transport), [](auto& control_block, auto& engine_record, auto& body_pump, auto& complete_load, auto& whole_body_transport, bool success, Requests::RequestTimingInfo const& timing_info, Optional<StringView> error_message, Optional<ResourceLoader::NetworkRequestEnd> const& network_request_end) {
if (network_request_end.has_value()) {
+ // 1. Run these steps, but abort when fetchParams is canceled:
+ // AD-HOC: A stopped fetch is not canceled, but takes no more of its body either.
+ if (!control_block->is_ongoing()) {
+ body_pump->handle_network_teardown(Requests::Request::TeardownReason::Stopped);
+ return;
+ }
+
Engine::Event::NetworkActivity::RequestFinished finished {
.total_size = network_request_end->total_size,
.timing_info = timing_info,
@@ -3027,7 +3047,13 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
complete_load->function()(success, timing_info, error_message);
return;
}
- whole_body_transport->when_delivered([complete_load = GC::Root { complete_load }, timing_info] {
+ whole_body_transport->when_delivered([control_block, body_pump = GC::Root { body_pump }, complete_load = GC::Root { complete_load }, timing_info] {
+ // 1. Run these steps, but abort when fetchParams is canceled:
+ // AD-HOC: A stopped fetch is not canceled, but takes no more of its body either.
+ if (!control_block->is_ongoing()) {
+ body_pump->handle_network_teardown(Requests::Request::TeardownReason::Stopped);
+ return;
+ }
complete_load->function()(true, timing_info, {});
});
});
@@ -3047,9 +3073,10 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
control_block->set_requires_network();
});
}
- fetch_params.controller()->set_network_transport(*network_transport);
+ fetch_params.set_body_transport(*network_transport);
+ fetch_params.control_block().set_has_started_request();
} else {
- fetch_params.controller()->set_body_transport(whole_body_transport);
+ fetch_params.set_body_transport(whole_body_transport);
}
// To transmit request’s body body, run these steps:
@@ -3168,7 +3195,7 @@ GC::Ref<PendingResponse> cors_preflight_fetch(JS::Realm& realm, Infrastructure::
auto preflight_response = http_network_or_cache_fetch(realm, preflight_fetch_params);
- preflight_response->when_loaded(GC::create_function(GC::Heap::the(), GC::captures(fetch_params.request(), returned_pending_response, GC::Ref { *preflight_controller }, preflight_fetch_params), [](NonnullRefPtr<Infrastructure::Request>& request, GC::Ref<PendingResponse>& returned_pending_response, GC::Ref<Infrastructure::FetchController>& preflight_controller, NonnullRefPtr<Infrastructure::FetchParams>& preflight_fetch_params, NonnullRefPtr<Infrastructure::Response> response) {
+ preflight_response->when_loaded(GC::create_function(GC::Heap::the(), GC::captures(fetch_params.request(), returned_pending_response, preflight_fetch_params), [](NonnullRefPtr<Infrastructure::Request>& request, GC::Ref<PendingResponse>& returned_pending_response, NonnullRefPtr<Infrastructure::FetchParams>& preflight_fetch_params, NonnullRefPtr<Infrastructure::Response> response) {
dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'CORS-preflight fetch' preflight_response load callback");
if (WebDriver::BiDi::network_events_enabled()) {
@@ -3179,7 +3206,7 @@ GC::Ref<PendingResponse> cors_preflight_fetch(JS::Realm& realm, Infrastructure::
}
// NB: Only the preflight response's headers are read.
- preflight_controller->stop_body_transport();
+ preflight_fetch_params->stop_body_transport();
// 7. If a CORS check for request and response returns success and response’s status is an ok status, then:
// NOTE: The CORS check is done on request rather than preflight to ensure the correct credentials mode is used.
diff --git a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp
index 2684ebf7e55..30d4b780490 100644
--- a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp
@@ -70,7 +70,8 @@ void NetworkBodyPump::visit_edges(Visitor& visitor)
void NetworkBodyPump::handle_network_data(Requests::ResponseData data)
{
// 1. Run these steps, but abort when fetchParams is canceled:
- if (m_fetch_params && m_fetch_params->is_canceled()) {
+ // AD-HOC: A stopped fetch is not canceled, but takes no more of its body either.
+ if (m_fetch_params && !m_fetch_params->control_block().is_ongoing()) {
m_channel->cancel();
return;
}
diff --git a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h
index 9eea94db046..eaacdb9614b 100644
--- a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h
+++ b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h
@@ -14,6 +14,7 @@
#include <LibHTTP/Cache/MemoryCache.h>
#include <LibJS/Heap/Cell.h>
#include <LibRequests/Request.h>
+#include <LibWeb/Export.h>
#include <LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h>
#include <LibWeb/Fetch/Engine/FetchByteChannel.h>
#include <LibWeb/Forward.h>
@@ -22,7 +23,7 @@ namespace Web::Fetch::Fetching {
// The producer half of a streamed response body: memory-cache accumulation, and the writes into the channel the
// stream pulls from.
-class NetworkBodyPump final : public JS::Cell {
+class WEB_API NetworkBodyPump final : public JS::Cell {
GC_CELL(NetworkBodyPump, JS::Cell);
GC_DECLARE_ALLOCATOR(NetworkBodyPump);
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchControlBlock.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchControlBlock.h
index 0a7985999e1..ddfd555dba8 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchControlBlock.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchControlBlock.h
@@ -10,6 +10,7 @@
#include <AK/Badge.h>
#include <AK/NonnullRefPtr.h>
#include <AK/RefPtr.h>
+#include <LibGC/Forward.h>
#include <LibWeb/Fetch/Engine/BodyIntent.h>
#include <LibWeb/Fetch/Infrastructure/FetchTimingInfo.h>
@@ -20,6 +21,8 @@ class FetchController;
// The state of a fetch that its controller and its fetch params share.
class FetchControlBlock : public AtomicRefCounted<FetchControlBlock> {
public:
+ GC_HOLDS_NO_CELL_EDGES;
+
enum class State : u8 {
Ongoing,
Terminated,
@@ -65,7 +68,7 @@ public:
[[nodiscard]] bool response_arrived() const { return m_response_arrived; }
[[nodiscard]] bool has_started_request() const { return m_has_started_request; }
- void set_has_started_request(Badge<FetchController>) { m_has_started_request = true; }
+ void set_has_started_request() { m_has_started_request = true; }
[[nodiscard]] bool requires_network() const { return m_requires_network; }
void set_requires_network() { m_requires_network = true; }
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp
index c1815d93b39..2a2939047c1 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp
@@ -7,7 +7,8 @@
#include <LibGC/Heap.h>
#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Fetch/Engine/NetworkTransportHandle.h>
+#include <LibWeb/Fetch/Engine/EngineCommand.h>
+#include <LibWeb/Fetch/Engine/FetchExecutor.h>
#include <LibWeb/Fetch/Fetching/PendingResponse.h>
#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
@@ -130,17 +131,6 @@ GC::Ref<Page> FetchController::page() const
return *m_page;
}
-void FetchController::set_network_transport(Engine::NetworkTransportHandle& network_transport)
-{
- set_body_transport(network_transport);
- m_control_block->set_has_started_request({});
-}
-
-void FetchController::set_body_transport(Engine::FetchBodyDeliveryGate::Transport& body_transport)
-{
- m_body_transport = body_transport;
-}
-
void FetchController::set_report_timing_steps(GC::Ref<GC::Function<void(JS::Object&)>> report_timing_steps)
{
m_report_timing_steps = report_timing_steps;
@@ -235,6 +225,11 @@ void FetchController::terminate()
stop_request();
}
+void FetchController::set_started_fetch(Engine::FetchId fetch_id, Engine::FetchExecutor& fetch_executor)
+{
+ m_started_fetch = StartedFetch { fetch_id, fetch_executor };
+}
+
void FetchController::stop_fetch()
{
if (m_control_block->is_canceled())
@@ -267,26 +262,32 @@ void FetchController::stop_fetch()
}
}
-// Stops the network request of a fetch that is no longer ongoing. HTTP-network fetch reads a response's body in steps
-// that "abort when fetchParams is canceled" (step 18.1) — and once aborted, "the user agent should close connection
-// unless it would be bad for performance to do so" (step 18.2.4). So a canceled fetch's request has to stop as well as
-// a stopped one's: otherwise it streams on until the server ends the response, and its callbacks root the fetch's realm
-// for all that time.
-// https://fetch.spec.whatwg.org/#concept-http-network-fetch
+static Engine::EngineCommand stop_command(FetchControlBlock::State state, Engine::FetchId fetch_id)
+{
+ switch (state) {
+ case FetchControlBlock::State::Aborted:
+ return Engine::Command::Abort { fetch_id };
+ case FetchControlBlock::State::Terminated:
+ return Engine::Command::Terminate { fetch_id };
+ case FetchControlBlock::State::Stopped:
+ return Engine::Command::Stop { fetch_id };
+ case FetchControlBlock::State::Ongoing:
+ break;
+ }
+ VERIFY_NOT_REACHED();
+}
+
+// Posts the command that stops the network request of a fetch that is no longer ongoing, to the executor the fetch was
+// started on.
void FetchController::stop_request()
{
end_rendering_pending_operation(this);
VERIFY(!m_control_block->is_ongoing());
m_awaited_network_completion.clear();
- stop_body_transport();
-}
-void FetchController::stop_body_transport()
-{
- if (auto body_transport = m_body_transport.strong_ref()) {
- m_body_transport = nullptr;
- body_transport->stop();
- }
+ if (!m_started_fetch.has_value())
+ return;
+ m_started_fetch->fetch_executor->post(stop_command(state(), m_started_fetch->fetch_id));
}
void FetchController::fetch_task_queued(u64 fetch_task_id, HTML::TaskID event_id)
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
index 2e3190cef2d..82be6106b2e 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
@@ -15,8 +15,9 @@
#include <LibJS/Heap/Cell.h>
#include <LibJS/Runtime/VM.h>
#include <LibWeb/Export.h>
-#include <LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h>
#include <LibWeb/Fetch/Engine/FetchByteChannel.h>
+#include <LibWeb/Fetch/Engine/FetchExecutor.h>
+#include <LibWeb/Fetch/Engine/Ids.h>
#include <LibWeb/Fetch/Infrastructure/FetchControlBlock.h>
#include <LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h>
#include <LibWeb/Fetch/Infrastructure/FetchTimingInfo.h>
@@ -97,15 +98,15 @@ public:
[[nodiscard]] GC::Ptr<Fetching::PendingResponse> pending_preloaded_response() const { return m_pending_preloaded_response; }
void set_pending_preloaded_response(GC::Ptr<Fetching::PendingResponse> pending_preloaded_response) { m_pending_preloaded_response = pending_preloaded_response; }
- void set_network_transport(Engine::NetworkTransportHandle&);
- void set_body_transport(Engine::FetchBodyDeliveryGate::Transport&);
bool requires_network() const { return m_control_block->requires_network(); }
bool has_started_request() const { return m_control_block->has_started_request(); }
void set_inner_fetch_controller(GC::Ref<FetchController>);
+ // The fetch this controller's fetch params started last, and the executor its start was posted to. The controller's
+ // stops are posted there, for that fetch.
+ void set_started_fetch(Engine::FetchId, Engine::FetchExecutor&);
+
void stop_fetch();
- // Stops the delivery of the current response's body without ending the fetch.
- void stop_body_transport();
void set_stop_steps(GC::Ref<GC::Function<void()>> stop_steps) { m_stop_steps = stop_steps; }
u64 next_fetch_task_id() { return m_next_fetch_task_id++; }
@@ -186,7 +187,11 @@ private:
// Widen this if preload handoff ever supports multiple consumers.
GC::Ptr<Fetching::PendingResponse> m_pending_preloaded_response;
- WeakPtr<Engine::FetchBodyDeliveryGate::Transport> m_body_transport;
+ struct StartedFetch {
+ Engine::FetchId fetch_id;
+ NonnullRefPtr<Engine::FetchExecutor> fetch_executor;
+ };
+ Optional<StartedFetch> m_started_fetch;
HashMap<u64, HTML::TaskID> m_ongoing_fetch_tasks;
u64 m_next_fetch_task_id { 0 };
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp
index b91b82b240d..00943f9574a 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp
@@ -54,10 +54,29 @@ Engine::StartFetchInput FetchParams::start_fetch_input(Engine::FetchId fetch_id,
return Engine::StartFetchInput { {}, fetch_id, m_control_block->body_intent(), m_blob_url_entry, move(event_sink) };
}
+void FetchParams::set_body_transport(Engine::FetchBodyDeliveryGate::Transport& transport) const
+{
+ VERIFY(m_engine_record);
+ if (m_is_cors_preflight)
+ m_engine_record->set_cors_preflight_body_transport(transport);
+ else
+ m_engine_record->set_body_transport(transport);
+}
+
+void FetchParams::stop_body_transport() const
+{
+ if (!m_engine_record)
+ return;
+ if (m_is_cors_preflight)
+ m_engine_record->stop_cors_preflight_body_transport();
+ else
+ m_engine_record->stop_body_transport();
+}
+
void FetchParams::discard_response_body(Response const& response) const
{
response.release_request_transfer_lease();
- controller()->stop_body_transport();
+ stop_body_transport();
}
GC::Ref<FetchController> FetchParams::controller() const
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h
index 1dc3e17161f..7edbd078dd1 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h
@@ -74,6 +74,11 @@ public:
[[nodiscard]] bool is_cors_preflight() const { return m_is_cors_preflight; }
void set_is_cors_preflight() { m_is_cors_preflight = true; }
+ // The transport of the response body these fetch params receive, which the fetch's engine record keeps.
+ void set_body_transport(Engine::FetchBodyDeliveryGate::Transport&) const;
+ // Stops that transport, if there is one, without ending the fetch.
+ void stop_body_transport() const;
+
// Ends the delivery of a response's body that the fetch will not read.
void discard_response_body(Response const&) const;
diff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txt
index 4a0e5e9f65b..ad7a4f4dd41 100644
--- a/Tests/LibWeb/CMakeLists.txt
+++ b/Tests/LibWeb/CMakeLists.txt
@@ -25,6 +25,7 @@ set(TEST_SOURCES
TestFetchController.cpp
TestFetchControllerRegistry.cpp
TestFetchEngineMessages.cpp
+ TestFetchEngineRecord.cpp
TestFetchExecutor.cpp
TestFetchResponse.cpp
TestFetchTaskDestination.cpp
diff --git a/Tests/LibWeb/TestAgentThreads.cpp b/Tests/LibWeb/TestAgentThreads.cpp
index f9bf9ec06e0..6ddfc1d6cb4 100644
--- a/Tests/LibWeb/TestAgentThreads.cpp
+++ b/Tests/LibWeb/TestAgentThreads.cpp
@@ -580,10 +580,11 @@ static void set_up_process()
Web::Platform::FontPlugin::install(*new Web::Platform::FontPlugin(false));
}
-// Each command an executor posts holds the executor until the command has run or been dropped.
-static bool has_queued_commands(Web::Fetch::Engine::FetchExecutor const& executor)
+// Each command an executor posts holds the executor until the command has run or been dropped. So do the agent and
+// each live controller of a fetch started through the executor.
+static bool has_queued_commands(Web::Fetch::Engine::FetchExecutor const& executor, size_t live_controller_count)
{
- return executor.ref_count() > 1;
+ return executor.ref_count() > 1 + live_controller_count;
}
TEST_CASE(an_agent_runs_on_a_thread_of_its_own)
@@ -666,7 +667,8 @@ TEST_CASE(a_fetch_started_just_before_close_never_runs_its_in_parallel_steps)
auto request = agent.fetch_and_close("about:blank"sv, Web::Fetch::Infrastructure::FetchAlgorithms::Input { Web::Fetch::Engine::BodyIntent::DrainAndDiscard });
// The worker's event loop has stopped with the command that runs the fetch's in-parallel steps still queued.
- EXPECT(has_queued_commands(*Web::HTML::surrounding_agent().fetch_executor));
+ // Those steps keep the fetch's controller alive.
+ EXPECT(has_queued_commands(*Web::HTML::surrounding_agent().fetch_executor, 1));
agent.shut_down();
diff --git a/Tests/LibWeb/TestFetchAlgorithms.cpp b/Tests/LibWeb/TestFetchAlgorithms.cpp
index d7ba1e8591e..bf73da60156 100644
--- a/Tests/LibWeb/TestFetchAlgorithms.cpp
+++ b/Tests/LibWeb/TestFetchAlgorithms.cpp
@@ -16,10 +16,17 @@
#include <LibJS/Runtime/Error.h>
#include <LibTest/TestCase.h>
#include <LibURL/Parser.h>
+#include <LibWeb/Fetch/Engine/EngineCommand.h>
+#include <LibWeb/Fetch/Engine/EngineCommandSink.h>
#include <LibWeb/Fetch/Engine/EngineEvent.h>
+#include <LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h>
+#include <LibWeb/Fetch/Engine/FetchByteChannel.h>
+#include <LibWeb/Fetch/Engine/InlineFetchExecutor.h>
+#include <LibWeb/Fetch/Engine/WholeBodyTransport.h>
#include <LibWeb/Fetch/Fetching/FetchEngine.h>
#include <LibWeb/Fetch/Fetching/FetchEventSink.h>
#include <LibWeb/Fetch/Fetching/Fetching.h>
+#include <LibWeb/Fetch/Fetching/NetworkBodyPump.h>
#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
#include <LibWeb/Fetch/Infrastructure/FetchParams.h>
@@ -38,14 +45,21 @@
#include <LibWeb/WebDriver/BiDi/BiDi.h>
#include <LibWeb/WebIDL/DOMException.h>
+using Web::Fetch::Engine::EngineCommand;
+using Web::Fetch::Engine::EngineCommandSink;
+using Web::Fetch::Engine::FetchBodyDeliveryGate;
+using Web::Fetch::Engine::FetchByteChannel;
+using Web::Fetch::Engine::WholeBodyTransport;
using Web::Fetch::Engine::Event::NetworkActivity;
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::Fetching::NetworkBodyPump;
using Web::Fetch::Infrastructure::FetchAlgorithms;
using Web::Fetch::Infrastructure::FetchController;
+using Web::Fetch::Infrastructure::FetchParams;
using Web::Fetch::Infrastructure::Request;
using Web::Fetch::Infrastructure::ResponseView;
@@ -243,6 +257,163 @@ TEST_CASE(a_stop_leaves_the_algorithms_for_the_next_fetch)
EXPECT_EQ(record->call_count, 3u);
}
+namespace {
+
+// What reached the steps a test set up, which the test reads once they have run.
+struct ReachedSteps : RefCounted<ReachedSteps> {
+ GC_HOLDS_NO_CELL_EDGES;
+
+ Vector<ByteString> steps;
+ bool marker_reached { false };
+};
+
+// Records each stop that reaches the fetch engine.
+class StopRecordingEngine final : public EngineCommandSink {
+public:
+ explicit StopRecordingEngine(NonnullRefPtr<ReachedSteps> reached)
+ : m_reached(move(reached))
+ {
+ }
+
+ virtual void handle_command(EngineCommand command) override
+ {
+ command.visit(
+ [&](Web::Fetch::Engine::Command::Abort const& abort) { m_reached->steps.append(ByteString::formatted("abort {}", abort.fetch_id.value())); },
+ [&](Web::Fetch::Engine::Command::Terminate const& terminate) { m_reached->steps.append(ByteString::formatted("terminate {}", terminate.fetch_id.value())); },
+ [&](Web::Fetch::Engine::Command::Stop const& stop) { m_reached->steps.append(ByteString::formatted("stop {}", stop.fetch_id.value())); },
+ [](auto const&) { FAIL("unexpected command"); });
+ }
+
+private:
+ NonnullRefPtr<ReachedSteps> m_reached;
+};
+
+// A fetch that has run to its end, with a response body whose transport the fetch's engine record keeps.
+struct FetchWithBody {
+ GC::Root<FetchController> controller;
+ NonnullRefPtr<FetchParams> fetch_params;
+ GC::Root<NetworkBodyPump> body_pump;
+ NonnullRefPtr<WholeBodyTransport> transport;
+};
+
+}
+
+static FetchWithBody fetch_with_a_body(FetchHarness const& harness)
+{
+ auto request = harness.create_request();
+ auto controller = GC::make_root(harness.fetch(request, FetchAlgorithms::Input { Web::Fetch::Engine::BodyIntent::DrainAndDiscard }));
+ auto fetch_params = controller->original_fetch_params();
+ VERIFY(fetch_params);
+ harness.run_tasks_until(GC::create_function(harness.realm->heap(), GC::captures(request), [](auto& request) { return request->done(); }));
+
+ auto body_pump = GC::make_root(NetworkBodyPump::create(fetch_params, FetchBodyDeliveryGate::NavigationHold::None, nullptr));
+ auto transport = Web::Fetch::Fetching::create_whole_body_transport(*body_pump->delivery_gate(), *body_pump->channel());
+ fetch_params->set_body_transport(*transport);
+ return { move(controller), fetch_params.release_nonnull(), move(body_pump), move(transport) };
+}
+
+// Hands the transport its body, as the network fetch does once the response's headers arrive.
+static void deliver_body(FetchWithBody& fetch, WholeBodyTransport::OnData on_data)
+{
+ fetch.transport->attach_to(*fetch.body_pump->delivery_gate());
+ auto body = Core::ImmutableBytes::adopt(MUST(ByteBuffer::copy("hello"sv.bytes())));
+ fetch.transport->set_body(move(body), move(on_data));
+}
+
+// Runs the deferred invocations queued so far, then those that they queue.
+static void run_queued_invocations(FetchHarness const& harness)
+{
+ auto reached = make_ref_counted<ReachedSteps>();
+ Core::deferred_invoke([reached] {
+ Core::deferred_invoke([reached] { reached->marker_reached = true; });
+ });
+ harness.run_tasks_until(GC::create_function(harness.realm->heap(), GC::captures(reached), [](auto& reached) { return reached->marker_reached; }));
+}
+
+TEST_CASE(each_stop_of_a_started_fetch_reaches_the_engine_for_its_fetch_id)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+
+ auto reached = make_ref_counted<ReachedSteps>();
+ Web::Fetch::Engine::FetchExecutorServices services { .event_loop = Core::EventLoop::current_weak() };
+ auto fetch_executor = Web::Fetch::Engine::InlineFetchExecutor::create(move(services), make<StopRecordingEngine>(reached));
+
+ auto& registry = Web::HTML::surrounding_agent().fetch_controller_registry;
+ auto create_controller = [&](Optional<u64> fetch_id) {
+ auto controller = GC::make_root(FetchController::create(registry));
+ if (fetch_id.has_value())
+ controller->set_started_fetch(Web::Fetch::Engine::FetchId { *fetch_id }, *fetch_executor);
+ return controller;
+ };
+ auto stopped = create_controller(1);
+ auto aborted = create_controller(2);
+ auto terminated = create_controller(3);
+ auto never_started = create_controller({});
+ // A navigation's manual redirect starts another fetch with the same controller.
+ auto redirected = create_controller(4);
+ redirected->set_started_fetch(Web::Fetch::Engine::FetchId { 5 }, *fetch_executor);
+
+ stopped->stop_fetch();
+ {
+ Web::HTML::TemporaryExecutionContext execution_context { *harness.realm, Web::HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ aborted->abort(*harness.realm, {});
+ never_started->abort(*harness.realm, {});
+ }
+ terminated->terminate();
+ never_started->terminate();
+ redirected->stop_fetch();
+ run_queued_invocations(harness);
+
+ EXPECT_EQ(reached->steps, (Vector<ByteString> { "stop 1", "abort 2", "terminate 3", "stop 5" }));
+}
+
+TEST_CASE(a_stop_reaches_the_body_transport_of_the_fetch_before_deliveries_queued_after_it)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+
+ auto stopped = fetch_with_a_body(harness);
+ auto aborted = fetch_with_a_body(harness);
+ auto terminated = fetch_with_a_body(harness);
+
+ stopped.controller->stop_fetch();
+ {
+ Web::HTML::TemporaryExecutionContext execution_context { *harness.realm, Web::HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ aborted.controller->abort(*harness.realm, {});
+ }
+ terminated.controller->terminate();
+
+ auto reached = make_ref_counted<ReachedSteps>();
+ for (auto* fetch : { &stopped, &aborted, &terminated }) {
+ deliver_body(*fetch, [reached](Requests::ResponseData) { reached->steps.append("data"); });
+ fetch->transport->when_delivered([reached] { reached->steps.append("end"); });
+ }
+ run_queued_invocations(harness);
+
+ EXPECT(reached->steps.is_empty());
+ for (auto* fetch : { &stopped, &aborted, &terminated })
+ EXPECT(fetch->body_pump->channel()->peek_up_to(0).state.has<FetchByteChannel::ConsumerCancelled>());
+}
+
+TEST_CASE(body_bytes_queued_before_a_stop_are_not_delivered)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+
+ auto fetch = fetch_with_a_body(harness);
+ deliver_body(fetch, [body_pump = fetch.body_pump](Requests::ResponseData data) { body_pump->handle_network_data(move(data)); });
+ fetch.controller->stop_fetch();
+ run_queued_invocations(harness);
+
+ auto buffered = fetch.body_pump->channel()->peek_up_to(5);
+ EXPECT(buffered.taken.is_empty());
+ EXPECT(buffered.state.has<FetchByteChannel::ConsumerCancelled>());
+}
+
static NEVER_INLINE void start_fetch_without_holding_its_controller(FetchHarness const& harness, Request& request, FetchAlgorithms::Input input)
{
(void)harness.fetch(request, move(input));
@@ -624,6 +795,47 @@ TEST_CASE(a_request_fetched_again_keeps_its_webdriver_bidi_request_id)
EXPECT_NE(events->request_ids[2], events->request_ids[0]);
}
+TEST_CASE(a_request_that_starts_after_its_fetch_was_stopped_reports_the_stop)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+
+ auto events = make_ref_counted<ReachedSteps>();
+ Web::WebDriver::BiDi::set_event_sink({
+ .on_event = [events](Web::HTML::Navigable const&, String const& name, JsonValue params) {
+ auto const& object = params.as_object();
+ auto event = ByteString::formatted("{} {}", name, object.get_u32("redirectCount"sv).value());
+ if (auto error_text = object.get_string("errorText"sv); error_text.has_value())
+ event = ByteString::formatted("{}: {}", event, *error_text);
+ events->steps.append(move(event));
+ },
+ .on_navigation_event = {},
+ });
+ Web::WebDriver::BiDiSessionState session_state;
+ session_state.is_active = true;
+ session_state.enabled_events = { "network.beforeRequestSent"_string, "network.fetchError"_string };
+ Web::WebDriver::BiDi::set_session_state(move(session_state));
+ ScopeGuard end_session = [] {
+ Web::WebDriver::BiDi::set_session_state({});
+ Web::WebDriver::BiDi::set_event_sink({});
+ };
+
+ auto request = harness.create_request_for("http://localhost/"sv);
+ auto controller = harness.fetch(request, FetchAlgorithms::Input { Web::Fetch::Engine::BodyIntent::DrainAndDiscard });
+ controller->stop_fetch();
+ // A redirect the stopped fetch follows moves its request on to the next redirect count.
+ request->set_redirect_count(1);
+ harness.run_tasks_until(GC::create_function(harness.realm->heap(), GC::captures(request), [](auto& request) { return request->done(); }));
+
+ EXPECT_EQ(events->steps, (Vector<ByteString> {
+ "network.beforeRequestSent 0",
+ "network.fetchError 0: Fetch was stopped",
+ "network.beforeRequestSent 1",
+ "network.fetchError 1: Fetch was stopped",
+ }));
+}
+
namespace {
// A page client that records the network activity reported to it.
diff --git a/Tests/LibWeb/TestFetchController.cpp b/Tests/LibWeb/TestFetchController.cpp
index 623c2b36494..ed08366688d 100644
--- a/Tests/LibWeb/TestFetchController.cpp
+++ b/Tests/LibWeb/TestFetchController.cpp
@@ -8,13 +8,29 @@
#include <LibGC/Heap.h>
#include <LibGC/Root.h>
#include <LibTest/TestCase.h>
+#include <LibWeb/Fetch/Engine/FetchEngineRecord.h>
#include <LibWeb/Fetch/Engine/WholeBodyTransport.h>
+#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
#include <LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h>
+#include <LibWeb/Fetch/Infrastructure/FetchParams.h>
+#include <LibWeb/Loader/LoaderConfig.h>
+using Web::Fetch::Engine::FetchEngineRecords;
using Web::Fetch::Engine::WholeBodyTransport;
+using Web::Fetch::Infrastructure::FetchAlgorithms;
using Web::Fetch::Infrastructure::FetchController;
using Web::Fetch::Infrastructure::FetchControllerRegistry;
+using Web::Fetch::Infrastructure::FetchParams;
+
+namespace {
+
+class IgnoringEventSink final : public Web::Fetch::Engine::EngineEventSink {
+public:
+ virtual void handle_event(Web::Fetch::Engine::EngineEvent) override { }
+};
+
+}
static GC::Heap& test_heap()
{
@@ -27,29 +43,71 @@ TEST_SETUP
GC::Heap::set_default_heap_for_testing(test_heap());
}
-TEST_CASE(a_terminated_fetch_stops_a_body_transport_without_a_request)
+static NonnullRefPtr<FetchParams> create_fetch_params(FetchController& controller)
+{
+ auto algorithms = FetchAlgorithms::create(FetchAlgorithms::Input { Web::Fetch::Engine::BodyIntent::DrainAndDiscard });
+ auto request = Web::Fetch::Infrastructure::Request::create();
+ auto timing_info = Web::Fetch::Infrastructure::FetchTimingInfo::create();
+ return FetchParams::create(controller, move(request), algorithms, move(timing_info), Web::current_loader_config());
+}
+
+static NonnullRefPtr<Web::Fetch::Engine::FetchEngineRecord> start_fetch(FetchEngineRecords& records)
+{
+ auto event_sink = make<IgnoringEventSink>();
+ return records.start(Web::Fetch::Engine::FetchId { 1 }, move(event_sink), Web::Fetch::Engine::NetworkActivityObservers::create()).release_nonnull();
+}
+
+TEST_CASE(a_controller_that_started_no_fetch_can_be_terminated)
+{
+ FetchControllerRegistry registry;
+ auto controller = GC::make_root(FetchController::create(registry));
+
+ controller->terminate();
+ EXPECT_EQ(controller->state(), FetchController::State::Terminated);
+}
+
+TEST_CASE(stopping_the_body_transport_leaves_the_fetch_ongoing)
{
FetchControllerRegistry registry;
+ FetchEngineRecords records { make<FetchEngineRecords::Agent>() };
auto controller = GC::make_root(FetchController::create(registry));
+ auto fetch_params = create_fetch_params(*controller);
+ fetch_params->set_engine_record(start_fetch(records));
auto transport = WholeBodyTransport::create();
bool stopped = false;
transport->set_on_stop([&] { stopped = true; });
- controller->set_body_transport(transport);
+ fetch_params->set_body_transport(transport);
- controller->terminate();
+ fetch_params->stop_body_transport();
EXPECT(stopped);
+ EXPECT_EQ(controller->state(), FetchController::State::Ongoing);
}
-TEST_CASE(stopping_the_body_transport_leaves_the_fetch_ongoing)
+TEST_CASE(a_cors_preflight_stops_its_own_body_transport_and_not_that_of_its_fetch)
{
FetchControllerRegistry registry;
+ FetchEngineRecords records { make<FetchEngineRecords::Agent>() };
auto controller = GC::make_root(FetchController::create(registry));
+ auto fetch_params = create_fetch_params(*controller);
+ fetch_params->set_engine_record(start_fetch(records));
+ auto preflight_controller = GC::make_root(FetchController::create(registry));
+ auto preflight_fetch_params = create_fetch_params(*preflight_controller);
+ preflight_fetch_params->set_engine_record(*fetch_params->engine_record());
+ preflight_fetch_params->set_is_cors_preflight();
+
auto transport = WholeBodyTransport::create();
bool stopped = false;
transport->set_on_stop([&] { stopped = true; });
- controller->set_body_transport(transport);
+ fetch_params->set_body_transport(transport);
+ auto preflight_transport = WholeBodyTransport::create();
+ bool preflight_stopped = false;
+ preflight_transport->set_on_stop([&] { preflight_stopped = true; });
+ preflight_fetch_params->set_body_transport(preflight_transport);
+
+ preflight_fetch_params->stop_body_transport();
+ EXPECT(preflight_stopped);
+ EXPECT(!stopped);
- controller->stop_body_transport();
+ fetch_params->stop_body_transport();
EXPECT(stopped);
- EXPECT_EQ(controller->state(), FetchController::State::Ongoing);
}
diff --git a/Tests/LibWeb/TestFetchEngineRecord.cpp b/Tests/LibWeb/TestFetchEngineRecord.cpp
new file mode 100644
index 00000000000..3c17e8242c0
--- /dev/null
+++ b/Tests/LibWeb/TestFetchEngineRecord.cpp
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibTest/TestCase.h>
+#include <LibWeb/Fetch/Engine/FetchEngineRecord.h>
+#include <LibWeb/Fetch/Engine/WholeBodyTransport.h>
+
+using namespace Web::Fetch::Engine;
+
+namespace {
+
+class IgnoringEventSink final : public EngineEventSink {
+public:
+ virtual void handle_event(EngineEvent) override { }
+};
+
+}
+
+static NonnullRefPtr<FetchEngineRecord> start_fetch(FetchEngineRecords& records, u64 fetch_id)
+{
+ auto event_sink = make<IgnoringEventSink>();
+ return records.start(FetchId { fetch_id }, move(event_sink), NetworkActivityObservers::create()).release_nonnull();
+}
+
+TEST_CASE(a_stop_of_a_fetch_stops_its_body_transport_and_leaves_that_of_its_cors_preflight)
+{
+ FetchEngineRecords records { make<FetchEngineRecords::Agent>() };
+ auto record = start_fetch(records, 1);
+ auto transport = WholeBodyTransport::create();
+ bool stopped = false;
+ transport->set_on_stop([&] { stopped = true; });
+ record->set_body_transport(transport);
+ auto preflight_transport = WholeBodyTransport::create();
+ bool preflight_stopped = false;
+ preflight_transport->set_on_stop([&] { preflight_stopped = true; });
+ record->set_cors_preflight_body_transport(preflight_transport);
+
+ records.stop_body_transport(FetchId { 1 });
+ EXPECT(stopped);
+ EXPECT(!preflight_stopped);
+
+ record->stop_cors_preflight_body_transport();
+ EXPECT(preflight_stopped);
+}
+
+TEST_CASE(a_stop_of_a_fetch_whose_record_is_gone_stops_nothing)
+{
+ FetchEngineRecords records { make<FetchEngineRecords::Agent>() };
+ auto ended_transport = WholeBodyTransport::create();
+ bool ended_stopped = false;
+ ended_transport->set_on_stop([&] { ended_stopped = true; });
+ start_fetch(records, 1)->set_body_transport(ended_transport);
+ auto record = start_fetch(records, 2);
+ auto transport = WholeBodyTransport::create();
+ bool stopped = false;
+ transport->set_on_stop([&] { stopped = true; });
+ record->set_body_transport(transport);
+
+ records.stop_body_transport(FetchId { 1 });
+ EXPECT(!ended_stopped);
+ EXPECT(!stopped);
+}
+
+TEST_CASE(a_start_of_a_fetch_out_of_fetch_id_order_dies)
+{
+ FetchEngineRecords records { make<FetchEngineRecords::Agent>() };
+ auto record = start_fetch(records, 2);
+
+ EXPECT_DEATH("Starting a fetch with the id of the last fetch started", (void)start_fetch(records, 2));
+ EXPECT_DEATH("Starting a fetch with an id below that of the last fetch started", (void)start_fetch(records, 1));
+}
+
+TEST_CASE(a_stop_of_a_fetch_the_engine_has_not_started_dies)
+{
+ FetchEngineRecords records { make<FetchEngineRecords::Agent>() };
+ auto record = start_fetch(records, 1);
+
+ EXPECT_DEATH("Stopping a fetch with an id above that of the last fetch started", records.stop_body_transport(FetchId { 2 }));
+}
diff --git a/Tests/LibWeb/Text/expected/Fetch/fetch-stopped-during-its-cors-preflight-stops-its-request.txt b/Tests/LibWeb/Text/expected/Fetch/fetch-stopped-during-its-cors-preflight-stops-its-request.txt
new file mode 100644
index 00000000000..d04b0c94b2d
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Fetch/fetch-stopped-during-its-cors-preflight-stops-its-request.txt
@@ -0,0 +1 @@
+request after the preflight stopped: true
diff --git a/Tests/LibWeb/Text/input/Fetch/fetch-stopped-during-its-cors-preflight-stops-its-request.html b/Tests/LibWeb/Text/input/Fetch/fetch-stopped-during-its-cors-preflight-stops-its-request.html
new file mode 100644
index 00000000000..de85eea6068
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Fetch/fetch-stopped-during-its-cors-preflight-stops-its-request.html
@@ -0,0 +1,68 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A fetch stopped while the server holds its CORS preflight stops the request it starts once the preflight is done.
+ promiseTest(async () => {
+ const countBodyPumps = () =>
+ Object.values(JSON.parse(internals.dumpGCGraph())).filter(cell => cell.class_name === "NetworkBodyPump")
+ .length;
+
+ // A collection can free a chain of cells one link at a time, and a stale pointer on the stack can keep a cell
+ // alive through one collection.
+ const collectUntilPumpsSettle = async () => {
+ let pumps = countBodyPumps();
+ for (;;) {
+ await internals.gcAsync();
+ const remaining = countBodyPumps();
+ if (remaining === pumps)
+ return pumps;
+ pumps = remaining;
+ }
+ };
+ const initialPumps = await collectUntilPumpsSettle();
+
+ const server = httpTestServer();
+ const id = uniqueID();
+ const preflightToken = `fetch-stopped-during-its-cors-preflight-${id}`;
+ const responseToken = `fetch-stopped-during-its-cors-preflight-response-${id}`;
+ await server.createEcho("OPTIONS", `/fetch-stopped-during-its-cors-preflight-${id}`, {
+ status: 204,
+ headers: {
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Headers": "X-Stopped-During-Preflight",
+ },
+ wait_for_unblock: preflightToken,
+ });
+ const url = await server.createEcho("GET", `/fetch-stopped-during-its-cors-preflight-${id}`, {
+ status: 200,
+ headers: { "Access-Control-Allow-Origin": "*", "Cache-Control": "no-store" },
+ body: "response",
+ wait_for_unblock: responseToken,
+ });
+
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ iframe.contentWindow.fetch(url, { headers: { "X-Stopped-During-Preflight": "1" } }).catch(() => {});
+
+ // The server has the preflight, and holds its response.
+ await server.waitForRequest(url);
+ iframe.contentWindow.stop();
+ await fetch(`${server.baseURL}/unblock/${preflightToken}`);
+
+ // The server holds the response to the request that follows the preflight, so nothing but a stop of that
+ // request lets go of its body pump.
+ const deadline = performance.now() + 10000;
+ let stopped = false;
+ for (;;) {
+ await internals.gcAsync();
+ stopped = countBodyPumps() === initialPumps;
+ if (stopped || performance.now() > deadline)
+ break;
+ await timeout(10);
+ }
+ println(`request after the preflight stopped: ${stopped}`);
+
+ await fetch(`${server.baseURL}/unblock/${responseToken}`);
+ iframe.remove();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/XHR/sync-xhr-file-body-releases-its-transport.html b/Tests/LibWeb/Text/input/XHR/sync-xhr-file-body-releases-its-transport.html
index 4d9ab9d9112..72a82fbae01 100644
--- a/Tests/LibWeb/Text/input/XHR/sync-xhr-file-body-releases-its-transport.html
+++ b/Tests/LibWeb/Text/input/XHR/sync-xhr-file-body-releases-its-transport.html
@@ -34,7 +34,7 @@
// The first body ends only after RequestServer has written its cache entry.
const check = await fetch(url, { headers });
println(`body came from the cache: ${check.headers.get(TEST_CACHE_STATUS_HEADER) === "read-from-cache"}`);
- await check.body.cancel();
+ await check.arrayBuffer();
await internals.gcAsync();
const initialPumps = countBodyPumps();