Skip to content

Truly independent web browser

LibWeb: Stream fetch response bodies through FetchByteChannel

Luke Wilde2779016755ce
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 0579be25b73..5767d46fff1 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -370,8 +370,10 @@ set(SOURCES
Fetch/Engine/FetchExecutor.cpp
Fetch/Engine/InlineFetchExecutor.cpp
Fetch/Engine/WholeBodyTransport.cpp
+ Fetch/Fetching/BodyStreamPullSource.cpp
Fetch/Fetching/Checks.cpp
Fetch/Fetching/FetchedDataReceiver.cpp
+ Fetch/Fetching/NetworkBodyPump.cpp
Fetch/Fetching/Fetching.cpp
Fetch/Fetching/PendingResponse.cpp
Fetch/Fetching/RefCountedFlag.cpp
diff --git a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
new file mode 100644
index 00000000000..e02afc60fe9
--- /dev/null
+++ b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
@@ -0,0 +1,268 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/HashMap.h>
+#include <AK/NeverDestroyed.h>
+#include <LibGC/Root.h>
+#include <LibJS/Runtime/Error.h>
+#include <LibWeb/Fetch/Fetching/BodyStreamPullSource.h>
+#include <LibWeb/Fetch/Infrastructure/FetchController.h>
+#include <LibWeb/Fetch/Infrastructure/FetchParams.h>
+#include <LibWeb/Fetch/Infrastructure/Task.h>
+#include <LibWeb/HTML/EventLoop/EventLoop.h>
+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
+#include <LibWeb/Streams/ReadableStream.h>
+#include <LibWeb/WebIDL/ExceptionOrUtils.h>
+#include <LibWeb/WebIDL/Promise.h>
+
+namespace Web::Fetch::Fetching {
+
+GC_DEFINE_ALLOCATOR(BodyStreamPullSource);
+
+// Roots a pull source only while a wake is owed; tokens are never reused, and the consumer loop must outlive every
+// source with a wake owed.
+class BodyStreamWakeRegistry {
+public:
+ static BodyStreamWakeRegistry& the()
+ {
+ static thread_local NeverDestroyed<BodyStreamWakeRegistry> registry;
+ return *registry;
+ }
+
+ BodyStreamWakeToken allocate_token() { return BodyStreamWakeToken { m_next_token++ }; }
+
+ void arm(BodyStreamWakeToken token, BodyStreamPullSource& source)
+ {
+ m_armed_sources.ensure(token, [&] { return GC::make_root(source); });
+ }
+ void disarm(BodyStreamWakeToken token) { m_armed_sources.remove(token); }
+
+ void notify(BodyStreamWakeToken token, Engine::WakeTicket ticket)
+ {
+ auto source = m_armed_sources.take(token);
+ if (!source.has_value())
+ return;
+ if ((*source)->on_wake(ticket) == BodyStreamPullSource::WakeResult::StillAwaited)
+ m_armed_sources.set(token, source.release_value());
+ }
+
+private:
+ u64 m_next_token { 1 };
+ HashMap<BodyStreamWakeToken, GC::Root<BodyStreamPullSource>> m_armed_sources;
+};
+
+NonnullRefPtr<BodyStreamWakeSink> BodyStreamWakeSink::create()
+{
+ return adopt_ref(*new BodyStreamWakeSink(BodyStreamWakeRegistry::the().allocate_token()));
+}
+
+BodyStreamWakeSink::BodyStreamWakeSink(BodyStreamWakeToken registry_token)
+ : m_loop(Core::EventLoop::current_weak())
+ , m_registry_token(registry_token)
+{
+}
+
+void BodyStreamWakeSink::wake(Engine::WakeTicket ticket)
+{
+ auto loop = m_loop->take();
+ if (!loop)
+ return;
+ loop->deferred_invoke([token = m_registry_token, ticket] {
+ BodyStreamWakeRegistry::the().notify(token, 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)
+ : m_realm(realm)
+ , m_fetch_params(fetch_params)
+ , m_stream(stream)
+ , m_channel(move(channel))
+ , m_registry_token(wake_sink.registry_token())
+{
+}
+
+BodyStreamPullSource::~BodyStreamPullSource() = default;
+
+void BodyStreamPullSource::visit_edges(Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_realm);
+ visitor.visit(m_fetch_params);
+ visitor.visit(m_stream);
+ visitor.visit(m_pending_pull_promise);
+}
+
+// This implements the pullAlgorithm of HTTP-network fetch.
+// https://fetch.spec.whatwg.org/#concept-http-network-fetch
+GC::Ref<WebIDL::Promise> BodyStreamPullSource::pull()
+{
+ // 1. Let promise be a new promise.
+ auto promise = WebIDL::create_promise(*m_realm);
+
+ // 2. Run the following steps in parallel:
+ // 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.
+ // 2. Wait until buffer is not empty.
+ VERIFY(!m_pending_pull_promise);
+ m_pending_pull_promise = promise;
+ if (!m_detached) {
+ BodyStreamWakeRegistry::the().arm(m_registry_token, *this);
+ m_expected_ticket = m_channel->arm_waiter();
+ }
+
+ // 3. Return promise.
+ return promise;
+}
+
+GC::Ref<WebIDL::Promise> BodyStreamPullSource::cancel(JS::Value reason)
+{
+ auto& realm = *m_realm;
+ m_channel->cancel();
+ BodyStreamWakeRegistry::the().disarm(m_registry_token);
+ m_detached = true;
+
+ // A pull promise created before the cancellation still settles.
+ if (auto promise = exchange(m_pending_pull_promise, nullptr))
+ WebIDL::resolve_promise(realm, *promise, JS::js_undefined());
+
+ // cancelAlgorithm: abort fetchParams's controller with reason, given reason.
+ m_fetch_params->controller()->abort(realm, reason);
+ return WebIDL::create_resolved_promise(realm, JS::js_undefined());
+}
+
+BodyStreamPullSource::WakeResult BodyStreamPullSource::on_wake(Engine::WakeTicket ticket)
+{
+ if (!m_pending_pull_promise)
+ return WakeResult::Consumed;
+ // This waiter's wake is still owed; the source stays rooted for it.
+ if (ticket != m_expected_ticket)
+ return WakeResult::StillAwaited;
+
+ // AD-HOC: While a sync XHR send() pauses the HTML event loop, the pull runs now rather than in a fetch task.
+ if (HTML::main_thread_event_loop().execution_paused()) {
+ run_pull_task();
+ return WakeResult::Consumed;
+ }
+
+ // 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] {
+ run_pull_task();
+ }));
+ return WakeResult::Consumed;
+}
+
+// A failed transmission errors the stream regardless of read demand, and an empty completed body closes without one.
+void BodyStreamPullSource::handle_network_settled()
+{
+ if (m_pending_pull_promise)
+ return;
+
+ if (HTML::main_thread_event_loop().execution_paused()) {
+ deliver_while_paused();
+ return;
+ }
+
+ auto& realm = *m_realm;
+ HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+
+ settle_stream(m_channel->take_up_to(0));
+}
+
+// This implements the ending of the in-parallel steps of HTTP-network fetch.
+// https://fetch.spec.whatwg.org/#concept-http-network-fetch
+void BodyStreamPullSource::settle_stream(Engine::FetchByteChannel::TakeResult const& result)
+{
+ result.state.visit(
+ [](Engine::FetchByteChannel::Open) { },
+ [](Engine::FetchByteChannel::ConsumerCancelled) { },
+ [&](Engine::FetchByteChannel::Closed) {
+ // 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.
+ // AD-HOC: Closing stream while buffer still holds bytes would lose them, so stream closes once they have
+ // been pulled into it.
+ if (result.buffered_byte_count == 0 && m_stream->is_readable()) {
+ m_stream->close();
+ m_detached = true;
+ }
+ },
+ [&](Engine::FetchByteChannel::Errored const& errored) {
+ // 2. Otherwise, if stream is readable, error stream with a TypeError.
+ if (m_stream->is_readable()) {
+ auto message = Utf16String::from_utf8(StringView { errored.message });
+ m_stream->error(JS::TypeError::create(*m_realm, message));
+ }
+ m_detached = true;
+ });
+}
+
+// AD-HOC: A sync XHR send() pauses the HTML event loop while it waits for exactly these bytes, and a stream set up
+// under that pause never starts pulling: the start promise's reaction is a microtask. So while the loop is
+// paused, bytes are pushed into the stream as they arrive, the way the specification's in-parallel steps
+// would deliver them (see the parallel-queue path in fetch_response_handover()).
+void BodyStreamPullSource::deliver_while_paused()
+{
+ // A pending pull's wake carries these bytes to run_pull_task() itself.
+ if (m_detached || m_pending_pull_promise)
+ return;
+
+ drain_into_stream();
+}
+
+void BodyStreamPullSource::run_pull_task()
+{
+ auto promise = exchange(m_pending_pull_promise, nullptr);
+ if (!promise)
+ return;
+
+ drain_into_stream();
+
+ // 3. Resolve promise with undefined.
+ auto& realm = *m_realm;
+ HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ WebIDL::resolve_promise(realm, *promise, JS::js_undefined());
+}
+
+void BodyStreamPullSource::drain_into_stream()
+{
+ auto& realm = *m_realm;
+ HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+
+ // The slices removed by one take reach the stream as one byte sequence, and a BYOB pull may consume only the
+ // current view's length.
+ auto result = [&] {
+ if (auto byte_length = m_stream->current_byob_request_view_byte_length(); byte_length.has_value())
+ return m_channel->take_up_to(*byte_length);
+ return m_channel->take_all();
+ }();
+
+ // 1. Pull from bytes buffer into stream.
+ if (!result.taken.is_empty()) {
+ ByteBuffer bytes;
+ for (auto const& taken : result.taken)
+ bytes.append(taken.bytes());
+ if (auto pull_result = m_stream->pull_from_bytes(bytes); pull_result.is_error()) {
+ // A failed enqueue ends the whole body.
+ 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();
+ m_channel->cancel();
+ m_detached = true;
+ return;
+ }
+ }
+
+ // 2. If stream is errored, then terminate fetchParams’s controller.
+ if (m_stream->is_errored())
+ m_fetch_params->controller()->terminate();
+
+ settle_stream(result);
+ if (result.state.has<Engine::FetchByteChannel::ConsumerCancelled>())
+ m_detached = true;
+}
+
+}
diff --git a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h
new file mode 100644
index 00000000000..678090adaee
--- /dev/null
+++ b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/DistinctNumeric.h>
+#include <LibCore/EventLoop.h>
+#include <LibGC/CellAllocator.h>
+#include <LibJS/Heap/Cell.h>
+#include <LibWeb/Fetch/Engine/FetchByteChannel.h>
+#include <LibWeb/Forward.h>
+
+namespace Web::Fetch::Fetching {
+
+class BodyStreamPullSource;
+
+// Never reused within a thread.
+AK_TYPEDEF_DISTINCT_ORDERED_ID(u64, BodyStreamWakeToken);
+
+// Delivers a channel's wakes to the pull source registered under its token, on the loop that created it.
+class BodyStreamWakeSink final : public Engine::FetchByteChannelConsumerSink {
+public:
+ static NonnullRefPtr<BodyStreamWakeSink> create();
+
+ BodyStreamWakeToken registry_token() const { return m_registry_token; }
+
+ virtual void wake(Engine::WakeTicket) override;
+
+private:
+ explicit BodyStreamWakeSink(BodyStreamWakeToken);
+
+ NonnullRefPtr<Core::WeakEventLoopReference> m_loop;
+ BodyStreamWakeToken const m_registry_token { 0 };
+};
+
+// The pull algorithm of a response stream whose bytes arrive through a FetchByteChannel.
+class BodyStreamPullSource final : public JS::Cell {
+ GC_CELL(BodyStreamPullSource, JS::Cell);
+ GC_DECLARE_ALLOCATOR(BodyStreamPullSource);
+
+public:
+ BodyStreamPullSource(JS::Realm&, GC::Ref<Infrastructure::FetchParams const>, GC::Ref<Streams::ReadableStream>, NonnullRefPtr<Engine::FetchByteChannel>, BodyStreamWakeSink const&);
+ virtual ~BodyStreamPullSource() override;
+
+ GC::Ref<WebIDL::Promise> pull();
+ GC::Ref<WebIDL::Promise> cancel(JS::Value reason);
+
+ enum class WakeResult : u8 {
+ Consumed,
+ StillAwaited,
+ };
+ WakeResult on_wake(Engine::WakeTicket);
+ void handle_network_settled();
+ void deliver_while_paused();
+
+private:
+ virtual void visit_edges(Visitor& visitor) override;
+
+ void settle_stream(Engine::FetchByteChannel::TakeResult const&);
+ void run_pull_task();
+ void drain_into_stream();
+
+ // The realm the stream is set up in.
+ GC::Ref<JS::Realm> m_realm;
+ GC::Ref<Infrastructure::FetchParams const> m_fetch_params;
+ GC::Ref<Streams::ReadableStream> m_stream;
+ NonnullRefPtr<Engine::FetchByteChannel> m_channel;
+ BodyStreamWakeToken const m_registry_token { 0 };
+
+ GC::Ptr<WebIDL::Promise> m_pending_pull_promise;
+ Engine::WakeTicket m_expected_ticket { 0 };
+
+ // Once the channel has ended, later pulls stay pending.
+ bool m_detached { false };
+};
+
+}
diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp b/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp
index 7b651b970ed..66008b7f2ec 100644
--- a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp
@@ -78,13 +78,6 @@ void FetchedDataReceiver::handle_network_data(JS::Realm& realm, Requests::Respon
return;
}
- if (state == NetworkState::Error) {
- // A response that died mid-body must not satisfy a sniff waiter with partial bytes.
- if (m_body)
- m_body->set_sniff_bytes_failed();
- return;
- }
-
// 1. If one or more bytes have been transmitted from response’s message body, then:
auto bytes = data.bytes();
if (bytes.is_empty())
@@ -226,19 +219,6 @@ void FetchedDataReceiver::enqueue_into_stream(JS::Realm& realm, ReadonlyBytes by
}
}
-void FetchedDataReceiver::abandon_cache_entry()
-{
- if (!m_http_cache || !m_fetch_params || !m_response)
- return;
-
- auto request = m_fetch_params->request();
- m_http_cache->abandon_entry(request->current_url(), request->method(), request->header_list(), m_response->header_list());
-
- m_http_cache.clear();
- m_cache_buffer.clear();
- m_cache_body.clear();
-}
-
void FetchedDataReceiver::close_stream(JS::Realm& realm)
{
if (m_http_cache && m_fetch_params) {
diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.h b/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.h
index 9a7a078b8d0..a38f8c3e6b7 100644
--- a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.h
+++ b/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.h
@@ -33,14 +33,10 @@ public:
enum class NetworkState {
Ongoing,
Complete,
- Error,
};
void handle_network_data(JS::Realm&, Requests::ResponseData, NetworkState);
void set_cached_response_body(Core::ImmutableBytes);
- // Drops the response's pending memory-cache entry, for a body that will not finish arriving.
- void abandon_cache_entry();
-
private:
FetchedDataReceiver(GC::Ptr<Infrastructure::FetchParams const>, GC::Ref<Streams::ReadableStream>, RefPtr<HTTP::MemoryCache>);
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 7ce64c60d0c..ec06ed14bd1 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -26,9 +26,13 @@
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOMURL/DOMURL.h>
#include <LibWeb/Fetch/BodyInit.h>
+#include <LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h>
+#include <LibWeb/Fetch/Engine/FetchByteChannel.h>
+#include <LibWeb/Fetch/Engine/WholeBodyTransport.h>
+#include <LibWeb/Fetch/Fetching/BodyStreamPullSource.h>
#include <LibWeb/Fetch/Fetching/Checks.h>
-#include <LibWeb/Fetch/Fetching/FetchedDataReceiver.h>
#include <LibWeb/Fetch/Fetching/Fetching.h>
+#include <LibWeb/Fetch/Fetching/NetworkBodyPump.h>
#include <LibWeb/Fetch/Fetching/PendingResponse.h>
#include <LibWeb/Fetch/Fetching/RefCountedFlag.h>
#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
@@ -1084,6 +1088,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
[](auto const&) -> ByteBuffer { VERIFY_NOT_REACHED(); });
success_steps->function()(move(bytes));
}
+ fetch_params.controller()->stop_body_transport();
} else {
auto reader = internal_response->body()->stream()->get_a_reader();
if (reader.is_exception()) {
@@ -2119,8 +2124,8 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru
// NOTE: If forwardResponse is a network error, this effectively caches the network error, which is
// sometimes known as "negative caching".
// NOTE: The associated body info is stored in the cache alongside the response.
- if (http_cache)
- store_response_in_cache(*http_cache, *http_request, *forward_response);
+ // NB: The network fetch stores forwardResponse as its headers arrive, before the end of its body can
+ // finalize the entry.
}
}
@@ -2315,6 +2320,16 @@ static URL::URL content_blocker_source_url_for_request(Infrastructure::Request&
return request.current_url();
}
+static NonnullRefPtr<Engine::WholeBodyTransport> create_whole_body_transport(Engine::FetchBodyDeliveryGate& delivery_gate, Engine::FetchByteChannel& channel)
+{
+ auto transport = Engine::WholeBodyTransport::create();
+ transport->set_on_stop([delivery_gate = NonnullRefPtr { delivery_gate }, channel = NonnullRefPtr { channel }] {
+ delivery_gate->detach_transport();
+ channel->cancel();
+ });
+ return transport;
+}
+
// 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.
@@ -2391,28 +2406,36 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
auto stream = Streams::ReadableStream::create(realm);
// 9. Let buffer be an empty byte sequence.
- auto fetched_data_receiver = GC::Heap::the().allocate<FetchedDataReceiver>(fetch_params, stream, move(http_cache));
+ // 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 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(), [&realm]() {
- // 1. Let promise be a new promise.
- // 2. Run the following steps in parallel:
- // NOTE: This is handled by FetchedDataReceiver, which pushes bytes into the controller as they arrive.
-
- // 3. Return promise.
- return WebIDL::create_resolved_promise(realm, JS::js_undefined());
+ 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(), [&realm, &fetch_params](JS::Value reason) {
- fetch_params.controller()->abort(realm, reason);
- return WebIDL::create_resolved_promise(realm, JS::js_undefined());
+ 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 on_headers_received = GC::create_function(GC::Heap::the(), [&fetch_params, pending_response, stream, request, fetched_data_receiver](Requests::Request* request_server_request, HTTP::HeaderList const& response_headers, Optional<u32> status_code, Optional<String> const& reason_phrase, Optional<Core::ImmutableBytes> javascript_bytecode, Optional<u64> javascript_bytecode_cache_vary_key, Requests::CacheState cache_state) {
+ // 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);
+
+ auto on_headers_received = GC::create_function(GC::Heap::the(), [&fetch_params, pending_response, stream, request, body_pump, delivery_gate, whole_body_transport, http_cache](Requests::Request* request_server_request, HTTP::HeaderList const& response_headers, Optional<u32> status_code, Optional<String> const& reason_phrase, Optional<Core::ImmutableBytes> javascript_bytecode, Optional<u64> javascript_bytecode_cache_vary_key, Requests::CacheState cache_state) {
if (pending_response->is_resolved()) {
// RequestServer will send us the response headers twice, the second time being for HTTP trailers. This
// fetch algorithm is not interested in trailers, so just drop them here.
@@ -2420,7 +2443,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
- // FetchedDataReceiver::queue_delivery_task()); record that, for consume_a_preloaded_resource().
+ // BodyStreamPullSource::on_wake()); record that, for consume_a_preloaded_resource().
fetch_params.controller()->set_response_arrived();
auto response = Infrastructure::Response::create();
@@ -2451,7 +2474,12 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
.client_id = request_server_request->request_server_client_id(),
.request_id = request_server_request->id(),
.request = RefPtr<Requests::Request> { request_server_request },
+ .body_delivery = delivery_gate,
});
+ } else {
+ // A body without a RequestServer request is never held for its navigation.
+ delivery_gate->release_hold();
+ whole_body_transport->attach_to(delivery_gate);
}
(void)request;
@@ -2466,12 +2494,17 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
for (auto const& [name, value] : response_headers.headers())
response->header_list()->append({ name, value });
- fetched_data_receiver->set_response(response);
+ body_pump->set_response(response);
// 14. Set response’s body to a new body whose stream is stream.
auto body = Infrastructure::Body::create(stream);
response->set_body(body);
- fetched_data_receiver->set_body(body);
+ body_pump->set_body(body);
+
+ // NB: HTTP-network-or-cache fetch's "Store httpRequest and forwardResponse in httpCache" runs here, as the
+ // headers arrive, so that the entry exists before the end of the body finalizes it.
+ if (http_cache)
+ store_response_in_cache(*http_cache, *request, *response);
// 17. Return response.
// NOTE: Typically response’s body’s stream is still being enqueued to after returning.
@@ -2479,46 +2512,70 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
});
// 16. Run these steps in parallel:
- // FIXME: 1. Run these steps, but abort when fetchParams is canceled:
- auto on_data_received = GC::create_function(GC::Heap::the(), [&realm, fetched_data_receiver](Requests::ResponseData data) {
- fetched_data_receiver->handle_network_data(realm, move(data), FetchedDataReceiver::NetworkState::Ongoing);
+ auto deliver_body_data = GC::create_function(GC::Heap::the(), [body_pump, pull_source](Requests::ResponseData data) {
+ body_pump->handle_network_data(move(data));
+ if (HTML::main_thread_event_loop().execution_paused())
+ pull_source->deliver_while_paused();
});
- auto on_cached_body_available = GC::create_function(GC::Heap::the(), [fetched_data_receiver](Core::ImmutableBytes data) {
- fetched_data_receiver->set_cached_response_body(move(data));
+ auto on_data_received = GC::create_function(GC::Heap::the(), [deliver_body_data, whole_body_transport](Requests::ResponseData data) {
+ if (!whole_body_transport->is_attached()) {
+ deliver_body_data->function()(move(data));
+ return;
+ }
+ auto body = MUST(Core::ImmutableBytes::copy(data.bytes()));
+ auto on_body_data = [deliver_body_data = GC::Root { deliver_body_data }](Requests::ResponseData data) {
+ deliver_body_data->function()(move(data));
+ };
+ whole_body_transport->set_body(move(body), move(on_body_data));
});
- auto on_complete = GC::create_function(GC::Heap::the(), [&realm, pending_response, stream, fetched_data_receiver, fetch_timing_info, cross_origin_isolated_capability](bool success, Requests::RequestTimingInfo const& timing_info, Optional<StringView> error_message) {
+ auto on_cached_body_available = GC::create_function(GC::Heap::the(), [body_pump](Core::ImmutableBytes data) {
+ body_pump->set_cached_response_body(move(data));
+ });
+
+ auto complete_load = GC::create_function(GC::Heap::the(), [&realm, pending_response, body_pump, pull_source, delivery_gate, fetch_timing_info, cross_origin_isolated_capability](bool success, Requests::RequestTimingInfo const& timing_info, Optional<StringView> error_message) {
HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ delivery_gate->detach_transport();
if (success) {
fetch_timing_info->update_final_timings(timing_info, cross_origin_isolated_capability);
- fetched_data_receiver->handle_network_data(realm, Requests::ResponseData::from_bytes({}), FetchedDataReceiver::NetworkState::Complete);
+ body_pump->handle_network_complete();
} else {
- fetched_data_receiver->handle_network_data(realm, Requests::ResponseData::from_bytes({}), FetchedDataReceiver::NetworkState::Error);
-
- // 16.1.2.2. Otherwise, if stream is readable, error stream with a TypeError.
auto error = Utf16String::formatted("Load failed: {}", error_message.value_or("Unknown error"sv));
-
- if (stream->is_readable())
- stream->error(JS::TypeError::create(realm, error));
+ body_pump->handle_network_error(error.to_utf8_but_should_be_ported_to_utf16());
if (!pending_response->is_resolved())
pending_response->resolve(Infrastructure::Response::network_error(error.to_utf8_but_should_be_ported_to_utf16()));
}
+
+ pull_source->handle_network_settled();
+ });
+
+ auto on_complete = GC::create_function(GC::Heap::the(), [complete_load, whole_body_transport](bool success, Requests::RequestTimingInfo const& timing_info, Optional<StringView> error_message) {
+ if (!success || !whole_body_transport->is_attached()) {
+ complete_load->function()(success, timing_info, error_message);
+ return;
+ }
+ whole_body_transport->when_delivered([complete_load = GC::Root { complete_load }, timing_info] {
+ complete_load->function()(true, timing_info, {});
+ });
});
auto transfer_lease = fetch_params.has_response_body_transfer_lease()
? Requests::RequestClient::TransferLease::Yes
: Requests::RequestClient::TransferLease::No;
auto network_request = ResourceLoader::the().load(load_request, on_headers_received, on_data_received, on_cached_body_available, on_complete, transfer_lease);
- fetched_data_receiver->set_network_request(network_request);
- if (network_request && fetch_params.has_response_body_transfer_lease())
- network_request->set_body_delivery_paused(true);
if (network_request) {
- network_request->on_teardown = [fetched_data_receiver = GC::Root { fetched_data_receiver }] {
- fetched_data_receiver->abandon_cache_entry();
+ delivery_gate->attach_transport(*network_request);
+ // The gate detaches before the cancellation reaches it.
+ network_request->on_teardown = [delivery_gate, channel, body_pump = GC::Root { body_pump }] {
+ delivery_gate->detach_transport();
+ channel->cancel();
+ body_pump->abandon_cache_entry();
};
+ } else {
+ fetch_params.controller()->set_body_transport(whole_body_transport);
}
fetch_params.controller()->set_pending_request(network_request);
diff --git a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp
new file mode 100644
index 00000000000..0df809fb055
--- /dev/null
+++ b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) 2024-2026, Tim Flynn <[email protected]>
+ * Copyright (c) 2025, Aliaksandr Kalenik <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibHTTP/Cache/MemoryCache.h>
+#include <LibWeb/Fetch/Fetching/NetworkBodyPump.h>
+#include <LibWeb/Fetch/Infrastructure/FetchParams.h>
+#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
+#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
+
+namespace Web::Fetch::Fetching {
+
+GC_DEFINE_ALLOCATOR(NetworkBodyPump);
+
+NetworkBodyPump::NetworkBodyPump(GC::Ptr<Infrastructure::FetchParams const> fetch_params, NonnullRefPtr<Engine::FetchByteChannel> channel, NonnullRefPtr<Engine::FetchBodyDeliveryGate> delivery_gate, RefPtr<HTTP::MemoryCache> http_cache)
+ : m_fetch_params(fetch_params)
+ , m_channel(move(channel))
+ , m_delivery_gate(move(delivery_gate))
+ , m_http_cache(move(http_cache))
+{
+}
+
+NetworkBodyPump::~NetworkBodyPump() = default;
+
+void NetworkBodyPump::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 terminal sniff call in handle_network_complete / handle_network_error.
+ if (m_network_complete)
+ m_body->set_sniff_bytes_complete();
+ if (m_network_failed)
+ m_body->set_sniff_bytes_failed();
+}
+
+void NetworkBodyPump::visit_edges(Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_fetch_params);
+ visitor.visit(m_response);
+ visitor.visit(m_body);
+}
+
+// This implements the transmission steps of HTTP-network fetch.
+// https://fetch.spec.whatwg.org/#concept-http-network-fetch
+void NetworkBodyPump::handle_network_data(Requests::ResponseData data)
+{
+ // 1. Run these steps, but abort when fetchParams is canceled:
+ if (m_fetch_params && m_fetch_params->is_canceled()) {
+ m_channel->cancel();
+ 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. Let filteredCoding be "@unknown".
+ // FIXME: 4. If codings is null or failure, then set filteredCoding to the empty string.
+ // FIXME: 5. Otherwise, if codings’s size is greater than 1, then set filteredCoding to "multiple".
+ // FIXME: 6. Otherwise, if codings[0] is the empty string, or it is supported by the user agent, and is a
+ // byte-case-insensitive match for an entry listed in the HTTP Content Coding Registry, then set
+ // filteredCoding to the result of byte-lowercasing codings[0].
+ // FIXME: 7. Set response’s body info’s content encoding to filteredCoding.
+ // FIXME: 8. Increase response’s body info’s encoded size by bytes’s length.
+ // FIXME: 9. Set bytes to the result of handling content codings given codings and bytes.
+ // FIXME: 10. Increase response’s body info’s decoded size by bytes’s length.
+ // FIXME: 11. If bytes is failure, then terminate fetchParams’s controller.
+
+ if (m_delivery_gate->did_deliver(bytes.size()) == Engine::FetchBodyDeliveryGate::DeliveryResult::Rejected)
+ return;
+
+ auto const* file_backed = data.file_backed_slice();
+
+ // Capture bytes for MIME sniffing
+ if (m_body) {
+ if (file_backed && m_body->source().has<Empty>())
+ 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 (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);
+ }
+ }
+
+ // 12. Append bytes to buffer. (Steps 12 and 13 live in FetchByteChannel's writes.)
+ if (file_backed)
+ m_channel->write(file_backed->slice);
+ else
+ m_channel->write_copy(bytes);
+}
+
+void NetworkBodyPump::handle_network_complete()
+{
+ m_network_complete = true;
+ // Mark sniff bytes as complete when the stream ends
+ if (m_body)
+ m_body->set_sniff_bytes_complete();
+
+ finalize_cache_entry();
+ m_channel->close();
+}
+
+void NetworkBodyPump::handle_network_error(StringView error_message)
+{
+ m_network_failed = true;
+ // A response that died mid-body must not satisfy a sniff waiter with partial bytes.
+ if (m_body)
+ m_body->set_sniff_bytes_failed();
+
+ abandon_cache_entry();
+ m_channel->error({ .message = MUST(ByteBuffer::copy(error_message.bytes())) });
+}
+
+void NetworkBodyPump::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;
+}
+
+void NetworkBodyPump::finalize_cache_entry()
+{
+ if (!m_http_cache || !m_fetch_params)
+ return;
+
+ auto request = m_fetch_params->request();
+ if (!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();
+}
+
+void NetworkBodyPump::abandon_cache_entry()
+{
+ if (!m_http_cache || !m_fetch_params || !m_response)
+ return;
+
+ auto request = m_fetch_params->request();
+ m_http_cache->abandon_entry(request->current_url(), request->method(), request->header_list(), m_response->header_list());
+
+ m_http_cache.clear();
+ m_cache_buffer.clear();
+ m_cache_body.clear();
+}
+
+}
diff --git a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h
new file mode 100644
index 00000000000..2e47bbe6f33
--- /dev/null
+++ b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2024-2026, Tim Flynn <[email protected]>
+ * Copyright (c) 2025, Aliaksandr Kalenik <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/ByteBuffer.h>
+#include <LibCore/ImmutableBytes.h>
+#include <LibGC/CellAllocator.h>
+#include <LibHTTP/Forward.h>
+#include <LibJS/Heap/Cell.h>
+#include <LibRequests/Request.h>
+#include <LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h>
+#include <LibWeb/Fetch/Engine/FetchByteChannel.h>
+#include <LibWeb/Forward.h>
+
+namespace Web::Fetch::Fetching {
+
+// The producer half of a streamed response body: sniff capture, memory-cache accumulation, and the writes into
+// the channel the stream pulls from.
+class NetworkBodyPump final : public JS::Cell {
+ GC_CELL(NetworkBodyPump, JS::Cell);
+ GC_DECLARE_ALLOCATOR(NetworkBodyPump);
+
+public:
+ virtual ~NetworkBodyPump() override;
+
+ void set_response(GC::Ref<Fetch::Infrastructure::Response const> response) { m_response = response; }
+ void set_body(GC::Ref<Fetch::Infrastructure::Body> body);
+
+ void handle_network_data(Requests::ResponseData);
+ void handle_network_complete();
+ void handle_network_error(StringView error_message);
+ void set_cached_response_body(Core::ImmutableBytes);
+
+ // Drops the response's pending memory-cache entry, for a body that will not finish arriving.
+ void abandon_cache_entry();
+
+private:
+ NetworkBodyPump(GC::Ptr<Infrastructure::FetchParams const>, NonnullRefPtr<Engine::FetchByteChannel>, NonnullRefPtr<Engine::FetchBodyDeliveryGate>, RefPtr<HTTP::MemoryCache>);
+
+ virtual void visit_edges(Visitor& visitor) override;
+
+ void finalize_cache_entry();
+
+ GC::Ptr<Infrastructure::FetchParams const> m_fetch_params;
+ GC::Ptr<Fetch::Infrastructure::Response const> m_response;
+ GC::Ptr<Fetch::Infrastructure::Body> m_body;
+
+ NonnullRefPtr<Engine::FetchByteChannel> m_channel;
+ NonnullRefPtr<Engine::FetchBodyDeliveryGate> m_delivery_gate;
+
+ RefPtr<HTTP::MemoryCache> m_http_cache;
+
+ // Bytes received before set_body(), flushed into the body's sniff buffer once it is attached.
+ 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 };
+
+ bool m_network_complete { false };
+ bool m_network_failed { false };
+};
+
+}
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp
index 68149e4f7ba..f4d3863d968 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp
@@ -56,6 +56,11 @@ void FetchController::set_pending_request(RefPtr<Requests::Request> const& reque
}
}
+void FetchController::set_body_transport(Engine::FetchBodyDeliveryGate::Transport& body_transport)
+{
+ m_body_transport = body_transport;
+}
+
void FetchController::set_report_timing_steps(Function<void(JS::Object&)> report_timing_steps)
{
m_report_timing_steps = GC::create_function(GC::Heap::the(), move(report_timing_steps));
@@ -190,6 +195,10 @@ void FetchController::stop_body_transport()
m_pending_request->stop();
m_pending_request = nullptr;
}
+ if (auto body_transport = m_body_transport.strong_ref()) {
+ m_body_transport = nullptr;
+ body_transport->stop();
+ }
}
void FetchController::fetch_task_queued(u64 fetch_task_id, HTML::TaskID event_id)
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
index ba964fd88db..9342347c77f 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
@@ -16,6 +16,7 @@
#include <LibJS/Runtime/VM.h>
#include <LibRequests/Forward.h>
#include <LibWeb/Export.h>
+#include <LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h>
#include <LibWeb/Fetch/Infrastructure/FetchTimingInfo.h>
#include <LibWeb/Forward.h>
#include <LibWeb/HTML/EventLoop/Task.h>
@@ -71,6 +72,7 @@ public:
void set_pending_preloaded_response(GC::Ptr<Fetching::PendingResponse> pending_preloaded_response) { m_pending_preloaded_response = pending_preloaded_response; }
void set_pending_request(RefPtr<Requests::Request> const&);
+ 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; }
void set_inner_fetch_controller(GC::Ref<FetchController>);
@@ -123,6 +125,7 @@ private:
GC::Ptr<Fetching::PendingResponse> m_pending_preloaded_response;
WeakPtr<Requests::Request> m_pending_request;
+ WeakPtr<Engine::FetchBodyDeliveryGate::Transport> m_body_transport;
bool m_requires_network { false };
bool m_has_started_request { false };
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
index 17dbdebef32..f9a6d57c55e 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
@@ -123,18 +123,30 @@ void Response::release_request_transfer_lease() const
void Response::resume_body_delivery() const
{
release_request_transfer_lease();
- if (m_request_server_request.has_value()) {
- if (m_request_server_request->request)
- m_request_server_request->request->resume_body_delivery();
- }
+ if (!m_request_server_request.has_value())
+ return;
+
+ auto const& request = m_request_server_request->request;
+ m_request_server_request->body_delivery.visit(
+ [&](RequestServerRequest::DeliveredByRequest) {
+ if (request)
+ request->resume_body_delivery();
+ },
+ [](NonnullRefPtr<Engine::FetchBodyDeliveryGate> const& gate) { gate->release_hold(); });
}
void Response::resume_body_delivery_up_to(size_t byte_count) const
{
- if (m_request_server_request.has_value()) {
- if (m_request_server_request->request)
- m_request_server_request->request->resume_body_delivery_up_to(byte_count);
- }
+ if (!m_request_server_request.has_value())
+ return;
+
+ auto const& request = m_request_server_request->request;
+ m_request_server_request->body_delivery.visit(
+ [&](RequestServerRequest::DeliveredByRequest) {
+ if (request)
+ request->resume_body_delivery_up_to(byte_count);
+ },
+ [&](NonnullRefPtr<Engine::FetchBodyDeliveryGate> const& gate) { 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 a0649799f30..02c200a5e03 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h
@@ -22,6 +22,7 @@
#include <LibRequests/Request.h>
#include <LibURL/URL.h>
#include <LibWeb/Export.h>
+#include <LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h>
#include <LibWeb/Fetch/Infrastructure/HTTP.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
#include <LibWebCommon/Fetch/Infrastructure/HTTP/ResponseCacheState.h>
@@ -62,9 +63,14 @@ public:
// RequestServer bookkeeping is transport state, not JS-visible response data.
struct RequestServerRequest {
+ // The request itself pauses and resumes the body's delivery.
+ struct DeliveredByRequest { };
+
int client_id { -1 };
u64 request_id { 0 };
RefPtr<Requests::Request> request;
+ // A body paced by a FetchByteChannel is released from the navigation hold through its delivery gate.
+ Variant<DeliveredByRequest, NonnullRefPtr<Engine::FetchBodyDeliveryGate>> body_delivery { DeliveredByRequest {} };
};
[[nodiscard]] static GC::Ref<Response> create();
diff --git a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp b/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
index 512f24ede7e..735773edad7 100644
--- a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
+++ b/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
@@ -1119,7 +1119,7 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(NullableDocumentOrXMLHttpRequestB
// queue, and progresses on the platform event loop (deferred invocations, IPC, timers) — all that's
// pumped here. So, the response arrives and is read to completion while the HTML event loop stays
// paused; see the parallel-queue path in fetch_response_handover(), and the direct delivery in
- // FetchedDataReceiver::queue_delivery_task(). Blink/WebKit block the thread outright for a sync load:
+ // BodyStreamPullSource::deliver_while_paused(). Blink/WebKit block the thread outright for a sync load:
// Blink on a WaitableEvent (ResourceRequestSender::SendSync), WebKit on a sync IPC reply
// (WebLoaderStrategy::loadResourceSynchronously). Gecko instead spins a nested event loop
// (XMLHttpRequestMainThread::SendInternal), with the top window suspended and its documents' microtasks
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 64e4c522d33..e9aa7e10d23 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -43,9 +43,11 @@ ALLOWED_REALM_MENTIONS = {
"Crypto": (8, 383, "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,
- "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",
+ 24,
+ 65,
+ "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": (
diff --git a/Tests/LibWeb/Text/expected/Cache/http-memory-cache-fetch-body-finalization.txt b/Tests/LibWeb/Text/expected/Cache/http-memory-cache-fetch-body-finalization.txt
new file mode 100644
index 00000000000..91ed8aa6c63
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Cache/http-memory-cache-fetch-body-finalization.txt
@@ -0,0 +1,11 @@
+unread success served from cache: true
+unread success content matches: true
+post-cancel refetch content matches: true
+cancelled delivery left no entry: true
+probe-1 failed mid-body
+probe-2 failed mid-body
+failed delivery left no entry: true
+failing delivery failed mid-body
+later delivery served from cache: true
+cached headers are the later delivery's: true
+cached content matches: true
diff --git a/Tests/LibWeb/Text/expected/Fetch/fetch-body-delivery-order.txt b/Tests/LibWeb/Text/expected/Fetch/fetch-body-delivery-order.txt
new file mode 100644
index 00000000000..a3c6fdafaab
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Fetch/fetch-body-delivery-order.txt
@@ -0,0 +1,4 @@
+reads resolve in chunk order: true
+a read's microtask ran before the next read resolved: true
+a read's timer fired before the next read resolved: true
+close followed the last bytes: true
diff --git a/Tests/LibWeb/Text/expected/Fetch/fetch-cached-body-paced-by-credit.txt b/Tests/LibWeb/Text/expected/Fetch/fetch-cached-body-paced-by-credit.txt
new file mode 100644
index 00000000000..895236d1ceb
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Fetch/fetch-cached-body-paced-by-credit.txt
@@ -0,0 +1,5 @@
+first response complete: true
+second response came from the cache: true
+cached body arrived in several reads: true
+no read exceeded the credit: true
+content complete: true
diff --git a/Tests/LibWeb/Text/expected/Fetch/fetch-read-spans-buffered-network-chunks.txt b/Tests/LibWeb/Text/expected/Fetch/fetch-read-spans-buffered-network-chunks.txt
new file mode 100644
index 00000000000..0022efd70a9
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Fetch/fetch-read-spans-buffered-network-chunks.txt
@@ -0,0 +1,2 @@
+reads coalesce chunks buffered together: true
+content matches: true
diff --git a/Tests/LibWeb/Text/expected/Fetch/file-body-larger-than-credit.txt b/Tests/LibWeb/Text/expected/Fetch/file-body-larger-than-credit.txt
new file mode 100644
index 00000000000..28aa6232e08
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Fetch/file-body-larger-than-credit.txt
@@ -0,0 +1 @@
+loaded
diff --git a/Tests/LibWeb/Text/expected/XHR/sync-xhr-file-body-releases-its-transport.txt b/Tests/LibWeb/Text/expected/XHR/sync-xhr-file-body-releases-its-transport.txt
new file mode 100644
index 00000000000..33462948588
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/XHR/sync-xhr-file-body-releases-its-transport.txt
@@ -0,0 +1,3 @@
+body came from the cache: true
+read the whole body: true
+body pump released: true
diff --git a/Tests/LibWeb/Text/expected/navigation/iframe-navigation-mid-body-failure.txt b/Tests/LibWeb/Text/expected/navigation/iframe-navigation-mid-body-failure.txt
index f2e51b012d1..1cc31179991 100644
--- a/Tests/LibWeb/Text/expected/navigation/iframe-navigation-mid-body-failure.txt
+++ b/Tests/LibWeb/Text/expected/navigation/iframe-navigation-mid-body-failure.txt
@@ -1,2 +1,3 @@
+body of the failed navigation: released
iframe produced a document from the partial body: false
iframe stayed on its initial document: true
diff --git a/Tests/LibWeb/Text/input/Cache/http-memory-cache-fetch-body-finalization.html b/Tests/LibWeb/Text/input/Cache/http-memory-cache-fetch-body-finalization.html
new file mode 100644
index 00000000000..15471826e8b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Cache/http-memory-cache-fetch-body-finalization.html
@@ -0,0 +1,139 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // The cache entry for a fetched body is finalized by the producer when the network delivery
+ // completes, not by the consumer reading it. An unread success must still fill the cache,
+ // while a cancelled or failed delivery must leave no entry behind.
+ //
+ // The Accept marker rides each request (CORS-safelisted, and these responses have no Vary).
+ // The server records the last marker it saw, which tells a hit from a miss.
+ asyncTest(async done => {
+ const server = httpTestServer();
+ const cacheableHeaders = {
+ "Access-Control-Allow-Origin": "*",
+ "Cache-Control": "max-age=500",
+ "Content-Type": "application/octet-stream",
+ };
+ const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
+ const lastSeenMarker = async url => {
+ const response = await fetch(server.recordedRequestHeadersURL(url));
+ return (await response.json())["Accept"][0];
+ };
+
+ // An unread successful response still finalizes its cache entry. No fetch in this loop
+ // reads its body, and the first check that reports a hit shows the producer finalized it.
+ {
+ const body = "unread but cacheable";
+ const url = await server.createEcho("GET", `/cache-finalize/unread-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: cacheableHeaders,
+ body,
+ });
+
+ await fetch(url, { mode: "cors", headers: { Accept: "initial" } });
+
+ // A check served from the cache never reaches the server, and its unique marker stays
+ // unseen. A check that missed is itself an unread delivery, and finalizes too.
+ let hitBody = null;
+ for (let attempt = 1; attempt <= 20 && hitBody === null; ++attempt) {
+ await delay(250);
+ const check = await fetch(url, { mode: "cors", headers: { Accept: `check-${attempt}` } });
+ if ((await lastSeenMarker(url)) !== `check-${attempt}`)
+ hitBody = await check.text();
+ }
+ println(`unread success served from cache: ${hitBody !== null}`);
+ println(`unread success content matches: ${hitBody === body}`);
+ }
+
+ // A consumer-cancelled delivery leaves no entry.
+ {
+ const body = "abcdefghij" + "K".repeat(54);
+ const url = await server.createEcho("GET", `/cache-finalize/cancelled-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: cacheableHeaders,
+ body,
+ });
+ const chunkedUrl = `${url}?chunks=10,54&chunk_delay_ms=400`;
+
+ const cancelled = await fetch(chunkedUrl, { mode: "cors", headers: { Accept: "probe-1" } });
+ await cancelled.body.cancel();
+ await delay(700);
+
+ const response = await fetch(chunkedUrl, { mode: "cors", headers: { Accept: "probe-2" } });
+ println(`post-cancel refetch content matches: ${(await response.text()) === body}`);
+ println(
+ `cancelled delivery left no entry: ${(await lastSeenMarker(url)) === "probe-2"}`
+ );
+ }
+
+ // A delivery that fails mid-body leaves no entry.
+ {
+ const url = await server.createEcho("GET", `/cache-finalize/network-error-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: { ...cacheableHeaders, "Content-Length": "100000" },
+ body: "far too short",
+ });
+
+ for (const marker of ["probe-1", "probe-2"]) {
+ try {
+ const response = await fetch(url, { mode: "cors", headers: { Accept: marker } });
+ await response.text();
+ println(`${marker} unexpectedly succeeded`);
+ } catch {
+ println(`${marker} failed mid-body`);
+ }
+ }
+ println(
+ `failed delivery left no entry: ${(await lastSeenMarker(url)) === "probe-2"}`
+ );
+ }
+
+ // A delivery that fails mid-body leaves nothing for a later delivery to finalize. The test server cuts a
+ // response short, advertising 10 KiB, when a request carries its incomplete-response header.
+ {
+ const incompleteResponseHeader = "X-Ladybird-Respond-With-Incomplete-Response";
+ const path = `/cache-finalize/failed-then-complete-${crypto.randomUUID()}`;
+ await server.createEcho("OPTIONS", path, {
+ status: 200,
+ headers: {
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Headers": incompleteResponseHeader,
+ },
+ });
+ const body = "complete";
+ const url = await server.createEcho("GET", path, {
+ status: 200,
+ headers: cacheableHeaders,
+ body,
+ });
+
+ try {
+ const failed = await fetch(url, {
+ mode: "cors",
+ headers: { Accept: "failing", [incompleteResponseHeader]: "1" },
+ });
+ await failed.text();
+ println("failing delivery unexpectedly succeeded");
+ } catch {
+ println("failing delivery failed mid-body");
+ }
+
+ await (await fetch(url, { mode: "cors", headers: { Accept: "complete" } })).text();
+
+ let hit = null;
+ for (let attempt = 1; attempt <= 20 && hit === null; ++attempt) {
+ await delay(250);
+ const check = await fetch(url, { mode: "cors", headers: { Accept: `check-${attempt}` } });
+ if ((await lastSeenMarker(url)) !== `check-${attempt}`)
+ hit = check;
+ else
+ await check.text();
+ }
+ println(`later delivery served from cache: ${hit !== null}`);
+ println(`cached headers are the later delivery's: ${hit?.headers.get("Content-Length") !== String(10 * 1024)}`);
+ println(`cached content matches: ${(await hit?.text()) === body}`);
+ }
+
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Fetch/fetch-body-delivery-order.html b/Tests/LibWeb/Text/input/Fetch/fetch-body-delivery-order.html
new file mode 100644
index 00000000000..dcce8c3b17f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Fetch/fetch-body-delivery-order.html
@@ -0,0 +1,57 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // Body bytes and the close reach the stream from queued tasks, one per delivery. A read's
+ // reaction and anything it queues run before the next chunk's delivery task, and the close
+ // follows the last bytes through the same queue. The chunks arrive 300 ms apart, and a timer a
+ // reaction queues fires before the next delivery; a run slow enough to let a chunk in first is
+ // retried with the chunks a second apart.
+ asyncTest(async done => {
+ const httpServer = httpTestServer();
+ const body = "A".repeat(16) + "B".repeat(16) + "C".repeat(16);
+
+ const url = await httpServer.createEcho("GET", `/delivery-order-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: {
+ "Access-Control-Allow-Origin": "*",
+ "Content-Type": "application/octet-stream",
+ },
+ body,
+ });
+
+ const readAll = async chunkDelayMs => {
+ const response = await fetch(`${url}?chunks=16,16,16&chunk_delay_ms=${chunkDelayMs}`);
+ const reader = response.body.getReader();
+ const events = [];
+ const chunks = [];
+ for (;;) {
+ const { value, done: streamDone } = await reader.read();
+ if (streamDone) {
+ events.push("close");
+ break;
+ }
+ const index = chunks.push(new TextDecoder().decode(value));
+ events.push(`read ${index}`);
+ queueMicrotask(() => events.push(`microtask after read ${index}`));
+ setTimeout(() => events.push(`timer after read ${index}`), 0);
+ }
+ await new Promise(resolve => setTimeout(resolve, 50));
+ return { events, chunks };
+ };
+ const beforeNextRead = ({ events, chunks }, kind) =>
+ chunks.every((_, i) => i + 1 === chunks.length || events.indexOf(`${kind} after read ${i + 1}`) < events.indexOf(`read ${i + 2}`));
+
+ let run = await readAll(300);
+ if (!beforeNextRead(run, "timer"))
+ run = await readAll(1000);
+ const { events, chunks } = run;
+ const position = event => events.indexOf(event);
+
+ println(`reads resolve in chunk order: ${chunks.join("") === body && chunks.every((chunk, i) => chunk[0] === "ABC"[i])}`);
+ println(`a read's microtask ran before the next read resolved: ${beforeNextRead(run, "microtask")}`);
+ println(`a read's timer fired before the next read resolved: ${beforeNextRead(run, "timer")}`);
+ println(`close followed the last bytes: ${position("close") > position(`microtask after read ${chunks.length}`)}`);
+
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Fetch/fetch-cached-body-paced-by-credit.html b/Tests/LibWeb/Text/input/Fetch/fetch-cached-body-paced-by-credit.html
new file mode 100644
index 00000000000..affaf4efcda
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Fetch/fetch-cached-body-paced-by-credit.html
@@ -0,0 +1,54 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A body the disk cache serves as one mapped file must reach the consumer in credit-sized
+ // pieces, like a body read from the network, never as one chunk of the whole file.
+ asyncTest(async done => {
+ const TEST_CACHE_ENABLED_HEADER = "X-Ladybird-Enable-Disk-Cache";
+ const TEST_CACHE_STATUS_HEADER = "X-Ladybird-Disk-Cache-Status";
+
+ const httpServer = httpTestServer();
+ const size = 4 * 1024 * 1024;
+ const url = await httpServer.createEcho("GET", `/cached-body-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: {
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Headers": TEST_CACHE_ENABLED_HEADER,
+ "Access-Control-Expose-Headers": TEST_CACHE_STATUS_HEADER,
+ "Cache-Control": "max-age=3600",
+ "Content-Type": "application/octet-stream",
+ },
+ body: "x".repeat(size),
+ });
+ const headers = { [TEST_CACHE_ENABLED_HEADER]: "1" };
+
+ const memoryCacheWasEnabled = internals.setHttpMemoryCacheEnabled(false);
+ try {
+ const first = await fetch(url, { headers });
+ println(`first response complete: ${(await first.arrayBuffer()).byteLength === size}`);
+
+ // The first body ends only after RequestServer has written its cache entry.
+ const second = await fetch(url, { headers });
+ println(`second response came from the cache: ${second.headers.get(TEST_CACHE_STATUS_HEADER) === "read-from-cache"}`);
+
+ const reader = second.body.getReader();
+ let reads = 0;
+ let largestRead = 0;
+ let total = 0;
+ for (;;) {
+ const { value, done: streamDone } = await reader.read();
+ if (streamDone) break;
+ reads++;
+ largestRead = Math.max(largestRead, value.length);
+ total += value.length;
+ }
+ println(`cached body arrived in several reads: ${reads > 1}`);
+ println(`no read exceeded the credit: ${largestRead <= 1024 * 1024}`);
+ println(`content complete: ${total === size}`);
+ } finally {
+ internals.setHttpMemoryCacheEnabled(memoryCacheWasEnabled);
+ }
+
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Fetch/fetch-read-spans-buffered-network-chunks.html b/Tests/LibWeb/Text/input/Fetch/fetch-read-spans-buffered-network-chunks.html
new file mode 100644
index 00000000000..58d31e90be7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Fetch/fetch-read-spans-buffered-network-chunks.html
@@ -0,0 +1,53 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // Network chunks that are buffered together must reach the consumer as one logical byte
+ // sequence: the body arrives as three transport chunks (10+27+27), the pipe through fetch
+ // response handover's identity TransformStream reads at most the first as it arrives, and after
+ // the rest are buffered together a single read returns them as one chunk, never one read per
+ // transport chunk.
+ // FIXME: Also cover a BYOB view spanning a chunk boundary once response bodies are
+ // JS-visible byte streams (the identity TransformStream's readable side is not one).
+ asyncTest(async done => {
+ const httpServer = httpTestServer();
+ const body = "abcdefghij" + "K".repeat(27) + "L".repeat(27);
+
+ const url = await httpServer.createEcho("GET", `/buffered-chunks-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: {
+ "Access-Control-Allow-Origin": "*",
+ "Content-Type": "application/octet-stream",
+ },
+ body,
+ });
+
+ const readAfter = async waitMs => {
+ const response = await fetch(`${url}?chunks=10,27,27&chunk_delay_ms=100`);
+ await new Promise(resolve => setTimeout(resolve, waitMs));
+
+ const reader = response.body.getReader();
+ let reads = 0;
+ let received = new Uint8Array(0);
+ for (;;) {
+ const { value, done: streamDone } = await reader.read();
+ if (streamDone) break;
+ reads++;
+ const merged = new Uint8Array(received.length + value.length);
+ merged.set(received);
+ merged.set(value, received.length);
+ received = merged;
+ }
+ return { reads, received };
+ };
+
+ // The first read starts after the last chunk has arrived, and a run too slow for that is retried with a
+ // longer wait.
+ let result = await readAfter(1300);
+ if (result.reads > 2)
+ result = await readAfter(5000);
+ println(`reads coalesce chunks buffered together: ${result.reads <= 2}`);
+ println(`content matches: ${new TextDecoder().decode(result.received) === body}`);
+
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Fetch/file-body-larger-than-credit.html b/Tests/LibWeb/Text/input/Fetch/file-body-larger-than-credit.html
new file mode 100644
index 00000000000..e6f772f9cfa
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Fetch/file-body-larger-than-credit.html
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A file: body arrives from its loader in one piece, larger than the credit a body stream grants at once.
+ asyncTest(done => {
+ const iframe = document.createElement("iframe");
+ iframe.onload = () => {
+ println("loaded");
+ done();
+ };
+ iframe.src = "../../../Assets/test-webm.webm";
+ document.body.appendChild(iframe);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/XHR/sync-xhr-file-body-releases-its-transport.html b/Tests/LibWeb/Text/input/XHR/sync-xhr-file-body-releases-its-transport.html
new file mode 100644
index 00000000000..4d9ab9d9112
--- /dev/null
+++ b/Tests/LibWeb/Text/input/XHR/sync-xhr-file-body-releases-its-transport.html
@@ -0,0 +1,64 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A synchronous request reads a body the disk cache serves as one mapped file straight from that file, and nothing
+ // is left delivering the rest of it into the stream no one reads.
+ asyncTest(async done => {
+ const TEST_CACHE_ENABLED_HEADER = "X-Ladybird-Enable-Disk-Cache";
+ const TEST_CACHE_STATUS_HEADER = "X-Ladybird-Disk-Cache-Status";
+
+ const httpServer = httpTestServer();
+ // Large enough that the response is handed over before most of its body has been delivered.
+ const size = 16 * 1024 * 1024;
+ const url = await httpServer.createEcho("GET", `/sync-xhr-cached-body-${crypto.randomUUID()}`, {
+ status: 200,
+ headers: {
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Headers": TEST_CACHE_ENABLED_HEADER,
+ "Access-Control-Expose-Headers": TEST_CACHE_STATUS_HEADER,
+ "Cache-Control": "max-age=3600",
+ "Content-Type": "application/octet-stream",
+ },
+ body: "x".repeat(size),
+ });
+ const headers = { [TEST_CACHE_ENABLED_HEADER]: "1" };
+
+ const countBodyPumps = () =>
+ Object.values(JSON.parse(internals.dumpGCGraph())).filter(cell => cell.class_name === "NetworkBodyPump")
+ .length;
+
+ const memoryCacheWasEnabled = internals.setHttpMemoryCacheEnabled(false);
+ try {
+ await (await fetch(url, { headers })).arrayBuffer();
+
+ // The first body ends only after RequestServer has written its cache entry.
+ const check = await fetch(url, { headers });
+ println(`body came from the cache: ${check.headers.get(TEST_CACHE_STATUS_HEADER) === "read-from-cache"}`);
+ await check.body.cancel();
+
+ await internals.gcAsync();
+ const initialPumps = countBodyPumps();
+
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", url, false);
+ xhr.setRequestHeader(TEST_CACHE_ENABLED_HEADER, "1");
+ xhr.send();
+ println(`read the whole body: ${xhr.responseText.length === size}`);
+
+ // A stale pointer on the stack can keep a cell alive through one conservative collection.
+ const deadline = performance.now() + 10000;
+ let released = false;
+ for (;;) {
+ await internals.gcAsync();
+ released = countBodyPumps() === initialPumps;
+ if (released || performance.now() > deadline)
+ break;
+ await new Promise(resolve => setTimeout(resolve, 10));
+ }
+ println(`body pump released: ${released}`);
+ } finally {
+ internals.setHttpMemoryCacheEnabled(memoryCacheWasEnabled);
+ }
+ done();
+ });
+</script>
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 b46ea7c90c6..0158ec592e4 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,9 +10,20 @@
const output = [];
const println = line => output.push(line);
- const countBodyReceivers = () =>
- Object.values(JSON.parse(internals.dumpGCGraph())).filter(cell => cell.class_name === "FetchedDataReceiver")
- .length;
+ // The body arrives through a body pump, or through a receiver when the navigation adopts a request fetched
+ // elsewhere.
+ const countBodyCells = () => {
+ const counts = { pumps: 0, pullSources: 0, receivers: 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;
+ };
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
// A stale pointer on the stack can keep a cell alive through one conservative collection.
@@ -20,14 +31,17 @@
const deadline = performance.now() + 10000;
for (;;) {
await internals.gcAsync();
- if (countBodyReceivers() === initial || performance.now() > deadline)
- return;
+ const counts = countBodyCells();
+ if (counts.pumps === initial.pumps && counts.pullSources === initial.pullSources && counts.receivers === initial.receivers)
+ 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`;
await sleep(10);
}
};
await internals.gcAsync();
- const initial = countBodyReceivers();
+ const initial = countBodyCells();
const frame = document.createElement("iframe");
let loaded = false;
@@ -37,7 +51,7 @@
// The body is held after its first chunk, and ends short once it is let go.
const arrivalDeadline = performance.now() + 10000;
- while (countBodyReceivers() === initial) {
+ for (let counts = countBodyCells(); counts.pumps === initial.pumps && counts.receivers === initial.receivers; counts = countBodyCells()) {
if (performance.now() > arrivalDeadline) {
println("body of the failed navigation never arrived");
return output;
@@ -46,8 +60,7 @@
}
await fetch(urls.unblock);
- // The navigation has settled once its body is released.
- await waitForRelease(initial);
+ println(`body of the failed navigation: ${await waitForRelease(initial)}`);
println(`iframe produced a document from the partial body: ${loaded}`);
const stayed = frame.contentDocument !== null && frame.contentDocument.querySelector("#partial") === null;
println(`iframe stayed on its initial document: ${stayed}`);