Skip to content

Truly independent web browser

LibWeb: Adopt transferred navigation bodies through FetchByteChannel

Luke Wildeab0e30c3079f
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 56ac49af4d2..4b0c7d9998d 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -360,7 +360,6 @@ set(SOURCES
Fetch/Fetching/BodyStreamPullSource.cpp
Fetch/Fetching/Checks.cpp
Fetch/Fetching/ClientContextSnapshots.cpp
- Fetch/Fetching/FetchedDataReceiver.cpp
Fetch/Fetching/NetworkBodyPump.cpp
Fetch/Fetching/Fetching.cpp
Fetch/Fetching/PendingResponse.cpp
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index 6e159aa0dc4..7e9908b9f75 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -138,6 +138,7 @@
#include <LibWeb/Editing/SpellCheckController.h>
#include <LibWeb/Editing/SpellingMarkers.h>
#include <LibWeb/Editing/WritingSuggestionController.h>
+#include <LibWeb/Fetch/Engine/NetworkTransportHandle.h>
#include <LibWeb/Fetch/Fetching/Checks.h>
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
#include <LibWeb/Fetch/Infrastructure/FetchRecord.h>
@@ -639,10 +640,9 @@ WebIDL::ExceptionOr<GC::Ref<Document>> Document::create_and_initialize(Type type
navigation_params.response->status());
}
- // AD-HOC: Retain the navigation fetch controller so aborting the document can cancel the main resource after
- // response commitment. Navigation fetches are not included in the document's subresource fetch group.
- if (navigation_params.fetch_controller)
- document->m_ongoing_navigation_fetch_controller = navigation_params.fetch_controller;
+ // AD-HOC: Retain the navigation's fetch controller, or an adopted body's transport, so aborting the document
+ // cancels its main resource, which is not in its fetch group.
+ document->m_ongoing_navigation_fetch = navigation_params.body_delivery();
// 17. If navigationParams's response has a `Refresh` header, then:
if (auto maybe_refresh = navigation_params.response->header_list()->get("Refresh"sv); maybe_refresh.has_value()) {
@@ -994,7 +994,7 @@ void Document::visit_edges(Cell::Visitor& visitor)
visitor.visit(m_pending_parsing_blocking_svg_script);
visitor.visit(m_history);
visitor.visit(m_html_parser_end_state);
- visitor.visit(m_ongoing_navigation_fetch_controller);
+ visitor.visit(m_ongoing_navigation_fetch);
visitor.visit(m_navigation_timing_entry);
visitor.visit(m_style_computer);
visitor.visit(m_font_computer);
@@ -5262,7 +5262,7 @@ void Document::schedule_svg_referenced_motion_path_update(SVG::SVGAnimateMotionE
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#completely-finish-loading
void Document::completely_finish_loading()
{
- m_ongoing_navigation_fetch_controller = nullptr;
+ m_ongoing_navigation_fetch = Empty {};
// 2. Set document's completely loaded time to the current time.
// AD-HOC: Set this unconditionally, even if the document has no navigable yet.
@@ -6721,7 +6721,9 @@ void Document::abort()
// If this resulted in any instances of the fetch algorithm being canceled
// or any queued tasks or any network data getting discarded,
// then make document unsalvageable given document and "fetch".
- bool canceled_fetch = false;
+ bool canceled_fetch = HTML::stop_body_delivery(m_ongoing_navigation_fetch);
+ m_ongoing_navigation_fetch = Empty {};
+
auto cancel_fetch = [&](GC::Ptr<Fetch::Infrastructure::FetchController> controller) {
if (!controller || controller->state() != Fetch::Infrastructure::FetchController::State::Ongoing)
return;
@@ -6729,9 +6731,6 @@ void Document::abort()
canceled_fetch = true;
};
- cancel_fetch(m_ongoing_navigation_fetch_controller);
- m_ongoing_navigation_fetch_controller = nullptr;
-
// AD-HOC: The fetch group belongs to the document's Window. Once the Window is associated with another document,
// as when the initial about:blank document is replaced, its fetches are not in the context of this document.
if (auto window = this->window(); window && window->associated_document_if_any().ptr() == this) {
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index 15ee315fa03..d6496113716 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -2138,9 +2138,9 @@ private:
// https://html.spec.whatwg.org/multipage/dom.html#concept-document-navigation-id
Optional<Utf16String> m_navigation_id;
- // AD-HOC: The main resource fetch is not part of the document's subresource fetch group, so retain its controller
- // separately while the navigation fetch is ongoing.
- GC::Ptr<Fetch::Infrastructure::FetchController> m_ongoing_navigation_fetch_controller;
+ // AD-HOC: The main resource fetch is not part of the document's subresource fetch group, so retain its controller,
+ // or the network transport of a body adopted without one, separately while the navigation fetch is ongoing.
+ Variant<Empty, GC::Ref<Fetch::Infrastructure::FetchController>, NonnullRefPtr<Fetch::Engine::NetworkTransportHandle>> m_ongoing_navigation_fetch;
// https://html.spec.whatwg.org/multipage/origin.html#active-sandboxing-flag-set
HTML::SandboxingFlagSet m_active_sandboxing_flag_set;
diff --git a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cpp b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cpp
index 2bacea00ce3..bde3ef2fba8 100644
--- a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cpp
+++ b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cpp
@@ -38,11 +38,6 @@ void NetworkTransportHandle::stop()
m_request->stop();
}
-void NetworkTransportHandle::resume_body_delivery()
-{
- m_request->resume_body_delivery();
-}
-
void NetworkTransportHandle::release_transfer_lease()
{
m_request->release_transfer_lease();
diff --git a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h
index 96ddf4aeebf..ff46a1335d4 100644
--- a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h
+++ b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h
@@ -29,7 +29,6 @@ public:
virtual void pause_body_delivery() override;
virtual void stop() override;
- void resume_body_delivery();
void release_transfer_lease();
void set_on_requires_network(Function<void()>);
diff --git a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
index 0f3eb5d64e9..531133d5e4b 100644
--- a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
@@ -75,7 +75,7 @@ void BodyStreamWakeSink::wake(Engine::WakeTicket ticket)
});
}
-BodyStreamPullSource::BodyStreamPullSource(JS::Realm& realm, GC::Ref<Infrastructure::FetchParams const> fetch_params, GC::Ref<Streams::ReadableStream> stream, NonnullRefPtr<Engine::FetchByteChannel> channel, BodyStreamWakeSink const& wake_sink)
+BodyStreamPullSource::BodyStreamPullSource(JS::Realm& realm, GC::Ptr<Infrastructure::FetchParams const> fetch_params, GC::Ref<Streams::ReadableStream> stream, NonnullRefPtr<Engine::FetchByteChannel> channel, BodyStreamWakeSink const& wake_sink)
: m_realm(realm)
, m_fetch_params(fetch_params)
, m_stream(stream)
@@ -129,7 +129,8 @@ GC::Ref<WebIDL::Promise> BodyStreamPullSource::cancel(JS::Value reason)
WebIDL::resolve_promise(realm, *promise, JS::js_undefined());
// cancelAlgorithm: abort fetchParams's controller with reason, given reason.
- m_fetch_params->controller()->abort(realm, reason);
+ if (m_fetch_params)
+ m_fetch_params->controller()->abort(realm, reason);
return WebIDL::create_resolved_promise(realm, JS::js_undefined());
}
@@ -149,9 +150,17 @@ BodyStreamPullSource::WakeResult BodyStreamPullSource::on_wake(Engine::WakeTicke
// 3. Queue a fetch task to run the following steps, with fetchParams’s task destination:
// NB: This task stays queued when the fetch is stopped.
- Infrastructure::queue_fetch_task(m_fetch_params->task_destination(), GC::create_function(heap(), [this] {
+ auto steps = GC::create_function(heap(), [this] {
run_pull_task();
- }));
+ });
+ if (m_fetch_params) {
+ Infrastructure::queue_fetch_task(m_fetch_params->task_destination(), steps);
+ return WakeResult::Consumed;
+ }
+
+ // AD-HOC: The tasks of a navigation body adopted from another process are queued without a document, since the
+ // previous document's tasks stop running once the new document replaces it.
+ HTML::queue_a_task(HTML::Task::Source::Networking, HTML::main_thread_event_loop(), nullptr, steps);
return WakeResult::Consumed;
}
@@ -249,7 +258,8 @@ void BodyStreamPullSource::drain_into_stream()
auto error = WebIDL::exception_to_throw_completion(realm.vm(), realm, pull_result.release_error());
if (m_stream->is_readable())
m_stream->error(error.value());
- m_fetch_params->controller()->terminate();
+ if (m_fetch_params)
+ m_fetch_params->controller()->terminate();
m_channel->cancel();
m_detached = true;
return;
@@ -257,7 +267,7 @@ void BodyStreamPullSource::drain_into_stream()
}
// 2. If stream is errored, then terminate fetchParams’s controller.
- if (m_stream->is_errored())
+ if (m_stream->is_errored() && m_fetch_params)
m_fetch_params->controller()->terminate();
settle_stream(result);
diff --git a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h
index 678090adaee..3bcbdfa53c0 100644
--- a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h
+++ b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h
@@ -42,7 +42,7 @@ class BodyStreamPullSource final : public JS::Cell {
GC_DECLARE_ALLOCATOR(BodyStreamPullSource);
public:
- BodyStreamPullSource(JS::Realm&, GC::Ref<Infrastructure::FetchParams const>, GC::Ref<Streams::ReadableStream>, NonnullRefPtr<Engine::FetchByteChannel>, BodyStreamWakeSink const&);
+ BodyStreamPullSource(JS::Realm&, GC::Ptr<Infrastructure::FetchParams const>, GC::Ref<Streams::ReadableStream>, NonnullRefPtr<Engine::FetchByteChannel>, BodyStreamWakeSink const&);
virtual ~BodyStreamPullSource() override;
GC::Ref<WebIDL::Promise> pull();
@@ -65,7 +65,8 @@ private:
// The realm the stream is set up in.
GC::Ref<JS::Realm> m_realm;
- GC::Ref<Infrastructure::FetchParams const> m_fetch_params;
+ // Null for a navigation body adopted from another process.
+ GC::Ptr<Infrastructure::FetchParams const> m_fetch_params;
GC::Ref<Streams::ReadableStream> m_stream;
NonnullRefPtr<Engine::FetchByteChannel> m_channel;
BodyStreamWakeToken const m_registry_token { 0 };
diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp b/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp
deleted file mode 100644
index a2d97514850..00000000000
--- a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
- * Copyright (c) 2024-2026, Tim Flynn <[email protected]>
- * Copyright (c) 2025, Aliaksandr Kalenik <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Function.h>
-#include <LibGC/Heap.h>
-#include <LibHTTP/Cache/MemoryCache.h>
-#include <LibWeb/Fetch/Fetching/FetchedDataReceiver.h>
-#include <LibWeb/Fetch/Infrastructure/FetchParams.h>
-#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
-#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
-#include <LibWeb/HTML/EventLoop/EventLoop.h>
-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
-#include <LibWeb/Streams/ReadableStream.h>
-#include <LibWeb/WebIDL/ExceptionOrUtils.h>
-
-namespace Web::Fetch::Fetching {
-
-GC_DEFINE_ALLOCATOR(FetchedDataReceiver);
-
-static constexpr size_t maximum_pending_bytes = 5 * MiB;
-
-FetchedDataReceiver::FetchedDataReceiver(GC::Ref<Streams::ReadableStream> stream)
- : FetchedDataReceiver(nullptr, stream, {})
-{
-}
-
-FetchedDataReceiver::FetchedDataReceiver(GC::Ptr<Infrastructure::FetchParams const> fetch_params, GC::Ref<Streams::ReadableStream> stream, RefPtr<HTTP::MemoryCache> http_cache)
- : m_fetch_params(fetch_params)
- , m_stream(stream)
- , m_http_cache(move(http_cache))
-{
-}
-
-FetchedDataReceiver::~FetchedDataReceiver() = default;
-
-void FetchedDataReceiver::set_body(GC::Ref<Fetch::Infrastructure::Body> body)
-{
- m_body = body;
- // Flush any bytes that were buffered before the body was set
- if (!m_pre_body_sniff_buffer.is_empty()) {
- m_body->append_sniff_bytes(m_pre_body_sniff_buffer);
- m_pre_body_sniff_buffer.clear();
- }
- // If the stream already completed before the body was set,
- // we missed the set_sniff_bytes_complete() call in handle_network_data.
- if (m_network_complete)
- m_body->set_sniff_bytes_complete();
-}
-
-void FetchedDataReceiver::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_fetch_params);
- visitor.visit(m_response);
- visitor.visit(m_body);
- visitor.visit(m_stream);
-}
-
-// This implements the parallel steps of the pullAlgorithm in HTTP-network-fetch.
-// https://fetch.spec.whatwg.org/#ref-for-in-parallel⑤
-void FetchedDataReceiver::handle_network_data(JS::Realm& realm, Requests::ResponseData data, NetworkState state)
-{
- if (state == NetworkState::Complete) {
- VERIFY(data.bytes().is_empty());
- m_network_complete = true;
- if (m_response) {
- auto body_info = m_response->body_info();
- body_info.decoded_size = m_decoded_body_size;
- m_response->set_body_info(move(body_info));
- }
- // Mark sniff bytes as complete when the stream ends
- if (m_body)
- m_body->set_sniff_bytes_complete();
-
- // 2. Otherwise, if the bytes transmission for response’s message body is done normally and stream is readable,
- // then close stream, and abort these in-parallel steps.
- // NB: The close follows any pending bytes through the same task queue; see deliver_pending_bytes().
- queue_delivery_task(realm);
- return;
- }
-
- // 1. If one or more bytes have been transmitted from response’s message body, then:
- auto bytes = data.bytes();
- if (bytes.is_empty())
- return;
-
- // 1. Let bytes be the transmitted bytes.
-
- // FIXME: 2. Let codings be the result of extracting header list values given `Content-Encoding` and response’s header list.
- // FIXME: 3. Increase response’s body info’s encoded size by bytes’s length.
- // FIXME: 4. Set bytes to the result of handling content codings given codings and bytes.
- // FIXME: 6. If bytes is failure, then terminate fetchParams’s controller.
-
- // 5. Increase response’s body info’s decoded size by bytes’s length.
- // NB: The response's body info is updated once the network completes.
- m_decoded_body_size += bytes.size();
-
- // Capture bytes for MIME sniffing
- if (m_body) {
- if (auto const* file_backed = data.file_backed_slice(); file_backed && !m_body->source().has_value())
- m_body->set_source(file_backed->payload, static_cast<u64>(file_backed->payload.size()));
- m_body->append_sniff_bytes(bytes);
- } else if (m_pre_body_sniff_buffer.size() < Infrastructure::MAX_SNIFF_BYTES) {
- auto space_remaining = Infrastructure::MAX_SNIFF_BYTES - m_pre_body_sniff_buffer.size();
- m_pre_body_sniff_buffer.append(bytes.slice(0, min(bytes.size(), space_remaining)));
- }
-
- if (m_http_cache && !m_cache_body_replaces_network_buffer) {
- if (auto const* file_backed = data.file_backed_slice(); file_backed && m_cache_buffer.is_empty()) {
- if (!m_cache_body.has_value())
- m_cache_body = file_backed->payload;
- } else {
- if (m_cache_body.has_value()) {
- m_cache_buffer.append(m_cache_body->bytes());
- m_cache_body.clear();
- }
- m_cache_buffer.append(bytes);
- }
- }
-
- // 7. Append bytes to buffer.
- m_pending_bytes.append(bytes);
- queue_delivery_task(realm);
-
- // 8. If the size of buffer is larger than an upper limit chosen by the user agent, ask the user agent to suspend
- // the ongoing fetch.
- if (m_pending_bytes.size() >= maximum_pending_bytes && !m_paused_network_delivery) {
- if (auto request = m_network_request.strong_ref()) {
- request->set_body_delivery_paused(true);
- m_paused_network_delivery = true;
- }
- }
-}
-
-// AD-HOC: These tasks are queued without a document on purpose. A navigation reads its new document's body through
-// this receiver while the fetch's task destination is still the previous document's global, and tasks
-// queued on that document stop running once it is replaced.
-static void queue_networking_task(GC::Ref<GC::Function<void()>> steps)
-{
- HTML::queue_a_task(HTML::Task::Source::Networking, HTML::main_thread_event_loop(), nullptr, steps);
-}
-
-// This implements the task-queueing half of the pullAlgorithm in HTTP-network-fetch: bytes are handed to the
-// stream from a networking task rather than from the network callback, so consumers see them interleaved with
-// the tasks their own reactions queue.
-// https://fetch.spec.whatwg.org/#ref-for-in-parallel④
-void FetchedDataReceiver::queue_delivery_task(JS::Realm& realm)
-{
- // AD-HOC: These tasks stand in for in-parallel steps, which a paused event loop doesn't stop — and a sync XHR
- // send() keeps it paused for as long as it waits for exactly these bytes (see the parallel-queue path in
- // fetch_response_handover()). So, while it's paused, deliver straight from the network callback instead.
- // Any bytes a queued task was to deliver go along; that task then finds nothing left to do.
- if (HTML::main_thread_event_loop().execution_paused()) {
- deliver_pending_bytes(realm);
- return;
- }
-
- if (m_delivery_task_queued)
- return;
- m_delivery_task_queued = true;
-
- queue_networking_task(GC::create_function(heap(), [this, &realm]() {
- m_delivery_task_queued = false;
- deliver_pending_bytes(realm);
- }));
-}
-
-void FetchedDataReceiver::deliver_pending_bytes(JS::Realm& realm)
-{
- auto bytes = move(m_pending_bytes);
- m_pending_bytes = {};
- if (!bytes.is_empty())
- enqueue_into_stream(realm, bytes);
-
- // 1. If the size of buffer is smaller than a lower limit chosen by the user agent and the ongoing fetch is
- // suspended, resume the fetch.
- if (m_paused_network_delivery) {
- m_paused_network_delivery = false;
- if (auto request = m_network_request.strong_ref())
- request->set_body_delivery_paused(false);
- }
-
- // The close goes through the queue too, so it lands behind whatever the consumer queued in reaction to the
- // bytes above, the way it does when a network completion trails the last data.
- // AD-HOC: Except while the event loop is paused; see queue_delivery_task().
- if (m_network_complete) {
- if (HTML::main_thread_event_loop().execution_paused()) {
- close_stream(realm);
- return;
- }
- queue_networking_task(GC::create_function(heap(), [this, &realm]() {
- close_stream(realm);
- }));
- }
-}
-
-void FetchedDataReceiver::set_cached_response_body(Core::ImmutableBytes body)
-{
- if (!m_http_cache)
- return;
-
- m_cache_buffer.clear();
- m_cache_body = move(body);
- m_cache_body_replaces_network_buffer = true;
-}
-
-// This implements the parallel steps of the pullAlgorithm in HTTP-network-fetch.
-// https://fetch.spec.whatwg.org/#ref-for-in-parallel④
-void FetchedDataReceiver::enqueue_into_stream(JS::Realm& realm, ReadonlyBytes bytes)
-{
- if (!m_stream->is_readable())
- return;
-
- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
-
- // 1. Pull from bytes buffer into stream.
- if (auto result = m_stream->enqueue_bytes(bytes); result.is_error()) {
- auto throw_completion = WebIDL::exception_to_throw_completion(realm.vm(), realm, result.release_error());
- // 2. If stream is errored, then terminate fetchParams’s controller.
- m_stream->error(throw_completion.value());
- if (m_fetch_params)
- m_fetch_params->controller()->terminate();
- }
-}
-
-void FetchedDataReceiver::close_stream(JS::Realm& realm)
-{
- if (m_http_cache && m_fetch_params) {
- auto request = m_fetch_params->request();
- if (m_stream->is_readable() && !m_fetch_params->is_canceled()
- && m_response && request->cache_mode() != HTTP::CacheMode::NoStore) {
- auto response_body = m_cache_body.has_value()
- ? m_cache_body.release_value()
- : Core::ImmutableBytes::adopt(move(m_cache_buffer));
- m_http_cache->finalize_entry(request->current_url(), request->method(), request->header_list(), m_response->status(), m_response->header_list(), move(response_body));
- }
-
- m_http_cache.clear();
- m_cache_body.clear();
- }
-
- if (!m_stream->is_readable())
- return;
-
- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
-
- m_stream->close();
-}
-
-}
diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.h b/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.h
deleted file mode 100644
index bbad190c5d0..00000000000
--- a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (c) 2024-2026, Tim Flynn <[email protected]>
- * Copyright (c) 2025, Aliaksandr Kalenik <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/ByteBuffer.h>
-#include <AK/WeakPtr.h>
-#include <LibCore/ImmutableBytes.h>
-#include <LibGC/CellAllocator.h>
-#include <LibHTTP/Forward.h>
-#include <LibJS/Heap/Cell.h>
-#include <LibRequests/Request.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::Fetch::Fetching {
-
-class FetchedDataReceiver final : public JS::Cell {
- GC_CELL(FetchedDataReceiver, JS::Cell);
- GC_DECLARE_ALLOCATOR(FetchedDataReceiver);
-
-public:
- explicit FetchedDataReceiver(GC::Ref<Streams::ReadableStream>);
- virtual ~FetchedDataReceiver() override;
-
- void set_response(GC::Ref<Fetch::Infrastructure::Response> response) { m_response = response; }
- void set_body(GC::Ref<Fetch::Infrastructure::Body> body);
- void set_network_request(RefPtr<Requests::Request> const& request) { m_network_request = request; }
-
- enum class NetworkState {
- Ongoing,
- Complete,
- };
- void handle_network_data(JS::Realm&, Requests::ResponseData, NetworkState);
- void set_cached_response_body(Core::ImmutableBytes);
-
-private:
- FetchedDataReceiver(GC::Ptr<Infrastructure::FetchParams const>, GC::Ref<Streams::ReadableStream>, RefPtr<HTTP::MemoryCache>);
-
- virtual void visit_edges(Visitor& visitor) override;
-
- void queue_delivery_task(JS::Realm&);
- void deliver_pending_bytes(JS::Realm&);
- void enqueue_into_stream(JS::Realm&, ReadonlyBytes);
- void close_stream(JS::Realm&);
-
- GC::Ptr<Infrastructure::FetchParams const> m_fetch_params;
- GC::Ptr<Fetch::Infrastructure::Response> m_response;
- GC::Ptr<Fetch::Infrastructure::Body> m_body;
-
- GC::Ref<Streams::ReadableStream> m_stream;
-
- RefPtr<HTTP::MemoryCache> m_http_cache;
-
- // Bytes received before set_body() is called. Held only until the body is attached and these
- // are flushed into the body's MIME-sniff buffer.
- ByteBuffer m_pre_body_sniff_buffer;
-
- // Whole-response buffer retained only when m_http_cache is non-null, for finalize_entry().
- ByteBuffer m_cache_buffer;
- Optional<Core::ImmutableBytes> m_cache_body;
- bool m_cache_body_replaces_network_buffer { false };
-
- u64 m_decoded_body_size { 0 };
- bool m_network_complete { false };
-
- // Bytes read off the network but not yet handed to the stream. They are delivered by a queued networking task
- // so that consumers see them interleaved with other tasks, and reading pauses while too many pile up.
- WeakPtr<Requests::Request> m_network_request;
- ByteBuffer m_pending_bytes;
- bool m_delivery_task_queued { false };
- bool m_paused_network_delivery { false };
-};
-
-}
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 6878fba8caf..09fe48b08d8 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -2611,6 +2611,127 @@ static NonnullRefPtr<Engine::WholeBodyTransport> create_whole_body_transport(Eng
return transport;
}
+namespace {
+
+// A network response's body stream and the objects that fill it from the transport.
+struct NetworkBodyStream {
+ GC::Ref<Streams::ReadableStream> stream;
+ NonnullRefPtr<Engine::FetchByteChannel> channel;
+ NonnullRefPtr<Engine::FetchBodyDeliveryGate> delivery_gate;
+ GC::Ref<NetworkBodyPump> body_pump;
+ GC::Ref<BodyStreamPullSource> pull_source;
+};
+
+}
+
+// https://fetch.spec.whatwg.org/#concept-http-network-fetch
+// NB: Steps 9 to 13 of HTTP-network fetch.
+static NetworkBodyStream create_network_body_stream(JS::Realm& realm, GC::Ptr<Infrastructure::FetchParams const> fetch_params, Engine::FetchBodyDeliveryGate::NavigationHold navigation_hold, RefPtr<HTTP::MemoryCache> http_cache)
+{
+ // 10. Let stream be a new ReadableStream.
+ auto stream = Streams::ReadableStream::create(realm);
+
+ // 9. Let buffer be an empty byte sequence.
+ // NB: The buffer is the FetchByteChannel; its watermarks are the user-agent-chosen lower and upper limits.
+ static constexpr Engine::FetchByteChannel::Watermarks network_body_watermarks { .low = 256 * KiB, .high = 1 * MiB };
+ auto delivery_gate = Engine::FetchBodyDeliveryGate::create(navigation_hold);
+ auto wake_sink = BodyStreamWakeSink::create();
+ auto channel = Engine::FetchByteChannel::create(network_body_watermarks, wake_sink, delivery_gate->create_channel_sink());
+ delivery_gate->grant_credit(channel->initial_credit());
+
+ auto body_pump = GC::Heap::the().allocate<NetworkBodyPump>(fetch_params, channel, delivery_gate, move(http_cache));
+ auto pull_source = GC::Heap::the().allocate<BodyStreamPullSource>(realm, fetch_params, stream, channel, *wake_sink);
+
+ // 11. Let pullAlgorithm be the following steps:
+ auto pull_algorithm = GC::create_function(GC::Heap::the(), [pull_source]() {
+ return pull_source->pull();
+ });
+
+ // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s controller with reason, given reason.
+ auto cancel_algorithm = GC::create_function(GC::Heap::the(), [pull_source](JS::Value reason) {
+ return pull_source->cancel(reason);
+ });
+
+ // 13. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm, cancelAlgorithm set to cancelAlgorithm.
+ stream->set_up_with_byte_reading_support(realm, pull_algorithm, cancel_algorithm);
+
+ return { stream, move(channel), move(delivery_gate), body_pump, pull_source };
+}
+
+GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, Infrastructure::Response& response, Optional<Utf16String> const& request_server_top_level_site, Requests::RequestTransferLeaseKey transfer_lease, RefPtr<Infrastructure::FetchTimingInfo> timing_info, Function<void(Optional<StringView> error)> on_network_settled)
+{
+ if (!ResourceLoader::is_initialized())
+ return {};
+
+ // The UI process moved the response to the RequestServer of the given top-level site.
+ auto request_client = ResourceLoader::the().request_client_for_top_level_site(request_server_top_level_site);
+ if (!request_client)
+ return {};
+
+ auto request = request_client->adopt_request(transfer_lease.source_client_id, transfer_lease.source_request_id, Requests::RequestClient::TransferLease::Yes);
+ if (!request)
+ return {};
+
+ HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+
+ // Only the bytes the navigation sniffs are delivered until it decides what the response becomes.
+ auto network_body_stream = create_network_body_stream(realm, nullptr, Engine::FetchBodyDeliveryGate::NavigationHold::Held, nullptr);
+ auto body = Infrastructure::Body::create(network_body_stream.stream);
+ network_body_stream.body_pump->set_body(body);
+ network_body_stream.body_pump->set_response(response);
+
+ auto channel = network_body_stream.channel;
+ auto delivery_gate = network_body_stream.delivery_gate;
+ auto network_transport = Engine::NetworkTransportHandle::create(*request);
+ delivery_gate->attach_transport(network_transport);
+ // A request either finishes or tears down, so the observer hears the body's end once.
+ auto network_settled = GC::make_root(GC::create_function(GC::Heap::the(), move(on_network_settled)));
+ // The gate detaches before the cancellation reaches it.
+ network_transport->set_on_teardown([delivery_gate, channel, network_settled] {
+ delivery_gate->detach_transport();
+ channel->cancel();
+ network_settled->function()("Transferred navigation response was stopped"sv);
+ });
+
+ auto body_pump = GC::make_root(network_body_stream.body_pump);
+ auto pull_source = GC::make_root(network_body_stream.pull_source);
+ auto cross_origin_isolated_capability = Bindings::principal_host_defined_environment_settings_object(realm).cross_origin_isolated_capability();
+ request->set_unbuffered_request_callbacks(
+ [](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Optional<Core::ImmutableBytes>, Optional<u64>, Requests::CacheState) { },
+ [body_pump](Requests::ResponseData data) {
+ body_pump->handle_network_data(move(data));
+ },
+ [body_pump](Core::ImmutableBytes data) {
+ body_pump->set_cached_response_body(move(data));
+ },
+ [&realm, body_pump, pull_source, delivery_gate, timing_info, cross_origin_isolated_capability, network_settled](u64, Requests::RequestTimingInfo const& request_timing_info, Optional<Requests::NetworkError> network_error) {
+ HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ delivery_gate->detach_transport();
+
+ if (network_error.has_value()) {
+ network_settled->function()("Transferred navigation response failed"sv);
+ body_pump->handle_network_error("Transferred navigation response failed"sv);
+ } else {
+ // AD-HOC: Nothing reports timing for a navigation fetch, so record the network phases and end time
+ // here for the Document's navigation timing entry.
+ if (timing_info) {
+ timing_info->update_final_timings(request_timing_info, cross_origin_isolated_capability);
+ timing_info->set_end_time(HighResolutionTime::unsafe_shared_current_time());
+ }
+ body_pump->handle_network_complete(static_cast<u64>(max<i64>(request_timing_info.encoded_body_size, 0)));
+ network_settled->function()({});
+ }
+
+ pull_source->handle_network_settled();
+ });
+
+ response.set_network_transport({
+ .handle = move(network_transport),
+ .body_delivery_gate = move(delivery_gate),
+ });
+ return body;
+}
+
// https://fetch.spec.whatwg.org/#concept-http-network-fetch
// Drop-in replacement for 'HTTP-network fetch', but obviously non-standard :^)
// It also handles file:// URLs since those can also go through ResourceLoader.
@@ -2673,35 +2794,16 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
- // 10. Let stream be a new ReadableStream.
- auto stream = Streams::ReadableStream::create(realm);
-
- // 9. Let buffer be an empty byte sequence.
- // NB: The buffer is the FetchByteChannel; its watermarks are the user-agent-chosen lower and upper limits.
- static constexpr Engine::FetchByteChannel::Watermarks network_body_watermarks { .low = 256 * KiB, .high = 1 * MiB };
+ // NB: Steps 9 to 13 run in create_network_body_stream().
auto navigation_hold = fetch_params.has_response_body_transfer_lease()
? Engine::FetchBodyDeliveryGate::NavigationHold::Held
: Engine::FetchBodyDeliveryGate::NavigationHold::None;
- auto delivery_gate = Engine::FetchBodyDeliveryGate::create(navigation_hold);
- auto wake_sink = BodyStreamWakeSink::create();
- auto channel = Engine::FetchByteChannel::create(network_body_watermarks, wake_sink, delivery_gate->create_channel_sink());
- delivery_gate->grant_credit(channel->initial_credit());
-
- auto body_pump = GC::Heap::the().allocate<NetworkBodyPump>(fetch_params, channel, delivery_gate, http_cache);
- auto pull_source = GC::Heap::the().allocate<BodyStreamPullSource>(realm, fetch_params, stream, channel, *wake_sink);
-
- // 11. Let pullAlgorithm be the following steps:
- auto pull_algorithm = GC::create_function(GC::Heap::the(), [pull_source]() {
- return pull_source->pull();
- });
-
- // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s controller with reason, given reason.
- auto cancel_algorithm = GC::create_function(GC::Heap::the(), [pull_source](JS::Value reason) {
- return pull_source->cancel(reason);
- });
-
- // 13. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm, cancelAlgorithm set to cancelAlgorithm.
- stream->set_up_with_byte_reading_support(realm, pull_algorithm, cancel_algorithm);
+ auto network_body_stream = create_network_body_stream(realm, &fetch_params, navigation_hold, http_cache);
+ auto stream = network_body_stream.stream;
+ auto channel = network_body_stream.channel;
+ auto delivery_gate = network_body_stream.delivery_gate;
+ auto body_pump = network_body_stream.body_pump;
+ auto pull_source = network_body_stream.pull_source;
// A load without a RequestServer request, such as one for a file: URL, hands over its whole body at once.
auto whole_body_transport = create_whole_body_transport(*delivery_gate, *channel);
@@ -2743,7 +2845,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
if (network_transport) {
response->set_network_transport({
.handle = *network_transport,
- .body_delivery = delivery_gate,
+ .body_delivery_gate = delivery_gate,
});
} else {
// A body without a RequestServer request is never held for its navigation.
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.h b/Libraries/LibWeb/Fetch/Fetching/Fetching.h
index 8dd3cd48305..af76ef268f1 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.h
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.h
@@ -14,6 +14,7 @@
#include <LibHTTP/Cookie/IncludeCredentials.h>
#include <LibHTTP/Forward.h>
#include <LibJS/Forward.h>
+#include <LibRequests/RequestTransferLease.h>
#include <LibURL/Forward.h>
#include <LibWeb/Export.h>
#include <LibWeb/Fetch/Infrastructure/NetworkPartitionKey.h>
@@ -56,6 +57,8 @@ WEB_API GC::Ptr<PendingResponse> http_redirect_fetch(JS::Realm&, Infrastructure:
GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm&, Infrastructure::FetchParams const&, IsAuthenticationFetch is_authentication_fetch = IsAuthenticationFetch::No, IsNewConnectionFetch is_new_connection_fetch = IsNewConnectionFetch::No);
GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(JS::Realm&, Infrastructure::FetchParams const&, HTTP::Cookie::IncludeCredentials include_credentials = HTTP::Cookie::IncludeCredentials::No, IsNewConnectionFetch is_new_connection_fetch = IsNewConnectionFetch::No, RefPtr<HTTP::MemoryCache> = {});
GC::Ref<PendingResponse> cors_preflight_fetch(JS::Realm&, Infrastructure::FetchParams const&);
+// on_network_settled runs once: when the network completes the body, or with an error when the body fails or stops.
+GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm&, Infrastructure::Response&, Optional<Utf16String> const& request_server_top_level_site, Requests::RequestTransferLeaseKey, RefPtr<Infrastructure::FetchTimingInfo>, Function<void(Optional<StringView> error)> on_network_settled);
void set_sec_fetch_dest_header(Infrastructure::Request&);
void set_sec_fetch_mode_header(Infrastructure::Request&);
void set_sec_fetch_site_header(Infrastructure::Request&);
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
index 6371966b8b2..ab9060971ef 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
@@ -123,24 +123,14 @@ void Response::release_request_transfer_lease() const
void Response::resume_body_delivery() const
{
release_request_transfer_lease();
- if (!m_network_transport.has_value())
- return;
-
- auto const& handle = m_network_transport->handle;
- m_network_transport->body_delivery.visit(
- [&](NetworkTransport::DeliveredByHandle) { handle->resume_body_delivery(); },
- [](NonnullRefPtr<Engine::FetchBodyDeliveryGate> const& gate) { gate->release_hold(); });
+ if (m_network_transport.has_value())
+ m_network_transport->body_delivery_gate->release_hold();
}
void Response::resume_body_delivery_up_to(size_t byte_count) const
{
- if (!m_network_transport.has_value())
- return;
-
- auto const& handle = m_network_transport->handle;
- m_network_transport->body_delivery.visit(
- [&](NetworkTransport::DeliveredByHandle) { handle->resume_body_delivery_up_to(byte_count); },
- [&](NonnullRefPtr<Engine::FetchBodyDeliveryGate> const& gate) { gate->release_hold_up_to(byte_count); });
+ if (m_network_transport.has_value())
+ m_network_transport->body_delivery_gate->release_hold_up_to(byte_count);
}
// https://fetch.spec.whatwg.org/#concept-response-url
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h
index 959e04339da..290a1b4baed 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h
@@ -62,12 +62,8 @@ public:
// RequestServer bookkeeping is transport state, not JS-visible response data.
struct NetworkTransport {
- // The handle itself pauses and resumes the body's delivery.
- struct DeliveredByHandle { };
-
NonnullRefPtr<Engine::NetworkTransportHandle> handle;
- // A body paced by a FetchByteChannel is released from the navigation hold through its delivery gate.
- Variant<DeliveredByHandle, NonnullRefPtr<Engine::FetchBodyDeliveryGate>> body_delivery { DeliveredByHandle {} };
+ NonnullRefPtr<Engine::FetchBodyDeliveryGate> body_delivery_gate;
};
[[nodiscard]] static GC::Ref<Response> create();
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index 1a9bdb4d976..c5dbd9ac12e 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -537,18 +537,17 @@ void LocalNavigable::handle_as_a_download(GC::Ref<Fetch::Infrastructure::Respons
start_download_for_response(response, download_url, move(suggested_filename), fetch_controller);
}
-static void stop_or_resume_response_body_delivery(LocalNavigable::NavigationParamsVariant const& navigation_params)
+// AD-HOC: Stopping the fetch controller, or the network transport of a body adopted without one, is an implementation
+// hook for tearing down a network body when no spec consumer remains.
+static void stop_response_body_delivery(NavigationParams const& navigation_params)
{
- // AD-HOC: FetchController::stop_fetch() is an implementation hook for tearing down a paused network body when no
- // spec consumer remains.
- auto const* nav_params = navigation_params.get_pointer<GC::Ref<NavigationParams>>();
- if (!nav_params)
- return;
+ stop_body_delivery(navigation_params.body_delivery());
+}
- if ((*nav_params)->fetch_controller)
- (*nav_params)->fetch_controller->stop_fetch();
- else
- (*nav_params)->response->resume_body_delivery();
+static void stop_response_body_delivery(LocalNavigable::NavigationParamsVariant const& navigation_params)
+{
+ if (auto const* nav_params = navigation_params.get_pointer<GC::Ref<NavigationParams>>())
+ stop_response_body_delivery(**nav_params);
}
static bool handle_navigation_response_as_download(GC::Ref<NavigationParams> navigation_params, bool source_allows_downloading, Optional<URL::Origin> interface_origin, Optional<ReadonlyBytes> initial_data = {})
@@ -587,10 +586,7 @@ static bool handle_navigation_response_as_download(GC::Ref<NavigationParams> nav
auto target_allows_downloading = !has_flag(navigation_params->final_sandboxing_flag_set, SandboxingFlagSet::SandboxedDownloads);
if (!source_allows_downloading || !target_allows_downloading) {
report_download_rejected();
- if (navigation_params->fetch_controller)
- navigation_params->fetch_controller->stop_fetch();
- else
- response->resume_body_delivery();
+ stop_response_body_delivery(*navigation_params);
return true;
}
@@ -598,7 +594,7 @@ static bool handle_navigation_response_as_download(GC::Ref<NavigationParams> nav
auto active_window = navigation_params->navigable->active_window();
if (!active_window) {
report_download_rejected();
- stop_or_resume_response_body_delivery(navigation_params);
+ stop_response_body_delivery(*navigation_params);
return true;
}
@@ -609,7 +605,7 @@ static bool handle_navigation_response_as_download(GC::Ref<NavigationParams> nav
// A request that another client adopted has no lease to hand over.
if (!lease.has_value()) {
report_download_rejected();
- stop_or_resume_response_body_delivery(navigation_params);
+ stop_response_body_delivery(*navigation_params);
return true;
}
auto suggested_filename = suggested_download_filename(download_url, *response->header_list(), {}, interface_origin);
@@ -2978,7 +2974,7 @@ void LocalNavigable::populate_session_history_entry_document(NavigationPopulatio
auto received_navigation_params = GC::create_function(heap(), [this, response_steps, respond_without_an_active_window](GC::Ref<InternalNavigationResult> result) {
if (!active_window()) {
- stop_or_resume_response_body_delivery(result->navigation_params);
+ stop_response_body_delivery(result->navigation_params);
respond_without_an_active_window();
return;
}
@@ -3037,7 +3033,7 @@ static void load_document_or_handle_download(GC::Ref<NavigationParams> navigatio
{
// AD-HOC: Match other browsers and show a UA error page for an empty HTTP error response to a top-level navigation.
if (navigation_params->navigable->is_top_level_traversable() && navigation_params->response->status() >= 400 && navigation_params->response->status() <= 599 && sniff_bytes.is_empty()) {
- stop_or_resume_response_body_delivery(navigation_params);
+ stop_response_body_delivery(*navigation_params);
if (navigation_params->reserved_environment)
navigation_params->reserved_environment->discard_environment();
@@ -3084,7 +3080,7 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent
GC::Ptr<GC::Function<void(GC::Ptr<PopulateSessionHistoryEntryDocumentOutput>)>> completion_steps)
{
if (!active_window()) {
- stop_or_resume_response_body_delivery(navigation_params);
+ stop_response_body_delivery(navigation_params);
return;
}
if (auto* params = navigation_params.get_pointer<GC::Ref<NavigationParams>>())
@@ -3096,7 +3092,7 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent
// NB: A reload history job keeps the traversal marker while its document is populated.
auto is_reload_traversal = navigation_timing_type == Bindings::NavigationTimingType::Reload && ongoing_navigation().has<Traversal>();
if (navigation_id.has_value() && ongoing_navigation() != navigation_id && !is_reload_traversal) {
- stop_or_resume_response_body_delivery(navigation_params);
+ stop_response_body_delivery(navigation_params);
if (completion_steps)
completion_steps->function()(nullptr);
return;
@@ -3160,10 +3156,7 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent
// 1. Run the environment discarding steps for navigationParams's reserved environment.
navigation_params.visit(
[](GC::Ref<NavigationParams> const& it) {
- if (it->fetch_controller)
- it->fetch_controller->stop_fetch();
- else
- it->response->resume_body_delivery();
+ stop_response_body_delivery(*it);
it->reserved_environment->discard_environment();
},
[](auto const&) { });
@@ -3211,7 +3204,7 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent
if (nav_params->navigable->active_browsing_context() && sniff_bytes.outcome == Fetch::Infrastructure::FetchBody::SniffOutcome::Complete) {
load_document_or_handle_download(nav_params, sniff_bytes.bytes, url, source_allows_downloading, source_interface_origin, *output);
} else {
- stop_or_resume_response_body_delivery(navigation_params);
+ stop_response_body_delivery(navigation_params);
if (sniff_bytes.outcome == Fetch::Infrastructure::FetchBody::SniffOutcome::Failed)
output->save_extra_document_state = false;
}
@@ -3227,18 +3220,23 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent
if (sniff_bytes->outcome == Fetch::Infrastructure::FetchBody::SniffOutcome::Complete) {
load_document_or_handle_download(nav_params, sniff_bytes->bytes, url, source_allows_downloading, source_interface_origin, *output);
} else {
- stop_or_resume_response_body_delivery(navigation_params);
+ stop_response_body_delivery(navigation_params);
output->save_extra_document_state = false;
}
} else {
- stop_or_resume_response_body_delivery(navigation_params);
+ stop_response_body_delivery(navigation_params);
}
output->navigation_params = navigation_params;
report_a_document_with_an_origin_of_its_own(*this, output);
if (completion_steps)
completion_steps->function()(output);
- }));
+ }),
+ Task::Priority::Normal,
+ // A task its document drops unrun stops the body it would have handed on.
+ GC::create_function(heap(), [navigation_params] {
+ stop_response_body_delivery(navigation_params);
+ }));
}
void LocalNavigable::create_navigation_params_for_navigation(NavigationPopulationRequest request, GC::Ref<SourceSnapshotParams> source_snapshot_params, NavigationParamsVariant navigation_params, Bindings::NavigationTimingType navigation_timing_type)
@@ -3246,7 +3244,7 @@ void LocalNavigable::create_navigation_params_for_navigation(NavigationPopulatio
auto navigation_id = request.navigation_id;
if (!active_window()) {
- stop_or_resume_response_body_delivery(navigation_params);
+ stop_response_body_delivery(navigation_params);
return;
}
@@ -3257,13 +3255,13 @@ void LocalNavigable::create_navigation_params_for_navigation(NavigationPopulatio
auto received_navigation_params = GC::create_function(heap(), [this, request, navigation_id](GC::Ref<InternalNavigationResult> result) mutable {
if (!active_window() || ongoing_navigation() != navigation_id) {
- stop_or_resume_response_body_delivery(result->navigation_params);
+ stop_response_body_delivery(result->navigation_params);
return;
}
create_navigation_population_result(*active_window(), result, GC::create_function(heap(), [this, request = move(request), navigation_id, result](NavigationPopulationResult population_result) mutable {
if (!active_window() || ongoing_navigation() != navigation_id) {
- stop_or_resume_response_body_delivery(result->navigation_params);
+ stop_response_body_delivery(result->navigation_params);
return;
}
page().client().navigation_params_creation_finished(*this, move(request), move(population_result));
diff --git a/Libraries/LibWeb/HTML/NavigationParams.cpp b/Libraries/LibWeb/HTML/NavigationParams.cpp
index 81faa63f59f..5258d06feed 100644
--- a/Libraries/LibWeb/HTML/NavigationParams.cpp
+++ b/Libraries/LibWeb/HTML/NavigationParams.cpp
@@ -7,6 +7,7 @@
#include <LibWeb/ContentSecurityPolicy/Directives/Names.h>
#include <LibWeb/ContentSecurityPolicy/PolicyList.h>
#include <LibWeb/DOM/Document.h>
+#include <LibWeb/Fetch/Engine/NetworkTransportHandle.h>
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
#include <LibWeb/HTML/LocalNavigable.h>
#include <LibWeb/HTML/NavigationParams.h>
@@ -27,6 +28,31 @@ void NavigationParams::visit_edges(Visitor& visitor)
visitor.visit(reserved_environment);
}
+NavigationParams::BodyDelivery NavigationParams::body_delivery() const
+{
+ if (fetch_controller)
+ return GC::Ref { *fetch_controller };
+ if (auto const& network_transport = response->network_transport(); network_transport.has_value())
+ return network_transport->handle;
+ return Empty {};
+}
+
+bool stop_body_delivery(NavigationParams::BodyDelivery const& body_delivery)
+{
+ return body_delivery.visit(
+ [](Empty) { return false; },
+ [](GC::Ref<Fetch::Infrastructure::FetchController> const& fetch_controller) {
+ if (fetch_controller->state() != Fetch::Infrastructure::FetchController::State::Ongoing)
+ return false;
+ fetch_controller->stop_fetch();
+ return true;
+ },
+ [](NonnullRefPtr<Fetch::Engine::NetworkTransportHandle> const& network_transport) {
+ network_transport->stop();
+ return true;
+ });
+}
+
void NonFetchSchemeNavigationParams::visit_edges(Visitor& visitor)
{
Base::visit_edges(visitor);
diff --git a/Libraries/LibWeb/HTML/NavigationParams.h b/Libraries/LibWeb/HTML/NavigationParams.h
index 33cd20a86b9..21002d802bb 100644
--- a/Libraries/LibWeb/HTML/NavigationParams.h
+++ b/Libraries/LibWeb/HTML/NavigationParams.h
@@ -119,6 +119,10 @@ struct NavigationParams : GC::Cell {
// a user navigation involvement used when obtaining a browsing context for the new Document
UserNavigationInvolvement user_involvement;
+ // The fetch controller, or else the transport of a body adopted without one.
+ using BodyDelivery = Variant<Empty, GC::Ref<Fetch::Infrastructure::FetchController>, NonnullRefPtr<Fetch::Engine::NetworkTransportHandle>>;
+ [[nodiscard]] BodyDelivery body_delivery() const;
+
protected:
void visit_edges(Visitor& visitor) override;
@@ -214,6 +218,9 @@ protected:
using NavigationParamsVariant = Variant<NavigationParamsNullOrError, GC::Ref<NavigationParams>, GC::Ref<NonFetchSchemeNavigationParams>>;
+// Returns whether a fetch controller or network transport was stopped.
+bool stop_body_delivery(NavigationParams::BodyDelivery const&);
+
bool check_a_navigation_responses_adherence_to_x_frame_options(GC::Ptr<Fetch::Infrastructure::Response> response, LocalNavigable* navigable, ContentSecurityPolicy::PolicyList const& csp_list, URL::Origin destination_origin);
}
diff --git a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp
index e213ff0682c..fa5d4d07f99 100644
--- a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp
+++ b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp
@@ -5,15 +5,10 @@
*/
#include <LibGC/Heap.h>
-#include <LibGC/Root.h>
-#include <LibJS/Runtime/ErrorTypes.h>
-#include <LibRequests/Request.h>
-#include <LibRequests/RequestClient.h>
-#include <LibWeb/Bindings/PrincipalHostDefined.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/Fetch/Engine/NetworkTransportHandle.h>
#include <LibWeb/Fetch/Fetching/ClientContextSnapshots.h>
-#include <LibWeb/Fetch/Fetching/FetchedDataReceiver.h>
+#include <LibWeb/Fetch/Fetching/Fetching.h>
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
#include <LibWeb/Fetch/Infrastructure/FetchTimingInfo.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
@@ -23,12 +18,7 @@
#include <LibWeb/HTML/NavigationParamsDescriptor.h>
#include <LibWeb/HTML/PolicyContainers.h>
#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
-#include <LibWeb/HighResolutionTime/TimeOrigin.h>
-#include <LibWeb/Loader/ResourceLoader.h>
-#include <LibWeb/Streams/ReadableStream.h>
#include <LibWeb/WebDriver/BiDi/Network.h>
-#include <LibWeb/WebIDL/Promise.h>
namespace Web::HTML {
@@ -222,6 +212,7 @@ void create_navigation_params_descriptor(JS::Realm& realm, NavigationParamsVaria
// A request that another client adopted has no lease to hand over.
auto const& network_transport = navigation_params->response->network_transport();
if (network_transport.has_value() && !network_transport->handle->transfer_lease().has_value()) {
+ stop_body_delivery(navigation_params->body_delivery());
completion_steps->function()(NavigationParamsNullOrError { "Unable to transfer response body"_utf16 });
return;
}
@@ -265,91 +256,18 @@ static RefPtr<Fetch::Infrastructure::Request> create_navigation_request_from_des
return request;
}
-static GC::Ptr<Fetch::Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, LocalNavigable& navigable, NavigationResponseBodyHandle handle, Fetch::Infrastructure::Response& response, RefPtr<Fetch::Infrastructure::FetchTimingInfo> timing_info, Optional<JsonObject> network_response, RefPtr<NavigationResponseNetworkEventState> network_response_state)
+// Reports the WebDriver BiDi event that ends an adopted navigation response, unless a download has taken it over.
+static Function<void(Optional<StringView>)> network_navigation_response_observer(LocalNavigable& navigable, Fetch::Infrastructure::Response& response, RefPtr<Fetch::Infrastructure::FetchTimingInfo> timing_info, Optional<JsonObject> network_response, RefPtr<NavigationResponseNetworkEventState> network_response_state)
{
- if (!ResourceLoader::is_initialized())
- return {};
-
- // The UI process moved the response to the RequestServer for the handle's site.
- auto request_client = ResourceLoader::the().request_client_for_top_level_site(handle.request_server_top_level_site);
- if (!request_client)
- return {};
-
- // Preserve the original RequestServer identity while WebContent decides whether this response will become a
- // document or a download. A download is adopted by the UI process using that identity.
- auto request = request_client->adopt_request(
- handle.request_server_client_id,
- handle.request_server_request_id,
- Requests::RequestClient::TransferLease::Yes);
- if (!request)
- return {};
-
- // Navigation may hand this response back to the UI process as a download. Do not consume any of its body before
- // populate_session_history_entry_document() decides whether to load it as a document or transfer it again.
- request->set_body_delivery_paused(true);
-
- auto stream = Streams::ReadableStream::create(realm);
- auto pull_algorithm = GC::create_function(realm.heap(), [&realm]() {
- return WebIDL::create_resolved_promise(realm, JS::js_undefined());
- });
- auto cancel_algorithm = GC::create_function(realm.heap(), [&realm, request](JS::Value) {
- request->stop();
- return WebIDL::create_resolved_promise(realm, JS::js_undefined());
- });
- stream->set_up_with_byte_reading_support(realm, pull_algorithm, cancel_algorithm);
-
- auto body = Fetch::Infrastructure::Body::create(stream);
- auto receiver = realm.heap().allocate<Fetch::Fetching::FetchedDataReceiver>(stream);
- receiver->set_response(response);
- receiver->set_body(body);
- auto receiver_root = GC::make_root(receiver);
- auto cross_origin_isolated_capability = Bindings::principal_host_defined_environment_settings_object(realm).cross_origin_isolated_capability();
-
auto observed_navigable = network_response.has_value() ? GC::Weak<LocalNavigable> { navigable } : GC::Weak<LocalNavigable> {};
- // NB: receiver_root traces response. Observing its navigable must not keep the navigable alive.
- request->set_unbuffered_request_callbacks(
- [](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Optional<Core::ImmutableBytes>, Optional<u64>, Requests::CacheState) { },
- [receiver_root, &realm](Requests::ResponseData data) {
- receiver_root->handle_network_data(realm, move(data), Fetch::Fetching::FetchedDataReceiver::NetworkState::Ongoing);
- },
- [receiver_root](Core::ImmutableBytes data) {
- receiver_root->set_cached_response_body(move(data));
- },
- [receiver_root, stream = GC::make_root(stream), body = GC::make_root(body), response = GC::Ptr { &response }, observed_navigable = move(observed_navigable), timing_info, network_response = move(network_response), network_response_state = move(network_response_state), cross_origin_isolated_capability, &realm](u64, Requests::RequestTimingInfo const& request_timing_info, Optional<Requests::NetworkError> network_error) {
- TemporaryExecutionContext execution_context { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };
- if (!network_error.has_value()) {
- // AD-HOC: Nothing reports timing for a navigation fetch, so record the network phases and end time here
- // for the Document's navigation timing entry.
- if (timing_info) {
- timing_info->update_final_timings(request_timing_info, cross_origin_isolated_capability);
- timing_info->set_end_time(HighResolutionTime::unsafe_shared_current_time());
- }
- auto body_info = response->body_info();
- body_info.encoded_size = max(request_timing_info.encoded_body_size, 0);
- response->set_body_info(move(body_info));
- receiver_root->handle_network_data(realm, Requests::ResponseData::from_bytes({}), Fetch::Fetching::FetchedDataReceiver::NetworkState::Complete);
- if (network_response.has_value() && observed_navigable && network_response_state->owner == NavigationResponseNetworkEventState::Owner::Renderer) {
- network_response_state->owner = NavigationResponseNetworkEventState::Owner::Completed;
- WebDriver::BiDi::network_navigation_response_finished(*observed_navigable, *network_response, *response, timing_info);
- }
- return;
- }
-
- if (network_response.has_value() && observed_navigable && network_response_state->owner == NavigationResponseNetworkEventState::Owner::Renderer) {
- network_response_state->owner = NavigationResponseNetworkEventState::Owner::Completed;
- WebDriver::BiDi::network_navigation_response_finished(*observed_navigable, *network_response, *response, timing_info, "Transferred navigation response failed"sv);
- }
- body->set_sniff_bytes_failed();
- if (stream->is_readable())
- stream->error(JS::TypeError::create(realm, "Transferred navigation response failed"_utf16));
- });
-
- auto network_transport = Fetch::Engine::NetworkTransportHandle::create(*request);
- response.set_network_transport({
- .handle = move(network_transport),
- });
- return body;
+ // NB: The body pump traces response. Observing its navigable must not keep the navigable alive.
+ return [response = GC::Ptr { &response }, observed_navigable = move(observed_navigable), timing_info = move(timing_info), network_response = move(network_response), network_response_state = move(network_response_state)](Optional<StringView> error) {
+ if (!network_response.has_value() || !observed_navigable || network_response_state->owner != NavigationResponseNetworkEventState::Owner::Renderer)
+ return;
+ network_response_state->owner = NavigationResponseNetworkEventState::Owner::Completed;
+ WebDriver::BiDi::network_navigation_response_finished(*observed_navigable, *network_response, *response, timing_info, error);
+ };
}
static ErrorOr<GC::Ref<Fetch::Infrastructure::Response>> create_navigation_response_from_descriptor(JS::Realm& realm, LocalNavigable& navigable, NavigationResponseDescriptor descriptor, RefPtr<Fetch::Infrastructure::FetchTimingInfo> timing_info, RefPtr<NavigationResponseNetworkEventState> network_response_state)
@@ -369,7 +287,11 @@ static ErrorOr<GC::Ref<Fetch::Infrastructure::Response>> create_navigation_respo
if (descriptor.body.has<ByteBuffer>()) {
response->set_body(Fetch::Infrastructure::byte_sequence_as_body(realm, descriptor.body.get<ByteBuffer>().bytes()));
} else if (descriptor.body.has<NavigationResponseBodyHandle>()) {
- auto body = adopt_navigation_response_body(realm, navigable, descriptor.body.get<NavigationResponseBodyHandle>(), response, timing_info, descriptor.webdriver_bidi_network_response.is_object() ? Optional<JsonObject>(descriptor.webdriver_bidi_network_response.as_object()) : Optional<JsonObject> {}, move(network_response_state));
+ auto const& handle = descriptor.body.get<NavigationResponseBodyHandle>();
+ Requests::RequestTransferLeaseKey transfer_lease { handle.request_server_client_id, handle.request_server_request_id };
+ auto network_response = descriptor.webdriver_bidi_network_response.is_object() ? Optional<JsonObject>(descriptor.webdriver_bidi_network_response.as_object()) : Optional<JsonObject> {};
+ auto on_network_settled = network_navigation_response_observer(navigable, response, timing_info, move(network_response), move(network_response_state));
+ auto body = Fetch::Fetching::adopt_navigation_response_body(realm, response, handle.request_server_top_level_site, transfer_lease, timing_info, move(on_network_settled));
if (!body)
return Error::from_string_literal("Unable to adopt transferred navigation response body");
response->set_body(body);
diff --git a/Meta/Linters/check_libjs_includes.py b/Meta/Linters/check_libjs_includes.py
index 6db6b409140..15ba2e3476b 100755
--- a/Meta/Linters/check_libjs_includes.py
+++ b/Meta/Linters/check_libjs_includes.py
@@ -43,7 +43,6 @@ ALLOWED_HEADERS = {
"LibJS/Runtime/Environment.h",
"LibJS/Runtime/Error.h",
"LibJS/Runtime/ErrorData.h",
- "LibJS/Runtime/ErrorTypes.h",
"LibJS/Runtime/ExternalMemory.h",
"LibJS/Runtime/FinalizationRegistry.h",
"LibJS/Runtime/FunctionEnvironment.h",
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index dedc8205dfc..b0d3e710c13 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -43,16 +43,15 @@ ALLOWED_REALM_MENTIONS = {
"Crypto": (8, 382, "WebCrypto algorithms still use realms for buffer/key/promise materialization"),
"DOM": (10, 33, "DOM abort plumbing and node helpers still have callback/materialization realm use"),
"Fetch": (
- 22,
- 62,
+ 20,
+ 55,
"Fetch bodies, headers, requests, responses, and controllers still materialize JS values/streams; "
- "the body receiver's delivery and close tasks carry the realm its stream is enqueued and closed in; "
"BodyStreamPullSource materializes stream pulls and errors on the consumer side, in its stream's realm",
),
"FileAPI": (4, 11, "File/Blob/FileReader algorithms still create streams, buffers, and events in selected realms"),
"HTML": (
64,
- 199,
+ 198,
"HTML algorithms still contain structured serialization, including posted-message preparation, canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; RemoteWindow mirrors Window's postMessage",
),
"IndexedDB": (
diff --git a/Tests/LibWeb/Text/expected/navigation/transferred-body-from-disk-cache.txt b/Tests/LibWeb/Text/expected/navigation/transferred-body-from-disk-cache.txt
new file mode 100644
index 00000000000..ab54ecb5b1c
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/navigation/transferred-body-from-disk-cache.txt
@@ -0,0 +1,3 @@
+first load is complete: true
+second load came from the cache: true
+second load is complete and not repeated: true
diff --git a/Tests/LibWeb/Text/expected/navigation/transferred-body-larger-than-its-buffers.txt b/Tests/LibWeb/Text/expected/navigation/transferred-body-larger-than-its-buffers.txt
new file mode 100644
index 00000000000..f4e2309b45d
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/navigation/transferred-body-larger-than-its-buffers.txt
@@ -0,0 +1 @@
+document received the whole body: true
diff --git a/Tests/LibWeb/Text/expected/navigation/transferred-body-released-when-unread.txt b/Tests/LibWeb/Text/expected/navigation/transferred-body-released-when-unread.txt
new file mode 100644
index 00000000000..02732176530
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/navigation/transferred-body-released-when-unread.txt
@@ -0,0 +1,3 @@
+body of a document removed while it arrives: released
+body of a refused document: released
+body of a download a sandboxed frame refuses: released
diff --git a/Tests/LibWeb/Text/expected/navigation/transferred-empty-body.txt b/Tests/LibWeb/Text/expected/navigation/transferred-empty-body.txt
new file mode 100644
index 00000000000..77ff3a63358
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/navigation/transferred-empty-body.txt
@@ -0,0 +1 @@
+empty document loaded
diff --git a/Tests/LibWeb/Text/expected/navigation/transferred-small-body-from-disk-cache.txt b/Tests/LibWeb/Text/expected/navigation/transferred-small-body-from-disk-cache.txt
new file mode 100644
index 00000000000..ab54ecb5b1c
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/navigation/transferred-small-body-from-disk-cache.txt
@@ -0,0 +1,3 @@
+first load is complete: true
+second load came from the cache: true
+second load is complete and not repeated: true
diff --git a/Tests/LibWeb/Text/input/navigation/iframe-navigation-mid-body-failure.html b/Tests/LibWeb/Text/input/navigation/iframe-navigation-mid-body-failure.html
index 0158ec592e4..30f4abef711 100644
--- a/Tests/LibWeb/Text/input/navigation/iframe-navigation-mid-body-failure.html
+++ b/Tests/LibWeb/Text/input/navigation/iframe-navigation-mid-body-failure.html
@@ -10,17 +10,14 @@
const output = [];
const println = line => output.push(line);
- // The body arrives through a body pump, or through a receiver when the navigation adopts a request fetched
- // elsewhere.
+ // The body arrives through a body pump, also when the navigation adopts a request fetched elsewhere.
const countBodyCells = () => {
- const counts = { pumps: 0, pullSources: 0, receivers: 0 };
+ const counts = { pumps: 0, pullSources: 0 };
for (const cell of Object.values(JSON.parse(internals.dumpGCGraph()))) {
if (cell.class_name === "NetworkBodyPump")
++counts.pumps;
else if (cell.class_name === "BodyStreamPullSource")
++counts.pullSources;
- else if (cell.class_name === "FetchedDataReceiver")
- ++counts.receivers;
}
return counts;
};
@@ -32,10 +29,10 @@
for (;;) {
await internals.gcAsync();
const counts = countBodyCells();
- if (counts.pumps === initial.pumps && counts.pullSources === initial.pullSources && counts.receivers === initial.receivers)
+ if (counts.pumps === initial.pumps && counts.pullSources === initial.pullSources)
return "released";
if (performance.now() > deadline)
- return `left ${counts.pumps - initial.pumps} pumps, ${counts.pullSources - initial.pullSources} pull sources and ${counts.receivers - initial.receivers} receivers`;
+ return `left ${counts.pumps - initial.pumps} pumps and ${counts.pullSources - initial.pullSources} pull sources`;
await sleep(10);
}
};
@@ -51,7 +48,7 @@
// The body is held after its first chunk, and ends short once it is let go.
const arrivalDeadline = performance.now() + 10000;
- for (let counts = countBodyCells(); counts.pumps === initial.pumps && counts.receivers === initial.receivers; counts = countBodyCells()) {
+ for (let counts = countBodyCells(); counts.pumps === initial.pumps; counts = countBodyCells()) {
if (performance.now() > arrivalDeadline) {
println("body of the failed navigation never arrived");
return output;
diff --git a/Tests/LibWeb/Text/input/navigation/transferred-body-from-disk-cache.html b/Tests/LibWeb/Text/input/navigation/transferred-body-from-disk-cache.html
new file mode 100644
index 00000000000..89a3ad0e7e7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/navigation/transferred-body-from-disk-cache.html
@@ -0,0 +1,45 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A navigation response the disk cache serves as one mapped file reaches the document that adopts it once and in
+ // full.
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const size = 256 * 1024;
+ const url = await server.createEcho("GET", `/transferred-cached-body-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: { "Cache-Control": "max-age=3600", "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><div class="filler">${"x".repeat(size)}</div>
+ <script>
+ addEventListener("load", () => parent.postMessage({
+ fillers: document.querySelectorAll(".filler").length,
+ length: document.querySelector(".filler").textContent.length,
+ deliveryType: performance.getEntriesByType("navigation")[0].deliveryType,
+ }, "*"));
+ <\/script>`,
+ });
+
+ const navigate = () =>
+ new Promise(resolve => {
+ window.addEventListener("message", event => resolve(event.data), { once: true });
+ const iframe = document.createElement("iframe");
+ iframe.src = url;
+ document.body.append(iframe);
+ });
+
+ // In test mode, the disk cache only stores responses to requests carrying the cache-enablement header, which a
+ // page cannot attach to a navigation request.
+ const diskCacheWasEnabledForNavigations = internals.setDiskCacheEnabledForNavigations(true);
+ try {
+ const first = await navigate();
+ println(`first load is complete: ${first.fillers === 1 && first.length === size}`);
+
+ // The first body ends only after RequestServer has written its cache entry.
+ const second = await navigate();
+ println(`second load came from the cache: ${second.deliveryType === "cache"}`);
+ println(`second load is complete and not repeated: ${second.fillers === 1 && second.length === size}`);
+ } finally {
+ internals.setDiskCacheEnabledForNavigations(diskCacheWasEnabledForNavigations);
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/navigation/transferred-body-larger-than-its-buffers.html b/Tests/LibWeb/Text/input/navigation/transferred-body-larger-than-its-buffers.html
new file mode 100644
index 00000000000..103e5443c50
--- /dev/null
+++ b/Tests/LibWeb/Text/input/navigation/transferred-body-larger-than-its-buffers.html
@@ -0,0 +1,23 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A navigation's response body reaches the document that adopts it in full, although it is larger than the
+ // buffers between RequestServer and that document together.
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const size = 4 * 1024 * 1024;
+ const url = await server.createEcho("GET", `/transferred-large-body-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: { "Cache-Control": "no-store", "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><div id="filler">${"x".repeat(size)}</div>
+ <script>parent.postMessage(document.getElementById("filler").textContent.length, "*");<\/script>`,
+ });
+
+ const length = new Promise(resolve => window.addEventListener("message", event => resolve(event.data), { once: true }));
+ const iframe = document.createElement("iframe");
+ iframe.src = url;
+ document.body.append(iframe);
+ println(`document received the whole body: ${(await length) === size}`);
+ iframe.remove();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/navigation/transferred-body-released-when-unread.html b/Tests/LibWeb/Text/input/navigation/transferred-body-released-when-unread.html
new file mode 100644
index 00000000000..473073fe147
--- /dev/null
+++ b/Tests/LibWeb/Text/input/navigation/transferred-body-released-when-unread.html
@@ -0,0 +1,159 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // Runs on a hostname of its own, in a process apart from the test page.
+ async function checkUnreadBodiesAreReleased(urls) {
+ const output = [];
+ const println = line => output.push(line);
+
+ const countCells = () => {
+ const counts = { pumps: 0, pullSources: 0 };
+ for (const cell of Object.values(JSON.parse(internals.dumpGCGraph()))) {
+ if (cell.class_name === "NetworkBodyPump")
+ ++counts.pumps;
+ else if (cell.class_name === "BodyStreamPullSource")
+ ++counts.pullSources;
+ }
+ return counts;
+ };
+
+ // A stale pointer on the stack can keep a cell alive through one conservative collection.
+ const waitForRelease = async initial => {
+ const deadline = performance.now() + 10000;
+ for (;;) {
+ await internals.gcAsync();
+ const counts = countCells();
+ if (counts.pumps <= initial.pumps && counts.pullSources <= initial.pullSources)
+ return "released";
+ if (performance.now() > deadline)
+ return `left ${counts.pumps - initial.pumps} pumps and ${counts.pullSources - initial.pullSources} pull sources`;
+ }
+ };
+
+ // The checker's own body is read once it has loaded.
+ if (document.readyState !== "complete")
+ await new Promise(resolve => addEventListener("load", resolve, { once: true }));
+ await internals.gcAsync();
+ const initial = countCells();
+
+ // The held document's first script posts a message once its body has begun parsing.
+ let frame = document.createElement("iframe");
+ const parsing = new Promise(resolve => {
+ addEventListener("message", function receive(event) {
+ if (event.source !== frame.contentWindow || event.data !== "parsing")
+ return;
+ removeEventListener("message", receive);
+ resolve();
+ });
+ });
+ frame.src = urls.heldMidBody;
+ document.body.append(frame);
+ await parsing;
+ frame.remove();
+ frame = null;
+ println(`body of a document removed while it arrives: ${await waitForRelease(initial)}`);
+
+ frame = document.createElement("iframe");
+ await new Promise(resolve => {
+ frame.onload = resolve;
+ frame.src = urls.refused;
+ document.body.append(frame);
+ });
+ frame.remove();
+ frame = null;
+ println(`body of a refused document: ${await waitForRelease(initial)}`);
+
+ // A sandboxed frame refuses the download its response asks for, and its parent's load waits for the refusal.
+ frame = document.createElement("iframe");
+ await new Promise(resolve => {
+ frame.onload = resolve;
+ frame.src = urls.downloadRefusingFrame;
+ document.body.append(frame);
+ });
+ frame.remove();
+ frame = null;
+ println(`body of a download a sandboxed frame refuses: ${await waitForRelease(initial)}`);
+
+ return output;
+ }
+
+ promiseTest(async () => {
+ const hostname = uniqueLocalhostHostname("unread-navigation-body");
+ const server = httpTestServer();
+ const size = 2 * 1024 * 1024;
+
+ // Each body outgrows its channel and the request's pipe together, and its request ends only when the body is
+ // read or the request is stopped.
+ const refused = new URL(await server.createEcho("GET", `/unread-body-refused-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: { "Cache-Control": "no-store", "Content-Type": "text/html", "X-Frame-Options": "DENY" },
+ body: "x".repeat(size),
+ }));
+ refused.hostname = hostname;
+
+ // The server holds the body after its first chunk until the test lets it go.
+ const token = `unread-body-${crypto.randomUUID()}`;
+ const heldMidBody = new URL(await server.createEcho("GET", `/unread-body-held-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: { "Cache-Control": "no-store", "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><body><script>parent.postMessage("parsing", "*")<\/script><!--${"a".repeat(2000)}-->${"x".repeat(size)}`,
+ }));
+ heldMidBody.hostname = hostname;
+ heldMidBody.search = `?chunks=1500&chunk_unblock_tokens=${token}`;
+ const unblock = new URL(`/unblock/${token}`, heldMidBody);
+
+ // A drained download could not end either, since the server holds it after its first chunk.
+ const attachment = new URL(await server.createEcho("GET", `/unread-body-attachment-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: { "Cache-Control": "no-store", "Content-Type": "application/octet-stream", "Content-Disposition": "attachment" },
+ body: "x".repeat(size),
+ }));
+ attachment.hostname = hostname;
+ attachment.search = `?chunks=1500&chunk_unblock_tokens=${token}`;
+ const downloadRefusingFrame = new URL(await server.createEcho("GET", `/unread-body-sandboxed-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: { "Cache-Control": "no-store", "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><iframe sandbox="allow-scripts allow-same-origin" src="${attachment.href}"></iframe>`,
+ }));
+ downloadRefusingFrame.hostname = hostname;
+
+ const urls = {
+ refused: refused.href,
+ heldMidBody: heldMidBody.href,
+ downloadRefusingFrame: downloadRefusingFrame.href,
+ unblock: unblock.href,
+ };
+ const checker = new URL(await server.createEcho("GET", `/unread-body-checker-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: { "Cache-Control": "no-store", "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><body><script>
+ (${checkUnreadBodiesAreReleased.toString()})(${JSON.stringify(urls)}).then(
+ output => parent.postMessage({ output }, "*"),
+ error => parent.postMessage({ error: String(error) }, "*"));
+ <\/script>`,
+ }));
+ checker.hostname = hostname;
+
+ const frame = document.createElement("iframe");
+ const result = new Promise(resolve => {
+ window.addEventListener("message", function receive(event) {
+ if (event.source !== frame.contentWindow)
+ return;
+ window.removeEventListener("message", receive);
+ resolve(event.data);
+ });
+ });
+ frame.src = checker;
+ document.body.append(frame);
+ try {
+ const { output, error } = await result;
+ if (error)
+ throw new Error(error);
+ for (const line of output)
+ println(line);
+ } finally {
+ await fetch(unblock);
+ frame.remove();
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/navigation/transferred-empty-body.html b/Tests/LibWeb/Text/input/navigation/transferred-empty-body.html
new file mode 100644
index 00000000000..863529ed4e8
--- /dev/null
+++ b/Tests/LibWeb/Text/input/navigation/transferred-empty-body.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A navigation response with an empty body still produces a document in the process that adopts it.
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const url = await server.createEcho("GET", `/transferred-empty-body-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: { "Cache-Control": "no-store", "Content-Type": "text/html" },
+ body: "",
+ });
+
+ const iframe = document.createElement("iframe");
+ const loaded = new Promise(resolve => iframe.addEventListener("load", resolve, { once: true }));
+ iframe.src = url;
+ document.body.append(iframe);
+ await loaded;
+ println("empty document loaded");
+ iframe.remove();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/navigation/transferred-small-body-from-disk-cache.html b/Tests/LibWeb/Text/input/navigation/transferred-small-body-from-disk-cache.html
new file mode 100644
index 00000000000..9b5e6a56c72
--- /dev/null
+++ b/Tests/LibWeb/Text/input/navigation/transferred-small-body-from-disk-cache.html
@@ -0,0 +1,45 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A navigation response the disk cache serves through the pipe, being smaller than a page, reaches the document
+ // that adopts it once and in full.
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const size = 2 * 1024;
+ const url = await server.createEcho("GET", `/transferred-small-cached-body-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: { "Cache-Control": "max-age=3600", "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><div class="filler">${"x".repeat(size)}</div>
+ <script>
+ addEventListener("load", () => parent.postMessage({
+ fillers: document.querySelectorAll(".filler").length,
+ length: document.querySelector(".filler").textContent.length,
+ deliveryType: performance.getEntriesByType("navigation")[0].deliveryType,
+ }, "*"));
+ <\/script>`,
+ });
+
+ const navigate = () =>
+ new Promise(resolve => {
+ window.addEventListener("message", event => resolve(event.data), { once: true });
+ const iframe = document.createElement("iframe");
+ iframe.src = url;
+ document.body.append(iframe);
+ });
+
+ // In test mode, the disk cache only stores responses to requests carrying the cache-enablement header, which a
+ // page cannot attach to a navigation request.
+ const diskCacheWasEnabledForNavigations = internals.setDiskCacheEnabledForNavigations(true);
+ try {
+ const first = await navigate();
+ println(`first load is complete: ${first.fillers === 1 && first.length === size}`);
+
+ // The first body ends only after RequestServer has written its cache entry.
+ const second = await navigate();
+ println(`second load came from the cache: ${second.deliveryType === "cache"}`);
+ println(`second load is complete and not repeated: ${second.fillers === 1 && second.length === size}`);
+ } finally {
+ internals.setDiskCacheEnabledForNavigations(diskCacheWasEnabledForNavigations);
+ }
+ });
+</script>
diff --git a/Tests/LibWebView/test-webdriver-bidi.py b/Tests/LibWebView/test-webdriver-bidi.py
index 8ee3de4ab78..27f95932c8d 100755
--- a/Tests/LibWebView/test-webdriver-bidi.py
+++ b/Tests/LibWebView/test-webdriver-bidi.py
@@ -18,6 +18,7 @@ import subprocess
import sys
import tempfile
import threading
+import time
import urllib.parse
helpers = importlib.import_module("test-webdriver-error-keep-alive")
@@ -133,6 +134,11 @@ class ReloadServer(http.server.ThreadingHTTPServer):
self.release_interception = threading.Event()
self.detached_final_received = threading.Event()
self.interception_transport_closed = threading.Event()
+ self.document_headers_sent: threading.Event = threading.Event()
+ self.release_document: threading.Event = threading.Event()
+ self.document_body: bytes = (
+ b"<!doctype html><title>Adopted document</title><p>" + b"BiDi adopted document\n" * 128
+ )
class ReloadHandler(http.server.BaseHTTPRequestHandler):
@@ -275,6 +281,30 @@ class ReloadHandler(http.server.BaseHTTPRequestHandler):
except (BrokenPipeError, ConnectionResetError):
pass
return
+ if self.path.startswith("/network-document/"):
+ truncated = self.path.rsplit("/", 1)[-1] == "truncated"
+ body = server.document_body
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html")
+ self.send_header("Content-Length", str(len(body) + (16 if truncated else 0)))
+ self.send_header("Cache-Control", "no-store")
+ self.send_header("Connection", "close")
+ self.end_headers()
+ self.close_connection = True
+ # A navigation reads 1445 bytes before it commits its document, so the held part starts after them.
+ held_from = 2048
+ try:
+ self.wfile.write(body[:held_from])
+ self.wfile.flush()
+ server.document_headers_sent.set()
+ if not server.release_document.wait(30):
+ raise TimeoutError("The test did not release the document response")
+ if not truncated:
+ self.wfile.write(body[held_from:])
+ self.wfile.flush()
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+ return
if server.block_reload:
server.request_received.set()
if not server.release_response.wait(30):
@@ -1154,6 +1184,95 @@ def check_network_download_events(bidi, context, server, downloads):
bidi.command("session.unsubscribe", {"subscriptions": [subscription]})
+def check_network_adopted_navigation_events(bidi, context, server):
+ # A cross-site navigation commits its document in another process, which adopts the body from RequestServer.
+ terminal_methods = {"network.responseCompleted", "network.fetchError"}
+ 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", "network.responseStarted", *sorted(terminal_methods)],
+ "contexts": [context],
+ },
+ )["subscription"]
+ try:
+ for kind in ["success", "truncated", "stopped"]:
+ url = f"http://localhost:{server.server_port}/network-document/{kind}"
+ server.document_headers_sent.clear()
+ server.release_document.clear()
+
+ def is_our_event(event, expected_url=url):
+ return event["params"].get("request", {}).get("url") == expected_url
+
+ def next_event(methods):
+ while True:
+ for index, event in enumerate(bidi.events):
+ if event["method"] in methods and is_our_event(event):
+ return bidi.events.pop(index)
+ bidi.read_message()
+
+ try:
+ bidi.send("browsingContext.navigate", {"context": context, "url": url, "wait": "none"})
+ before = next_event({"network.beforeRequestSent"})["params"]
+ started = next_event({"network.responseStarted", *terminal_methods})
+ assert started["method"] == "network.responseStarted", started
+ started = started["params"]
+ assert server.document_headers_sent.wait(10)
+ request_id = started["request"]["request"]
+ assert before["request"]["request"] == request_id, (before, started)
+
+ # The document commits while the rest of its body is held.
+ deadline = time.monotonic() + 10
+ while True:
+ result = bidi.response(
+ bidi.send(
+ "script.evaluate",
+ {"target": {"context": context}, "expression": "document.URL", "awaitPromise": False},
+ )
+ )
+ if result["type"] == "success" and result["result"]["result"].get("value") == url:
+ break
+ assert time.monotonic() < deadline, "The navigation did not commit its document"
+ assert not any(event["method"] in terminal_methods and is_our_event(event) for event in bidi.events), (
+ bidi.events
+ )
+
+ if kind == "stopped":
+ # A stop in the document's process ends the adopted body with a fetch error.
+ bidi.evaluate(context, "window.stop()")
+ else:
+ server.release_document.set()
+ terminal = next_event(terminal_methods)
+ expected_method = "network.responseCompleted" if kind == "success" else "network.fetchError"
+ assert terminal["method"] == expected_method, terminal
+ params = terminal["params"]
+ assert params["context"] == context, params
+ assert params["request"]["request"] == request_id, params
+ assert params["navigation"] == started["navigation"], params
+ if kind == "success":
+ response = params["response"]
+ assert response["bodySize"] == len(server.document_body), response
+ assert response["content"]["size"] == len(server.document_body), response
+ assert response["bytesReceived"] == response["headersSize"] + len(server.document_body), response
+ else:
+ assert isinstance(params["errorText"], str) and params["errorText"], params
+
+ # Only the document's process reports the end of its body, and only once.
+ bidi.evaluate(context, "0")
+ assert not any(event["method"] in terminal_methods and is_our_event(event) for event in bidi.events), (
+ bidi.events
+ )
+ finally:
+ server.release_document.set()
+ finally:
+ if sys.exc_info()[0] is None:
+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})
+ bidi.command("browsingContext.navigate", {"context": context, "url": "about:blank", "wait": "complete"})
+
+
def check_screenshot_handles(bidi, context):
bidi.command("browsingContext.activate", {"context": context})
element = bidi.evaluate(context, "document.body.style.height = '20px'; document.body")["result"]
@@ -1831,6 +1950,7 @@ def run_test(
return
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_screenshot_handles(bidi, context)
check_input_handles(bidi, context)
check_input_queue(bidi, context)