Skip to content

Truly independent web browser

LibWeb: Keep a fetch's shared state in a fetch control block

Luke Wilde440ae2c450c9
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index 1d3e2429913..2b28e41a69c 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -459,7 +459,7 @@ WebIDL::ExceptionOr<GC::Ref<Document>> Document::create_and_initialize(Type type
// rebuilt from a descriptor carry the fetch's timing info directly.
RefPtr<Fetch::Infrastructure::FetchTimingInfo> navigation_fetch_timing_info = navigation_params.fetch_timing_info;
if (navigation_params.fetch_controller)
- navigation_fetch_timing_info = navigation_params.fetch_controller->timing_info();
+ navigation_fetch_timing_info = navigation_params.fetch_controller->full_timing_info();
// 8. Let loadTimingInfo be a new document load timing info with its navigation start time set to navigationParams's response's timing info's start time.
DOM::DocumentLoadTimingInfo load_timing_info;
diff --git a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
index 9229a2655d0..dd6cfd192c1 100644
--- a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
@@ -241,7 +241,7 @@ void BodyStreamPullSource::push_while_paused()
{
if (m_detached || m_pending_pull_promise || m_push_ticket.has_value() || !HTML::main_thread_event_loop().execution_paused())
return;
- if (!m_fetch_params || m_fetch_params->body_intent() != Engine::BodyIntent::SyncAccumulate)
+ if (!m_fetch_params || m_fetch_params->control_block().body_intent() != Engine::BodyIntent::SyncAccumulate)
return;
m_push_ticket = arm_waiter(Engine::FetchByteChannel::BufferedAtLeast { 1 });
}
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 15731a01912..ad502bfc728 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -390,7 +390,7 @@ GC::Ref<Infrastructure::FetchController> fetch(JS::Realm& realm, Infrastructure:
request.credentials_mode(),
request.integrity_metadata(),
on_preloaded_response_available,
- fetch_params->body_intent(),
+ fetch_params->control_block().body_intent(),
preload_reports_timing);
fetch_params->set_preload_reports_timing(preload_reports_timing);
@@ -781,7 +781,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam
// (the fully-read in step 22, and fetch response handover's tasks, body pipe and body read). Record
// that the response has arrived (a network response was recorded as its headers came in) — so
// consume_a_preloaded_resource() re-targets an in-flight preload's fetch only til then.
- fetch_params.controller()->set_response_arrived();
+ fetch_params.control_block().set_response_arrived();
if (response_was_null)
response = resolved_response;
@@ -1017,7 +1017,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
// 3. If fetchParams's request's destination is "document", then set fetchParams's controller's full timing info
// to fetchParams's timing info.
if (fetch_params.request()->is_navigation_request())
- fetch_params.controller()->set_full_timing_info(fetch_params.timing_info());
+ fetch_params.control_block().set_full_timing_info(fetch_params.timing_info());
// AD-HOC: We extract steps 1-2 of processResponseEndOfBody into a separate lambda so we can also call it from
// the error path. The fetch spec only runs processResponseEndOfBody on successful body read (via the
@@ -1172,7 +1172,10 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
auto algorithms = fetch_params.controller()->algorithms();
- auto body_intent = fetch_params.body_intent();
+ // NB: Nobody reads the body of a fetch stopped before its handover.
+ auto body_intent = fetch_params.control_block().state() == Infrastructure::FetchControlBlock::State::Stopped
+ ? Engine::BodyIntent::DrainAndDiscard
+ : fetch_params.control_block().body_intent();
// AD-HOC: A fetch whose body intent is SyncAccumulate is a sync XHR send()
// (https://xhr.spec.whatwg.org/#the-send()-method, step 12) — or a preload fetch that "consume a preloaded
@@ -2213,7 +2216,7 @@ static GC::Ref<PendingResponse> continue_http_network_or_cache_fetch(JS::Object&
}
// AD-HOC: If the controller is already in the non-spec Stopped state, we should cancel the network request immediately.
- if (http_fetch_params->controller()->state() == Infrastructure::FetchController::State::Stopped)
+ if (http_fetch_params->control_block().state() == Infrastructure::FetchControlBlock::State::Stopped)
http_fetch_params->controller()->stop_fetch();
auto returned_pending_response = PendingResponse::create(fetch_params);
@@ -2850,7 +2853,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
// AD-HOC: From here on, the response's body delivery is scheduled against the event loop (see
// BodyStreamPullSource::on_wake()); record that, for consume_a_preloaded_resource().
- fetch_params.controller()->set_response_arrived();
+ fetch_params.control_block().set_response_arrived();
auto response = Infrastructure::Response::create();
response->set_status(status_code.value_or(200));
@@ -2972,6 +2975,11 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
tear_down_network_body(*delivery_gate, *channel, reason);
body_pump->abandon_cache_entry();
});
+ if (request->destination() == Infrastructure::Request::Destination::Font) {
+ network_transport->set_on_requires_network([control_block = NonnullRefPtr { fetch_params.control_block() }] {
+ control_block->set_requires_network();
+ });
+ }
fetch_params.controller()->set_network_transport(*network_transport);
} else {
fetch_params.controller()->set_body_transport(whole_body_transport);
@@ -3114,15 +3122,14 @@ 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([request = fetch_params.request(), returned_pending_response, preflight_controller](NonnullRefPtr<Infrastructure::Response> response) {
+ preflight_response->when_loaded([request = fetch_params.request(), returned_pending_response, preflight_controller, preflight_fetch_params](NonnullRefPtr<Infrastructure::Response> response) {
dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'CORS-preflight fetch' preflight_response load callback");
if (WebDriver::BiDi::g_network_events_enabled) {
- auto params = preflight_controller->fetch_params();
if (response->is_network_error())
- WebDriver::BiDi::network_fetch_error(*params, response->network_error_message().value_or("Preflight failed"_string));
+ WebDriver::BiDi::network_fetch_error(*preflight_fetch_params, response->network_error_message().value_or("Preflight failed"_string));
else
- WebDriver::BiDi::network_response_completed(*params, *response);
+ WebDriver::BiDi::network_response_completed(*preflight_fetch_params, *response);
}
// NB: Only the preflight response's headers are read.
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchControlBlock.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchControlBlock.h
new file mode 100644
index 00000000000..94df00ac676
--- /dev/null
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchControlBlock.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/AtomicRefCounted.h>
+#include <AK/Badge.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/RefPtr.h>
+#include <LibWeb/Fetch/Engine/BodyIntent.h>
+#include <LibWeb/Fetch/Infrastructure/FetchTimingInfo.h>
+
+namespace Web::Fetch::Infrastructure {
+
+class FetchController;
+
+// The state of a fetch that its controller and its fetch params share.
+class FetchControlBlock : public AtomicRefCounted<FetchControlBlock> {
+public:
+ enum class State : u8 {
+ Ongoing,
+ Terminated,
+ Aborted,
+ Stopped,
+ };
+
+ [[nodiscard]] static NonnullRefPtr<FetchControlBlock> create() { return adopt_ref(*new FetchControlBlock); }
+
+ [[nodiscard]] State state() const { return m_state; }
+ void set_state(Badge<FetchController>, State state) { m_state = state; }
+
+ [[nodiscard]] RefPtr<FetchTimingInfo> full_timing_info() const { return m_full_timing_info; }
+ void set_full_timing_info(NonnullRefPtr<FetchTimingInfo> full_timing_info) { m_full_timing_info = move(full_timing_info); }
+
+ [[nodiscard]] Engine::BodyIntent body_intent() const { return m_body_intent; }
+ void set_body_intent(Badge<FetchController>, Engine::BodyIntent body_intent)
+ {
+ VERIFY(!m_response_arrived);
+ m_body_intent = body_intent;
+ }
+
+ // AD-HOC: Whether this fetch's response has arrived, from the network or at main fetch. From then on,
+ // consume_a_preloaded_resource() no longer changes the fetch's body intent or task destination.
+ void set_response_arrived() { m_response_arrived = true; }
+ [[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; }
+
+ [[nodiscard]] bool requires_network() const { return m_requires_network; }
+ void set_requires_network() { m_requires_network = true; }
+
+private:
+ FetchControlBlock() = default;
+
+ // https://fetch.spec.whatwg.org/#fetch-controller-state
+ // state (default "ongoing")
+ // "ongoing", "terminated", or "aborted"
+ State m_state { State::Ongoing };
+
+ // https://fetch.spec.whatwg.org/#fetch-controller-full-timing-info
+ // full timing info (default null)
+ // Null or a fetch timing info.
+ RefPtr<FetchTimingInfo> m_full_timing_info;
+
+ Engine::BodyIntent m_body_intent { Engine::BodyIntent::DrainAndDiscard };
+ bool m_response_arrived { false };
+ bool m_has_started_request { false };
+ bool m_requires_network { false };
+};
+
+}
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp
index 65d76e09105..1915bb3aebe 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp
@@ -5,7 +5,6 @@
*/
#include <LibGC/Heap.h>
-#include <LibGC/Weak.h>
#include <LibJS/Runtime/VM.h>
#include <LibWeb/Fetch/Engine/NetworkTransportHandle.h>
#include <LibWeb/Fetch/Fetching/PendingResponse.h>
@@ -26,6 +25,7 @@ GC_DEFINE_ALLOCATOR(FetchController);
FetchController::FetchController(FetchControllerRegistry& registry)
: m_registry(registry)
, m_token(registry.add({}, *this))
+ , m_control_block(FetchControlBlock::create())
{
}
@@ -41,7 +41,6 @@ void FetchController::visit_edges(JS::Cell::Visitor& visitor)
if (m_awaited_network_completion.has_value())
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_task_destination);
visitor.visit(m_pending_preloaded_response);
@@ -62,6 +61,39 @@ void FetchController::set_algorithms(Badge<FetchParams>, GC::Ref<FetchAlgorithms
{
VERIFY(!m_algorithms);
m_algorithms = algorithms;
+ m_control_block->set_body_intent({}, algorithms->body_intent());
+}
+
+void FetchController::retarget(TaskDestination task_destination, Engine::BodyIntent body_intent)
+{
+ m_task_destination = move(task_destination);
+ m_control_block->set_body_intent({}, body_intent);
+}
+
+void FetchController::set_original_fetch_params(Badge<FetchParams>, FetchParams const& fetch_params)
+{
+ m_original_fetch_params = fetch_params;
+}
+
+void FetchController::report_webdriver_bidi_fetch_error(StringView error_text) const
+{
+ if (!WebDriver::BiDi::g_network_events_enabled)
+ return;
+ if (auto fetch_params = m_original_fetch_params.ptr())
+ WebDriver::BiDi::network_fetch_error(*fetch_params, error_text);
+}
+
+void FetchController::cancel_webdriver_bidi_network_interception() const
+{
+ if (!WebDriver::BiDi::is_active())
+ return;
+ if (auto fetch_params = original_fetch_params())
+ WebDriver::BiDi::cancel_network_interception(*fetch_params);
+}
+
+GC::Ptr<FetchParams> FetchController::original_fetch_params() const
+{
+ return m_original_fetch_params.ptr();
}
GC::Ref<FetchAlgorithms const> FetchController::algorithms() const
@@ -73,12 +105,7 @@ GC::Ref<FetchAlgorithms const> FetchController::algorithms() const
void FetchController::set_network_transport(Engine::NetworkTransportHandle& network_transport)
{
set_body_transport(network_transport);
- m_has_started_request = true;
- if (m_fetch_params && m_fetch_params->request()->destination() == Request::Destination::Font) {
- network_transport.set_on_requires_network(GC::weak_callback(*this, [](auto& controller) {
- controller.m_requires_network = true;
- }));
- }
+ m_control_block->set_has_started_request({});
}
void FetchController::set_body_transport(Engine::FetchBodyDeliveryGate::Transport& body_transport)
@@ -133,28 +160,20 @@ void FetchController::did_complete_network_body(Engine::FetchByteChannel const&
NonnullRefPtr<FetchTimingInfo> FetchController::extract_full_timing_info() const
{
// 1. Assert: this’s full timing info is not null.
- VERIFY(m_full_timing_info);
+ auto full_timing_info = m_control_block->full_timing_info();
+ VERIFY(full_timing_info);
// 2. Return this’s full timing info.
- return *m_full_timing_info;
-}
-
-RefPtr<FetchTimingInfo> FetchController::timing_info() const
-{
- if (!m_fetch_params)
- return nullptr;
- return m_fetch_params->timing_info();
+ return full_timing_info.release_nonnull();
}
// https://fetch.spec.whatwg.org/#fetch-controller-abort
void FetchController::abort(JS::Realm& realm, Optional<JS::Value> error)
{
// 1. Set controller’s state to "aborted".
- m_state = State::Aborted;
- if (WebDriver::BiDi::g_network_events_enabled && m_fetch_params)
- WebDriver::BiDi::network_fetch_error(*m_fetch_params, "Fetch was aborted"sv);
- else if (WebDriver::BiDi::is_active() && m_fetch_params)
- WebDriver::BiDi::cancel_network_interception(*m_fetch_params);
+ m_control_block->set_state({}, State::Aborted);
+ report_webdriver_bidi_fetch_error("Fetch was aborted"sv);
+ cancel_webdriver_bidi_network_interception();
// 2. Let fallbackError be an "AbortError" DOMException.
auto fallback_error = WebIDL::AbortError::create("Fetch was aborted"_utf16);
@@ -181,23 +200,20 @@ void FetchController::abort(JS::Realm& realm, Optional<JS::Value> error)
void FetchController::terminate()
{
// To terminate a fetch controller controller, set controller’s state to "terminated".
- m_state = State::Terminated;
- if (WebDriver::BiDi::g_network_events_enabled && m_fetch_params)
- WebDriver::BiDi::network_fetch_error(*m_fetch_params, "Fetch was terminated"sv);
- else if (WebDriver::BiDi::is_active() && m_fetch_params)
- WebDriver::BiDi::cancel_network_interception(*m_fetch_params);
+ m_control_block->set_state({}, State::Terminated);
+ report_webdriver_bidi_fetch_error("Fetch was terminated"sv);
+ cancel_webdriver_bidi_network_interception();
stop_request();
}
void FetchController::stop_fetch()
{
- if (m_state == State::Aborted || m_state == State::Terminated)
+ if (state() == State::Aborted || state() == State::Terminated)
return;
- m_state = State::Stopped;
- if (WebDriver::BiDi::is_active() && m_fetch_params)
- WebDriver::BiDi::cancel_network_interception(*m_fetch_params);
+ m_control_block->set_state({}, State::Stopped);
+ cancel_webdriver_bidi_network_interception();
// AD-HOC: Some HTML elements need to stop an ongoing fetching process without causing any network error to be raised
// (which abort() and terminate() will both do). This is tricky because the fetch process runs across several
@@ -211,11 +227,8 @@ void FetchController::stop_fetch()
});
});
- // NB: Nobody reads a stopped fetch's body.
- if (m_fetch_params)
- m_fetch_params->set_body_intent(Engine::BodyIntent::DrainAndDiscard);
if (m_algorithms)
- m_algorithms = FetchAlgorithms::create(FetchAlgorithms::Input { Engine::BodyIntent::DrainAndDiscard });
+ m_algorithms = FetchAlgorithms::create(FetchAlgorithms::Input { m_control_block->body_intent() });
stop_request();
@@ -234,7 +247,7 @@ void FetchController::stop_fetch()
void FetchController::stop_request()
{
end_rendering_pending_operation(this);
- VERIFY(m_state != State::Ongoing);
+ VERIFY(state() != State::Ongoing);
m_awaited_network_completion.clear();
stop_body_transport();
}
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
index 8a817173826..20ab4583517 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
@@ -11,12 +11,14 @@
#include <AK/WeakPtr.h>
#include <LibGC/Function.h>
#include <LibGC/Ptr.h>
+#include <LibGC/Weak.h>
#include <LibJS/Forward.h>
#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/Infrastructure/FetchControlBlock.h>
#include <LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h>
#include <LibWeb/Fetch/Infrastructure/FetchTimingInfo.h>
#include <LibWeb/Fetch/Infrastructure/Task.h>
@@ -38,23 +40,18 @@ class WEB_API FetchController : public JS::Cell {
GC_DECLARE_ALLOCATOR(FetchController);
public:
- enum class State : u8 {
- Ongoing,
- Terminated,
- Aborted,
- Stopped,
- };
+ using State = FetchControlBlock::State;
[[nodiscard]] static GC::Ref<FetchController> create(FetchControllerRegistry&);
[[nodiscard]] FetchControllerToken token() const { return m_token; }
+ [[nodiscard]] FetchControlBlock& control_block() const { return *m_control_block; }
- void set_full_timing_info(NonnullRefPtr<FetchTimingInfo> full_timing_info) { m_full_timing_info = move(full_timing_info); }
void set_report_timing_steps(Function<void(JS::Object&)> report_timing_steps);
void set_next_manual_redirect_steps(Function<void()> next_manual_redirect_steps);
- [[nodiscard]] State state() const { return m_state; }
- [[nodiscard]] RefPtr<FetchTimingInfo> timing_info() const;
+ [[nodiscard]] State state() const { return m_control_block->state(); }
+ [[nodiscard]] RefPtr<FetchTimingInfo> full_timing_info() const { return m_control_block->full_timing_info(); }
void report_timing(JS::Object&) const;
void process_next_manual_redirect() const;
@@ -68,31 +65,30 @@ public:
Optional<HTML::IPCSerializationRecord> const& serialized_abort_reason() const { return m_serialized_abort_reason; }
void terminate();
- 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>);
[[nodiscard]] GC::Ref<FetchAlgorithms const> algorithms() const;
+ // The fetch params created with the controller, for which WebDriver BiDi reports errors and intercepts requests.
+ void set_original_fetch_params(Badge<FetchParams>, FetchParams const&);
+ [[nodiscard]] GC::Ptr<FetchParams> original_fetch_params() const;
+
[[nodiscard]] TaskDestination const& task_destination() const { return m_task_destination; }
void set_task_destination(TaskDestination task_destination) { m_task_destination = move(task_destination); }
+ // Moves the fetch, before its response has arrived, to another task destination and body intent.
+ void retarget(TaskDestination, Engine::BodyIntent);
+
[[nodiscard]] bool is_keepalive() const { return m_is_keepalive; }
void set_keepalive(bool is_keepalive) { m_is_keepalive = is_keepalive; }
- // 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.
- // consume_a_preloaded_resource() checks this before re-targeting an in-flight preload's fetch.
- void set_response_arrived() { m_response_arrived = true; }
- [[nodiscard]] bool response_arrived() const { return m_response_arrived; }
+ [[nodiscard]] bool response_arrived() const { return m_control_block->response_arrived(); }
[[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_requires_network; }
- bool has_started_request() const { return m_has_started_request; }
+ 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>);
void stop_fetch();
@@ -114,18 +110,13 @@ private:
virtual void visit_edges(JS::Cell::Visitor&) override;
virtual void finalize() override;
+ void report_webdriver_bidi_fetch_error(StringView error_text) const;
+ void cancel_webdriver_bidi_network_interception() const;
+
WeakPtr<FetchControllerRegistry> m_registry;
FetchControllerToken m_token;
-
- // https://fetch.spec.whatwg.org/#fetch-controller-state
- // state (default "ongoing")
- // "ongoing", "terminated", or "aborted"
- State m_state { State::Ongoing };
-
- // https://fetch.spec.whatwg.org/#fetch-controller-full-timing-info
- // full timing info (default null)
- // Null or a fetch timing info.
- RefPtr<FetchTimingInfo> m_full_timing_info;
+ NonnullRefPtr<FetchControlBlock> m_control_block;
+ GC::Weak<FetchParams> m_original_fetch_params;
// https://fetch.spec.whatwg.org/#fetch-controller-report-timing-steps
// report timing steps (default null)
@@ -148,8 +139,6 @@ private:
// Null or an algorithm accepting nothing.
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)
@@ -174,14 +163,11 @@ private:
TaskDestination m_task_destination;
bool m_is_keepalive { false };
- bool m_response_arrived { false };
// NB: Assumes one waiting consumer for a pending preloaded response.
// Widen this if preload handoff ever supports multiple consumers.
GC::Ptr<Fetching::PendingResponse> m_pending_preloaded_response;
WeakPtr<Engine::FetchBodyDeliveryGate::Transport> m_body_transport;
- bool m_requires_network { false };
- bool m_has_started_request { false };
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 95905cd2e77..2c51222f9d4 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp
@@ -15,20 +15,20 @@ 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_body_intent(algorithms->body_intent())
, m_controller(controller)
+ , m_control_block(controller->control_block())
, m_timing_info(move(timing_info))
, m_loader_config(move(loader_config))
{
- m_controller->set_fetch_params({}, *this);
m_controller->set_algorithms({}, algorithms);
+ m_controller->set_original_fetch_params({}, *this);
}
FetchParams::FetchParams(FetchParams const& params)
: m_request(params.m_request)
- , m_body_intent(params.m_body_intent)
, m_cross_origin_isolated_capability(params.m_cross_origin_isolated_capability)
, m_controller(params.m_controller)
+ , m_control_block(params.m_control_block)
, m_timing_info(params.m_timing_info)
, m_preloaded_response_candidate(params.m_preloaded_response_candidate)
, m_has_response_body_transfer_lease(params.m_has_response_body_transfer_lease)
@@ -57,14 +57,15 @@ void FetchParams::visit_edges(JS::Cell::Visitor& visitor)
bool FetchParams::is_aborted() const
{
// A fetch params fetchParams is aborted if its controller’s state is "aborted".
- return m_controller->state() == FetchController::State::Aborted;
+ return m_control_block->state() == FetchControlBlock::State::Aborted;
}
// https://fetch.spec.whatwg.org/#fetch-params-canceled
bool FetchParams::is_canceled() const
{
// A fetch params fetchParams is canceled if its controller’s state is "aborted" or "terminated".
- return m_controller->state() == FetchController::State::Aborted || m_controller->state() == FetchController::State::Terminated;
+ auto state = m_control_block->state();
+ return state == FetchControlBlock::State::Aborted || state == FetchControlBlock::State::Terminated;
}
}
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h
index 1d8dc29c2c4..ec97c1345f0 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h
@@ -36,13 +36,11 @@ public:
[[nodiscard]] NonnullRefPtr<Request> request() const { return m_request; }
void set_request(NonnullRefPtr<Request> request) { m_request = move(request); }
[[nodiscard]] GC::Ref<FetchController> controller() const { return m_controller; }
+ [[nodiscard]] FetchControlBlock& control_block() const { return *m_control_block; }
[[nodiscard]] NonnullRefPtr<FetchTimingInfo> timing_info() const { return m_timing_info; }
[[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]] Engine::BodyIntent body_intent() const { return m_body_intent; }
- void set_body_intent(Engine::BodyIntent body_intent) { m_body_intent = body_intent; }
-
[[nodiscard]] HTML::CanUseCrossOriginIsolatedAPIs cross_origin_isolated_capability() const { return m_cross_origin_isolated_capability; }
void set_cross_origin_isolated_capability(HTML::CanUseCrossOriginIsolatedAPIs cross_origin_isolated_capability) { m_cross_origin_isolated_capability = cross_origin_isolated_capability; }
@@ -73,8 +71,6 @@ private:
// A request.
NonnullRefPtr<Request> m_request;
- Engine::BodyIntent m_body_intent;
-
// https://fetch.spec.whatwg.org/#fetch-params-cross-origin-isolated-capability
// cross-origin isolated capability (default false)
// A boolean.
@@ -84,6 +80,7 @@ private:
// controller (default a new fetch controller)
// A fetch controller.
GC::Ref<FetchController> m_controller;
+ NonnullRefPtr<FetchControlBlock> m_control_block;
// https://fetch.spec.whatwg.org/#fetch-params-timing-info
// timing info
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchTimingInfo.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchTimingInfo.h
index d9d1abe25c9..d9d669e465e 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchTimingInfo.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchTimingInfo.h
@@ -6,8 +6,8 @@
#pragma once
+#include <AK/AtomicRefCounted.h>
#include <AK/NonnullRefPtr.h>
-#include <AK/RefCounted.h>
#include <AK/String.h>
#include <AK/Vector.h>
#include <LibRequests/Forward.h>
@@ -19,7 +19,7 @@
namespace Web::Fetch::Infrastructure {
// https://fetch.spec.whatwg.org/#fetch-timing-info
-class WEB_API FetchTimingInfo : public RefCounted<FetchTimingInfo> {
+class WEB_API FetchTimingInfo : public AtomicRefCounted<FetchTimingInfo> {
public:
[[nodiscard]] static NonnullRefPtr<FetchTimingInfo> create();
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 51b8a6fe5df..62665dcaaee 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -576,6 +576,7 @@ namespace Web::Fetch::Infrastructure {
class Body;
class FetchAlgorithms;
+class FetchControlBlock;
class FetchController;
class FetchControllerRegistry;
class FetchParams;
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index d2526c2febd..19c565bcab1 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -562,7 +562,7 @@ static bool handle_navigation_response_as_download(GC::Ref<NavigationParams> nav
if (WebDriver::BiDi::g_network_events_enabled && response->network_transport().has_value() && !network_response.is_object() && navigation_params->request) {
RefPtr<Fetch::Infrastructure::FetchTimingInfo> timing_info = navigation_params->fetch_timing_info;
if (navigation_params->fetch_controller)
- timing_info = navigation_params->fetch_controller->timing_info();
+ timing_info = navigation_params->fetch_controller->full_timing_info();
if (timing_info) {
auto metadata = WebDriver::BiDi::network_response_for_navigation(
*navigation_params->request, *timing_info, *response->record());
diff --git a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp
index 7db13bc453a..5868e528d0f 100644
--- a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp
+++ b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp
@@ -136,8 +136,8 @@ static NavigationParamsDescriptor create_navigation_params_descriptor(Navigation
request = create_navigation_request_descriptor(*params.request);
Optional<NavigationFetchTimingInfoDescriptor> fetch_timing_info;
- if (params.fetch_controller && params.fetch_controller->timing_info())
- fetch_timing_info = create_navigation_fetch_timing_info_descriptor(*params.fetch_controller->timing_info());
+ if (params.fetch_controller && params.fetch_controller->full_timing_info())
+ fetch_timing_info = create_navigation_fetch_timing_info_descriptor(*params.fetch_controller->full_timing_info());
else if (params.fetch_timing_info)
fetch_timing_info = create_navigation_fetch_timing_info_descriptor(*params.fetch_timing_info);
@@ -158,7 +158,7 @@ static NavigationParamsDescriptor create_navigation_params_descriptor(Navigation
.id = params.id,
.navigable_id = params.navigable->id(),
.request = move(request),
- .response = create_navigation_response_descriptor(*params.response, params.request.ptr(), params.fetch_controller ? params.fetch_controller->timing_info().ptr() : params.fetch_timing_info.ptr()),
+ .response = create_navigation_response_descriptor(*params.response, params.request.ptr(), params.fetch_controller ? params.fetch_controller->full_timing_info().ptr() : params.fetch_timing_info.ptr()),
.fetch_timing_info = move(fetch_timing_info),
.coop_enforcement_result = params.coop_enforcement_result,
.reserved_environment = move(reserved_environment),
diff --git a/Libraries/LibWeb/HTML/PreloadEntry.cpp b/Libraries/LibWeb/HTML/PreloadEntry.cpp
index 846e002d5b7..3fde9272c55 100644
--- a/Libraries/LibWeb/HTML/PreloadEntry.cpp
+++ b/Libraries/LibWeb/HTML/PreloadEntry.cpp
@@ -126,11 +126,8 @@ bool consume_a_preloaded_resource(
// in-flight preload (XMLHttpRequestMainThread::FindPreload, FetchPreloader::AsyncConsume); Blink never
// reuses a resource for a sync request (Resource::CanReuse), and WebKit's sync load bypasses its cache
// and preloads (DocumentThreadableLoader::loadRequest).
- if (consumer_body_intent == Fetch::Engine::BodyIntent::SyncAccumulate && entry->controller) {
- entry->controller->set_task_destination(ParallelQueue::create());
- if (auto fetch_params = entry->controller->fetch_params())
- fetch_params->set_body_intent(consumer_body_intent);
- }
+ if (consumer_body_intent == Fetch::Engine::BodyIntent::SyncAccumulate && entry->controller)
+ entry->controller->retarget(ParallelQueue::create(), consumer_body_intent);
}
// 10. Otherwise, call onResponseAvailable with entry's response.
else {
diff --git a/Libraries/LibWeb/WebDriver/BiDi/Network.cpp b/Libraries/LibWeb/WebDriver/BiDi/Network.cpp
index f5560b4f5e6..e5c88d3cf6e 100644
--- a/Libraries/LibWeb/WebDriver/BiDi/Network.cpp
+++ b/Libraries/LibWeb/WebDriver/BiDi/Network.cpp
@@ -89,7 +89,7 @@ static GC::Ptr<NetworkContinuation> blocked_request(Request const& request)
static GC::Ptr<NetworkContinuation> blocked_request(FetchController const& controller)
{
- auto fetch_params = controller.fetch_params();
+ auto fetch_params = controller.original_fetch_params();
if (!fetch_params)
return nullptr;
auto blocked = blocked_request(*fetch_params->request());
@@ -248,7 +248,7 @@ JsonArray get_network_intercepts(FetchParams const& fetch_params, StringView pha
// NB: An existing request keeps its original context. A request first observed after instrumentation was
// enabled can still discover its context, and blocking must use that same context.
auto navigable = request_navigable(*request);
- if (!navigable || fetch_params.is_canceled() || fetch_params.controller()->state() == FetchController::State::Stopped)
+ if (!navigable || fetch_params.is_canceled() || fetch_params.control_block().state() == FetchControlBlock::State::Stopped)
return intercepts;
if (!state)
initialize_network_request(*request, navigable);
@@ -526,14 +526,14 @@ void block_network_request(FetchParams const& fetch_params, RefPtr<Fetch::Infras
auto request = fetch_params.request();
// NB: Cancellation runs through the controller's original parameters, rather than a prepared HTTP clone.
// Bind both requests to the same identity before exposing a blocked request.
- if (auto original_params = fetch_params.controller()->fetch_params()) {
+ if (auto original_params = fetch_params.controller()->original_fetch_params()) {
synchronize_network_request(*original_params->request(), *request);
if (!original_request)
original_request = original_params->request();
}
initialize_network_request(*request);
auto state = request->webdriver_bidi_network_request();
- if (fetch_params.is_canceled() || fetch_params.controller()->state() == FetchController::State::Stopped) {
+ if (fetch_params.is_canceled() || fetch_params.control_block().state() == FetchControlBlock::State::Stopped) {
if (response)
stop_response_transport(fetch_params, *response);
continuation->invoke(NetworkContinuationAction::Fail, Response::network_error("Intercepted fetch was stopped"_string));
diff --git a/Tests/LibWebView/test-webdriver-bidi.py b/Tests/LibWebView/test-webdriver-bidi.py
index 4c2cb02a9d6..cefa86b1416 100755
--- a/Tests/LibWebView/test-webdriver-bidi.py
+++ b/Tests/LibWebView/test-webdriver-bidi.py
@@ -136,6 +136,8 @@ class ReloadServer(http.server.ThreadingHTTPServer):
self.interception_transport_closed = threading.Event()
self.document_headers_sent: threading.Event = threading.Event()
self.release_document: threading.Event = threading.Event()
+ self.preflight_received: threading.Event = threading.Event()
+ self.release_preflight: threading.Event = threading.Event()
self.document_body: bytes = (
b"<!doctype html><title>Adopted document</title><p>" + b"BiDi adopted document\n" * 128
)
@@ -330,6 +332,18 @@ class ReloadHandler(http.server.BaseHTTPRequestHandler):
except BrokenPipeError:
pass
+ def do_OPTIONS(self):
+ server = self.server
+ assert isinstance(server, ReloadServer)
+ server.preflight_received.set()
+ if not server.release_preflight.wait(30):
+ raise TimeoutError("The test did not release the preflight response")
+ self.send_response(204)
+ self.send_header("Access-Control-Allow-Origin", "*")
+ self.send_header("Access-Control-Allow-Methods", "PUT")
+ self.send_header("Access-Control-Allow-Headers", "X-BiDi")
+ self.end_headers()
+
def log_message(self, format, *args):
pass
@@ -975,6 +989,104 @@ def check_network_document_abort_releases_blocked_object(bidi, context, server):
bidi.evaluate(context, "objectFrame.remove(); 0")
+def check_network_abort_while_blocked_after_gc(bidi, context, server):
+ url = f"http://127.0.0.1:{server.server_port}/network-interception/abort-after-gc"
+ subscription = bidi.command("session.subscribe", {"events": ["network.beforeRequestSent", "network.fetchError"]})[
+ "subscription"
+ ]
+ intercept = bidi.command(
+ "network.addIntercept",
+ {"phases": ["beforeRequestSent"], "urlPatterns": [{"type": "string", "pattern": url}]},
+ )["intercept"]
+ try:
+ pending = bidi.send(
+ "script.evaluate",
+ {
+ "target": {"context": context},
+ "expression": f"window.interceptionAbort = new AbortController(); fetch({json.dumps(url)}, "
+ "{signal: interceptionAbort.signal}).then(() => 'fulfilled', error => error.name)",
+ "awaitPromise": True,
+ },
+ )
+ event = intercepted_event(bidi, "network.beforeRequestSent", url)
+ request_id = event["request"]["request"]
+ # A collection while the request is blocked keeps its fetch, which the abort then ends once.
+ bidi.evaluate(context, "internals.gc(); 0")
+ bidi.evaluate(context, "interceptionAbort.abort(); 0")
+ result = bidi.response(pending)
+ assert result["type"] == "success" and result["result"]["result"]["value"] == "AbortError", result
+ error = bidi.event("network.fetchError")
+ while error["request"]["url"] != url:
+ error = bidi.event("network.fetchError")
+ assert error["request"]["request"] == request_id, error
+ result = bidi.response(bidi.send("network.continueRequest", {"request": request_id}))
+ assert result["type"] == "error" and result["error"] == "no such request", result
+
+ # The aborted fetch's resource timing entry is reported after its error event.
+ entry_count = f"performance.getEntriesByName({json.dumps(url)}).length"
+ deadline = time.monotonic() + 10
+ while not bidi.evaluate(context, entry_count)["result"].get("value"):
+ assert time.monotonic() < deadline, "The aborted fetch reported no resource timing"
+ assert not any(
+ event["method"] == "network.fetchError" and event["params"]["request"]["url"] == url
+ for event in bidi.events
+ ), bidi.events
+ finally:
+ if sys.exc_info()[0] is None:
+ bidi.command("network.removeIntercept", {"intercept": intercept})
+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})
+
+
+def check_network_cancel_with_events_off(bidi, context, server, kind):
+ url = f"http://127.0.0.1:{server.server_port}/network-interception/events-off-{kind}"
+ subscription = bidi.command("session.subscribe", {"events": ["network.beforeRequestSent"]})["subscription"]
+ intercept = bidi.command(
+ "network.addIntercept",
+ {"phases": ["beforeRequestSent"], "urlPatterns": [{"type": "string", "pattern": url}]},
+ )["intercept"]
+ try:
+ pending = None
+ if kind == "abort":
+ pending = bidi.send(
+ "script.evaluate",
+ {
+ "target": {"context": context},
+ "expression": f"window.interceptionAbort = new AbortController(); fetch({json.dumps(url)}, "
+ "{signal: interceptionAbort.signal}).then(() => 'fulfilled', error => error.name)",
+ "awaitPromise": True,
+ },
+ )
+ else:
+ markup = f'<object data="{url}"></object>'
+ bidi.evaluate(
+ context,
+ "window.objectFrame = document.createElement('iframe'); "
+ f"objectFrame.srcdoc = {json.dumps(markup)}; document.body.append(objectFrame); 0",
+ )
+ event = intercepted_event(bidi, "network.beforeRequestSent", url)
+ request_id = event["request"]["request"]
+
+ # With no network event subscribed the session stays active, and an abort or a stop still releases the request.
+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})
+ subscription = None
+ if kind == "abort":
+ bidi.evaluate(context, "interceptionAbort.abort(); 0")
+ result = bidi.response(pending)
+ assert result["type"] == "success" and result["result"]["result"]["value"] == "AbortError", result
+ else:
+ bidi.evaluate(context, "objectFrame.contentWindow.stop(); 0")
+ for blocked_id in [request_id, *take_blocked_requests(bidi, context, url)]:
+ result = bidi.response(bidi.send("network.continueRequest", {"request": blocked_id}))
+ assert result["type"] == "error" and result["error"] == "no such request", result
+ finally:
+ if sys.exc_info()[0] is None:
+ bidi.command("network.removeIntercept", {"intercept": intercept})
+ if subscription is not None:
+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})
+ if kind == "stop":
+ bidi.evaluate(context, "objectFrame.remove(); 0")
+
+
def check_network_provided_body_at_response_started(bidi, context, server):
url = f"http://127.0.0.1:{server.server_port}/network-interception/fail-body"
provided = "provided body"
@@ -1155,6 +1267,11 @@ def check_network_interception(bidi, context, server, case="all"):
check_network_provided_body_at_response_started(bidi, context, server)
if case in ["all", "document-abort-object"]:
check_network_document_abort_releases_blocked_object(bidi, context, server)
+ if case in ["all", "abort-after-gc"]:
+ check_network_abort_while_blocked_after_gc(bidi, context, server)
+ for kind in ["abort", "stop"]:
+ if case in ["all", f"events-off-{kind}"]:
+ check_network_cancel_with_events_off(bidi, context, server, kind)
for action in ["cancel", "default"]:
if case in ["all", "auth-response-matrix", "auth-action-extras", f"auth-{action}-extra"]:
for credentials in [{"type": "password", "username": "user", "password": "pass"}, {}]:
@@ -1364,6 +1481,60 @@ def check_network_adopted_navigation_events(bidi, context, server):
bidi.command("browsingContext.navigate", {"context": context, "url": "about:blank", "wait": "complete"})
+def check_network_abort_before_transport(bidi, context, server):
+ # A cross-origin fetch waits for its CORS preflight before its own request starts, so it has no network transport.
+ terminal_methods = {"network.responseCompleted", "network.fetchError"}
+ url = f"http://localhost:{server.server_port}/network-preflight"
+ bidi.command(
+ "browsingContext.navigate",
+ {"context": context, "url": f"http://127.0.0.1:{server.server_port}/reload", "wait": "complete"},
+ )
+ subscription = bidi.command(
+ "session.subscribe",
+ {"events": ["network.beforeRequestSent", *sorted(terminal_methods)], "contexts": [context]},
+ )["subscription"]
+ server.preflight_received.clear()
+ server.release_preflight.clear()
+
+ def is_our_event(event):
+ request = event["params"].get("request", {})
+ return request.get("url") == url and request.get("method") == "PUT"
+
+ try:
+ bidi.evaluate(
+ context,
+ f"window.bidiAbort = new AbortController(); fetch('{url}', {{ method: 'PUT', headers: {{ 'X-BiDi': '1' }}, signal: window.bidiAbort.signal }}).catch(() => {{}}); 0",
+ )
+ assert server.preflight_received.wait(10), "The fetch did not send its preflight"
+ bidi.evaluate(context, "window.bidiAbort.abort(); 0")
+ while True:
+ terminal = next(
+ (event for event in bidi.events if event["method"] in terminal_methods and is_our_event(event)), None
+ )
+ if terminal is not None:
+ bidi.events.remove(terminal)
+ break
+ bidi.read_message()
+ assert terminal["method"] == "network.fetchError", terminal
+ assert isinstance(terminal["params"]["errorText"], str) and terminal["params"]["errorText"], terminal
+
+ # Releasing the preflight reports nothing more for the aborted request. The request then ends with a network
+ # error, whose report would come before the request's resource timing entry.
+ entry_count = f"performance.getEntriesByName({json.dumps(url)}).length"
+ assert not bidi.evaluate(context, entry_count)["result"].get("value"), "The aborted request ended early"
+ server.release_preflight.set()
+ deadline = time.monotonic() + 10
+ while not bidi.evaluate(context, entry_count)["result"].get("value"):
+ assert time.monotonic() < deadline, "The aborted request reported no resource timing"
+ assert not any(event["method"] in terminal_methods and is_our_event(event) for event in bidi.events), (
+ bidi.events
+ )
+ finally:
+ server.release_preflight.set()
+ if sys.exc_info()[0] is None:
+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})
+
+
def check_screenshot_handles(bidi, context):
bidi.command("browsingContext.activate", {"context": context})
element = bidi.evaluate(context, "document.body.style.height = '20px'; document.body")["result"]
@@ -2042,6 +2213,7 @@ def run_test(
check_network_interception(bidi, context, server, network_interception_case)
check_network_download_events(bidi, context, server, downloads)
check_network_adopted_navigation_events(bidi, context, server)
+ check_network_abort_before_transport(bidi, context, server)
check_screenshot_handles(bidi, context)
check_input_handles(bidi, context)
check_input_queue(bidi, context)
@@ -2248,6 +2420,9 @@ if __name__ == "__main__":
"fail-transport",
"provided-body-at-response-started",
"document-abort-object",
+ "abort-after-gc",
+ "events-off-abort",
+ "events-off-stop",
"auth-gates",
"auth-omit",
"auth-cors",