Skip to content

Truly independent web browser

LibWeb: Keep a response's body in the response, its stream in the view

Luke Wildeef5b88b94f62
diff --git a/Libraries/LibWeb/DOM/DocumentLoading.cpp b/Libraries/LibWeb/DOM/DocumentLoading.cpp
index 416d8b2fde2..50b88d36da5 100644
--- a/Libraries/LibWeb/DOM/DocumentLoading.cpp
+++ b/Libraries/LibWeb/DOM/DocumentLoading.cpp
@@ -133,7 +133,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_html_document(HTML::Navi
// FIXME: The additional check for a non-empty body fixes issues with loading javascript urls in iframes, which
// default to an "about:blank" url. Is this a spec bug?
if (document->url().to_string() == "about:blank"_string
- && navigation_params.response->body()->length().value_or(0) == 0) {
+ && navigation_params.response->body_length().value_or(0) == 0) {
TRY(document->populate_with_html_head_and_body());
if (navigation_params.navigable && navigation_params.navigable->is_top_level_traversable())
document->set_supported_color_schemes({ "light"_utf16_fly_string, "dark"_utf16_fly_string });
@@ -143,7 +143,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_html_document(HTML::Navi
// AD-HOC: For about:srcdoc, the body bytes are always immediately available in the response source (the srcdoc
// string was inlined when the navigation params were created). Bypass the async body-reading pipeline
// and set up a deferred parser directly, so the document is parsed as soon as scripts may run for it.
- else if (auto const& source = navigation_params.response->body()->source();
+ else if (auto source = navigation_params.response->body_source();
source.has_value() && document->url() == URL::about_srcdoc()) {
auto mime_type = Fetch::Infrastructure::extract_mime_type(navigation_params.response->header_list());
auto url = navigation_params.response->url().value();
diff --git a/Libraries/LibWeb/DOM/DocumentLoading.h b/Libraries/LibWeb/DOM/DocumentLoading.h
index c7d3773eaa8..f8bab12958a 100644
--- a/Libraries/LibWeb/DOM/DocumentLoading.h
+++ b/Libraries/LibWeb/DOM/DocumentLoading.h
@@ -65,7 +65,7 @@ GC::Ref<DOM::Document> create_document_for_inline_content(GC::Ptr<HTML::LocalNav
move(navigation_id),
navigable,
nullptr,
- Fetch::Infrastructure::ResponseView::create(response),
+ Fetch::Infrastructure::ResponseView::create(response, nullptr),
nullptr,
nullptr,
move(coop_enforcement_result),
diff --git a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
index 7b873b1f7e8..7e5bdb306f5 100644
--- a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
@@ -93,6 +93,7 @@ void BodyStreamPullSource::visit_edges(Visitor& visitor)
visitor.visit(m_fetch_params);
visitor.visit(m_stream);
visitor.visit(m_pending_pull_promise);
+ visitor.visit(m_on_resource_header);
}
// This implements the pullAlgorithm of HTTP-network fetch.
@@ -127,10 +128,13 @@ GC::Ref<WebIDL::Promise> BodyStreamPullSource::cancel(JS::Value reason)
m_end_ticket = {};
m_pull_ticket = {};
m_push_ticket = {};
+ m_resource_header_ticket = {};
- // A pull promise created before the cancellation still settles.
+ // A pull promise created before the cancellation still settles, and so does a read of the resource header.
if (auto promise = exchange(m_pending_pull_promise, nullptr))
WebIDL::resolve_promise(realm, *promise, JS::js_undefined());
+ if (auto on_resource_header = exchange(m_on_resource_header, nullptr))
+ on_resource_header->function()({}, Infrastructure::Body::SniffOutcome::Failed);
// cancelAlgorithm: abort fetchParams's controller with reason, given reason.
if (m_fetch_params)
@@ -144,6 +148,36 @@ void BodyStreamPullSource::watch_channel()
push_while_paused();
}
+void BodyStreamPullSource::read_resource_header(Infrastructure::Body::ResourceHeaderCallback on_resource_header)
+{
+ VERIFY(!m_has_taken_bytes);
+ VERIFY(!m_on_resource_header);
+ m_on_resource_header = on_resource_header;
+ m_resource_header_ticket = arm_waiter(Engine::FetchByteChannel::PrefixOf { Infrastructure::MAX_SNIFF_BYTES });
+}
+
+// The channel kept the header from the moment its waiter was due, so a later error does not fail a complete one. A
+// cancellation or a transfer keeps none, and fails it.
+void BodyStreamPullSource::on_resource_header_wake(Engine::WakeTicket ticket)
+{
+ auto kept = m_channel->take_prefix(ticket);
+ auto outcome = Infrastructure::Body::SniffOutcome::Failed;
+ if (kept.has_value()) {
+ outcome = kept->state.visit(
+ [](Engine::FetchByteChannel::Open) { return Infrastructure::Body::SniffOutcome::Complete; },
+ [](Engine::FetchByteChannel::Closed) { return Infrastructure::Body::SniffOutcome::Complete; },
+ [](Engine::FetchByteChannel::Errored const&) { return Infrastructure::Body::SniffOutcome::Failed; },
+ [](Engine::FetchByteChannel::ConsumerCancelled) { return Infrastructure::Body::SniffOutcome::Failed; },
+ [](Engine::FetchByteChannel::Transferred) { return Infrastructure::Body::SniffOutcome::Failed; });
+ }
+
+ Core::ImmutableBytes resource_header;
+ if (outcome == Infrastructure::Body::SniffOutcome::Complete && !kept->taken.is_empty())
+ resource_header = kept->taken.first();
+ auto on_resource_header = exchange(m_on_resource_header, nullptr);
+ on_resource_header->function()(move(resource_header), outcome);
+}
+
Engine::WakeTicket BodyStreamPullSource::arm_waiter(Engine::FetchByteChannel::WakeOn wake_on)
{
BodyStreamWakeRegistry::the().arm(m_registry_token, *this);
@@ -161,10 +195,13 @@ BodyStreamPullSource::WakeResult BodyStreamPullSource::on_wake(Engine::WakeTicke
} else if (ticket == m_end_ticket) {
m_end_ticket = {};
on_end_wake();
+ } else if (ticket == m_resource_header_ticket) {
+ m_resource_header_ticket = {};
+ on_resource_header_wake(ticket);
}
// 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())
+ if (m_end_ticket.has_value() || m_pull_ticket.has_value() || m_push_ticket.has_value() || m_resource_header_ticket.has_value())
return WakeResult::StillAwaited;
return WakeResult::Consumed;
}
@@ -291,6 +328,8 @@ void BodyStreamPullSource::drain_into_stream()
// 1. Pull from bytes buffer into stream.
if (!result.taken.is_empty()) {
+ VERIFY(!m_on_resource_header);
+ m_has_taken_bytes = true;
ByteBuffer bytes;
for (auto const& taken : result.taken)
bytes.append(taken.bytes());
@@ -318,8 +357,10 @@ void BodyStreamPullSource::drain_into_stream()
// 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)
+GC::Ref<Infrastructure::Body> create_body_from_channel(JS::Realm& realm, GC::Ptr<Infrastructure::FetchParams const> fetch_params, NonnullRefPtr<Engine::FetchByteChannel> channel)
{
+ HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+
auto wake_sink = BodyStreamWakeSink::create();
channel->attach_consumer(wake_sink);
@@ -341,7 +382,10 @@ GC::Ref<Streams::ReadableStream> create_body_stream_from_channel(JS::Realm& real
stream->set_up_with_byte_reading_support(realm, pull_algorithm, cancel_algorithm);
pull_source->watch_channel();
- return stream;
+ auto read_resource_header = GC::create_function(GC::Heap::the(), [pull_source](Infrastructure::Body::ResourceHeaderCallback on_resource_header) {
+ pull_source->read_resource_header(on_resource_header);
+ });
+ return Infrastructure::Body::create_over_arriving_bytes(stream, read_resource_header);
}
}
diff --git a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h
index 53c88a8e376..6ccd7b3f678 100644
--- a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h
+++ b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h
@@ -12,6 +12,7 @@
#include <LibJS/Heap/Cell.h>
#include <LibWeb/Export.h>
#include <LibWeb/Fetch/Engine/FetchByteChannel.h>
+#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
#include <LibWeb/Forward.h>
namespace Web::Fetch::Fetching {
@@ -59,6 +60,10 @@ public:
// Waits for the channel to end, and while the HTML event loop is paused for its bytes too.
void watch_channel();
+ // Reads the resource header once the channel buffers it or ends, leaving its bytes in the channel. It is read
+ // before any byte is taken from the channel.
+ void read_resource_header(Infrastructure::Body::ResourceHeaderCallback);
+
private:
virtual void visit_edges(Visitor& visitor) override;
@@ -67,6 +72,7 @@ private:
void push_while_paused();
void on_push_wake();
void on_end_wake();
+ void on_resource_header_wake(Engine::WakeTicket);
void settle_without_reading();
void settle_stream(Engine::FetchByteChannel::TakeResult const&);
void run_pull_task();
@@ -84,12 +90,15 @@ private:
Optional<Engine::WakeTicket> m_end_ticket;
Optional<Engine::WakeTicket> m_pull_ticket;
Optional<Engine::WakeTicket> m_push_ticket;
+ Optional<Engine::WakeTicket> m_resource_header_ticket;
+ GC::Ptr<GC::Function<void(Core::ImmutableBytes, Infrastructure::Body::SniffOutcome)>> m_on_resource_header;
+ bool m_has_taken_bytes { false };
// Once the channel has ended, later pulls stay pending.
bool m_detached { false };
};
-// A response body's stream read from channel, which becomes the channel's consumer.
-WEB_API GC::Ref<Streams::ReadableStream> create_body_stream_from_channel(JS::Realm&, GC::Ptr<Infrastructure::FetchParams const>, NonnullRefPtr<Engine::FetchByteChannel>);
+// The view of a body whose bytes arrive through the channel; its stream's pull source is the channel's consumer.
+WEB_API GC::Ref<Infrastructure::Body> create_body_from_channel(JS::Realm&, GC::Ptr<Infrastructure::FetchParams const>, NonnullRefPtr<Engine::FetchByteChannel>);
}
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index b78b84aed83..3c162fcbb94 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -162,6 +162,22 @@ private:
GC_DEFINE_ALLOCATOR(ResponseBodyForwardingReadRequest);
+// The view of the body of response, which takes the channel the body's bytes arrive through.
+static GC::Ptr<Infrastructure::Body> create_body_view(JS::Realm& realm, Infrastructure::Response& response, GC::Ptr<Infrastructure::FetchParams const> fetch_params)
+{
+ auto body = response.body();
+ if (!body.has_value())
+ return {};
+
+ if (auto const* bytes = body->bytes().get_pointer<Core::ImmutableBytes>())
+ return Infrastructure::Body::create_over_bytes(realm, *bytes);
+
+ auto channel = body->bytes().get<NonnullRefPtr<Engine::FetchByteChannel>>();
+ auto length = body->length();
+ response.set_body(Infrastructure::ResponseBody { Infrastructure::ResponseBody::ReadThroughStream {}, length });
+ return create_body_from_channel(realm, fetch_params, move(channel));
+}
+
class HTTPCache {
public:
AK_ALLOC_WITH_KMALLOC;
@@ -214,7 +230,7 @@ static RefPtr<HTTP::MemoryCache> determine_the_http_cache_partition(Infrastructu
return HTTPCache::the().get(*partition);
}
-static GC::Ptr<Infrastructure::Response> select_response_from_cache(JS::Realm& realm, HTTP::MemoryCache& http_cache, Infrastructure::Request const& request)
+static GC::Ptr<Infrastructure::Response> select_response_from_cache(HTTP::MemoryCache& http_cache, Infrastructure::Request const& request)
{
if (!g_http_memory_cache_enabled)
return {};
@@ -234,8 +250,7 @@ static GC::Ptr<Infrastructure::Response> select_response_from_cache(JS::Realm& r
response->set_javascript_bytecode_cache_vary_key(cache_entry->javascript_bytecode_cache_vary_key);
response->set_javascript_bytecode_cache_memory_cache_request_headers(HTTP::HeaderList::create(cache_entry->request_headers->headers()));
- auto [response_body, _] = safely_extract_body(realm, cache_entry->response_body.bytes());
- response->set_body(response_body);
+ response->set_body(Infrastructure::ResponseBody::from_bytes(cache_entry->response_body));
return response;
}
@@ -881,7 +896,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam
});
// 2. If response’s body is null, then run processBodyError and abort these steps.
- if (!response->body()) {
+ if (!response->body().has_value()) {
process_body_error->function()({});
return;
}
@@ -895,14 +910,15 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam
}
// 2. Set response’s body to bytes as a body.
- response->set_body(Infrastructure::byte_sequence_as_body(realm, bytes));
+ response->set_body(Infrastructure::ResponseBody::from_bytes(Core::ImmutableBytes::adopt(move(bytes))));
// 3. Run fetch response handover given fetchParams and response.
fetch_response_handover(realm, fetch_params, *response);
});
// 4. Fully read response’s body given processBody and processBodyError.
- response->body()->fully_read(realm, process_body, process_body_error, fetch_params.task_destination());
+ auto body_view = create_body_view(realm, *response, &fetch_params);
+ body_view->fully_read(realm, process_body, process_body_error, fetch_params.task_destination());
}
// 24. Otherwise, run fetch response handover given fetchParams and response.
else {
@@ -954,7 +970,10 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
{
dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'fetch response handover' with: fetch_params @ {}, response @ {}", &fetch_params, &response);
- auto response_view = Infrastructure::ResponseView::create(response);
+ // NB: The body view takes the channel that the internal response's body arrives through.
+ auto internal_body = response.unsafe_response()->body().copy();
+ auto body_view = create_body_view(realm, *response.unsafe_response(), &fetch_params);
+ auto response_view = Infrastructure::ResponseView::create(response, body_view);
// 1. Let timingInfo be fetchParams’s timing info.
auto timing_info = fetch_params.timing_info();
@@ -1123,19 +1142,28 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
// 6. Let internalResponse be response, if response is a network error; otherwise response’s internal response.
auto internal_response = response.is_network_error() ? GC::Ref { response } : response.unsafe_response();
- // NB: The network can finish while an unread response body still has buffered bytes. Its timing must not
- // wait for the consumer to drain the stream.
- if (internal_response->body() && (fetch_params.request()->initiator_type().has_value() || (WebDriver::BiDi::g_network_events_enabled && !fetch_params.request()->is_navigation_request()))) {
- internal_response->body()->when_network_complete(GC::create_function(GC::Heap::the(), [&fetch_params, &response, setup_report_timing_steps, report_timing_if_appropriate] {
+ // AD-HOC: Report a body's timing once the network has delivered it. Fetch reports it from the flush of the
+ // transform the body is piped through, which backpressure on an unread body can hold back.
+ if (internal_body.has_value() && (fetch_params.request()->initiator_type().has_value() || (WebDriver::BiDi::g_network_events_enabled && !fetch_params.request()->is_navigation_request()))) {
+ auto network_completion_steps = GC::create_function(GC::Heap::the(), [&fetch_params, response_view, setup_report_timing_steps, report_timing_if_appropriate] {
setup_report_timing_steps();
report_timing_if_appropriate();
if (WebDriver::BiDi::g_network_events_enabled)
- WebDriver::BiDi::network_response_completed(fetch_params, *response.unsafe_response());
- }));
+ WebDriver::BiDi::network_response_completed(fetch_params, *response_view->record()->unsafe_response());
+ });
+ internal_body->bytes().visit(
+ [&](Core::ImmutableBytes const&) { network_completion_steps->function()(); },
+ [&](NonnullRefPtr<Engine::FetchByteChannel> const& channel) {
+ if (channel->peek_up_to(0).state.has<Engine::FetchByteChannel::Closed>())
+ network_completion_steps->function()();
+ else
+ fetch_params.controller()->when_network_completes_body(*channel, network_completion_steps);
+ },
+ [](Infrastructure::ResponseBody::ReadThroughStream) { });
}
- if (Core::StatsLog::the() && internal_response->body())
- track_rendering_pending_stream(fetch_params.controller().ptr(), *internal_response->body()->stream());
+ if (Core::StatsLog::the() && body_view)
+ track_rendering_pending_stream(fetch_params.controller().ptr(), *body_view->stream());
auto algorithms = fetch_params.algorithms();
@@ -1166,7 +1194,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
}
// 7. If internalResponse’s body is null, then run processResponseEndOfBody.
- if (!internal_response->body()) {
+ if (!internal_response->body().has_value()) {
process_response_end_of_body();
}
// 8. Otherwise:
@@ -1180,7 +1208,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
// support, which can no longer be read with a BYOB reader. Response bodies remain readable byte streams
// in other engines, so forward the chunks of such a stream into a new readable byte stream instead, and
// run processResponseEndOfBody once there are no more chunks, as the flush algorithm below would.
- if (auto stream = internal_response->body()->stream(); stream->is_readable_byte_stream() && !stream->is_locked()) {
+ if (auto stream = body_view->stream(); stream->is_readable_byte_stream() && !stream->is_locked()) {
auto reader = MUST(stream->get_a_reader());
auto forwarded_stream = Streams::ReadableStream::create(realm);
auto end_of_body_steps = GC::create_function(GC::Heap::the(), [process_response_end_of_body] {
@@ -1198,7 +1226,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
});
forwarded_stream->set_up_with_byte_reading_support(realm, pull_algorithm, cancel_algorithm);
- internal_response->body()->set_stream(forwarded_stream);
+ body_view->set_stream(forwarded_stream);
} else {
// 1. Let transformStream be a new TransformStream.
auto transform_stream = Streams::TransformStream::create(realm);
@@ -1220,7 +1248,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
transform_stream->set_up(realm, identity_transform_algorithm, flush_algorithm);
// 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream.
- internal_response->body()->set_stream(internal_response->body()->stream()->piped_through(transform_stream));
+ body_view->set_stream(body_view->stream()->piped_through(transform_stream));
}
break;
}
@@ -1234,7 +1262,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
process_response_end_of_body();
});
auto discard_error = GC::create_function(GC::Heap::the(), [](JS::Value) { });
- internal_response->body()->incrementally_read(realm, discard_chunk, end_of_body, discard_error, fetch_params.task_destination());
+ body_view->incrementally_read(realm, discard_chunk, end_of_body, discard_error, fetch_params.task_destination());
break;
}
case Engine::BodyIntent::SyncAccumulate:
@@ -1249,8 +1277,8 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
// 1. Let processBody given nullOrBytes be this step: run fetchParams’s process response consume body given
// response and nullOrBytes.
auto process_body = GC::create_function(GC::Heap::the(), [algorithms, &response, response_view](ByteBuffer bytes) {
- if (response.body()) {
- if (auto const& source = response.body()->source(); source.has_value()) {
+ if (auto body = response.body(); body.has_value()) {
+ if (auto source = body->source(); source.has_value()) {
(algorithms->process_response_consume_body())(response_view, *source);
return;
}
@@ -1277,7 +1305,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
// 3. If internalResponse's body is null, then queue a fetch task to run processBody given null, with
// fetchParams’s task destination.
- if (!internal_response->body()) {
+ if (!internal_response->body().has_value()) {
// AD-HOC: For a sync XHR's body, run processBody directly (see read_body_in_parallel above;
// processResponseEndOfBody already ran, right after it).
if (read_body_in_parallel) {
@@ -1314,7 +1342,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
success_steps->function()({});
fetch_params.controller()->stop_body_transport();
} else {
- auto reader = internal_response->body()->stream()->get_a_reader();
+ auto reader = body_view->stream()->get_a_reader();
if (reader.is_exception()) {
auto throw_completion = WebIDL::exception_to_throw_completion(realm.vm(), realm, reader.release_error());
process_body_error->function()(throw_completion.release_value());
@@ -1323,7 +1351,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
}
}
} else {
- internal_response->body()->fully_read(realm, process_body, process_body_error, fetch_params.task_destination());
+ body_view->fully_read(realm, process_body, process_body_error, fetch_params.task_destination());
}
}
}
@@ -1352,7 +1380,7 @@ GC::Ref<PendingResponse> scheme_fetch(JS::Realm& realm, Infrastructure::FetchPar
auto response = Infrastructure::Response::create();
response->set_status_message("OK"sv);
response->header_list()->append({ "Content-Type"sv, "text/html;charset=utf-8"sv });
- response->set_body(Infrastructure::byte_sequence_as_body(realm, ""sv.bytes()));
+ response->set_body(Infrastructure::byte_sequence_as_response_body(""sv.bytes()));
return PendingResponse::create(fetch_params, response);
}
@@ -1444,7 +1472,7 @@ GC::Ref<PendingResponse> scheme_fetch(JS::Realm& realm, Infrastructure::FetchPar
response->set_status_message("OK"sv);
// 3. Set response’s body to bodyWithType’s body.
- response->set_body(body_with_type.body);
+ response->set_body(Infrastructure::ResponseBody::from_extracted_body(body_with_type.body));
// 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ».
auto content_length_header = HTTP::Header::isomorphic_encode("Content-Length"sv, serialized_full_length);
@@ -1499,7 +1527,7 @@ GC::Ref<PendingResponse> scheme_fetch(JS::Realm& realm, Infrastructure::FetchPar
auto sliced_body_with_type = safely_extract_body(realm, sliced_blob->raw_bytes());
// 10. Set response’s body to slicedBodyWithType’s body.
- response->set_body(sliced_body_with_type.body);
+ response->set_body(Infrastructure::ResponseBody::from_extracted_body(sliced_body_with_type.body));
// 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded.
auto serialized_sliced_length = String::number(sliced_blob->size());
@@ -1551,7 +1579,7 @@ GC::Ref<PendingResponse> scheme_fetch(JS::Realm& realm, Infrastructure::FetchPar
auto header = HTTP::Header::isomorphic_encode("Content-Type"sv, mime_type);
response->header_list()->append(move(header));
- response->set_body(Infrastructure::byte_sequence_as_body(realm, data_url_struct.value().body));
+ response->set_body(Infrastructure::byte_sequence_as_response_body(data_url_struct.value().body));
return PendingResponse::create(fetch_params, response);
}
// -> "file"
@@ -2064,7 +2092,7 @@ static void process_http_network_or_cache_response(JS::Object& global_object, In
if (WebDriver::BiDi::g_network_events_enabled && authentication_handled == AuthenticationHandled::No) {
auto intercepts = WebDriver::BiDi::get_network_intercepts(fetch_params, "authRequired"sv);
if (!intercepts.is_empty()) {
- WebDriver::BiDi::block_network_request(realm.global_object(), fetch_params, response, "authRequired"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), [&realm, &fetch_params, http_request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials](WebDriver::BiDi::NetworkContinuationAction action, GC::Ptr<Infrastructure::Response> continued_response) {
+ WebDriver::BiDi::block_network_request(fetch_params, response, "authRequired"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), [&realm, &fetch_params, http_request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials](WebDriver::BiDi::NetworkContinuationAction action, GC::Ptr<Infrastructure::Response> continued_response) {
if (action == WebDriver::BiDi::NetworkContinuationAction::ProvideCredentials) {
stop_discarded_response_body(*fetch_params.controller(), *continued_response);
auto pending_response = http_network_or_cache_fetch(realm, fetch_params, IsAuthenticationFetch::Yes);
@@ -2232,7 +2260,7 @@ static GC::Ref<PendingResponse> continue_http_network_or_cache_fetch(JS::Object&
WebDriver::BiDi::synchronize_network_request(*fetch_params.request(), *http_request);
auto intercepts = WebDriver::BiDi::get_network_intercepts(*http_fetch_params, "responseStarted"sv);
if (!response->is_network_error() && !intercepts.is_empty()) {
- WebDriver::BiDi::block_network_request(realm.global_object(), *http_fetch_params, response, "responseStarted"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), [&realm, &fetch_params, http_request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials](WebDriver::BiDi::NetworkContinuationAction, GC::Ptr<Infrastructure::Response> continued_response) {
+ WebDriver::BiDi::block_network_request(*http_fetch_params, response, "responseStarted"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), [&realm, &fetch_params, http_request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials](WebDriver::BiDi::NetworkContinuationAction, GC::Ptr<Infrastructure::Response> continued_response) {
process_http_network_or_cache_response(realm.global_object(), fetch_params, *http_request, *continued_response, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials);
}));
return;
@@ -2531,7 +2559,7 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru
// validation, as per the "Constructing Responses from Caches" chapter of HTTP Caching [HTTP-CACHING],
// if any.
// NOTE: As mandated by HTTP, this still takes the `Vary` header into account.
- stored_response = select_response_from_cache(realm, *http_cache, *http_request);
+ stored_response = select_response_from_cache(*http_cache, *http_request);
// 2. If storedResponse is non-null, then:
if (stored_response) {
@@ -2562,7 +2590,7 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru
auto intercepts = WebDriver::BiDi::get_network_intercepts(*http_fetch_params, "beforeRequestSent"sv);
if (!intercepts.is_empty()) {
auto returned_pending_response = PendingResponse::create(fetch_params);
- WebDriver::BiDi::block_network_request(realm.global_object(), *http_fetch_params, nullptr, "beforeRequestSent"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), [&realm, &fetch_params, http_fetch_params, response, stored_response, http_cache, is_authentication_fetch, is_new_connection_fetch, include_credentials, returned_pending_response](WebDriver::BiDi::NetworkContinuationAction action, GC::Ptr<Infrastructure::Response> continued_response) {
+ WebDriver::BiDi::block_network_request(*http_fetch_params, nullptr, "beforeRequestSent"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), [&realm, &fetch_params, http_fetch_params, response, stored_response, http_cache, is_authentication_fetch, is_new_connection_fetch, include_credentials, returned_pending_response](WebDriver::BiDi::NetworkContinuationAction action, GC::Ptr<Infrastructure::Response> continued_response) {
// AD-HOC: The fetch can be canceled while its request is blocked.
if (fetch_params.is_canceled()) {
returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(fetch_params));
@@ -2615,9 +2643,8 @@ static URL::URL content_blocker_source_url_for_request(Infrastructure::Request&
namespace {
-// A network response's body stream and the objects that fill it from the transport.
-struct NetworkBodyStream {
- GC::Ref<Streams::ReadableStream> stream;
+// A network response's body channel and the objects that fill it from the transport.
+struct NetworkBody {
NonnullRefPtr<Engine::FetchByteChannel> channel;
NonnullRefPtr<Engine::FetchBodyDeliveryGate> delivery_gate;
GC::Ref<NetworkBodyPump> body_pump;
@@ -2626,8 +2653,8 @@ struct NetworkBodyStream {
}
// https://fetch.spec.whatwg.org/#concept-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)
+// NB: Step 9 of HTTP-network fetch. Steps 10 to 13 run in create_body_from_channel(), where the body is first read.
+static NetworkBody create_network_body(GC::Ptr<Infrastructure::FetchParams const> fetch_params, Engine::FetchBodyDeliveryGate::NavigationHold navigation_hold, RefPtr<HTTP::MemoryCache> http_cache)
{
// 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.
@@ -2637,9 +2664,8 @@ 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 stream = create_body_stream_from_channel(realm, fetch_params, channel);
- return { stream, move(channel), move(delivery_gate), body_pump };
+ return { move(channel), move(delivery_gate), body_pump };
}
// The gate detaches before the channel's ending reaches it.
@@ -2657,7 +2683,7 @@ static void tear_down_network_body(Engine::FetchBodyDeliveryGate& delivery_gate,
VERIFY_NOT_REACHED();
}
-static NonnullRefPtr<Engine::WholeBodyTransport> create_whole_body_transport(Engine::FetchBodyDeliveryGate& delivery_gate, Engine::FetchByteChannel& channel)
+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 }] {
@@ -2683,13 +2709,11 @@ GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, I
HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
// Only the bytes the navigation sniffs are delivered until it decides what the response becomes.
- auto network_body_stream = create_network_body_stream(realm, nullptr, Engine::FetchBodyDeliveryGate::NavigationHold::Held, nullptr);
- auto body = Infrastructure::Body::create(network_body_stream.stream);
- network_body_stream.body_pump->set_body(body);
- network_body_stream.body_pump->set_response(response);
+ auto network_body = create_network_body(nullptr, Engine::FetchBodyDeliveryGate::NavigationHold::Held, nullptr);
+ network_body.body_pump->set_response(response);
- auto channel = network_body_stream.channel;
- auto delivery_gate = network_body_stream.delivery_gate;
+ auto channel = network_body.channel;
+ auto delivery_gate = network_body.delivery_gate;
auto network_transport = Engine::NetworkTransportHandle::create(*request);
delivery_gate->attach_transport(network_transport);
// A request either finishes or tears down, so the observer hears the body's end once.
@@ -2701,7 +2725,7 @@ GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, I
network_settled->function()("Transferred navigation response was stopped"sv);
});
- auto body_pump = GC::make_root(network_body_stream.body_pump);
+ auto body_pump = GC::make_root(network_body.body_pump);
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) { },
@@ -2729,12 +2753,13 @@ GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, I
}
});
+ response.set_body(Infrastructure::ResponseBody { channel, {} });
response.set_network_transport({
.handle = move(network_transport),
.body_delivery_gate = move(delivery_gate),
.body_channel = move(channel),
});
- return body;
+ return create_body_view(realm, response, nullptr);
}
// https://fetch.spec.whatwg.org/#concept-http-network-fetch
@@ -2799,20 +2824,19 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
- // NB: Steps 9 to 13 run in create_network_body_stream().
+ // NB: Step 9 runs in create_network_body().
auto navigation_hold = fetch_params.has_response_body_transfer_lease()
? Engine::FetchBodyDeliveryGate::NavigationHold::Held
: Engine::FetchBodyDeliveryGate::NavigationHold::None;
- auto network_body_stream = create_network_body_stream(realm, &fetch_params, navigation_hold, http_cache);
- auto stream = network_body_stream.stream;
- auto channel = network_body_stream.channel;
- auto delivery_gate = network_body_stream.delivery_gate;
- auto body_pump = network_body_stream.body_pump;
+ auto network_body = create_network_body(&fetch_params, navigation_hold, http_cache);
+ auto channel = network_body.channel;
+ auto delivery_gate = network_body.delivery_gate;
+ auto body_pump = network_body.body_pump;
// 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, channel, delivery_gate, whole_body_transport, http_cache](Engine::NetworkTransportHandle* network_transport, 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) {
+ auto on_headers_received = GC::create_function(GC::Heap::the(), [&fetch_params, pending_response, request, body_pump, channel, delivery_gate, whole_body_transport, http_cache](Engine::NetworkTransportHandle* network_transport, 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.
@@ -2873,9 +2897,8 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
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);
- body_pump->set_body(body);
+ // NB: The stream is made from the channel where the body is first read.
+ response->set_body(Infrastructure::ResponseBody { channel, {} });
// 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.
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.h b/Libraries/LibWeb/Fetch/Fetching/Fetching.h
index af76ef268f1..67c352bcda2 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.h
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.h
@@ -59,6 +59,8 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
GC::Ref<PendingResponse> cors_preflight_fetch(JS::Realm&, Infrastructure::FetchParams const&);
// on_network_settled runs once: when the network completes the body, or with an error when the body fails or stops.
GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm&, Infrastructure::Response&, Optional<Utf16String> const& request_server_top_level_site, Requests::RequestTransferLeaseKey, RefPtr<Infrastructure::FetchTimingInfo>, Function<void(Optional<StringView> error)> on_network_settled);
+// Stopping the transport also cancels the channel.
+WEB_API NonnullRefPtr<Engine::WholeBodyTransport> create_whole_body_transport(Engine::FetchBodyDeliveryGate&, Engine::FetchByteChannel&);
void set_sec_fetch_dest_header(Infrastructure::Request&);
void set_sec_fetch_mode_header(Infrastructure::Request&);
void set_sec_fetch_site_header(Infrastructure::Request&);
diff --git a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp
index 82ef2a631b8..6ddd3a998a6 100644
--- a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp
@@ -8,6 +8,7 @@
#include <LibHTTP/Cache/MemoryCache.h>
#include <LibWeb/Fetch/Fetching/NetworkBodyPump.h>
+#include <LibWeb/Fetch/Infrastructure/FetchController.h>
#include <LibWeb/Fetch/Infrastructure/FetchParams.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
@@ -42,30 +43,11 @@ void NetworkBodyPump::update_response_body_info()
m_response->set_body_info(move(body_info));
}
-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();
- m_body->set_network_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.
@@ -113,14 +95,6 @@ void NetworkBodyPump::handle_network_data(Requests::ResponseData data)
m_channel->write_copy(bytes);
}
- // Capture bytes for MIME sniffing
- if (m_body) {
- 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())
@@ -143,25 +117,16 @@ void NetworkBodyPump::handle_network_complete(Optional<u64> encoded_body_size)
m_encoded_body_size = encoded_body_size.value_or(m_decoded_body_size);
if (m_response)
update_response_body_info();
- // Mark sniff bytes as complete when the stream ends
- if (m_body)
- m_body->set_sniff_bytes_complete();
-
finalize_cache_entry();
m_channel->close();
- if (m_body)
- m_body->set_network_complete();
+ if (m_fetch_params)
+ m_fetch_params->controller()->did_complete_network_body(*m_channel);
}
void NetworkBodyPump::handle_network_error(StringView error_message)
{
- m_network_failed = true;
if (WebDriver::BiDi::g_network_events_enabled && m_fetch_params)
WebDriver::BiDi::network_fetch_error(*m_fetch_params, error_message);
- // 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())) });
}
diff --git a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h
index 61e1262075a..23322592994 100644
--- a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h
+++ b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h
@@ -20,8 +20,8 @@
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.
+// The producer half of a streamed response body: memory-cache accumulation, and the writes into the channel the
+// stream pulls from.
class NetworkBodyPump final : public JS::Cell {
GC_CELL(NetworkBodyPump, JS::Cell);
GC_DECLARE_ALLOCATOR(NetworkBodyPump);
@@ -30,7 +30,6 @@ public:
virtual ~NetworkBodyPump() override;
void set_response(GC::Ref<Fetch::Infrastructure::Response>);
- void set_body(GC::Ref<Fetch::Infrastructure::Body> body);
void handle_network_data(Requests::ResponseData);
void handle_network_complete(Optional<u64> encoded_body_size = {});
@@ -50,16 +49,12 @@ private:
GC::Ptr<Infrastructure::FetchParams const> m_fetch_params;
GC::Ptr<Fetch::Infrastructure::Response> 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;
@@ -68,7 +63,6 @@ private:
u64 m_encoded_body_size { 0 };
u64 m_decoded_body_size { 0 };
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 1bbc033f1d0..30d8e168533 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp
@@ -41,6 +41,8 @@ void FetchController::visit_edges(JS::Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
visitor.visit(m_report_timing_steps);
+ if (m_awaited_network_completion.has_value())
+ visitor.visit(m_awaited_network_completion->steps);
visitor.visit(m_next_manual_redirect_steps);
visitor.visit(m_fetch_params);
visitor.visit(m_pending_preloaded_response);
@@ -94,6 +96,19 @@ void FetchController::process_next_manual_redirect() const
m_next_manual_redirect_steps->function()();
}
+void FetchController::when_network_completes_body(Engine::FetchByteChannel const& body, GC::Ref<GC::Function<void()>> steps)
+{
+ m_awaited_network_completion = AwaitedNetworkCompletion { body, steps };
+}
+
+void FetchController::did_complete_network_body(Engine::FetchByteChannel const& body)
+{
+ if (!m_awaited_network_completion.has_value() || m_awaited_network_completion->body.ptr() != &body)
+ return;
+ auto steps = m_awaited_network_completion.release_value().steps;
+ steps->function()();
+}
+
// https://fetch.spec.whatwg.org/#extract-full-timing-info
NonnullRefPtr<FetchTimingInfo> FetchController::extract_full_timing_info() const
{
@@ -200,6 +215,7 @@ void FetchController::stop_request()
{
end_rendering_pending_operation(this);
VERIFY(m_state != State::Ongoing);
+ m_awaited_network_completion.clear();
stop_body_transport();
}
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
index b3a5cf45a47..605996372db 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 <LibWeb/Export.h>
#include <LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h>
+#include <LibWeb/Fetch/Engine/FetchByteChannel.h>
#include <LibWeb/Fetch/Infrastructure/FetchTimingInfo.h>
#include <LibWeb/Forward.h>
#include <LibWeb/HTML/EventLoop/Task.h>
@@ -53,6 +54,11 @@ public:
void report_timing(JS::Object&) const;
void process_next_manual_redirect() const;
+
+ // Runs the steps once the network has delivered all of the body whose bytes arrive through the channel, in place of
+ // any steps set before.
+ void when_network_completes_body(Engine::FetchByteChannel const&, GC::Ref<GC::Function<void()>> steps);
+ void did_complete_network_body(Engine::FetchByteChannel const&);
[[nodiscard]] NonnullRefPtr<FetchTimingInfo> extract_full_timing_info() const;
void abort(JS::Realm&, Optional<JS::Value>);
Optional<HTML::IPCSerializationRecord> const& serialized_abort_reason() const { return m_serialized_abort_reason; }
@@ -110,6 +116,12 @@ private:
// Null or an algorithm accepting a global object.
GC::Ptr<GC::Function<void(JS::Object&)>> m_report_timing_steps;
+ struct AwaitedNetworkCompletion {
+ NonnullRefPtr<Engine::FetchByteChannel const> body;
+ GC::Ref<GC::Function<void()>> steps;
+ };
+ Optional<AwaitedNetworkCompletion> m_awaited_network_completion;
+
// https://fetch.spec.whatwg.org/#fetch-controller-report-timing-steps
// serialized abort reason (default null)
// Null or a Record (result of StructuredSerialize).
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp
index cac0b552bdc..04ab31846b0 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp
@@ -27,89 +27,71 @@ FetchBody::FetchBody(Optional<Core::ImmutableBytes> source, Optional<u64> length
{
}
-void FetchBody::append_sniff_bytes(ReadonlyBytes bytes)
+ResponseBody::ResponseBody(Bytes bytes, Optional<u64> length)
+ : m_bytes(move(bytes))
+ , m_length(length)
{
- if (m_sniff_outcome.has_value())
- return;
-
- size_t space_remaining = MAX_SNIFF_BYTES - m_sniff_bytes.size();
- if (space_remaining == 0) {
- set_sniff_bytes_complete();
- return;
- }
-
- size_t to_append = min(bytes.size(), space_remaining);
- m_sniff_bytes.append(bytes.slice(0, to_append));
-
- if (m_sniff_bytes.size() >= MAX_SNIFF_BYTES)
- set_sniff_bytes_complete();
}
-void FetchBody::set_sniff_bytes_complete()
+ResponseBody ResponseBody::from_bytes(Core::ImmutableBytes bytes)
{
- if (!m_sniff_outcome.has_value())
- m_sniff_outcome = SniffOutcome::Complete;
+ auto length = bytes.size();
+ return ResponseBody { move(bytes), length };
}
-void FetchBody::set_sniff_bytes_failed()
+ResponseBody ResponseBody::from_extracted_body(Body const& body)
{
- if (!m_sniff_outcome.has_value())
- m_sniff_outcome = SniffOutcome::Failed;
+ if (auto const& source = body.source(); source.has_value())
+ return ResponseBody { *source, body.length() };
+ return ResponseBody { ReadThroughStream {}, body.length() };
}
-Optional<FetchBody::SniffBytes> FetchBody::sniff_bytes_if_available() const
+Optional<Core::ImmutableBytes const&> ResponseBody::source() const
{
- // Non-streaming body: source has bytes
- if (m_source.has_value()) {
- auto bytes = m_source->bytes();
- return SniffBytes { bytes.slice(0, min(bytes.size(), MAX_SNIFF_BYTES)) };
- }
-
- // Streaming body: bytes captured during fetch
- if (m_sniff_outcome.has_value())
- return SniffBytes { m_sniff_bytes, *m_sniff_outcome };
-
- // Still waiting for bytes
+ if (auto const* bytes = m_bytes.get_pointer<Core::ImmutableBytes>())
+ return *bytes;
return {};
}
GC::Ref<Body> Body::create(GC::Ref<Streams::ReadableStream> stream, FetchBody fetch_body)
{
- return GC::Heap::the().allocate<Body>(stream, move(fetch_body));
+ return GC::Heap::the().allocate<Body>(stream, move(fetch_body), NeverSniffed {});
}
-// NB: Source-backed bodies are complete even when their streams still have queued bytes.
-Body::Body(GC::Ref<Streams::ReadableStream> stream, FetchBody fetch_body)
- : m_stream(stream)
- , m_fetch_body(move(fetch_body))
- , m_network_complete(m_fetch_body.source().has_value() || stream->is_closed())
+GC::Ref<Body> Body::create_over_bytes(JS::Realm& realm, Core::ImmutableBytes bytes)
{
+ auto [extracted_body, _] = safely_extract_body(realm, bytes);
+ auto resource_header = bytes.slice(0, min(bytes.size(), MAX_SNIFF_BYTES));
+ return GC::Heap::the().allocate<Body>(extracted_body->stream(), FetchBody {}, ReadResourceHeader { move(resource_header) });
}
-void Body::visit_edges(Cell::Visitor& visitor)
+GC::Ref<Body> Body::create_over_arriving_bytes(GC::Ref<Streams::ReadableStream> stream, ResourceHeaderReader reader)
{
- Base::visit_edges(visitor);
- visitor.visit(m_stream);
- visitor.visit(m_sniff_bytes_callback);
- visitor.visit(m_network_complete_callback);
+ return GC::Heap::the().allocate<Body>(stream, FetchBody {}, UnreadResourceHeader { reader });
}
-void Body::append_sniff_bytes(ReadonlyBytes bytes)
+Body::Body(GC::Ref<Streams::ReadableStream> stream, FetchBody fetch_body, ResourceHeader resource_header)
+ : m_stream(stream)
+ , m_fetch_body(move(fetch_body))
+ , m_resource_header(move(resource_header))
{
- m_fetch_body.append_sniff_bytes(bytes);
- notify_sniff_bytes_waiter();
}
-void Body::set_sniff_bytes_complete()
+void Body::visit_edges(Cell::Visitor& visitor)
{
- m_fetch_body.set_sniff_bytes_complete();
- notify_sniff_bytes_waiter();
+ Base::visit_edges(visitor);
+ visitor.visit(m_stream);
+ if (auto const* unread = m_resource_header.get_pointer<UnreadResourceHeader>())
+ visitor.visit(unread->reader);
+ visitor.visit(m_sniff_bytes_callback);
}
-void Body::set_sniff_bytes_failed()
+Optional<Body::SniffBytes> Body::sniff_bytes_if_available() const
{
- m_fetch_body.set_sniff_bytes_failed();
- notify_sniff_bytes_waiter();
+ VERIFY(!m_resource_header.has<NeverSniffed>());
+ if (auto const* read = m_resource_header.get_pointer<ReadResourceHeader>())
+ return SniffBytes { read->bytes.bytes(), read->outcome };
+ return {};
}
void Body::wait_for_sniff_bytes(SniffBytesCallback on_ready)
@@ -119,44 +101,31 @@ void Body::wait_for_sniff_bytes(SniffBytesCallback on_ready)
return;
}
- // Wait for bytes to arrive
+ VERIFY(!m_sniff_bytes_callback);
m_sniff_bytes_callback = on_ready;
+
+ auto const* unread = m_resource_header.get_pointer<UnreadResourceHeader>();
+ if (!unread)
+ return;
+ auto reader = unread->reader;
+ m_resource_header = ReadingResourceHeader {};
+ reader->function()(GC::create_function(heap(), [body = GC::Ref { *this }](Core::ImmutableBytes bytes, SniffOutcome outcome) {
+ body->did_read_resource_header(move(bytes), outcome);
+ }));
}
-void Body::notify_sniff_bytes_waiter()
+void Body::did_read_resource_header(Core::ImmutableBytes bytes, SniffOutcome outcome)
{
- if (!m_sniff_bytes_callback || m_sniff_bytes_wake_queued || !sniff_bytes_if_available().has_value())
- return;
+ VERIFY(m_resource_header.has<ReadingResourceHeader>());
+ m_resource_header = ReadResourceHeader { move(bytes), outcome };
- m_sniff_bytes_wake_queued = true;
auto steps = GC::create_function(heap(), [body = GC::Ref { *this }] {
- body->m_sniff_bytes_wake_queued = false;
- auto sniff_bytes = body->sniff_bytes_if_available();
- if (!body->m_sniff_bytes_callback || !sniff_bytes.has_value())
- return;
auto callback = exchange(body->m_sniff_bytes_callback, nullptr);
- callback->function()(sniff_bytes.value());
+ callback->function()(*body->sniff_bytes_if_available());
});
HTML::queue_a_task(HTML::Task::Source::Networking, HTML::main_thread_event_loop(), nullptr, steps);
}
-void Body::when_network_complete(ProcessEndOfBodyCallback callback)
-{
- if (m_network_complete) {
- callback->function()();
- return;
- }
- VERIFY(!m_network_complete_callback);
- m_network_complete_callback = callback;
-}
-
-void Body::set_network_complete()
-{
- m_network_complete = true;
- if (auto callback = exchange(m_network_complete_callback, nullptr))
- callback->function()();
-}
-
// https://fetch.spec.whatwg.org/#concept-body-clone
GC::Ref<Body> Body::clone(JS::Realm& realm)
{
@@ -254,6 +223,13 @@ GC::Ref<Body> byte_sequence_as_body(JS::Realm& realm, ReadonlyBytes bytes)
return body;
}
+// https://fetch.spec.whatwg.org/#byte-sequence-as-a-body
+// NB: The body's stream is made from its bytes where the body is first read.
+ResponseBody byte_sequence_as_response_body(ReadonlyBytes bytes)
+{
+ return ResponseBody::from_bytes(MUST(Core::ImmutableBytes::copy(bytes)));
+}
+
void cancel_incremental_read(Streams::ReadableStreamDefaultReader& reader)
{
reader.cancel({});
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h
index dea57deb0ed..4f29ce959ac 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h
@@ -16,6 +16,7 @@
#include <LibGC/Ptr.h>
#include <LibGC/Root.h>
#include <LibWeb/Export.h>
+#include <LibWeb/Fetch/Engine/FetchByteChannel.h>
#include <LibWeb/Fetch/Infrastructure/Task.h>
#include <LibWeb/Streams/ReadableStream.h>
#include <LibWeb/WebIDL/Promise.h>
@@ -25,7 +26,7 @@ namespace Web::Fetch::Infrastructure {
// https://mimesniff.spec.whatwg.org/#reading-the-resource-header
static constexpr size_t MAX_SNIFF_BYTES = 1445;
-// A body's source, length and sniff bytes, without its stream.
+// A body's source and length, without its stream.
class WEB_API FetchBody {
public:
FetchBody() = default;
@@ -40,27 +41,6 @@ public:
[[nodiscard]] Optional<Core::ImmutableBytes> const& source() const { return m_source; }
[[nodiscard]] Optional<u64> const& length() const { return m_length; }
- // https://mimesniff.spec.whatwg.org/#reading-the-resource-header
- // Non-standard infrastructure to obtain the "resource header" for MIME type sniffing.
- // The spec defines resource header as the byte sequence to sniff, obtained by reading
- // "until [...] 1445 or more bytes have been read" or end of resource is reached.
- // For a body with a source, bytes are available immediately.
- // For streaming bodies, bytes are captured during fetch.
- enum class SniffOutcome : u8 {
- Complete,
- Failed,
- };
- struct SniffBytes {
- ReadonlyBytes bytes;
- SniffOutcome outcome { SniffOutcome::Complete };
- };
- Optional<SniffBytes> sniff_bytes_if_available() const;
-
- // Failed reports a response that died mid-body, whose partial bytes are not sniffable.
- void append_sniff_bytes(ReadonlyBytes bytes);
- void set_sniff_bytes_complete();
- void set_sniff_bytes_failed();
-
private:
// https://fetch.spec.whatwg.org/#concept-body-source
// A source (null, a byte sequence, a Blob object, or a FormData object), initially null.
@@ -70,11 +50,31 @@ private:
// https://fetch.spec.whatwg.org/#concept-body-total-bytes
// A length (null or an integer), initially null.
Optional<u64> m_length;
+};
- // https://mimesniff.spec.whatwg.org/#reading-the-resource-header
- // Non-standard: Captured "resource header" bytes for MIME type sniffing.
- ByteBuffer m_sniff_bytes;
- Optional<SniffOutcome> m_sniff_outcome;
+// A response's body as fetch keeps it: its length and where its bytes are.
+class WEB_API ResponseBody {
+public:
+ // The bytes are read through a stream outside fetch.
+ struct ReadThroughStream { };
+ using Bytes = Variant<Core::ImmutableBytes, NonnullRefPtr<Engine::FetchByteChannel>, ReadThroughStream>;
+
+ ResponseBody(Bytes, Optional<u64> length);
+
+ [[nodiscard]] static ResponseBody from_bytes(Core::ImmutableBytes);
+ [[nodiscard]] static ResponseBody from_extracted_body(Body const&);
+
+ [[nodiscard]] Bytes const& bytes() const { return m_bytes; }
+
+ // https://fetch.spec.whatwg.org/#concept-body-source
+ [[nodiscard]] Optional<Core::ImmutableBytes const&> source() const;
+
+ // https://fetch.spec.whatwg.org/#concept-body-total-bytes
+ [[nodiscard]] Optional<u64> const& length() const { return m_length; }
+
+private:
+ Bytes m_bytes;
+ Optional<u64> m_length;
};
// https://fetch.spec.whatwg.org/#concept-body
@@ -92,7 +92,25 @@ public:
// processEndOfBody must be an algorithm accepting no arguments
using ProcessEndOfBodyCallback = GC::Ref<GC::Function<void()>>;
+ // https://mimesniff.spec.whatwg.org/#reading-the-resource-header
+ // The resource header is the first 1445 bytes, or all of a shorter body; a body that errored first is Failed.
+ enum class SniffOutcome : u8 {
+ Complete,
+ Failed,
+ };
+ struct SniffBytes {
+ ReadonlyBytes bytes;
+ SniffOutcome outcome { SniffOutcome::Complete };
+ };
+ using SniffBytesCallback = GC::Ref<GC::Function<void(SniffBytes)>>;
+ using ResourceHeaderCallback = GC::Ref<GC::Function<void(Core::ImmutableBytes, SniffOutcome)>>;
+ using ResourceHeaderReader = GC::Ref<GC::Function<void(ResourceHeaderCallback)>>;
+
+ // A body that extraction made keeps its source and length, and is never sniffed.
[[nodiscard]] static GC::Ref<Body> create(GC::Ref<Streams::ReadableStream>, FetchBody = {});
+ [[nodiscard]] static GC::Ref<Body> create_over_bytes(JS::Realm&, Core::ImmutableBytes);
+ // The reader reads the resource header from where the body's bytes arrive.
+ [[nodiscard]] static GC::Ref<Body> create_over_arriving_bytes(GC::Ref<Streams::ReadableStream>, ResourceHeaderReader);
[[nodiscard]] GC::Ref<Streams::ReadableStream> stream() const { return *m_stream; }
void set_stream(GC::Ref<Streams::ReadableStream> value) { m_stream = value; }
@@ -100,18 +118,10 @@ public:
[[nodiscard]] Optional<Core::ImmutableBytes> const& source() const { return m_fetch_body.source(); }
[[nodiscard]] Optional<u64> const& length() const { return m_fetch_body.length(); }
- using SniffBytesCallback = GC::Ref<GC::Function<void(FetchBody::SniffBytes)>>;
- Optional<FetchBody::SniffBytes> sniff_bytes_if_available() const { return m_fetch_body.sniff_bytes_if_available(); }
+ [[nodiscard]] Optional<SniffBytes> sniff_bytes_if_available() const;
+ // A waiter runs at once if the resource header is available, and otherwise once, from a networking task.
void wait_for_sniff_bytes(SniffBytesCallback on_ready);
- // Sniff bytes becoming available wake a pending waiter once, from a networking task.
- void append_sniff_bytes(ReadonlyBytes bytes);
- void set_sniff_bytes_complete();
- void set_sniff_bytes_failed();
-
- void when_network_complete(ProcessEndOfBodyCallback);
- void set_network_complete();
-
[[nodiscard]] GC::Ref<Body> clone(JS::Realm&);
void fully_read(JS::Realm&, ProcessBodyCallback process_body, ProcessBodyErrorCallback process_body_error, TaskDestination) const;
@@ -122,9 +132,20 @@ public:
virtual void visit_edges(JS::Cell::Visitor&) override;
private:
- Body(GC::Ref<Streams::ReadableStream>, FetchBody);
+ struct NeverSniffed { };
+ struct UnreadResourceHeader {
+ ResourceHeaderReader reader;
+ };
+ struct ReadingResourceHeader { };
+ struct ReadResourceHeader {
+ Core::ImmutableBytes bytes;
+ SniffOutcome outcome { SniffOutcome::Complete };
+ };
+ using ResourceHeader = Variant<NeverSniffed, UnreadResourceHeader, ReadingResourceHeader, ReadResourceHeader>;
+
+ Body(GC::Ref<Streams::ReadableStream>, FetchBody, ResourceHeader);
- void notify_sniff_bytes_waiter();
+ void did_read_resource_header(Core::ImmutableBytes, SniffOutcome);
// https://fetch.spec.whatwg.org/#concept-body-stream
// A stream (a ReadableStream object).
@@ -132,10 +153,8 @@ private:
FetchBody m_fetch_body;
- GC::Ptr<GC::Function<void(FetchBody::SniffBytes)>> m_sniff_bytes_callback;
- GC::Ptr<GC::Function<void()>> m_network_complete_callback;
- bool m_network_complete { false };
- bool m_sniff_bytes_wake_queued { false };
+ ResourceHeader m_resource_header;
+ GC::Ptr<GC::Function<void(SniffBytes)>> m_sniff_bytes_callback;
};
// https://fetch.spec.whatwg.org/#body-with-type
@@ -146,6 +165,7 @@ struct BodyWithType {
};
WEB_API GC::Ref<Body> byte_sequence_as_body(JS::Realm&, ReadonlyBytes);
+WEB_API ResponseBody byte_sequence_as_response_body(ReadonlyBytes);
WEB_API void cancel_incremental_read(Streams::ReadableStreamDefaultReader&);
}
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.cpp
index 03bd778f2c2..95c3c992320 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.cpp
@@ -11,23 +11,33 @@ namespace Web::Fetch::Infrastructure {
GC_DEFINE_ALLOCATOR(ResponseView);
-GC::Ref<ResponseView> ResponseView::create(GC::Ref<Response> record)
+GC::Ref<ResponseView> ResponseView::create(GC::Ref<Response> record, GC::Ptr<Body> body_view)
{
- return GC::Heap::the().allocate<ResponseView>(record);
+ VERIFY(record->unsafe_response()->body().has_value() == (body_view != nullptr));
+ return GC::Heap::the().allocate<ResponseView>(record, body_view);
+}
+
+GC::Ref<ResponseView> ResponseView::create(JS::Realm& realm, GC::Ref<Response> record)
+{
+ auto body = record->unsafe_response()->body();
+ if (!body.has_value())
+ return create(record, nullptr);
+ return create(record, Body::create_over_bytes(realm, body->bytes().get<Core::ImmutableBytes>()));
}
GC::Ref<ResponseView> ResponseView::network_error(String message)
{
- return create(Response::network_error(move(message)));
+ return create(Response::network_error(move(message)), nullptr);
}
GC::Ref<ResponseView> ResponseView::aborted_network_error()
{
- return create(Response::aborted_network_error());
+ return create(Response::aborted_network_error(), nullptr);
}
-ResponseView::ResponseView(GC::Ref<Response> record)
+ResponseView::ResponseView(GC::Ref<Response> record, GC::Ptr<Body> body_view)
: m_record(record)
+ , m_body_view(body_view)
{
}
@@ -35,6 +45,24 @@ void ResponseView::visit_edges(Visitor& visitor)
{
Base::visit_edges(visitor);
visitor.visit(m_record);
+ visitor.visit(m_body_view);
+}
+
+Optional<u64> ResponseView::body_length() const
+{
+ if (auto body = m_record->body(); body.has_value())
+ return body->length();
+ return {};
+}
+
+Optional<Core::ImmutableBytes> ResponseView::body_source() const
+{
+ auto body = m_record->body();
+ if (!body.has_value())
+ return {};
+ if (auto source = body->source(); source.has_value())
+ return *source;
+ return {};
}
// https://html.spec.whatwg.org/multipage/urls-and-fetching.html#unsafe-response
@@ -43,13 +71,14 @@ GC::Ref<ResponseView> ResponseView::unsafe_response()
auto unsafe_response = m_record->unsafe_response();
if (unsafe_response == m_record)
return *this;
- return create(unsafe_response);
+ return create(unsafe_response, m_body_view);
}
// https://fetch.spec.whatwg.org/#concept-response-clone
GC::Ref<ResponseView> ResponseView::clone(JS::Realm& realm) const
{
- return create(m_record->clone(realm));
+ auto body_view = m_body_view ? m_body_view->clone(realm) : GC::Ptr<Body> {};
+ return create(m_record->clone(), body_view);
}
}
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h
index 04f257c8c54..4a695298eb7 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h
@@ -19,7 +19,10 @@ class WEB_API ResponseView final : public JS::Cell {
GC_DECLARE_ALLOCATOR(ResponseView);
public:
- [[nodiscard]] static GC::Ref<ResponseView> create(GC::Ref<Response>);
+ // body_view is the view of the body of record's unsafe response.
+ [[nodiscard]] static GC::Ref<ResponseView> create(GC::Ref<Response> record, GC::Ptr<Body> body_view);
+ // The body of record's unsafe response is null or bytes.
+ [[nodiscard]] static GC::Ref<ResponseView> create(JS::Realm&, GC::Ref<Response> record);
[[nodiscard]] static GC::Ref<ResponseView> network_error(String message);
[[nodiscard]] static GC::Ref<ResponseView> aborted_network_error();
@@ -31,7 +34,9 @@ public:
[[nodiscard]] Status status() const { return m_record->status(); }
[[nodiscard]] ByteString const& status_message() const { return m_record->status_message(); }
[[nodiscard]] NonnullRefPtr<HTTP::HeaderList> const& header_list() const { return m_record->header_list(); }
- [[nodiscard]] GC::Ptr<Body> body() const { return m_record->body(); }
+ [[nodiscard]] GC::Ptr<Body> body() const { return m_record->body().has_value() ? m_body_view : nullptr; }
+ [[nodiscard]] Optional<u64> body_length() const;
+ [[nodiscard]] Optional<Core::ImmutableBytes> body_source() const;
[[nodiscard]] Optional<Response::CacheState> const& cache_state() const { return m_record->cache_state(); }
[[nodiscard]] bool timing_allow_passed() const { return m_record->timing_allow_passed(); }
[[nodiscard]] Vector<Vector<String>> const& navigation_timing_allow_values_list() const { return m_record->navigation_timing_allow_values_list(); }
@@ -60,11 +65,12 @@ public:
[[nodiscard]] Vector<Core::ImmutableBytes> release_body_for_transfer() const { return m_record->release_body_for_transfer(); }
private:
- explicit ResponseView(GC::Ref<Response>);
+ ResponseView(GC::Ref<Response>, GC::Ptr<Body>);
virtual void visit_edges(Visitor&) override;
GC::Ref<Response> m_record;
+ GC::Ptr<Body> m_body_view;
};
}
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
index 917563df577..29a7a356a67 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
@@ -40,12 +40,6 @@ Response::Response(NonnullRefPtr<HTTP::HeaderList> header_list)
{
}
-void Response::visit_edges(JS::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_body);
-}
-
// https://fetch.spec.whatwg.org/#ref-for-concept-network-error%E2%91%A3
// A network error is a response whose status is always 0, status message is always
// the empty byte sequence, header list is always empty, and body is always null.
@@ -63,7 +57,7 @@ GC::Ref<Response> Response::network_error(String message)
auto response = Response::create();
response->set_status(0);
response->set_type(Type::Error);
- VERIFY(!response->body());
+ VERIFY(!response->body().has_value());
response->m_network_error_message = move(message);
return response;
}
@@ -107,7 +101,7 @@ bool Response::is_network_error() const
return false;
if (!header_list()->is_empty())
return false;
- if (body())
+ if (body().has_value())
return false;
if (body_info() != BodyInfo {})
return false;
@@ -186,12 +180,12 @@ ErrorOr<Optional<URL::URL>> Response::location_url(Optional<StringView> request_
}
// https://fetch.spec.whatwg.org/#concept-response-clone
-GC::Ref<Response> Response::clone(JS::Realm& realm) const
+GC::Ref<Response> Response::clone() const
{
// To clone a response response, run these steps:
// 1. If response is a filtered response, then return a new identical filtered response whose internal response is a clone of response’s internal response.
if (is<FilteredResponse>(*this)) {
- auto internal_response = static_cast<FilteredResponse const&>(*this).internal_response()->clone(realm);
+ auto internal_response = static_cast<FilteredResponse const&>(*this).internal_response()->clone();
if (is<BasicFilteredResponse>(*this))
return BasicFilteredResponse::create(internal_response);
if (is<CORSFilteredResponse>(*this))
@@ -229,8 +223,12 @@ GC::Ref<Response> Response::clone(JS::Realm& realm) const
// FIXME: service worker timing info
// 3. If response’s body is non-null, then set newResponse’s body to the result of cloning response’s body.
- if (m_body)
- new_response->set_body(m_body->clone(realm));
+ // NB: ResponseView::clone() tees the body's stream, and a response whose bytes are still in a channel is never
+ // cloned.
+ if (m_body.has_value()) {
+ VERIFY(!m_body->bytes().has<NonnullRefPtr<Engine::FetchByteChannel>>());
+ new_response->set_body(*m_body);
+ }
// 4. Return newResponse.
return new_response;
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h
index f800caf9bb7..41708dbcafa 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h
@@ -95,8 +95,8 @@ public:
virtual NonnullRefPtr<HTTP::HeaderList> const& header_list() const { return m_header_list; }
virtual void set_header_list(NonnullRefPtr<HTTP::HeaderList> header_list) { m_header_list = move(header_list); }
- [[nodiscard]] virtual GC::Ptr<Body> body() const { return m_body; }
- virtual void set_body(GC::Ptr<Body> body) { m_body = body; }
+ [[nodiscard]] virtual Optional<ResponseBody const&> body() const { return m_body; }
+ virtual void set_body(Optional<ResponseBody> body) { m_body = move(body); }
[[nodiscard]] virtual Optional<CacheState> const& cache_state() const { return m_cache_state; }
virtual void set_cache_state(Optional<CacheState> cache_state) { m_cache_state = move(cache_state); }
@@ -135,7 +135,7 @@ public:
[[nodiscard]] Optional<URL::URL const&> url() const;
[[nodiscard]] ErrorOr<Optional<URL::URL>> location_url(Optional<StringView> request_fragment) const;
- [[nodiscard]] GC::Ref<Response> clone(JS::Realm&) const;
+ [[nodiscard]] GC::Ref<Response> clone() const;
[[nodiscard]] GC::Ref<Response> unsafe_response();
@@ -158,8 +158,6 @@ public:
protected:
explicit Response(NonnullRefPtr<HTTP::HeaderList>);
- virtual void visit_edges(JS::Cell::Visitor&) override;
-
private:
// https://fetch.spec.whatwg.org/#concept-response-type
// A response has an associated type which is "basic", "cors", "default", "error", "opaque", or "opaqueredirect". Unless stated otherwise, it is "default".
@@ -187,7 +185,7 @@ private:
// https://fetch.spec.whatwg.org/#concept-response-body
// A response has an associated body (null or a body). Unless stated otherwise it is null.
- GC::Ptr<Body> m_body;
+ Optional<ResponseBody> m_body;
// https://fetch.spec.whatwg.org/#concept-response-cache-state
// A response has an associated cache state (the empty string, "local", or "validated"). Unless stated otherwise, it is the empty string.
@@ -265,8 +263,8 @@ public:
virtual NonnullRefPtr<HTTP::HeaderList> const& header_list() const override { return m_internal_response->header_list(); }
virtual void set_header_list(NonnullRefPtr<HTTP::HeaderList> header_list) override { m_internal_response->set_header_list(header_list); }
- [[nodiscard]] virtual GC::Ptr<Body> body() const override { return m_internal_response->body(); }
- virtual void set_body(GC::Ptr<Body> body) override { m_internal_response->set_body(body); }
+ [[nodiscard]] virtual Optional<ResponseBody const&> body() const override { return m_internal_response->body(); }
+ virtual void set_body(Optional<ResponseBody> body) override { m_internal_response->set_body(move(body)); }
[[nodiscard]] virtual Optional<CacheState> const& cache_state() const override { return m_internal_response->cache_state(); }
virtual void set_cache_state(Optional<CacheState> cache_state) override { m_internal_response->set_cache_state(move(cache_state)); }
@@ -356,7 +354,7 @@ public:
[[nodiscard]] virtual Status status() const override { return 0; }
[[nodiscard]] virtual ByteString const& status_message() const override { return m_method; }
virtual NonnullRefPtr<HTTP::HeaderList> const& header_list() const override { return m_header_list; }
- [[nodiscard]] virtual GC::Ptr<Body> body() const override { return nullptr; }
+ [[nodiscard]] virtual Optional<ResponseBody const&> body() const override { return {}; }
private:
OpaqueFilteredResponse(GC::Ref<Response>, NonnullRefPtr<HTTP::HeaderList>);
@@ -378,7 +376,7 @@ public:
[[nodiscard]] virtual Status status() const override { return 0; }
[[nodiscard]] virtual ByteString const& status_message() const override { return m_method; }
virtual NonnullRefPtr<HTTP::HeaderList> const& header_list() const override { return m_header_list; }
- [[nodiscard]] virtual GC::Ptr<Body> body() const override { return nullptr; }
+ [[nodiscard]] virtual Optional<ResponseBody const&> body() const override { return {}; }
private:
OpaqueRedirectFilteredResponse(GC::Ref<Response>, NonnullRefPtr<HTTP::HeaderList>);
diff --git a/Libraries/LibWeb/Fetch/Response.cpp b/Libraries/LibWeb/Fetch/Response.cpp
index 17da9c1307b..fb895277df8 100644
--- a/Libraries/LibWeb/Fetch/Response.cpp
+++ b/Libraries/LibWeb/Fetch/Response.cpp
@@ -132,14 +132,15 @@ WebIDL::ExceptionOr<GC::Ref<Response>> Response::create_with_body(ResponseInit c
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Response with null body status cannot have a body"_utf16 };
// 2. Set response’s body to body’s body.
- response->set_body(body->body);
+ response->set_body(Infrastructure::ResponseBody::from_extracted_body(body->body));
// 3. If body’s type is non-null and response’s header list does not contain `Content-Type`, then append (`Content-Type`, body’s type) to response’s header list.
if (body->type.has_value() && !response->header_list()->contains("Content-Type"sv))
response->header_list()->append(HTTP::Header::isomorphic_encode("Content-Type"sv, *body->type));
}
- auto response_object = create(Infrastructure::ResponseView::create(response));
+ auto body_view = body.has_value() ? GC::Ptr<Infrastructure::Body> { body->body } : nullptr;
+ auto response_object = create(Infrastructure::ResponseView::create(response, body_view));
response_object->m_headers = headers;
return response_object;
}
@@ -182,7 +183,7 @@ WebIDL::ExceptionOr<GC::Ref<Response>> Response::redirect(Utf16String const& url
response->header_list()->append(move(header));
// 4. Let responseObject be the result of creating a Response object, given a new response, "immutable", and the current realm.
- auto response_object = Response::create(Infrastructure::ResponseView::create(response), Headers::Guard::Immutable);
+ auto response_object = Response::create(Infrastructure::ResponseView::create(response, nullptr), Headers::Guard::Immutable);
// 8. Return responseObject.
return response_object;
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 90083dfab98..8fd9abf19e4 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -558,7 +558,10 @@ class Response;
namespace Web::Fetch::Engine {
+class FetchBodyDeliveryGate;
+class FetchByteChannel;
class NetworkTransportHandle;
+class WholeBodyTransport;
}
diff --git a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp b/Libraries/LibWeb/HTML/HTMLLinkElement.cpp
index 92c507549c8..c2d9c915e1d 100644
--- a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLLinkElement.cpp
@@ -1030,14 +1030,14 @@ void HTMLLinkElement::preload(LinkProcessingOptions& options, Function<void(Fetc
// 11. Set controller to the result of fetching request, with processResponseConsumeBody set to the following steps
// given a response response and null, failure, or a byte sequence bodyBytes:
Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };
- fetch_algorithms_input.process_response_consume_body = [&realm, options = GC::Ref { options }, process_response = move(process_response), entry, report_timing](GC::Ref<Fetch::Infrastructure::ResponseView> response_view, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {
+ fetch_algorithms_input.process_response_consume_body = [options = GC::Ref { options }, process_response = move(process_response), entry, report_timing](GC::Ref<Fetch::Infrastructure::ResponseView> response_view, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {
// FIXME: If the response is CORS cross-origin, we must use its internal response to query any of its data. See:
// https://github.com/whatwg/html/issues/9355
auto response = response_view->record()->unsafe_response();
// 1. If bodyBytes is a byte sequence, then set response's body to bodyBytes as a body.
if (auto* byte_sequence = body_bytes.get_pointer<Core::ImmutableBytes>())
- response->set_body(Fetch::Infrastructure::byte_sequence_as_body(realm, byte_sequence->bytes()));
+ response->set_body(Fetch::Infrastructure::ResponseBody::from_bytes(*byte_sequence));
// 2. Otherwise, set response to a network error.
else
response = Fetch::Infrastructure::Response::network_error("Expected preload response to contain a body"_string);
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index 67cfd7a51a7..c46ed05b45a 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -2150,7 +2150,7 @@ static GC::Ref<NavigationParams> create_navigation_params_from_a_srcdoc_resource
response->url_list().append(URL::about_srcdoc());
response->header_list()->append({ "Content-Type"sv, "text/html"sv });
auto document_resource_utf8 = MUST(document_resource.get<Utf16String>().utf16_view().to_utf8());
- response->set_body(Fetch::Infrastructure::byte_sequence_as_body(realm, document_resource_utf8.bytes()));
+ response->set_body(Fetch::Infrastructure::byte_sequence_as_response_body(document_resource_utf8.bytes()));
// 3. Let responseOrigin be the result of determining the origin given response's URL, targetSnapshotParams's sandboxing flags, and entry's document state's origin.
auto response_origin = determine_the_origin(response->url(), target_snapshot_params.sandboxing_flags, origin);
@@ -2209,7 +2209,7 @@ static GC::Ref<NavigationParams> create_navigation_params_from_a_srcdoc_resource
move(navigation_id),
navigable,
nullptr,
- Fetch::Infrastructure::ResponseView::create(response),
+ Fetch::Infrastructure::ResponseView::create(realm, response),
nullptr,
nullptr,
move(coop_enforcement_result),
@@ -3190,20 +3190,20 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent
// Get sniff bytes for MIME type detection. For streaming responses where bytes
// haven't arrived yet, we must wait asynchronously.
- auto sniff_bytes = body ? body->sniff_bytes_if_available() : Optional<Fetch::Infrastructure::FetchBody::SniffBytes> { Fetch::Infrastructure::FetchBody::SniffBytes {} };
+ auto sniff_bytes = body ? body->sniff_bytes_if_available() : Optional<Fetch::Infrastructure::Body::SniffBytes> { Fetch::Infrastructure::Body::SniffBytes {} };
if (!sniff_bytes.has_value()) {
// Async path: bytes not yet available, wait for them
nav_params->response->resume_body_delivery_up_to(Fetch::Infrastructure::MAX_SNIFF_BYTES);
body->wait_for_sniff_bytes(GC::create_function(heap(),
- [output, nav_params, navigation_params, completion_steps, source_allows_downloading, source_interface_origin, url](Fetch::Infrastructure::FetchBody::SniffBytes sniff_bytes) {
+ [output, nav_params, navigation_params, completion_steps, source_allows_downloading, source_interface_origin, url](Fetch::Infrastructure::Body::SniffBytes sniff_bytes) {
// AD-HOC: The document may have been destroyed between when the fetch started and when the
// bytes arrived. A response that failed mid-sniff must not be loaded as a document
// off its partial bytes either.
- if (nav_params->navigable->active_browsing_context() && sniff_bytes.outcome == Fetch::Infrastructure::FetchBody::SniffOutcome::Complete) {
+ if (nav_params->navigable->active_browsing_context() && sniff_bytes.outcome == Fetch::Infrastructure::Body::SniffOutcome::Complete) {
load_document_or_handle_download(nav_params, sniff_bytes.bytes, url, source_allows_downloading, source_interface_origin, *output);
} else {
stop_response_body_delivery(navigation_params);
- if (sniff_bytes.outcome == Fetch::Infrastructure::FetchBody::SniffOutcome::Failed)
+ if (sniff_bytes.outcome == Fetch::Infrastructure::Body::SniffOutcome::Failed)
output->save_extra_document_state = false;
}
output->navigation_params = navigation_params;
@@ -3215,7 +3215,7 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent
}
// Sync path: bytes available immediately
- if (sniff_bytes->outcome == Fetch::Infrastructure::FetchBody::SniffOutcome::Complete) {
+ if (sniff_bytes->outcome == Fetch::Infrastructure::Body::SniffOutcome::Complete) {
load_document_or_handle_download(nav_params, sniff_bytes->bytes, url, source_allows_downloading, source_interface_origin, *output);
} else {
stop_response_body_delivery(navigation_params);
@@ -4055,7 +4055,7 @@ GC::Ptr<DOM::Document> LocalNavigable::evaluate_javascript_url(URL::URL const& u
auto response = Fetch::Infrastructure::Response::create(vm);
response->url_list().append(active_document()->url());
response->header_list()->append({ "Content-Type"sv, "text/html;charset=utf-8"sv });
- response->set_body(Fetch::Infrastructure::byte_sequence_as_body(realm, result_utf8.bytes()));
+ response->set_body(Fetch::Infrastructure::byte_sequence_as_response_body(result_utf8.bytes()));
// 12. Let policyContainer be targetNavigable's active document's policy container.
auto const& policy_container = active_document()->policy_container();
@@ -4100,7 +4100,7 @@ GC::Ptr<DOM::Document> LocalNavigable::evaluate_javascript_url(URL::URL const& u
navigation_id,
this,
nullptr,
- Fetch::Infrastructure::ResponseView::create(response),
+ Fetch::Infrastructure::ResponseView::create(realm, response),
nullptr,
nullptr,
move(coop_enforcement_result),
diff --git a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp
index 0b0c28ef81e..bc643545dc4 100644
--- a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp
+++ b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp
@@ -53,13 +53,6 @@ static NavigationRequestDescriptor create_navigation_request_descriptor(Fetch::I
};
}
-static Optional<ByteBuffer> copy_body_source(Fetch::Infrastructure::Body const& body)
-{
- if (auto const& source = body.source(); source.has_value())
- return MUST(source->copy_to_byte_buffer());
- return {};
-}
-
static NavigationResponseDescriptor create_navigation_response_descriptor(Fetch::Infrastructure::ResponseView const& response, Fetch::Infrastructure::Request const* request, Fetch::Infrastructure::FetchTimingInfo const* timing_info)
{
Vector<HTTP::Header> headers;
@@ -78,9 +71,9 @@ static NavigationResponseDescriptor create_navigation_response_descriptor(Fetch:
};
}
- if (body.has<Empty>() && response.body()) {
- if (auto body_bytes = copy_body_source(*response.body()); body_bytes.has_value())
- body = body_bytes.release_value();
+ if (body.has<Empty>()) {
+ if (auto source = response.body_source(); source.has_value())
+ body = MUST(source->copy_to_byte_buffer());
}
auto network_response = request && timing_info && response.network_transport().has_value() ? WebDriver::BiDi::network_response_for_navigation(*request, *timing_info, *response.record()) : Optional<JsonObject> {};
@@ -284,19 +277,22 @@ static ErrorOr<GC::Ref<Fetch::Infrastructure::ResponseView>> create_navigation_r
response->set_navigation_timing_allow_values_list(move(descriptor.navigation_timing_allow_values_list));
response->set_redirect_taint(descriptor.redirect_taint);
- if (descriptor.body.has<ByteBuffer>()) {
- response->set_body(Fetch::Infrastructure::byte_sequence_as_body(realm, descriptor.body.get<ByteBuffer>().bytes()));
- } else if (descriptor.body.has<NavigationResponseBodyHandle>()) {
+ if (descriptor.body.has<NavigationResponseBodyHandle>()) {
auto const& handle = descriptor.body.get<NavigationResponseBodyHandle>();
Requests::RequestTransferLeaseKey transfer_lease { handle.request_server_client_id, handle.request_server_request_id };
auto network_response = descriptor.webdriver_bidi_network_response.is_object() ? Optional<JsonObject>(descriptor.webdriver_bidi_network_response.as_object()) : Optional<JsonObject> {};
auto on_network_settled = network_navigation_response_observer(navigable, response, timing_info, move(network_response), move(network_response_state));
- auto body = Fetch::Fetching::adopt_navigation_response_body(realm, response, handle.request_server_top_level_site, transfer_lease, timing_info, move(on_network_settled));
- if (!body)
+ auto body_view = Fetch::Fetching::adopt_navigation_response_body(realm, response, handle.request_server_top_level_site, transfer_lease, timing_info, move(on_network_settled));
+ if (!body_view)
return Error::from_string_literal("Unable to adopt transferred navigation response body");
- response->set_body(body);
+ return Fetch::Infrastructure::ResponseView::create(response, body_view);
+ }
+
+ if (descriptor.body.has<ByteBuffer>()) {
+ auto bytes = Core::ImmutableBytes::adopt(move(descriptor.body.get<ByteBuffer>()));
+ response->set_body(Fetch::Infrastructure::ResponseBody::from_bytes(move(bytes)));
}
- return Fetch::Infrastructure::ResponseView::create(response);
+ return Fetch::Infrastructure::ResponseView::create(realm, response);
}
ErrorOr<NavigationParamsVariant> create_navigation_params_from_descriptor(JS::Realm& realm, LocalNavigable& navigable, NavigationParamsVariantDescriptor descriptor)
diff --git a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp
index 96a634a3b8f..3cfd2fa6a2f 100644
--- a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp
@@ -62,7 +62,7 @@ void IncrementalDocumentParser::start()
// FIXME: The spec allows starting the parse after 500 ms or 1024 bytes, whichever comes first.
// We only honor the byte threshold.
auto parser = GC::Ref { *this };
- m_body->wait_for_sniff_bytes(GC::create_function(GC::Heap::the(), [parser](Web::Fetch::Infrastructure::FetchBody::SniffBytes sniff_bytes) {
+ m_body->wait_for_sniff_bytes(GC::create_function(GC::Heap::the(), [parser](Web::Fetch::Infrastructure::Body::SniffBytes sniff_bytes) {
// A failed response initializes the parser too.
parser->initialize_parser(sniff_bytes.bytes);
}));
diff --git a/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp
index a4de865af1f..266802d7e1c 100644
--- a/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp
@@ -146,7 +146,7 @@ void issue_speculative_fetch(JS::Realm& realm, DOM::Document& document, URL::URL
// speculative fetch succeeds, offer its response to the normal parser's fetch the way a preload is, through
// the document's map of preloaded resources. That fetch still runs main fetch's checks before using it.
Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };
- fetch_algorithms_input.process_response_consume_body = [&realm, document = GC::Ref { document }, parser = GC::Weak { document.active_parser() }, request](GC::Ref<Fetch::Infrastructure::ResponseView> response_view, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {
+ fetch_algorithms_input.process_response_consume_body = [document = GC::Ref { document }, parser = GC::Weak { document.active_parser() }, request](GC::Ref<Fetch::Infrastructure::ResponseView> response_view, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {
auto response = response_view->record();
auto* byte_sequence = body_bytes.get_pointer<Core::ImmutableBytes>();
if (response->is_network_error() || !byte_sequence)
@@ -174,7 +174,7 @@ void issue_speculative_fetch(JS::Realm& realm, DOM::Document& document, URL::URL
return;
// NB: Keep the filtered response, which main fetch uses as is. Unfiltered, it would be treated as same-origin.
- internal_response->set_body(Fetch::Infrastructure::byte_sequence_as_body(realm, byte_sequence->bytes()));
+ internal_response->set_body(Fetch::Infrastructure::ResponseBody::from_bytes(*byte_sequence));
auto entry = PreloadEntry::create();
entry->response = response;
diff --git a/Libraries/LibWeb/WebDriver/BiDi/Network.cpp b/Libraries/LibWeb/WebDriver/BiDi/Network.cpp
index 9c46cbe9cd1..64370f3b092 100644
--- a/Libraries/LibWeb/WebDriver/BiDi/Network.cpp
+++ b/Libraries/LibWeb/WebDriver/BiDi/Network.cpp
@@ -12,7 +12,6 @@
#include <AK/Time.h>
#include <LibRequests/Request.h>
#include <LibWeb/DOM/Document.h>
-#include <LibWeb/Fetch/BodyInit.h>
#include <LibWeb/Fetch/Infrastructure/ClientContextSnapshot.h>
#include <LibWeb/Fetch/Infrastructure/FetchParams.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
@@ -52,7 +51,6 @@ void NetworkContinuation::visit_edges(JS::Cell::Visitor& visitor)
Base::visit_edges(visitor);
visitor.visit(fetch_params);
visitor.visit(response);
- visitor.visit(global_object);
visitor.visit_possible_values(m_callback.raw_capture_range());
}
@@ -73,7 +71,6 @@ void NetworkContinuation::clear_blocked_state()
fetch_params = nullptr;
original_request = nullptr;
response = nullptr;
- global_object = nullptr;
}
static HashMap<String, GC::Root<NetworkContinuation>>& blocked_requests()
@@ -484,7 +481,7 @@ static JsonObject get_the_response_data(Response const& response, FetchTimingInf
auto mime_type = extract_mime_type(response.header_list());
result.set("mimeType"sv, mime_type.has_value() ? mime_type->essence() : String {});
auto body_info = response.body_info();
- if (auto body = response.body(); body && body->source().has_value() && body_info.decoded_size == 0) {
+ if (auto body = response.body(); body.has_value() && body->source().has_value() && body_info.decoded_size == 0) {
body_info.decoded_size = body->source()->size();
if (url.has_value() && url->scheme() == "data"sv)
body_info.encoded_size = body_info.decoded_size;
@@ -525,7 +522,7 @@ static JsonObject process_a_network_event(HTML::Navigable const& navigable, Requ
return params;
}
-void block_network_request(JS::Object& global_object, FetchParams const& fetch_params, GC::Ptr<Fetch::Infrastructure::Response> response, String phase, JsonArray intercepts, GC::Ref<NetworkContinuation> continuation, RefPtr<Fetch::Infrastructure::Request> original_request)
+void block_network_request(FetchParams const& fetch_params, GC::Ptr<Fetch::Infrastructure::Response> response, String phase, JsonArray intercepts, GC::Ref<NetworkContinuation> continuation, RefPtr<Fetch::Infrastructure::Request> original_request)
{
auto request = fetch_params.request();
// NB: Cancellation runs through the controller's original parameters, rather than a prepared HTTP clone.
@@ -556,7 +553,6 @@ void block_network_request(JS::Object& global_object, FetchParams const& fetch_p
continuation->fetch_params = fetch_params;
continuation->original_request = original_request;
continuation->response = response;
- continuation->global_object = global_object;
if (original_request)
original_request->set_webdriver_bidi_network_request(state);
blocked_requests().set(state->id, GC::make_root(continuation));
@@ -680,12 +676,12 @@ static ErrorOr<JsonValue, Error> continue_network_request_impl(StringView method
replacement->set_status_message(response->status_message());
replacement->set_header_list(response->header_list());
response = replacement;
- auto bytes = overrides.body.release_value();
- auto body = Fetch::safely_extract_body(HTML::relevant_realm(*blocked->global_object), ReadonlyBytes { bytes.bytes() }).body;
- response->set_body(body);
+ auto body = ResponseBody::from_bytes(Core::ImmutableBytes::adopt(overrides.body.release_value()));
+ auto length = *body.length();
+ response->set_body(move(body));
auto info = response->body_info();
- info.encoded_size = *body->length();
- info.decoded_size = *body->length();
+ info.encoded_size = length;
+ info.decoded_size = length;
response->set_body_info(info);
}
}
diff --git a/Libraries/LibWeb/WebDriver/BiDi/Network.h b/Libraries/LibWeb/WebDriver/BiDi/Network.h
index efeccba6292..ead459b83ce 100644
--- a/Libraries/LibWeb/WebDriver/BiDi/Network.h
+++ b/Libraries/LibWeb/WebDriver/BiDi/Network.h
@@ -55,7 +55,6 @@ public:
GC::Ptr<Fetch::Infrastructure::FetchParams const> fetch_params;
RefPtr<Fetch::Infrastructure::Request> original_request;
GC::Ptr<Fetch::Infrastructure::Response> response;
- GC::Ptr<JS::Object> global_object;
private:
explicit NetworkContinuation(Callback);
@@ -98,7 +97,7 @@ void apply_network_cache_behavior(Fetch::Infrastructure::Request&);
void apply_network_extra_headers(Fetch::Infrastructure::Request&);
void apply_network_request_header_overrides(Fetch::Infrastructure::Request&);
JsonArray get_network_intercepts(Fetch::Infrastructure::FetchParams const&, StringView phase);
-void block_network_request(JS::Object&, Fetch::Infrastructure::FetchParams const&, GC::Ptr<Fetch::Infrastructure::Response>, String phase, JsonArray intercepts, GC::Ref<NetworkContinuation>, RefPtr<Fetch::Infrastructure::Request> original_request = nullptr);
+void block_network_request(Fetch::Infrastructure::FetchParams const&, GC::Ptr<Fetch::Infrastructure::Response>, String phase, JsonArray intercepts, GC::Ref<NetworkContinuation>, RefPtr<Fetch::Infrastructure::Request> original_request = nullptr);
WEB_API Response continue_network_request(StringView method, JsonObject const&);
void initialize_network_request(Fetch::Infrastructure::Request&, GC::Ptr<HTML::Navigable> = nullptr, Optional<Utf16String> const& navigation = {});
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 96d4513d9db..446f3c75dc4 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -43,8 +43,8 @@ ALLOWED_REALM_MENTIONS = {
"Crypto": (8, 382, "WebCrypto algorithms still use realms for buffer/key/promise materialization"),
"DOM": (10, 33, "DOM abort plumbing and node helpers still have callback/materialization realm use"),
"Fetch": (
- 22,
- 59,
+ 20,
+ 60,
"Fetch bodies, headers, requests, responses, response views, and controllers still materialize JS values/streams; "
"BodyStreamPullSource creates body streams and materializes their pulls and errors on the consumer side, each in "
"its stream's realm",
diff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txt
index 27d562200a7..e3fc7354949 100644
--- a/Tests/LibWeb/CMakeLists.txt
+++ b/Tests/LibWeb/CMakeLists.txt
@@ -27,7 +27,6 @@ set(TEST_SOURCES
TestEventLoop.cpp
TestFaviconDecoding.cpp
TestFetchBodyDeliveryGate.cpp
- TestFetchBodySniffBytes.cpp
TestFetchBodyStream.cpp
TestFetchByteChannel.cpp
TestFetchEngineMessages.cpp
@@ -94,7 +93,6 @@ endif()
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)
diff --git a/Tests/LibWeb/TestDownloadReader.cpp b/Tests/LibWeb/TestDownloadReader.cpp
index 418ee09a084..de07a769808 100644
--- a/Tests/LibWeb/TestDownloadReader.cpp
+++ b/Tests/LibWeb/TestDownloadReader.cpp
@@ -84,8 +84,8 @@ TEST_CASE(download_reader_is_registered_with_page_client)
page->set_top_level_traversable(traversable);
auto response = Web::Fetch::Infrastructure::Response::create(vm);
- response->set_body(Web::Fetch::Infrastructure::byte_sequence_as_body(*realm, "download contents"sv.bytes()));
- traversable->handle_as_a_download(Web::Fetch::Infrastructure::ResponseView::create(response), URL::about_blank(), nullptr, "download.txt", {});
+ response->set_body(Web::Fetch::Infrastructure::byte_sequence_as_response_body("download contents"sv.bytes()));
+ traversable->handle_as_a_download(Web::Fetch::Infrastructure::ResponseView::create(*realm, response), URL::about_blank(), nullptr, "download.txt", {});
EXPECT(client->m_registered_download_id.has_value());
if (!client->m_registered_download_id.has_value())
diff --git a/Tests/LibWeb/TestFetchBodySniffBytes.cpp b/Tests/LibWeb/TestFetchBodySniffBytes.cpp
deleted file mode 100644
index b84eeb8d866..00000000000
--- a/Tests/LibWeb/TestFetchBodySniffBytes.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibCore/EventLoop.h>
-#include <LibTest/TestCase.h>
-#include <LibWeb/Bindings/MainThreadVM.h>
-#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
-#include <LibWeb/HTML/EventLoop/EventLoop.h>
-#include <LibWeb/Platform/FontPlugin.h>
-
-using Web::Fetch::Infrastructure::Body;
-using Web::Fetch::Infrastructure::FetchBody;
-using Web::Fetch::Infrastructure::MAX_SNIFF_BYTES;
-
-namespace {
-
-struct SniffWaiter {
- size_t wake_count { 0 };
- ByteBuffer bytes;
- Optional<FetchBody::SniffOutcome> outcome;
-
- GC::Ref<GC::Function<void(FetchBody::SniffBytes)>> callback(GC::Heap& heap)
- {
- return GC::create_function(heap, [this](FetchBody::SniffBytes sniff_bytes) {
- ++wake_count;
- bytes = MUST(ByteBuffer::copy(sniff_bytes.bytes));
- outcome = sniff_bytes.outcome;
- });
- }
-};
-
-GC::Ref<Body> create_body_without_source(JS::Realm& realm)
-{
- auto stream = Web::Fetch::Infrastructure::byte_sequence_as_body(realm, {})->stream();
- return Body::create(stream);
-}
-
-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;
-}
-
-void spin_until(GC::Heap& heap, Function<bool()> condition)
-{
- Web::HTML::main_thread_event_loop().spin_until(GC::create_function(heap, move(condition)));
-}
-
-// Runs every networking task queued so far.
-void run_queued_tasks(GC::Heap& heap)
-{
- IGNORE_USE_IN_ESCAPING_LAMBDA bool reached = false;
- Web::HTML::queue_a_task(Web::HTML::Task::Source::Networking, Web::HTML::main_thread_event_loop(), nullptr, GC::create_function(heap, [&reached] {
- reached = true;
- }));
- spin_until(heap, [&reached] { return reached; });
-}
-
-}
-
-TEST_CASE(sniff_waiter_runs_from_a_task_after_its_bytes_arrive)
-{
- Core::EventLoop event_loop;
- install_font_plugin();
- auto realm = Web::Bindings::create_a_principal_javascript_realm();
- auto& heap = realm->heap();
- auto body = create_body_without_source(*realm);
-
- SniffWaiter waiter;
- body->wait_for_sniff_bytes(waiter.callback(heap));
-
- auto bytes = MUST(ByteBuffer::create_uninitialized(MAX_SNIFF_BYTES));
- bytes.bytes().fill('a');
- body->append_sniff_bytes(bytes);
- EXPECT_EQ(waiter.wake_count, 0u);
-
- spin_until(heap, [&waiter] { return waiter.wake_count > 0; });
- EXPECT_EQ(waiter.wake_count, 1u);
- EXPECT_EQ(waiter.bytes, bytes);
- EXPECT(waiter.outcome == FetchBody::SniffOutcome::Complete);
-}
-
-TEST_CASE(sniff_waiter_runs_once_however_often_its_bytes_are_completed)
-{
- Core::EventLoop event_loop;
- install_font_plugin();
- auto realm = Web::Bindings::create_a_principal_javascript_realm();
- auto& heap = realm->heap();
- auto body = create_body_without_source(*realm);
-
- SniffWaiter waiter;
- body->wait_for_sniff_bytes(waiter.callback(heap));
-
- body->append_sniff_bytes("short"sv.bytes());
- body->set_sniff_bytes_complete();
- body->set_sniff_bytes_complete();
- body->append_sniff_bytes("ignored"sv.bytes());
- EXPECT_EQ(waiter.wake_count, 0u);
-
- run_queued_tasks(heap);
- EXPECT_EQ(waiter.wake_count, 1u);
- EXPECT_EQ(waiter.bytes, MUST(ByteBuffer::copy("short"sv.bytes())));
- EXPECT(waiter.outcome == FetchBody::SniffOutcome::Complete);
-}
-
-TEST_CASE(sniff_waiter_hears_a_failed_body_from_a_task)
-{
- Core::EventLoop event_loop;
- install_font_plugin();
- auto realm = Web::Bindings::create_a_principal_javascript_realm();
- auto& heap = realm->heap();
- auto body = create_body_without_source(*realm);
-
- SniffWaiter waiter;
- body->wait_for_sniff_bytes(waiter.callback(heap));
-
- body->append_sniff_bytes("partial"sv.bytes());
- body->set_sniff_bytes_failed();
- EXPECT_EQ(waiter.wake_count, 0u);
-
- run_queued_tasks(heap);
- EXPECT_EQ(waiter.wake_count, 1u);
- EXPECT(waiter.outcome == FetchBody::SniffOutcome::Failed);
-}
diff --git a/Tests/LibWeb/TestFetchBodyStream.cpp b/Tests/LibWeb/TestFetchBodyStream.cpp
index f8b3fd02835..1878455dda0 100644
--- a/Tests/LibWeb/TestFetchBodyStream.cpp
+++ b/Tests/LibWeb/TestFetchBodyStream.cpp
@@ -10,8 +10,11 @@
#include <LibCore/Timer.h>
#include <LibJS/Runtime/TypedArray.h>
#include <LibTest/TestCase.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/Fetching.h>
#include <LibWeb/Fetch/Infrastructure/FetchParams.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/Scripting/Environments.h>
@@ -20,10 +23,14 @@
#include <LibWeb/Streams/ReadableStream.h>
#include <LibWeb/Streams/ReadableStreamDefaultReader.h>
+using Web::Fetch::Engine::FetchBodyDeliveryGate;
using Web::Fetch::Engine::FetchByteChannel;
+using Web::Fetch::Engine::FetchByteChannelConsumerSink;
using Web::Fetch::Engine::FetchByteChannelProducerSink;
+using Web::Fetch::Infrastructure::Body;
using Web::Fetch::Infrastructure::FetchAlgorithms;
using Web::Fetch::Infrastructure::FetchParams;
+using Web::Fetch::Infrastructure::MAX_SNIFF_BYTES;
namespace {
@@ -77,10 +84,11 @@ struct BodyStreamHarness {
{
}
- void create_stream()
+ void create_stream(FetchByteChannel::Watermarks watermarks = { .low = 16, .high = 64 })
{
- channel = FetchByteChannel::create({ .low = 16, .high = 64 }, adopt_ref(*new IgnoringProducerSink));
- stream = Web::Fetch::Fetching::create_body_stream_from_channel(*realm, fetch_params, *channel);
+ channel = FetchByteChannel::create(watermarks, adopt_ref(*new IgnoringProducerSink));
+ body = Web::Fetch::Fetching::create_body_from_channel(*realm, fetch_params, *channel);
+ stream = body->stream();
}
// The bytes the channel holds that have not been pulled into the stream.
@@ -117,10 +125,55 @@ struct BodyStreamHarness {
Web::HTML::TemporaryExecutionContext execution_context;
GC::Ptr<FetchParams const> fetch_params;
RefPtr<FetchByteChannel> channel;
+ GC::Ptr<Body> body;
GC::Ptr<Web::Streams::ReadableStream> stream;
GC::Ptr<Web::Streams::ReadableStreamDefaultReader> reader;
};
+struct SniffWaiter {
+ size_t wake_count { 0 };
+ ByteBuffer bytes;
+ Optional<Body::SniffOutcome> outcome;
+
+ Body::SniffBytesCallback callback(GC::Heap& heap)
+ {
+ return GC::create_function(heap, [this](Body::SniffBytes sniff_bytes) {
+ ++wake_count;
+ bytes = MUST(ByteBuffer::copy(sniff_bytes.bytes));
+ outcome = sniff_bytes.outcome;
+ });
+ }
+};
+
+Core::ImmutableBytes make_bytes(size_t size, u8 first_value)
+{
+ auto bytes = MUST(ByteBuffer::create_uninitialized(size));
+ for (size_t i = 0; i < size; ++i)
+ bytes[i] = static_cast<u8>(first_value + i);
+ return Core::ImmutableBytes::adopt(move(bytes));
+}
+
+// Runs channel wakes and networking tasks until the waiter has woken, or for ten seconds.
+void wait_for_wake(GC::Heap& heap, SniffWaiter const& waiter)
+{
+ 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(heap, [&waiter, deadline] {
+ return waiter.wake_count > 0 || !deadline->is_active();
+ }));
+}
+
+// Runs channel wakes and every networking task they queue.
+void run_wakes_and_tasks(GC::Heap& heap)
+{
+ BodyStreamHarness::run_wakes();
+ IGNORE_USE_IN_ESCAPING_LAMBDA bool reached = false;
+ Web::HTML::queue_a_task(Web::HTML::Task::Source::Networking, Web::HTML::main_thread_event_loop(), nullptr, GC::create_function(heap, [&reached] {
+ reached = true;
+ }));
+ Web::HTML::main_thread_event_loop().spin_until(GC::create_function(heap, [&reached] { return reached; }));
+}
+
}
TEST_CASE(an_error_reaches_a_stream_nobody_reads)
@@ -191,3 +244,256 @@ TEST_CASE(bytes_reach_a_stream_while_the_event_loop_is_paused)
EXPECT_EQ(read->chunk(), "pushed"sv);
EXPECT(harness.stream->is_closed());
}
+
+TEST_CASE(sniffing_waits_for_the_resource_header_and_leaves_it_in_the_channel)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ BodyStreamHarness harness;
+ harness.create_stream({ .low = 2 * KiB, .high = 4 * KiB });
+ auto& heap = harness.realm->heap();
+
+ SniffWaiter waiter;
+ harness.body->wait_for_sniff_bytes(waiter.callback(heap));
+
+ auto whole_body = make_bytes(2000, 0);
+ EXPECT_EQ(harness.channel->write(whole_body.slice(0, 500)), FetchByteChannel::WriteResult::Accepted);
+ run_wakes_and_tasks(heap);
+ EXPECT_EQ(waiter.wake_count, 0u);
+
+ EXPECT_EQ(harness.channel->write(whole_body.slice(500, 1500)), FetchByteChannel::WriteResult::Accepted);
+ EXPECT_EQ(waiter.wake_count, 0u);
+ wait_for_wake(heap, waiter);
+ EXPECT_EQ(waiter.wake_count, 1u);
+ EXPECT(waiter.outcome == Body::SniffOutcome::Complete);
+ EXPECT_EQ(waiter.bytes.bytes(), whole_body.bytes().trim(MAX_SNIFF_BYTES));
+
+ // A transfer of the body after sniffing still carries it from its first byte.
+ ByteBuffer transferred;
+ for (auto const& taken : harness.channel->transfer_out())
+ transferred.append(taken.bytes());
+ EXPECT_EQ(transferred.bytes(), whole_body.bytes());
+}
+
+TEST_CASE(sniffing_a_body_set_up_during_a_pause_waits_for_the_resource_header)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ BodyStreamHarness harness;
+ auto& heap = harness.realm->heap();
+ auto whole_body = make_bytes(2000, 0);
+ {
+ auto pause = Web::HTML::main_thread_event_loop().pause(Web::HTML::EventLoop::UpdateTheRendering::No);
+ harness.create_stream({ .low = 2 * KiB, .high = 4 * KiB });
+ EXPECT_EQ(harness.channel->write(whole_body.slice(0, 100)), FetchByteChannel::WriteResult::Accepted);
+ BodyStreamHarness::run_wakes();
+ }
+
+ EXPECT_EQ(harness.channel->write(whole_body.slice(100, 400)), FetchByteChannel::WriteResult::Accepted);
+ SniffWaiter waiter;
+ harness.body->wait_for_sniff_bytes(waiter.callback(heap));
+ run_wakes_and_tasks(heap);
+ EXPECT_EQ(waiter.wake_count, 0u);
+
+ EXPECT_EQ(harness.channel->write(whole_body.slice(500, 1500)), FetchByteChannel::WriteResult::Accepted);
+ wait_for_wake(heap, waiter);
+ EXPECT_EQ(waiter.wake_count, 1u);
+ EXPECT(waiter.outcome == Body::SniffOutcome::Complete);
+ EXPECT_EQ(waiter.bytes.bytes(), whole_body.bytes().trim(MAX_SNIFF_BYTES));
+
+ ByteBuffer transferred;
+ for (auto const& taken : harness.channel->transfer_out())
+ transferred.append(taken.bytes());
+ EXPECT_EQ(transferred.bytes(), whole_body.bytes());
+}
+
+TEST_CASE(sniffing_a_body_that_ends_short_gives_all_of_it)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ BodyStreamHarness harness;
+ harness.create_stream({ .low = 2 * KiB, .high = 4 * KiB });
+ auto& heap = harness.realm->heap();
+
+ SniffWaiter waiter;
+ harness.body->wait_for_sniff_bytes(waiter.callback(heap));
+
+ EXPECT_EQ(harness.channel->write(MUST(Core::ImmutableBytes::copy("short"sv.bytes()))), FetchByteChannel::WriteResult::Accepted);
+ (void)harness.channel->close();
+ EXPECT_EQ(waiter.wake_count, 0u);
+ wait_for_wake(heap, waiter);
+ EXPECT_EQ(waiter.wake_count, 1u);
+ EXPECT(waiter.outcome == Body::SniffOutcome::Complete);
+ EXPECT_EQ(waiter.bytes, MUST(ByteBuffer::copy("short"sv.bytes())));
+}
+
+TEST_CASE(sniffing_a_body_that_errors_fails)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ BodyStreamHarness harness;
+ harness.create_stream({ .low = 2 * KiB, .high = 4 * KiB });
+ auto& heap = harness.realm->heap();
+
+ SniffWaiter waiter;
+ harness.body->wait_for_sniff_bytes(waiter.callback(heap));
+
+ EXPECT_EQ(harness.channel->write(MUST(Core::ImmutableBytes::copy("partial"sv.bytes()))), FetchByteChannel::WriteResult::Accepted);
+ (void)harness.channel->error({ .message = MUST(ByteBuffer::copy("failed"sv.bytes())) });
+ EXPECT_EQ(waiter.wake_count, 0u);
+ wait_for_wake(heap, waiter);
+ EXPECT_EQ(waiter.wake_count, 1u);
+ EXPECT(waiter.outcome == Body::SniffOutcome::Failed);
+}
+
+TEST_CASE(sniffing_keeps_a_complete_header_through_a_later_error)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ BodyStreamHarness harness;
+ harness.create_stream({ .low = 2 * KiB, .high = 4 * KiB });
+ auto& heap = harness.realm->heap();
+
+ SniffWaiter waiter;
+ harness.body->wait_for_sniff_bytes(waiter.callback(heap));
+
+ // The body fails once its resource header is complete, before the sniff waiter's wake has run.
+ auto header = make_bytes(MAX_SNIFF_BYTES, 0);
+ EXPECT_EQ(harness.channel->write(header), FetchByteChannel::WriteResult::Accepted);
+ (void)harness.channel->error({ .message = MUST(ByteBuffer::copy("failed"sv.bytes())) });
+ EXPECT_EQ(waiter.wake_count, 0u);
+ wait_for_wake(heap, waiter);
+ EXPECT_EQ(waiter.wake_count, 1u);
+ EXPECT(waiter.outcome == Body::SniffOutcome::Complete);
+ EXPECT_EQ(waiter.bytes.bytes(), header.bytes());
+
+ BodyStreamHarness::run_wakes();
+ EXPECT(harness.stream->is_errored());
+}
+
+// A transport's teardown cancels or transfers the channel itself, before the resource header is complete or after the
+// channel kept it, and the sniff fails once either way.
+static void check_a_channel_ending_fails_the_sniff_once(size_t written_byte_count, bool transfer)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ BodyStreamHarness harness;
+ harness.create_stream({ .low = 2 * KiB, .high = 4 * KiB });
+ auto& heap = harness.realm->heap();
+
+ SniffWaiter waiter;
+ harness.body->wait_for_sniff_bytes(waiter.callback(heap));
+ EXPECT_EQ(harness.channel->write(make_bytes(written_byte_count, 0)), FetchByteChannel::WriteResult::Accepted);
+ if (transfer)
+ (void)harness.channel->transfer_out();
+ else
+ (void)harness.channel->cancel();
+
+ wait_for_wake(heap, waiter);
+ run_wakes_and_tasks(heap);
+ EXPECT_EQ(waiter.wake_count, 1u);
+ EXPECT(waiter.outcome == Body::SniffOutcome::Failed);
+}
+
+TEST_CASE(a_cancelled_channel_fails_a_sniff_short_of_its_header)
+{
+ check_a_channel_ending_fails_the_sniff_once(100, false);
+}
+
+TEST_CASE(a_cancelled_channel_fails_a_sniff_whose_header_it_kept)
+{
+ check_a_channel_ending_fails_the_sniff_once(MAX_SNIFF_BYTES, false);
+}
+
+TEST_CASE(a_transferred_channel_fails_a_sniff_short_of_its_header)
+{
+ check_a_channel_ending_fails_the_sniff_once(100, true);
+}
+
+TEST_CASE(a_transferred_channel_fails_a_sniff_whose_header_it_kept)
+{
+ check_a_channel_ending_fails_the_sniff_once(MAX_SNIFF_BYTES, true);
+}
+
+TEST_CASE(a_body_over_bytes_sniffs_at_once)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ BodyStreamHarness harness;
+ auto& heap = harness.realm->heap();
+
+ auto bytes = make_bytes(2000, 0);
+ auto body = Body::create_over_bytes(*harness.realm, bytes);
+ auto sniff_bytes = body->sniff_bytes_if_available();
+ EXPECT(sniff_bytes.has_value());
+ EXPECT_EQ(sniff_bytes->bytes, bytes.bytes().trim(MAX_SNIFF_BYTES));
+
+ SniffWaiter waiter;
+ body->wait_for_sniff_bytes(waiter.callback(heap));
+ EXPECT_EQ(waiter.wake_count, 1u);
+}
+
+namespace {
+
+class CountingConsumerSink final : public FetchByteChannelConsumerSink {
+public:
+ virtual void wake(Web::Fetch::Engine::WakeTicket) override { ++wake_count; }
+
+ size_t wake_count { 0 };
+};
+
+}
+
+TEST_CASE(stopping_a_whole_body_transport_cancels_its_channel_and_wakes_its_reader)
+{
+ Core::EventLoop event_loop;
+ auto gate = FetchBodyDeliveryGate::create(FetchBodyDeliveryGate::NavigationHold::None);
+ auto channel = FetchByteChannel::create({ .low = 16, .high = 64 }, gate->create_channel_sink());
+ gate->grant_credit(channel->initial_credit());
+ auto reader = adopt_ref(*new CountingConsumerSink);
+ channel->attach_consumer(reader);
+ (void)channel->arm_waiter(FetchByteChannel::EndOnly {});
+
+ auto transport = Web::Fetch::Fetching::create_whole_body_transport(*gate, *channel);
+ transport->attach_to(gate);
+ transport->set_body(make_bytes(1000, 0), [&](Requests::ResponseData data) {
+ EXPECT_EQ(gate->did_deliver(data.bytes().size()), Web::Fetch::Engine::FetchBodyDeliveryGate::DeliveryResult::Accepted);
+ (void)channel->write(MUST(Core::ImmutableBytes::copy(data.bytes())));
+ });
+ event_loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ EXPECT_EQ(channel->peek_up_to(0).buffered_byte_count, 64u);
+ EXPECT_EQ(reader->wake_count, 0u);
+
+ transport->stop();
+ EXPECT(channel->peek_up_to(0).state.has<FetchByteChannel::ConsumerCancelled>());
+ EXPECT_EQ(reader->wake_count, 1u);
+}
+
+TEST_CASE(network_completion_runs_only_the_steps_awaited_for_its_body)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ BodyStreamHarness harness;
+ auto& heap = harness.realm->heap();
+ auto controller = Web::Fetch::Infrastructure::FetchController::create();
+ auto earlier = FetchByteChannel::create({ .low = 16, .high = 64 }, adopt_ref(*new IgnoringProducerSink));
+ auto later = FetchByteChannel::create({ .low = 16, .high = 64 }, adopt_ref(*new IgnoringProducerSink));
+
+ // A later body's steps replace an earlier body's, and run once.
+ IGNORE_USE_IN_ESCAPING_LAMBDA size_t earlier_runs = 0;
+ IGNORE_USE_IN_ESCAPING_LAMBDA size_t later_runs = 0;
+ controller->when_network_completes_body(*earlier, GC::create_function(heap, [&] { ++earlier_runs; }));
+ controller->when_network_completes_body(*later, GC::create_function(heap, [&] { ++later_runs; }));
+ controller->did_complete_network_body(*earlier);
+ EXPECT_EQ(earlier_runs, 0u);
+ EXPECT_EQ(later_runs, 0u);
+ controller->did_complete_network_body(*later);
+ controller->did_complete_network_body(*later);
+ EXPECT_EQ(later_runs, 1u);
+
+ // A stopped fetch runs no awaited steps.
+ controller->when_network_completes_body(*earlier, GC::create_function(heap, [&] { ++earlier_runs; }));
+ controller->stop_fetch();
+ controller->did_complete_network_body(*earlier);
+ EXPECT_EQ(earlier_runs, 0u);
+}
diff --git a/Tests/LibWeb/TestFetchResponse.cpp b/Tests/LibWeb/TestFetchResponse.cpp
index 0051db16e0b..7f5fc055855 100644
--- a/Tests/LibWeb/TestFetchResponse.cpp
+++ b/Tests/LibWeb/TestFetchResponse.cpp
@@ -47,8 +47,6 @@ GC_DEFINE_ALLOCATOR(TransferTrackingResponse);
TEST_CASE(javascript_bytecode_cache_memory_cache_request_headers_are_cloned)
{
auto vm = JS::VM::create();
- auto root_execution_context = JS::create_simple_execution_context<JS::GlobalObject>(*vm);
- auto& realm = *root_execution_context->realm;
auto request_headers = HTTP::HeaderList::create({
{ "User-Agent"sv, "Ladybird"sv },
@@ -56,7 +54,7 @@ TEST_CASE(javascript_bytecode_cache_memory_cache_request_headers_are_cloned)
auto response = Web::Fetch::Infrastructure::Response::create();
response->set_javascript_bytecode_cache_memory_cache_request_headers(request_headers);
- auto cloned_response = response->clone(realm);
+ auto cloned_response = response->clone();
auto const& cloned_request_headers = cloned_response->javascript_bytecode_cache_memory_cache_request_headers();
request_headers->set({ "User-Agent"sv, "Changed"sv });
diff --git a/Tests/LibWeb/Text/expected/Fetch/fetch-unread-resource-timing-after-a-redirect.txt b/Tests/LibWeb/Text/expected/Fetch/fetch-unread-resource-timing-after-a-redirect.txt
new file mode 100644
index 00000000000..6eb74b243d0
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Fetch/fetch-unread-resource-timing-after-a-redirect.txt
@@ -0,0 +1,5 @@
+entries while the final body is held: 0
+body used before timing: false
+sizes: 4000/4000
+body length: 4000
+entries after reading the body: 1
diff --git a/Tests/LibWeb/Text/input/Fetch/fetch-unread-resource-timing-after-a-redirect.html b/Tests/LibWeb/Text/input/Fetch/fetch-unread-resource-timing-after-a-redirect.html
new file mode 100644
index 00000000000..91d861a742f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Fetch/fetch-unread-resource-timing-after-a-redirect.html
@@ -0,0 +1,55 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // The redirect's empty body finishes as its headers arrive. The final response's timing waits for its own body,
+ // which the server holds after its first byte, and is reported once that body has arrived, before it is read.
+ asyncTest(async done => {
+ const server = httpTestServer();
+ const token = crypto.randomUUID();
+ const unblockURL = `${server.baseURL}/unblock/${token}`;
+ const corsHeaders = { "Access-Control-Allow-Origin": "*", "Timing-Allow-Origin": "*" };
+
+ const body = "x".repeat(4000);
+ const finalURL = new URL(await server.createEcho("GET", `/unread-resource-timing-after-a-redirect-${token}/final`, {
+ status: 200,
+ headers: { ...corsHeaders, "Content-Type": "text/plain", "Content-Length": `${body.length}` },
+ body,
+ }));
+ finalURL.search = `?chunks=1&chunk_unblock_tokens=${token}`;
+
+ const redirectURL = await server.createEcho("GET", `/unread-resource-timing-after-a-redirect-${token}/redirect`, {
+ status: 302,
+ headers: { ...corsHeaders, "Location": finalURL.href, "Content-Length": "0" },
+ body: "",
+ });
+
+ const isEntryOfTheFetch = entry => entry.name === redirectURL || entry.name === finalURL.href;
+ const entriesOfTheFetch = () => performance.getEntriesByType("resource").filter(isEntryOfTheFetch).length;
+
+ try {
+ const response = await fetch(redirectURL);
+ println(`entries while the final body is held: ${entriesOfTheFetch()}`);
+
+ const observed = new Promise(resolve => {
+ const observer = new PerformanceObserver(list => {
+ const entry = list.getEntries().find(isEntryOfTheFetch);
+ if (entry) {
+ observer.disconnect();
+ resolve(entry);
+ }
+ });
+ observer.observe({ type: "resource", buffered: true });
+ });
+ await fetch(unblockURL);
+ const entry = await observed;
+ println(`body used before timing: ${response.bodyUsed}`);
+ println(`sizes: ${entry.encodedBodySize}/${entry.decodedBodySize}`);
+
+ println(`body length: ${(await response.text()).length}`);
+ println(`entries after reading the body: ${entriesOfTheFetch()}`);
+ } finally {
+ await fetch(unblockURL);
+ }
+ done();
+ });
+</script>
diff --git a/Tests/LibWebView/test-webdriver-bidi.py b/Tests/LibWebView/test-webdriver-bidi.py
index 27f95932c8d..8e4d9faa1bd 100755
--- a/Tests/LibWebView/test-webdriver-bidi.py
+++ b/Tests/LibWebView/test-webdriver-bidi.py
@@ -932,6 +932,50 @@ def check_network_failed_response_transport(bidi, context, server):
bidi.command("session.unsubscribe", {"subscriptions": [subscription]})
+def check_network_provided_body_at_response_started(bidi, context, server):
+ url = f"http://127.0.0.1:{server.server_port}/network-interception/fail-body"
+ provided = "provided body"
+ server.interception_transport_closed.clear()
+ subscription = bidi.command(
+ "session.subscribe", {"events": ["network.responseStarted", "network.responseCompleted"]}
+ )["subscription"]
+ intercept = bidi.command(
+ "network.addIntercept",
+ {
+ "phases": ["responseStarted"],
+ "urlPatterns": [{"type": "string", "pattern": url}],
+ },
+ )["intercept"]
+ try:
+ pending = bidi.send(
+ "script.evaluate",
+ {
+ "target": {"context": context},
+ "awaitPromise": True,
+ "expression": f"fetch({json.dumps(url)}).then(response => response.text())",
+ },
+ )
+ # The original body is still arriving when the provided one replaces it.
+ event = intercepted_event(bidi, "network.responseStarted", url)
+ bidi.command(
+ "network.provideResponse",
+ {"request": event["request"]["request"], "body": {"type": "string", "value": provided}},
+ )
+ result = bidi.response(pending)
+ assert result["type"] == "success" and result["result"]["result"]["value"] == provided, result
+ assert server.interception_transport_closed.wait(30), "The provided body left the original transport open"
+ completed = bidi.event("network.responseCompleted")
+ while completed["request"]["url"] != url:
+ completed = bidi.event("network.responseCompleted")
+ response = completed["response"]
+ assert response["bodySize"] == len(provided), response
+ assert response["content"]["size"] == len(provided), response
+ finally:
+ if sys.exc_info()[0] is None:
+ bidi.command("network.removeIntercept", {"intercept": intercept})
+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})
+
+
def check_network_scoped_headers(bidi, context, server):
other = bidi.command("browsingContext.create", {"type": "tab"})["context"]
@@ -1064,6 +1108,8 @@ def check_network_interception(bidi, context, server, case="all"):
check_network_scoped_headers(bidi, context, server)
if case in ["all", "fail-transport"]:
check_network_failed_response_transport(bidi, context, server)
+ if case in ["all", "provided-body-at-response-started"]:
+ check_network_provided_body_at_response_started(bidi, context, server)
for action in ["cancel", "default"]:
if case in ["all", "auth-response-matrix", "auth-action-extras", f"auth-{action}-extra"]:
for credentials in [{"type": "password", "username": "user", "password": "pass"}, {}]:
@@ -2155,6 +2201,7 @@ if __name__ == "__main__":
"navigation",
"scoped-headers",
"fail-transport",
+ "provided-body-at-response-started",
"auth-gates",
"auth-omit",
"auth-cors",