Skip to content

Truly independent web browser

LibWeb: Settle network body streams through their FetchByteChannel

Luke Wilde82b8e87a5a5a
diff --git a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
index bc71364fde4..04df4552524 100644
--- a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
@@ -109,8 +109,9 @@ GC::Ref<WebIDL::Promise> BodyStreamPullSource::pull()
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();
+ if (auto push_ticket = exchange(m_push_ticket, {}); push_ticket.has_value())
+ m_channel->disarm_waiter(*push_ticket);
+ m_pull_ticket = arm_waiter(Engine::FetchByteChannel::BufferedAtLeast { 1 });
}
// 3. Return promise.
@@ -123,6 +124,9 @@ GC::Ref<WebIDL::Promise> BodyStreamPullSource::cancel(JS::Value reason)
m_channel->cancel();
BodyStreamWakeRegistry::the().disarm(m_registry_token);
m_detached = true;
+ m_end_ticket = {};
+ m_pull_ticket = {};
+ m_push_ticket = {};
// A pull promise created before the cancellation still settles.
if (auto promise = exchange(m_pending_pull_promise, nullptr))
@@ -134,18 +138,47 @@ GC::Ref<WebIDL::Promise> BodyStreamPullSource::cancel(JS::Value reason)
return WebIDL::create_resolved_promise(realm, JS::js_undefined());
}
+void BodyStreamPullSource::watch_channel()
+{
+ m_end_ticket = arm_waiter(Engine::FetchByteChannel::EndOnly {});
+ push_while_paused();
+}
+
+Engine::WakeTicket BodyStreamPullSource::arm_waiter(Engine::FetchByteChannel::WakeOn wake_on)
+{
+ BodyStreamWakeRegistry::the().arm(m_registry_token, *this);
+ return m_channel->arm_waiter(wake_on);
+}
+
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)
+ if (ticket == m_pull_ticket) {
+ m_pull_ticket = {};
+ on_pull_wake();
+ } else if (ticket == m_push_ticket) {
+ m_push_ticket = {};
+ on_push_wake();
+ } else if (ticket == m_end_ticket) {
+ m_end_ticket = {};
+ on_end_wake();
+ }
+
+ // The source stays rooted while any of its waiters is still owed a wake.
+ if (m_end_ticket.has_value() || m_pull_ticket.has_value() || m_push_ticket.has_value())
return WakeResult::StillAwaited;
+ return WakeResult::Consumed;
+}
+
+void BodyStreamPullSource::on_pull_wake()
+{
+ if (!m_pending_pull_promise)
+ return;
// 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;
+ push_while_paused();
+ return;
}
// 3. Queue a fetch task to run the following steps, with fetchParams’s task destination:
@@ -155,26 +188,46 @@ BodyStreamPullSource::WakeResult BodyStreamPullSource::on_wake(Engine::WakeTicke
});
if (m_fetch_params) {
Infrastructure::queue_fetch_task(m_fetch_params->task_destination(), steps);
- return WakeResult::Consumed;
+ return;
}
// 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;
}
-// A failed transmission errors the stream regardless of read demand, and an empty completed body closes without one.
-void BodyStreamPullSource::handle_network_settled()
+// 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 sync XHR body path in fetch_response_handover()).
+void BodyStreamPullSource::push_while_paused()
{
- if (m_pending_pull_promise)
+ if (m_detached || m_pending_pull_promise || m_push_ticket.has_value() || !HTML::main_thread_event_loop().execution_paused())
+ return;
+ if (!m_fetch_params || m_fetch_params->algorithms()->body_intent() != Engine::BodyIntent::SyncAccumulate)
return;
+ m_push_ticket = arm_waiter(Engine::FetchByteChannel::BufferedAtLeast { 1 });
+}
- if (HTML::main_thread_event_loop().execution_paused()) {
- deliver_while_paused();
+void BodyStreamPullSource::on_push_wake()
+{
+ if (m_detached || m_pending_pull_promise)
return;
- }
+ drain_into_stream();
+ push_while_paused();
+}
+
+// A pending pull or the push while paused carries the body's end itself.
+void BodyStreamPullSource::on_end_wake()
+{
+ if (m_detached || m_pending_pull_promise || m_push_ticket.has_value())
+ return;
+ settle_without_reading();
+}
+// A failed transmission errors the stream regardless of read demand, and an empty completed body closes without one.
+void BodyStreamPullSource::settle_without_reading()
+{
auto& realm = *m_realm;
HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
@@ -209,19 +262,6 @@ void BodyStreamPullSource::settle_stream(Engine::FetchByteChannel::TakeResult co
});
}
-// 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 sync XHR body 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);
@@ -276,4 +316,29 @@ void BodyStreamPullSource::drain_into_stream()
m_detached = true;
}
+// https://fetch.spec.whatwg.org/#concept-http-network-fetch
+// NB: Steps 10 to 13 of HTTP-network fetch.
+GC::Ref<Streams::ReadableStream> create_body_stream_from_channel(JS::Realm& realm, GC::Ptr<Infrastructure::FetchParams const> fetch_params, NonnullRefPtr<Engine::FetchByteChannel> channel, BodyStreamWakeSink const& wake_sink)
+{
+ // 10. Let stream be a new ReadableStream.
+ auto stream = Streams::ReadableStream::create(realm);
+ auto pull_source = GC::Heap::the().allocate<BodyStreamPullSource>(realm, fetch_params, stream, move(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);
+ pull_source->watch_channel();
+
+ return stream;
+}
+
}
diff --git a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h
index 3bcbdfa53c0..67793bb3f59 100644
--- a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h
+++ b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h
@@ -10,6 +10,7 @@
#include <LibCore/EventLoop.h>
#include <LibGC/CellAllocator.h>
#include <LibJS/Heap/Cell.h>
+#include <LibWeb/Export.h>
#include <LibWeb/Fetch/Engine/FetchByteChannel.h>
#include <LibWeb/Forward.h>
@@ -21,7 +22,7 @@ class BodyStreamPullSource;
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 {
+class WEB_API BodyStreamWakeSink final : public Engine::FetchByteChannelConsumerSink {
public:
static NonnullRefPtr<BodyStreamWakeSink> create();
@@ -36,7 +37,8 @@ private:
BodyStreamWakeToken const m_registry_token { 0 };
};
-// The pull algorithm of a response stream whose bytes arrive through a FetchByteChannel.
+// The pull algorithm of a response stream whose bytes arrive through a FetchByteChannel. The channel's end reaches the
+// stream even when no pull is pending.
class BodyStreamPullSource final : public JS::Cell {
GC_CELL(BodyStreamPullSource, JS::Cell);
GC_DECLARE_ALLOCATOR(BodyStreamPullSource);
@@ -53,12 +55,19 @@ public:
StillAwaited,
};
WakeResult on_wake(Engine::WakeTicket);
- void handle_network_settled();
- void deliver_while_paused();
+
+ // Waits for the channel to end, and while the HTML event loop is paused for its bytes too.
+ void watch_channel();
private:
virtual void visit_edges(Visitor& visitor) override;
+ Engine::WakeTicket arm_waiter(Engine::FetchByteChannel::WakeOn);
+ void on_pull_wake();
+ void push_while_paused();
+ void on_push_wake();
+ void on_end_wake();
+ void settle_without_reading();
void settle_stream(Engine::FetchByteChannel::TakeResult const&);
void run_pull_task();
void drain_into_stream();
@@ -72,10 +81,15 @@ private:
BodyStreamWakeToken const m_registry_token { 0 };
GC::Ptr<WebIDL::Promise> m_pending_pull_promise;
- Engine::WakeTicket m_expected_ticket { 0 };
+ Optional<Engine::WakeTicket> m_end_ticket;
+ Optional<Engine::WakeTicket> m_pull_ticket;
+ Optional<Engine::WakeTicket> m_push_ticket;
// Once the channel has ended, later pulls stay pending.
bool m_detached { false };
};
+// A response body's stream read from channel, whose consumer sink is wake_sink.
+WEB_API GC::Ref<Streams::ReadableStream> create_body_stream_from_channel(JS::Realm&, GC::Ptr<Infrastructure::FetchParams const>, NonnullRefPtr<Engine::FetchByteChannel>, BodyStreamWakeSink const&);
+
}
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 3f7c3926e74..12cf29a6045 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -2612,18 +2612,14 @@ struct NetworkBodyStream {
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.
+// NB: Step 9 of HTTP-network fetch; steps 10 to 13 run in create_body_stream_from_channel().
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 };
@@ -2633,22 +2629,9 @@ static NetworkBodyStream create_network_body_stream(JS::Realm& realm, GC::Ptr<In
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);
+ auto stream = create_body_stream_from_channel(realm, fetch_params, channel, *wake_sink);
- return { stream, move(channel), move(delivery_gate), body_pump, pull_source };
+ return { stream, move(channel), move(delivery_gate), body_pump };
}
// The gate detaches before the channel's ending reaches it.
@@ -2711,7 +2694,6 @@ GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, I
});
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) { },
@@ -2721,8 +2703,7 @@ GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, I
[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 };
+ [body_pump, delivery_gate, timing_info, cross_origin_isolated_capability, network_settled](u64, Requests::RequestTimingInfo const& request_timing_info, Optional<Requests::NetworkError> network_error) {
delivery_gate->detach_transport();
if (network_error.has_value()) {
@@ -2738,8 +2719,6 @@ GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, I
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({
@@ -2821,7 +2800,6 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
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);
@@ -2902,10 +2880,8 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
});
// 16. Run these steps in parallel:
- auto deliver_body_data = GC::create_function(GC::Heap::the(), [body_pump, pull_source](Requests::ResponseData data) {
+ auto deliver_body_data = GC::create_function(GC::Heap::the(), [body_pump](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_data_received = GC::create_function(GC::Heap::the(), [deliver_body_data, whole_body_transport](Requests::ResponseData data) {
@@ -2924,7 +2900,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
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, request, fetch_timing_info, cross_origin_isolated_capability](bool success, Requests::RequestTimingInfo const& timing_info, Optional<StringView> error_message) {
+ auto complete_load = GC::create_function(GC::Heap::the(), [&realm, pending_response, body_pump, delivery_gate, request, 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();
@@ -2938,8 +2914,6 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
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) {
diff --git a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp b/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
index 0ede8501761..a8c87667c67 100644
--- a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
+++ b/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
@@ -1124,7 +1124,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 sync XHR body path in fetch_response_handover(), and the direct delivery in
- // BodyStreamPullSource::deliver_while_paused(). Blink/WebKit block the thread outright for a sync load:
+ // BodyStreamPullSource::push_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 19899c7fda4..96d4513d9db 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -44,9 +44,10 @@ ALLOWED_REALM_MENTIONS = {
"DOM": (10, 33, "DOM abort plumbing and node helpers still have callback/materialization realm use"),
"Fetch": (
22,
- 57,
+ 59,
"Fetch bodies, headers, requests, responses, response views, and controllers still materialize JS values/streams; "
- "BodyStreamPullSource materializes stream pulls and errors on the consumer side, in its stream's realm",
+ "BodyStreamPullSource creates body streams and materializes their pulls and errors on the consumer side, each 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/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txt
index 639c23ba2c8..27d562200a7 100644
--- a/Tests/LibWeb/CMakeLists.txt
+++ b/Tests/LibWeb/CMakeLists.txt
@@ -28,6 +28,7 @@ set(TEST_SOURCES
TestFaviconDecoding.cpp
TestFetchBodyDeliveryGate.cpp
TestFetchBodySniffBytes.cpp
+ TestFetchBodyStream.cpp
TestFetchByteChannel.cpp
TestFetchEngineMessages.cpp
TestFetchExecutor.cpp
@@ -94,6 +95,7 @@ target_link_libraries(TestDownloadReader PRIVATE LibGC LibJS LibURL)
target_link_libraries(TestFaviconDecoding PRIVATE LibCore LibGC LibGfx LibJS)
target_link_libraries(TestFetchBodyDeliveryGate PRIVATE LibCore LibThreading)
target_link_libraries(TestFetchBodySniffBytes PRIVATE LibCore LibGC LibJS)
+target_link_libraries(TestFetchBodyStream PRIVATE LibCore LibGC LibJS)
target_link_libraries(TestFetchByteChannel PRIVATE LibThreading)
target_link_libraries(TestFetchResponse PRIVATE LibGC LibHTTP LibJS LibRequests LibURL)
target_link_libraries(TestFetchURL PRIVATE LibURL)
diff --git a/Tests/LibWeb/FetchTestDocument.h b/Tests/LibWeb/FetchTestDocument.h
new file mode 100644
index 00000000000..5eef4744112
--- /dev/null
+++ b/Tests/LibWeb/FetchTestDocument.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Bindings/MainThreadVM.h>
+#include <LibWeb/Bindings/PrincipalHostDefined.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/HTML/LocalTraversableNavigable.h>
+#include <LibWeb/Platform/FontPlugin.h>
+
+inline void install_font_plugin()
+{
+ static Web::Platform::FontPlugin font_plugin { false };
+ static bool installed = false;
+ if (installed)
+ return;
+ Web::Platform::FontPlugin::install(font_plugin);
+ installed = true;
+}
+
+// The active document of a new top-level traversable in a new principal realm.
+inline GC::Ref<Web::DOM::Document> create_test_document()
+{
+ auto principal_realm = Web::Bindings::create_a_principal_javascript_realm();
+ auto& page = Web::Bindings::principal_host_defined_page(*principal_realm);
+ auto traversable = Web::HTML::LocalTraversableNavigable::create_a_new_top_level_traversable(page, nullptr, {});
+ page.set_top_level_traversable(traversable);
+ return *traversable->active_document();
+}
diff --git a/Tests/LibWeb/TestFetchBodyStream.cpp b/Tests/LibWeb/TestFetchBodyStream.cpp
new file mode 100644
index 00000000000..f1cf4e059ec
--- /dev/null
+++ b/Tests/LibWeb/TestFetchBodyStream.cpp
@@ -0,0 +1,194 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "FetchTestDocument.h"
+#include <AK/Time.h>
+#include <LibCore/EventLoop.h>
+#include <LibCore/Timer.h>
+#include <LibJS/Runtime/TypedArray.h>
+#include <LibTest/TestCase.h>
+#include <LibWeb/Fetch/Engine/FetchByteChannel.h>
+#include <LibWeb/Fetch/Fetching/BodyStreamPullSource.h>
+#include <LibWeb/Fetch/Infrastructure/FetchParams.h>
+#include <LibWeb/HTML/EventLoop/EventLoop.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
+#include <LibWeb/Loader/LoaderConfig.h>
+#include <LibWeb/Streams/ReadableStream.h>
+#include <LibWeb/Streams/ReadableStreamDefaultReader.h>
+
+using Web::Fetch::Engine::FetchByteChannel;
+using Web::Fetch::Engine::FetchByteChannelProducerSink;
+using Web::Fetch::Infrastructure::FetchAlgorithms;
+using Web::Fetch::Infrastructure::FetchParams;
+
+namespace {
+
+class IgnoringProducerSink final : public FetchByteChannelProducerSink {
+public:
+ virtual void grant_credit(u64) override { }
+ virtual void consumer_cancelled() override { }
+};
+
+// What one read of a stream gives.
+class RecordingReadRequest final : public Web::Streams::ReadRequest {
+ GC_CELL(RecordingReadRequest, Web::Streams::ReadRequest);
+ GC_DECLARE_ALLOCATOR(RecordingReadRequest);
+
+public:
+ virtual void on_chunk(JS::Value chunk) override
+ {
+ auto& array = as<JS::Uint8Array>(chunk.as_object());
+ auto record = JS::make_typed_array_with_buffer_witness_record(array, JS::ArrayBuffer::Order::SeqCst);
+ m_chunk = MUST(array.viewed_array_buffer()->copy_to_byte_buffer(array.byte_offset(), JS::typed_array_byte_length(record)));
+ m_chunk_received = true;
+ }
+ virtual void on_close() override { m_closed = true; }
+ virtual void on_error(JS::Value) override { m_errored = true; }
+
+ bool settled() const { return m_chunk_received || m_closed || m_errored; }
+ StringView chunk() const { return m_chunk_received ? StringView { m_chunk } : "<no chunk>"sv; }
+ bool closed() const { return m_closed; }
+
+private:
+ ByteBuffer m_chunk;
+ bool m_chunk_received { false };
+ bool m_closed { false };
+ bool m_errored { false };
+};
+
+GC_DEFINE_ALLOCATOR(RecordingReadRequest);
+
+GC::Ref<FetchParams> create_sync_xhr_fetch_params()
+{
+ auto algorithms = FetchAlgorithms::create(FetchAlgorithms::Input { Web::Fetch::Engine::BodyIntent::SyncAccumulate });
+ auto request = Web::Fetch::Infrastructure::Request::create();
+ auto timing_info = Web::Fetch::Infrastructure::FetchTimingInfo::create();
+ return FetchParams::create(move(request), algorithms, move(timing_info), Web::current_loader_config());
+}
+
+struct BodyStreamHarness {
+ BodyStreamHarness()
+ : realm(create_test_document()->relevant_settings_object().realm())
+ , execution_context(*realm, Web::HTML::TemporaryExecutionContext::CallbacksEnabled::Yes)
+ {
+ }
+
+ void create_stream()
+ {
+ auto wake_sink = Web::Fetch::Fetching::BodyStreamWakeSink::create();
+ channel = FetchByteChannel::create({ .low = 16, .high = 64 }, wake_sink, adopt_ref(*new IgnoringProducerSink));
+ stream = Web::Fetch::Fetching::create_body_stream_from_channel(*realm, fetch_params, *channel, *wake_sink);
+ }
+
+ // The bytes the channel holds that have not been pulled into the stream.
+ u64 channel_byte_count()
+ {
+ return channel->peek_up_to(0).buffered_byte_count;
+ }
+
+ // Reads one chunk of the stream, running the event loop until the read settles, or for ten seconds.
+ GC::Ref<RecordingReadRequest> read()
+ {
+ if (!reader)
+ reader = MUST(stream->get_a_reader());
+ auto request = realm->heap().allocate<RecordingReadRequest>();
+ reader->read_a_chunk(*request);
+ if (!request->settled()) {
+ auto deadline = Core::Timer::create_single_shot(AK::Duration::from_seconds(10), [] { });
+ deadline->start();
+ Web::HTML::main_thread_event_loop().spin_until(GC::create_function(realm->heap(), [request, deadline] {
+ return request->settled() || !deadline->is_active();
+ }));
+ }
+ return request;
+ }
+
+ // Runs every deferred invocation queued so far, which includes every channel wake.
+ static void run_wakes()
+ {
+ for (size_t i = 0; i < 3; ++i)
+ Core::EventLoop::current().pump(Core::EventLoop::WaitMode::PollForEvents);
+ }
+
+ GC::Ref<JS::Realm> realm;
+ Web::HTML::TemporaryExecutionContext execution_context;
+ GC::Ptr<FetchParams const> fetch_params;
+ RefPtr<FetchByteChannel> channel;
+ GC::Ptr<Web::Streams::ReadableStream> stream;
+ GC::Ptr<Web::Streams::ReadableStreamDefaultReader> reader;
+};
+
+}
+
+TEST_CASE(an_error_reaches_a_stream_nobody_reads)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ BodyStreamHarness harness;
+ harness.create_stream();
+
+ (void)harness.channel->error({ .message = MUST(ByteBuffer::copy("failed"sv.bytes())) });
+ EXPECT(harness.stream->is_readable());
+
+ BodyStreamHarness::run_wakes();
+ EXPECT(harness.stream->is_errored());
+}
+
+TEST_CASE(an_empty_close_closes_a_stream_nobody_reads)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ BodyStreamHarness harness;
+ harness.create_stream();
+
+ (void)harness.channel->close();
+ EXPECT(harness.stream->is_readable());
+
+ BodyStreamHarness::run_wakes();
+ EXPECT(harness.stream->is_closed());
+}
+
+TEST_CASE(a_close_leaves_unread_bytes_readable)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ BodyStreamHarness harness;
+ harness.create_stream();
+
+ EXPECT_EQ(harness.channel->write(MUST(Core::ImmutableBytes::copy("unread"sv.bytes()))), FetchByteChannel::WriteResult::Accepted);
+ (void)harness.channel->close();
+
+ BodyStreamHarness::run_wakes();
+ EXPECT(harness.stream->is_readable());
+ EXPECT_EQ(harness.channel_byte_count(), 6u);
+
+ auto read = harness.read();
+ EXPECT_EQ(read->chunk(), "unread"sv);
+ EXPECT(harness.stream->is_closed());
+}
+
+TEST_CASE(bytes_reach_a_stream_while_the_event_loop_is_paused)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ BodyStreamHarness harness;
+ harness.fetch_params = create_sync_xhr_fetch_params();
+ auto pause = Web::HTML::main_thread_event_loop().pause(Web::HTML::EventLoop::UpdateTheRendering::No);
+ harness.create_stream();
+
+ EXPECT_EQ(harness.channel->write(MUST(Core::ImmutableBytes::copy("pushed"sv.bytes()))), FetchByteChannel::WriteResult::Accepted);
+ BodyStreamHarness::run_wakes();
+ EXPECT_EQ(harness.channel_byte_count(), 0u);
+
+ (void)harness.channel->close();
+ BodyStreamHarness::run_wakes();
+ EXPECT(harness.stream->is_readable());
+
+ auto read = harness.read();
+ EXPECT_EQ(read->chunk(), "pushed"sv);
+ EXPECT(harness.stream->is_closed());
+}