Skip to content

Truly independent web browser

LibWeb: Report the end of a fetch's network body to its agent

Luke Wildea94dfdccc211
diff --git a/Libraries/LibWeb/Fetch/Engine/EngineEvent.h b/Libraries/LibWeb/Fetch/Engine/EngineEvent.h
index 39519f4bc71..c85de8396e1 100644
--- a/Libraries/LibWeb/Fetch/Engine/EngineEvent.h
+++ b/Libraries/LibWeb/Fetch/Engine/EngineEvent.h
@@ -22,7 +22,7 @@ struct ResponseDelivery {
FetchTimingSeed timing_seed;
};
-// Sent once per delivery after its last byte, whether or not the transport has completed.
+// Sent only for a body still arriving at its response's handover, once the network completes it.
struct EndOfBody {
struct FinalSizes {
u64 encoded_body_size { 0 };
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.cpp b/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.cpp
index ac0ec3aeed1..3af815e8789 100644
--- a/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.cpp
+++ b/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.cpp
@@ -210,6 +210,22 @@ Optional<Core::ImmutableBytes> FetchByteChannel::whole_body() const
return m_whole_body;
}
+bool FetchByteChannel::set_delivery_id_unless_closed(DeliveryId delivery_id)
+{
+ MutexLocker locker { m_mutex };
+ VERIFY(!m_delivery_id.has_value());
+ if (m_state.has<Closed>())
+ return false;
+ m_delivery_id = delivery_id;
+ return true;
+}
+
+Optional<DeliveryId> FetchByteChannel::delivery_id() const
+{
+ MutexLocker locker { m_mutex };
+ return m_delivery_id;
+}
+
FetchByteChannel::TerminateResult FetchByteChannel::cancel()
{
PendingNotifications notifications;
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.h b/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.h
index 7922250704e..9c966b55178 100644
--- a/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.h
+++ b/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.h
@@ -96,6 +96,11 @@ public:
void keep_whole_body(Core::ImmutableBytes);
[[nodiscard]] Optional<Core::ImmutableBytes> whole_body() const;
+ // The delivery of the handed-over response these bytes are the body of. Set once, unless the channel is Closed, and
+ // returns whether it was set.
+ [[nodiscard]] bool set_delivery_id_unless_closed(DeliveryId);
+ [[nodiscard]] Optional<DeliveryId> delivery_id() const;
+
// Consumer side.
// The consumer attaches its sink once, before any arm_waiter() call.
void attach_consumer(NonnullRefPtr<FetchByteChannelConsumerSink>);
@@ -183,6 +188,7 @@ private:
State m_state { Open {} };
bool m_transport_ended { false };
Optional<Core::ImmutableBytes> m_whole_body;
+ Optional<DeliveryId> m_delivery_id;
Vector<ArmedWaiter, 2> m_armed_waiters;
Vector<KeptPrefix, 1> m_kept_prefixes;
u64 m_next_ticket { 1 };
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.cpp b/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.cpp
index cda30c70ed5..356a62e127c 100644
--- a/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.cpp
+++ b/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.cpp
@@ -4,11 +4,14 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/Atomic.h>
#include <AK/Format.h>
#include <LibWeb/Fetch/Engine/FetchEngineRecord.h>
namespace Web::Fetch::Engine {
+static Atomic<u64> s_next_delivery_id { 1 };
+
FetchEngineRecord::FetchEngineRecord(FetchEngineRecords& records, FetchId fetch_id, NonnullOwnPtr<EngineEventSink> event_sink, NonnullRefPtr<NetworkActivityObservers const> network_activity_observers)
: m_records(records)
, m_fetch_id(fetch_id)
@@ -51,6 +54,14 @@ void FetchEngineRecord::add_network_transport(NetworkTransportHandle& handle, Fe
records->add_network_transport(handle, delivery_gate);
}
+Optional<DeliveryId> FetchEngineRecord::deliver_body(FetchByteChannel& channel)
+{
+ DeliveryId delivery_id { s_next_delivery_id.fetch_add(1) };
+ if (!channel.set_delivery_id_unless_closed(delivery_id))
+ return {};
+ return delivery_id;
+}
+
void FetchEngineRecords::Agent::misbehaved(StringView reason)
{
dbgln("FetchEngineRecords: The agent misbehaved: {}", reason);
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.h b/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.h
index 08fbf6be630..041c71bea18 100644
--- a/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.h
+++ b/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.h
@@ -59,6 +59,10 @@ public:
void add_network_transport(NetworkTransportHandle&, FetchBodyDeliveryGate&);
+ // Marks the channel as the body of a response handed over to the agent that started the fetch, and returns the id
+ // of that delivery. A Closed channel, whose body has arrived whole, is not marked and gets none.
+ Optional<DeliveryId> deliver_body(FetchByteChannel&);
+
private:
friend class FetchEngineRecords;
diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.cpp b/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.cpp
index 06abe192472..4c12d5fffdc 100644
--- a/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.cpp
@@ -162,8 +162,10 @@ void FetchEventSink::handle_event(Engine::EngineEvent event)
[&](Engine::Event::NetworkActivity const& network_activity) {
controller->page()->did_receive_network_activity(network_activity);
},
+ [&](Engine::Event::EndOfBody const& end_of_body) {
+ controller->did_end_body(end_of_body);
+ },
[](Engine::Event::ResponseDelivery const&) { VERIFY_NOT_REACHED(); },
- [](Engine::Event::EndOfBody const&) { VERIFY_NOT_REACHED(); },
[](Engine::Event::ConsumeBodyResult const&) { VERIFY_NOT_REACHED(); },
[](Engine::Event::BodyChannelReadable const&) { VERIFY_NOT_REACHED(); },
[](Engine::Event::DeliveryEnd const&) { VERIFY_NOT_REACHED(); },
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 077942a056f..d0ce3ca5daa 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -1104,17 +1104,15 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
if (fetch_params.request()->is_navigation_request())
fetch_params.control_block().set_full_timing_info(fetch_params.timing_info());
- // AD-HOC: We extract steps 1-2 of processResponseEndOfBody into a separate lambda so we can also call it from
- // the error path. The fetch spec only runs processResponseEndOfBody on successful body read (via the
- // transform stream's flush algorithm). However, processResponseConsumeBody is called for both success
- // and failure, and specs like HTML's preload algorithm expect to be able to call reportTiming from
- // within processResponseConsumeBody. So we ensure report_timing_steps is set on error too, which allows
- // reportTiming to work without asserting, and still produces useful timing data for failed fetches.
+ // AD-HOC: We extract step 2 of processResponseEndOfBody into a separate lambda, given unsafeEndTime, so that the
+ // error path and network completion can also run it. The fetch spec only runs processResponseEndOfBody on
+ // successful body read (via the transform stream's flush algorithm). However, processResponseConsumeBody
+ // is called for both success and failure, and specs like HTML's preload algorithm expect to be able to
+ // call reportTiming from within processResponseConsumeBody. So we ensure report_timing_steps is set on
+ // error too, which allows reportTiming to work without asserting, and still produces useful timing data
+ // for failed fetches.
auto timing_reported = RefCountedFlag::create(false);
- auto setup_report_timing_steps = GC::create_function(GC::Heap::the(), GC::captures(response_view->record(), NonnullRefPtr { fetch_params }, controller, timing_info, timing_reported), [](auto& response, auto& fetch_params, auto& controller, auto& timing_info, auto& timing_reported) {
- // 1. Let unsafeEndTime be the unsafe shared current time.
- auto unsafe_end_time = HighResolutionTime::unsafe_shared_current_time();
-
+ auto setup_report_timing_steps = GC::create_function(GC::Heap::the(), GC::captures(response_view->record(), NonnullRefPtr { fetch_params }, controller, timing_info, timing_reported), [](auto& response, auto& fetch_params, auto& controller, auto& timing_info, auto& timing_reported, HighResolutionTime::DOMHighResTimeStamp unsafe_end_time) {
// 2. Set fetchParams’s controller’s report timing steps to the following steps given a global object global:
controller->set_report_timing_steps(GC::create_function(GC::Heap::the(), GC::captures(response, fetch_params, timing_info, unsafe_end_time, timing_reported), [](auto& response, auto& fetch_params, auto& timing_info, auto& unsafe_end_time, auto& timing_reported, JS::Object& global) {
// NB: Network completion and consuming the response body can both request a timing report.
@@ -1197,8 +1195,11 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
// 4. Let processResponseEndOfBody be the following steps:
auto process_response_end_of_body = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { fetch_params }, controller, response_view, setup_report_timing_steps, report_timing_if_appropriate), [](auto& fetch_params, auto& controller, auto& response_view, auto& setup_report_timing_steps, auto& report_timing_if_appropriate) {
- // 1-2. (See setup_report_timing_steps above)
- setup_report_timing_steps->function()();
+ // 1. Let unsafeEndTime be the unsafe shared current time.
+ auto unsafe_end_time = HighResolutionTime::unsafe_shared_current_time();
+
+ // 2. (See setup_report_timing_steps above)
+ setup_report_timing_steps->function()(unsafe_end_time);
if (WebDriver::BiDi::network_events_enabled() && !response_view->is_network_error())
WebDriver::BiDi::network_response_completed(fetch_params, *response_view->record()->unsafe_response());
@@ -1234,20 +1235,31 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
// 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::network_events_enabled() && !fetch_params.request()->is_navigation_request()))) {
- auto network_completion_steps = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { fetch_params }, response_view, setup_report_timing_steps, report_timing_if_appropriate), [](auto& fetch_params, auto& response_view, auto& setup_report_timing_steps, auto& report_timing_if_appropriate) {
- setup_report_timing_steps->function()();
- report_timing_if_appropriate->function()();
- if (WebDriver::BiDi::network_events_enabled())
- WebDriver::BiDi::network_response_completed(*fetch_params, *response_view->record()->unsafe_response());
- });
+ if (internal_body.has_value()) {
+ GC::Ptr<GC::Function<void(HighResolutionTime::DOMHighResTimeStamp)>> network_completion_steps;
+ if (fetch_params.request()->initiator_type().has_value() || (WebDriver::BiDi::network_events_enabled() && !fetch_params.request()->is_navigation_request())) {
+ network_completion_steps = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { fetch_params }, response_view, setup_report_timing_steps, report_timing_if_appropriate), [](auto& fetch_params, auto& response_view, auto& setup_report_timing_steps, auto& report_timing_if_appropriate, HighResolutionTime::DOMHighResTimeStamp unsafe_end_time) {
+ setup_report_timing_steps->function()(unsafe_end_time);
+ report_timing_if_appropriate->function()();
+ if (WebDriver::BiDi::network_events_enabled())
+ WebDriver::BiDi::network_response_completed(*fetch_params, *response_view->record()->unsafe_response());
+ });
+ }
+ auto run_network_completion_steps_now = [&] {
+ if (network_completion_steps)
+ network_completion_steps->function()(HighResolutionTime::unsafe_shared_current_time());
+ };
internal_body->bytes().visit(
- [&](Core::ImmutableBytes const&) { network_completion_steps->function()(); },
+ [&](Core::ImmutableBytes const&) { run_network_completion_steps_now(); },
[&](NonnullRefPtr<Engine::FetchByteChannel> const& channel) {
- if (channel->peek_up_to(0).state.has<Engine::FetchByteChannel::Closed>())
- network_completion_steps->function()();
- else
- controller->when_network_completes_body(*channel, network_completion_steps);
+ auto* engine_record = fetch_params.engine_record();
+ VERIFY(engine_record);
+ auto delivery_id = engine_record->deliver_body(*channel);
+ if (!delivery_id.has_value()) {
+ run_network_completion_steps_now();
+ return;
+ }
+ controller->when_body_ends(*delivery_id, internal_response, network_completion_steps);
},
[](Infrastructure::ResponseBody::ReadThroughStream) { });
}
@@ -1390,7 +1402,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
// failure.
auto process_body_error = GC::create_function(GC::Heap::the(), GC::captures(algorithms, response_view, fetch_params.controller(), setup_report_timing_steps), [](auto& algorithms, auto& response_view, auto& controller, auto& setup_report_timing_steps, JS::Value) {
// AD-HOC: See comment on setup_report_timing_steps above.
- setup_report_timing_steps->function()();
+ setup_report_timing_steps->function()(HighResolutionTime::unsafe_shared_current_time());
// NB: A failed read does not always close or error the body's stream, which would otherwise end this.
end_rendering_pending_operation(controller.ptr());
algorithms->process_response_consume_body()->function()(response_view, Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag {});
diff --git a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp
index 30d4b780490..245efc22cee 100644
--- a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp
@@ -7,12 +7,15 @@
*/
#include <LibHTTP/Cache/MemoryCache.h>
+#include <LibWeb/Fetch/Engine/EngineEvent.h>
+#include <LibWeb/Fetch/Engine/FetchEngineRecord.h>
#include <LibWeb/Fetch/Fetching/Fetching.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>
+#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/WebDriver/BiDi/Network.h>
namespace Web::Fetch::Fetching {
@@ -48,15 +51,7 @@ void NetworkBodyPump::set_response(NonnullRefPtr<Infrastructure::Response> respo
{
m_response = move(response);
if (m_network_complete)
- update_response_body_info();
-}
-
-void NetworkBodyPump::update_response_body_info()
-{
- auto body_info = m_response->body_info();
- body_info.encoded_size = m_encoded_body_size;
- body_info.decoded_size = m_decoded_body_size;
- m_response->set_body_info(move(body_info));
+ m_response->set_body_sizes(m_encoded_body_size, m_decoded_body_size);
}
void NetworkBodyPump::visit_edges(Visitor& visitor)
@@ -140,12 +135,21 @@ void NetworkBodyPump::handle_network_complete(Optional<i64> request_server_encod
m_encoded_body_size = static_cast<u64>(max<i64>(*request_server_encoded_body_size, 0));
else
m_encoded_body_size = m_decoded_body_size;
- if (m_response)
- update_response_body_info();
+ auto delivery_id = m_channel->delivery_id();
+ if (m_response && !delivery_id.has_value())
+ m_response->set_body_sizes(m_encoded_body_size, m_decoded_body_size);
finalize_cache_entry();
+ if (delivery_id.has_value()) {
+ Engine::Event::EndOfBody end_of_body {
+ .delivery_id = *delivery_id,
+ .final_sizes = { .encoded_body_size = m_encoded_body_size, .decoded_body_size = m_decoded_body_size },
+ .end_time = HighResolutionTime::unsafe_shared_current_time(),
+ };
+ auto* engine_record = m_fetch_params->engine_record();
+ VERIFY(engine_record);
+ engine_record->event_sink().handle_event(move(end_of_body));
+ }
m_channel->close();
- if (m_fetch_controller)
- m_fetch_controller->did_complete_network_body(*m_channel);
}
void NetworkBodyPump::handle_network_error(StringView error_message)
diff --git a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h
index eaacdb9614b..be408aab071 100644
--- a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h
+++ b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h
@@ -35,7 +35,8 @@ public:
[[nodiscard]] NonnullRefPtr<Engine::FetchByteChannel> const& channel() const { return m_channel; }
[[nodiscard]] NonnullRefPtr<Engine::FetchBodyDeliveryGate> const& delivery_gate() const { return m_delivery_gate; }
- // The pump records the body's sizes in the response once the body completes.
+ // The pump records the body's sizes in the response once the body completes, unless the response was handed over
+ // while its body still arrived. The fetch's agent then records them when the pump reports the body's end.
void set_response(NonnullRefPtr<Fetch::Infrastructure::Response>);
void handle_network_data(Requests::ResponseData);
@@ -54,7 +55,6 @@ private:
// Drops a pending memory-cache entry that matches the response's request, for a body that will not finish arriving.
void abandon_cache_entry(HTTP::MemoryCache::StoredResponse);
void finalize_cache_entry();
- void update_response_body_info();
RefPtr<Infrastructure::FetchParams const> m_fetch_params;
// The controller of m_fetch_params, which the pump keeps alive with them.
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp
index 2a2939047c1..34b65da13fe 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp
@@ -8,6 +8,7 @@
#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/VM.h>
#include <LibWeb/Fetch/Engine/EngineCommand.h>
+#include <LibWeb/Fetch/Engine/EngineEvent.h>
#include <LibWeb/Fetch/Engine/FetchExecutor.h>
#include <LibWeb/Fetch/Fetching/PendingResponse.h>
#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
@@ -53,8 +54,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);
+ if (m_awaited_end_of_body.has_value())
+ visitor.visit(m_awaited_end_of_body->steps);
visitor.visit(m_next_manual_redirect_steps);
visitor.visit(m_algorithms);
visitor.visit(m_task_destination);
@@ -161,17 +162,22 @@ 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)
+void FetchController::when_body_ends(Engine::DeliveryId delivery_id, Response& response, GC::Ptr<GC::Function<void(HighResolutionTime::DOMHighResTimeStamp)>> steps)
{
- m_awaited_network_completion = AwaitedNetworkCompletion { body, steps };
+ m_awaited_end_of_body = AwaitedEndOfBody { delivery_id, response.make_weak_ptr<Response>(), steps };
}
-void FetchController::did_complete_network_body(Engine::FetchByteChannel const& body)
+void FetchController::did_end_body(Engine::Event::EndOfBody const& end_of_body)
{
- if (!m_awaited_network_completion.has_value() || m_awaited_network_completion->body.ptr() != &body)
+ if (!m_awaited_end_of_body.has_value() || m_awaited_end_of_body->delivery_id != end_of_body.delivery_id)
return;
- auto steps = m_awaited_network_completion.release_value().steps;
- steps->function()();
+ auto awaited = m_awaited_end_of_body.release_value();
+
+ if (auto response = awaited.response.strong_ref())
+ response->set_body_sizes(end_of_body.final_sizes.encoded_body_size, end_of_body.final_sizes.decoded_body_size);
+
+ if (awaited.steps)
+ awaited.steps->function()(end_of_body.end_time);
}
// https://fetch.spec.whatwg.org/#extract-full-timing-info
@@ -283,7 +289,7 @@ void FetchController::stop_request()
{
end_rendering_pending_operation(this);
VERIFY(!m_control_block->is_ongoing());
- m_awaited_network_completion.clear();
+ m_awaited_end_of_body.clear();
if (!m_started_fetch.has_value())
return;
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
index 7b6c0d52648..da0c417f16a 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h
@@ -59,10 +59,10 @@ 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, unless the
- // fetch is aborted, terminated or stopped first. A later call replaces them.
- void when_network_completes_body(Engine::FetchByteChannel const&, GC::Ref<GC::Function<void()>> steps);
- void did_complete_network_body(Engine::FetchByteChannel const&);
+ // Once the network has delivered all of the delivery's body, records its sizes in the response, if still alive, then
+ // runs the steps given its end time. An abort, termination or stop of the fetch, or a later call, drops this first.
+ void when_body_ends(Engine::DeliveryId, Response&, GC::Ptr<GC::Function<void(HighResolutionTime::DOMHighResTimeStamp)>> steps);
+ void did_end_body(Engine::Event::EndOfBody 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; }
@@ -135,11 +135,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;
+ struct AwaitedEndOfBody {
+ Engine::DeliveryId delivery_id;
+ WeakPtr<Response> response;
+ GC::Ptr<GC::Function<void(HighResolutionTime::DOMHighResTimeStamp)>> steps;
};
- Optional<AwaitedNetworkCompletion> m_awaited_network_completion;
+ Optional<AwaitedEndOfBody> m_awaited_end_of_body;
// https://fetch.spec.whatwg.org/#fetch-controller-report-timing-steps
// serialized abort reason (default null)
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
index f17909594f2..4870ce6c4e1 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
@@ -89,6 +89,14 @@ bool Response::is_network_error() const
return true;
}
+void Response::set_body_sizes(u64 encoded_size, u64 decoded_size)
+{
+ auto body_info = this->body_info();
+ body_info.encoded_size = encoded_size;
+ body_info.decoded_size = decoded_size;
+ set_body_info(move(body_info));
+}
+
void Response::release_request_transfer_lease() const
{
if (m_network_transport.has_value())
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h
index 3d3d425c651..a5832995d90 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h
@@ -15,6 +15,7 @@
#include <AK/Time.h>
#include <AK/Utf16String.h>
#include <AK/Vector.h>
+#include <AK/Weakable.h>
#include <LibCore/ImmutableBytes.h>
#include <LibHTTP/HeaderList.h>
#include <LibURL/URL.h>
@@ -29,7 +30,9 @@
namespace Web::Fetch::Infrastructure {
// https://fetch.spec.whatwg.org/#concept-response
-class WEB_API Response : public RefCounted<Response> {
+class WEB_API Response
+ : public RefCounted<Response>
+ , public Weakable<Response> {
public:
GC_HOLDS_NO_CELL_EDGES;
@@ -114,6 +117,7 @@ public:
[[nodiscard]] virtual BodyInfo const& body_info() const { return m_body_info; }
virtual void set_body_info(BodyInfo body_info) { m_body_info = move(body_info); }
+ void set_body_sizes(u64 encoded_size, u64 decoded_size);
[[nodiscard]] virtual RedirectTaint redirect_taint() const { return m_redirect_taint; }
virtual void set_redirect_taint(RedirectTaint redirect_taint) { m_redirect_taint = redirect_taint; }
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index ab32b7b5284..39a6e68f68b 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -575,6 +575,7 @@ class WholeBodyTransport;
namespace Web::Fetch::Engine::Event {
+struct EndOfBody;
struct NetworkActivity;
}
diff --git a/Tests/LibWeb/TestFetchAlgorithms.cpp b/Tests/LibWeb/TestFetchAlgorithms.cpp
index 27702049755..9f6ec69d498 100644
--- a/Tests/LibWeb/TestFetchAlgorithms.cpp
+++ b/Tests/LibWeb/TestFetchAlgorithms.cpp
@@ -41,6 +41,7 @@
#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h>
+#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
#include <LibWeb/Fetch/Infrastructure/Task.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/NavigationParams.h>
@@ -61,6 +62,7 @@ using Web::Fetch::Engine::FetchByteChannel;
using Web::Fetch::Engine::NetworkTransportHandle;
using Web::Fetch::Engine::WholeBodyTransport;
using Web::Fetch::Engine::Command::TransportControl;
+using Web::Fetch::Engine::Event::EndOfBody;
using Web::Fetch::Engine::Event::NetworkActivity;
using Web::Fetch::Engine::Event::ReadRequestBodyStream;
using Web::Fetch::Engine::Event::RequestBodyEndOfBody;
@@ -72,6 +74,7 @@ using Web::Fetch::Infrastructure::FetchAlgorithms;
using Web::Fetch::Infrastructure::FetchController;
using Web::Fetch::Infrastructure::FetchParams;
using Web::Fetch::Infrastructure::Request;
+using Web::Fetch::Infrastructure::Response;
using Web::Fetch::Infrastructure::ResponseView;
namespace {
@@ -684,26 +687,96 @@ struct ResourceLoaderWithoutRequestServer {
}
};
-// A RequestServer client of the agent's resource loader, whose RequestServer end of the connection the test holds.
-struct ResourceLoaderWithStandInRequestServer {
- explicit ResourceLoaderWithStandInRequestServer(GC::Heap& heap)
+// What a RequestServer the test stands in for has been asked to start.
+struct StartedRequests : RefCounted<StartedRequests> {
+ GC_HOLDS_NO_CELL_EDGES;
+
+ IPC::Transport* request_server { nullptr };
+ Vector<u64> ids;
+ Vector<ByteString> methods;
+};
+
+// A RequestServer client of the agent's resource loader, whose RequestServer end of the connection the test holds and
+// answers for.
+class StandInRequestServer {
+public:
+ explicit StandInRequestServer(FetchHarness const& harness)
+ : m_harness(harness)
{
- Web::ResourceLoader::initialize(heap);
+ Web::ResourceLoader::initialize(harness.realm->heap());
auto pair = MUST(IPC::Transport::create_paired());
- client = make_ref_counted<Requests::RequestClient>(move(pair.local), 1);
- Web::ResourceLoader::the().set_client({}, *client);
- request_server = MUST(pair.remote_handle.create_transport());
+ m_client = make_ref_counted<Requests::RequestClient>(move(pair.local), 1);
+ Web::ResourceLoader::the().set_client({}, *m_client);
+ m_request_server = MUST(pair.remote_handle.create_transport());
+ m_started->request_server = m_request_server.ptr();
}
- ~ResourceLoaderWithStandInRequestServer()
+ ~StandInRequestServer()
{
// The client can hear of its RequestServer's death after the resource loader is gone.
- client->on_request_server_died = nullptr;
+ m_client->on_request_server_died = nullptr;
Web::ResourceLoader::shut_down();
}
- RefPtr<Requests::RequestClient> client;
- OwnPtr<IPC::Transport> request_server;
+ // Runs the agent's tasks until another request with the method has started, and returns its id.
+ u64 wait_for_request(StringView method)
+ {
+ // The RequestServer end is not part of the event loop, so keep the loop from sleeping until it has news.
+ auto wake_timer = Core::Timer::create_repeating(AK::Duration::from_milliseconds(10), [] { });
+ wake_timer->start();
+
+ auto expected = ByteString { method };
+ m_harness.run_tasks_until(GC::create_function(m_harness.realm->heap(), GC::captures(m_started, m_taken_count, expected), [](auto& started, auto& taken_count, auto& expected) {
+ (void)started->request_server->read_as_many_messages_as_possible_without_blocking([&](auto&& raw_message) {
+ auto message = MUST(RequestServerEndpoint::decode_message(raw_message.bytes.bytes(), raw_message.attachments));
+ if (message->message_id() != Messages::RequestServer::StartRequest::static_message_id())
+ return;
+ auto const& start = static_cast<Messages::RequestServer::StartRequest&>(*message);
+ started->ids.append(start.request_id());
+ started->methods.append(start.method());
+ });
+ for (size_t index = taken_count; index < started->methods.size(); ++index) {
+ if (started->methods[index] == expected)
+ return true;
+ }
+ return false;
+ }));
+ for (size_t index = m_taken_count; index < m_started->methods.size(); ++index) {
+ if (m_started->methods[index] == method) {
+ m_taken_count = index + 1;
+ return m_started->ids[index];
+ }
+ }
+ VERIFY_NOT_REACHED();
+ }
+
+ void send(IPC::MessageBuffer message)
+ {
+ MUST(message.transfer_message(*m_request_server));
+ }
+
+ void send_headers(u64 request_id, u32 status_code, Vector<HTTP::Header> headers = {})
+ {
+ send(MUST(Messages::RequestClient::HeadersBecameAvailable::static_encode(request_id, URL::about_blank(), move(headers), status_code, Optional<String> {}, Requests::CacheState::NotCached, ByteString {})));
+ }
+
+ void send_finished(u64 request_id, Requests::RequestTimingInfo timing_info, Optional<Requests::NetworkError> network_error = {})
+ {
+ send(MUST(Messages::RequestClient::RequestFinished::static_encode(request_id, 0, timing_info, network_error)));
+ }
+
+ void send_transferred(u64 request_id)
+ {
+ send(MUST(Messages::RequestClient::RequestTransferred::static_encode(request_id)));
+ }
+
+private:
+ FetchHarness const& m_harness;
+ RefPtr<Requests::RequestClient> m_client;
+ OwnPtr<IPC::Transport> m_request_server;
+ NonnullRefPtr<StartedRequests> m_started { make_ref_counted<StartedRequests>() };
+ // The started requests a wait has already returned or passed over.
+ size_t m_taken_count { 0 };
};
}
@@ -789,7 +862,7 @@ class AdoptedNavigationBody {
public:
explicit AdoptedNavigationBody(FetchHarness const& harness)
: m_harness(harness)
- , m_resource_loader(harness.realm->heap())
+ , m_request_server(harness)
{
auto& agent = Web::HTML::surrounding_agent();
Web::Fetch::Engine::FetchExecutorServices services { .event_loop = Core::EventLoop::current_weak() };
@@ -813,11 +886,11 @@ public:
// Sends the message as RequestServer, and runs the agent's tasks until the body's request has received it.
void receive(IPC::MessageBuffer message)
{
- MUST(message.transfer_message(*m_resource_loader.request_server));
+ m_request_server.send(move(message));
auto marker = ByteString::formatted("received {}", ++m_received_count);
auto request_id = handle().request_id().value();
auto marker_message = MUST(Messages::RequestClient::HeadersBecameAvailable::static_encode(request_id, URL::about_blank(), Vector<HTTP::Header> {}, Optional<u32> {}, Optional<String> {}, Requests::CacheState::NotCached, marker));
- MUST(marker_message.transfer_message(*m_resource_loader.request_server));
+ m_request_server.send(move(marker_message));
auto weak_handle = handle().make_weak_ptr<NetworkTransportHandle>();
m_harness.run_tasks_until(GC::create_function(m_harness.realm->heap(), GC::captures(weak_handle, marker), [](auto& weak_handle, auto& marker) {
@@ -853,7 +926,7 @@ public:
private:
FetchHarness const& m_harness;
- ResourceLoaderWithStandInRequestServer m_resource_loader;
+ StandInRequestServer m_request_server;
NonnullRefPtr<PostedCommands> m_posted_commands { make_ref_counted<PostedCommands>() };
RefPtr<Web::Fetch::Engine::FetchExecutor> m_engine_executor;
GC::Root<Web::Fetch::Infrastructure::Body> m_body;
@@ -975,6 +1048,181 @@ TEST_CASE(the_holders_of_an_adopted_navigation_body_post_its_controls_to_the_age
EXPECT_EQ(adopted.commands->steps, (Vector<ByteString> { "navigation body adopted", release, release_up_to, stop }));
}
+static Requests::RequestTimingInfo finished_timing_info(i64 microseconds)
+{
+ return {
+ .domain_lookup_start_microseconds = microseconds,
+ .domain_lookup_end_microseconds = microseconds + 1000,
+ .connect_start_microseconds = microseconds + 2000,
+ .connect_end_microseconds = microseconds + 3000,
+ .request_start_microseconds = microseconds + 4000,
+ .response_start_microseconds = microseconds + 5000,
+ .encoded_body_size = 1234,
+ };
+}
+
+static FetchAlgorithms::Input recording_responses(GC::Heap& heap, NonnullRefPtr<AlgorithmCalls> const& record)
+{
+ FetchAlgorithms::Input input { Web::Fetch::Engine::BodyIntent::DrainAndDiscard };
+ input.process_response = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView> response) {
+ record->responses.append(GC::make_root(response));
+ });
+ return input;
+}
+
+static void run_until_responses(FetchHarness const& harness, NonnullRefPtr<AlgorithmCalls> const& record, size_t count)
+{
+ harness.run_tasks_until(GC::create_function(harness.realm->heap(), GC::captures(record, count), [](auto& record, auto& count) { return record->responses.size() == count; }));
+ VERIFY(record->responses.size() == count);
+}
+
+static void run_until_encoded_size(FetchHarness const& harness, NonnullRefPtr<Response const> const& response, u64 encoded_size)
+{
+ harness.run_tasks_until(GC::create_function(harness.realm->heap(), GC::captures(response, encoded_size), [](auto& response, auto& encoded_size) { return response->body_info().encoded_size == encoded_size; }));
+}
+
+namespace {
+
+// A fetch whose response has been handed over while its body still arrives from the stand-in RequestServer.
+struct DeliveredBody {
+ GC::Root<FetchController> controller;
+ NonnullRefPtr<Response const> response;
+ Web::Fetch::Engine::DeliveryId delivery_id;
+ u64 request_id { 0 };
+};
+
+}
+
+static DeliveredBody deliver_a_body(FetchHarness const& harness, StandInRequestServer& request_server, StringView url, Optional<Request::InitiatorType> initiator_type = {})
+{
+ auto record = make_ref_counted<AlgorithmCalls>();
+ auto request = harness.create_request_for(url);
+ request->set_initiator_type(initiator_type);
+ auto controller = GC::make_root(harness.fetch(request, recording_responses(harness.realm->heap(), record)));
+ auto request_id = request_server.wait_for_request("GET"sv);
+ request_server.send_headers(request_id, 200);
+ run_until_responses(harness, record, 1);
+ auto response = record->responses[0]->record()->unsafe_response();
+ auto delivery_id = response->network_transport()->body_channel->delivery_id();
+ VERIFY(delivery_id.has_value());
+ return { move(controller), move(response), *delivery_id, request_id };
+}
+
+// Reports the end of the delivered body, as the engine would once the body had arrived whole.
+static void report_end_of_body(DeliveredBody const& delivered)
+{
+ EndOfBody end_of_body {
+ .delivery_id = delivered.delivery_id,
+ .final_sizes = { .encoded_body_size = 1, .decoded_body_size = 1 },
+ .end_time = 1,
+ };
+ FetchEventSink event_sink { *delivered.controller };
+ event_sink.handle_event(move(end_of_body));
+}
+
+// A request whose response main fetch reads whole, to check its integrity, before handing it over.
+static NonnullRefPtr<Request> create_request_checked_for_integrity(FetchHarness const& harness, StringView url)
+{
+ auto request = harness.create_request_for(url);
+ request->set_mode(Request::Mode::CORS);
+ // The digest of an empty body.
+ request->set_integrity_metadata("sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="_utf16);
+ return request;
+}
+
+TEST_CASE(a_body_that_ends_before_its_response_is_handed_over_gets_its_sizes_from_its_pump)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+ StandInRequestServer request_server { harness };
+
+ auto record = make_ref_counted<AlgorithmCalls>();
+ auto request = create_request_checked_for_integrity(harness, "http://127.0.0.1:8000/ended-before-handover"sv);
+ (void)harness.fetch(request, recording_responses(harness.realm->heap(), record));
+ auto request_id = request_server.wait_for_request("GET"sv);
+ request_server.send_headers(request_id, 200, { { "Access-Control-Allow-Origin"sv, "*"sv } });
+ request_server.send_finished(request_id, finished_timing_info(1000));
+ run_until_responses(harness, record, 1);
+
+ auto response = record->responses[0]->record()->unsafe_response();
+ EXPECT_EQ(response->body_info().encoded_size, 1234u);
+ EXPECT(!response->network_transport()->body_channel->delivery_id().has_value());
+}
+
+TEST_CASE(a_body_that_ends_after_its_response_is_handed_over_gets_its_sizes_from_its_end)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+ StandInRequestServer request_server { harness };
+
+ auto delivered = deliver_a_body(harness, request_server, "http://127.0.0.1:8000/ended-after-handover"sv);
+ EXPECT_EQ(delivered.response->body_info().encoded_size, 0u);
+
+ request_server.send_finished(delivered.request_id, finished_timing_info(1000));
+ run_until_encoded_size(harness, delivered.response, 1234);
+ EXPECT_EQ(delivered.response->body_info().encoded_size, 1234u);
+}
+
+TEST_CASE(a_body_that_ends_after_its_response_is_handed_over_reports_the_end_time_of_its_end)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+ StandInRequestServer request_server { harness };
+
+ auto delivered = deliver_a_body(harness, request_server, "http://127.0.0.1:8000/reported"sv, Request::InitiatorType::Fetch);
+ report_end_of_body(delivered);
+
+ auto fetch_params = delivered.controller->original_fetch_params();
+ VERIFY(fetch_params);
+ EXPECT_EQ(fetch_params->timing_info()->end_time(), 1);
+}
+
+TEST_CASE(a_stopped_fetch_no_longer_awaits_the_end_of_its_body)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+ StandInRequestServer request_server { harness };
+
+ auto delivered = deliver_a_body(harness, request_server, "http://127.0.0.1:8000/stopped"sv);
+ delivered.controller->stop_fetch();
+ report_end_of_body(delivered);
+ EXPECT_EQ(delivered.response->body_info().encoded_size, 0u);
+}
+
+TEST_CASE(a_body_that_fails_or_moves_away_reports_no_end)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+ StandInRequestServer request_server { harness };
+
+ auto failed = deliver_a_body(harness, request_server, "http://127.0.0.1:8000/failed"sv);
+ auto transferred = deliver_a_body(harness, request_server, "http://127.0.0.1:8000/transferred"sv);
+ request_server.send_finished(failed.request_id, finished_timing_info(1000), Requests::NetworkError::IncompleteContent);
+ request_server.send_transferred(transferred.request_id);
+ auto failed_channel = failed.response->network_transport()->body_channel;
+ auto transferred_channel = transferred.response->network_transport()->body_channel;
+ harness.run_tasks_until(GC::create_function(harness.realm->heap(), GC::captures(failed_channel, transferred_channel), [](auto& failed_channel, auto& transferred_channel) {
+ return failed_channel->peek_up_to(0).state.template has<FetchByteChannel::Errored>()
+ && transferred_channel->peek_up_to(0).state.template has<FetchByteChannel::Transferred>();
+ }));
+
+ EXPECT(failed_channel->peek_up_to(0).state.has<FetchByteChannel::Errored>());
+ EXPECT(transferred_channel->peek_up_to(0).state.has<FetchByteChannel::Transferred>());
+ EXPECT_EQ(failed.response->body_info().encoded_size, 0u);
+ EXPECT_EQ(transferred.response->body_info().encoded_size, 0u);
+
+ // Each fetch still awaits the end of its body.
+ report_end_of_body(failed);
+ report_end_of_body(transferred);
+ EXPECT_EQ(failed.response->body_info().encoded_size, 1u);
+ EXPECT_EQ(transferred.response->body_info().encoded_size, 1u);
+}
+
namespace {
// The WebDriver BiDi network events that reached the event sink, by name and request id.
diff --git a/Tests/LibWeb/TestFetchBodyStream.cpp b/Tests/LibWeb/TestFetchBodyStream.cpp
index d88baf34e0a..8f67623dccd 100644
--- a/Tests/LibWeb/TestFetchBodyStream.cpp
+++ b/Tests/LibWeb/TestFetchBodyStream.cpp
@@ -11,12 +11,15 @@
#include <LibCore/Timer.h>
#include <LibJS/Runtime/TypedArray.h>
#include <LibTest/TestCase.h>
+#include <LibWeb/Fetch/Engine/EngineEvent.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/FetchController.h>
#include <LibWeb/Fetch/Infrastructure/FetchParams.h>
+#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/Scripting/Agent.h>
#include <LibWeb/HTML/Scripting/Environments.h>
@@ -25,14 +28,17 @@
#include <LibWeb/Streams/ReadableStream.h>
#include <LibWeb/Streams/ReadableStreamDefaultReader.h>
+using Web::Fetch::Engine::DeliveryId;
using Web::Fetch::Engine::FetchBodyDeliveryGate;
using Web::Fetch::Engine::FetchByteChannel;
using Web::Fetch::Engine::FetchByteChannelConsumerSink;
using Web::Fetch::Engine::FetchByteChannelProducerSink;
+using Web::Fetch::Engine::Event::EndOfBody;
using Web::Fetch::Infrastructure::Body;
using Web::Fetch::Infrastructure::FetchAlgorithms;
using Web::Fetch::Infrastructure::FetchParams;
using Web::Fetch::Infrastructure::MAX_SNIFF_BYTES;
+using Web::Fetch::Infrastructure::Response;
namespace {
@@ -484,7 +490,16 @@ TEST_CASE(stopping_a_whole_body_transport_cancels_its_channel_and_wakes_its_read
EXPECT_EQ(reader->wake_count, 1u);
}
-TEST_CASE(network_completion_runs_only_the_steps_awaited_for_its_body)
+static EndOfBody end_of_body(DeliveryId delivery_id, u64 encoded_body_size, u64 decoded_body_size, double end_time)
+{
+ return {
+ .delivery_id = delivery_id,
+ .final_sizes = { .encoded_body_size = encoded_body_size, .decoded_body_size = decoded_body_size },
+ .end_time = end_time,
+ };
+}
+
+TEST_CASE(the_end_of_a_body_runs_only_the_steps_awaited_for_its_delivery)
{
Core::EventLoop event_loop;
install_font_plugin();
@@ -492,24 +507,59 @@ TEST_CASE(network_completion_runs_only_the_steps_awaited_for_its_body)
auto& heap = harness.realm->heap();
auto& controller_registry = static_cast<Web::HTML::Agent&>(*harness.realm->vm().agent()).fetch_controller_registry;
auto controller = Web::Fetch::Infrastructure::FetchController::create(controller_registry);
- auto earlier = FetchByteChannel::create({ .low = 16, .high = 64 }, adopt_ref(*new IgnoringProducerSink));
- auto later = FetchByteChannel::create({ .low = 16, .high = 64 }, adopt_ref(*new IgnoringProducerSink));
+ auto earlier = Response::create();
+ auto later = Response::create();
- // A later body's steps replace an earlier body's, and run once.
+ // A later delivery's steps replace an earlier delivery's, and run once, given the body's end time.
auto earlier_runs = make_ref_counted<SharedValue<size_t>>();
- auto later_runs = make_ref_counted<SharedValue<size_t>>();
- controller->when_network_completes_body(*earlier, GC::create_function(heap, GC::captures(earlier_runs), [](auto& earlier_runs) { ++earlier_runs->value; }));
- controller->when_network_completes_body(*later, GC::create_function(heap, GC::captures(later_runs), [](auto& later_runs) { ++later_runs->value; }));
- controller->did_complete_network_body(*earlier);
+ auto later_end_times = make_ref_counted<SharedValue<Vector<double>>>();
+ controller->when_body_ends(DeliveryId(1), earlier, GC::create_function(heap, GC::captures(earlier_runs), [](auto& earlier_runs, double) { ++earlier_runs->value; }));
+ controller->when_body_ends(DeliveryId(2), later, GC::create_function(heap, GC::captures(later_end_times), [](auto& later_end_times, double end_time) { later_end_times->value.append(end_time); }));
+ controller->did_end_body(end_of_body(DeliveryId(1), 10, 20, 30));
EXPECT_EQ(earlier_runs->value, 0u);
- EXPECT_EQ(later_runs->value, 0u);
- controller->did_complete_network_body(*later);
- controller->did_complete_network_body(*later);
- EXPECT_EQ(later_runs->value, 1u);
-
- // A stopped fetch runs no awaited steps.
- controller->when_network_completes_body(*earlier, GC::create_function(heap, GC::captures(earlier_runs), [](auto& earlier_runs) { ++earlier_runs->value; }));
+ EXPECT(later_end_times->value.is_empty());
+ EXPECT_EQ(earlier->body_info().encoded_size, 0u);
+ controller->did_end_body(end_of_body(DeliveryId(2), 40, 50, 60));
+ controller->did_end_body(end_of_body(DeliveryId(2), 70, 80, 90));
+ EXPECT_EQ(later_end_times->value, (Vector<double> { 60 }));
+ EXPECT_EQ(later->body_info().encoded_size, 40u);
+ EXPECT_EQ(later->body_info().decoded_size, 50u);
+
+ // A stopped fetch runs no awaited steps and records no sizes.
+ controller->when_body_ends(DeliveryId(3), earlier, GC::create_function(heap, GC::captures(earlier_runs), [](auto& earlier_runs, double) { ++earlier_runs->value; }));
controller->stop_fetch();
- controller->did_complete_network_body(*earlier);
+ controller->did_end_body(end_of_body(DeliveryId(3), 10, 20, 30));
EXPECT_EQ(earlier_runs->value, 0u);
+ EXPECT_EQ(earlier->body_info().encoded_size, 0u);
+}
+
+TEST_CASE(the_end_of_a_body_without_steps_records_its_sizes)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ BodyStreamHarness harness;
+ auto& controller_registry = static_cast<Web::HTML::Agent&>(*harness.realm->vm().agent()).fetch_controller_registry;
+ auto controller = Web::Fetch::Infrastructure::FetchController::create(controller_registry);
+ auto response = Response::create();
+
+ controller->when_body_ends(DeliveryId(1), response, nullptr);
+ controller->did_end_body(end_of_body(DeliveryId(1), 10, 20, 30));
+ EXPECT_EQ(response->body_info().encoded_size, 10u);
+ EXPECT_EQ(response->body_info().decoded_size, 20u);
+}
+
+TEST_CASE(an_awaited_end_of_body_does_not_keep_its_response)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ BodyStreamHarness harness;
+ auto& controller_registry = static_cast<Web::HTML::Agent&>(*harness.realm->vm().agent()).fetch_controller_registry;
+ auto controller = Web::Fetch::Infrastructure::FetchController::create(controller_registry);
+ RefPtr<Response> response = Response::create();
+ auto weak_response = response->make_weak_ptr<Response>();
+
+ controller->when_body_ends(DeliveryId(1), *response, nullptr);
+ response = nullptr;
+ EXPECT(!weak_response.strong_ref());
+ controller->did_end_body(end_of_body(DeliveryId(1), 10, 20, 30));
}