Skip to content

Truly independent web browser

LibWeb: Give a fetch's agent its own copy of the fetch's timing

Luke Wilde81a3266a1cbd
diff --git a/Libraries/LibWeb/Fetch/Engine/EngineEvent.h b/Libraries/LibWeb/Fetch/Engine/EngineEvent.h
index c85de8396e1..0dfec960e2d 100644
--- a/Libraries/LibWeb/Fetch/Engine/EngineEvent.h
+++ b/Libraries/LibWeb/Fetch/Engine/EngineEvent.h
@@ -11,7 +11,6 @@
#include <LibWeb/Fetch/Engine/FetchTimingSeed.h>
#include <LibWeb/Fetch/Engine/Ids.h>
#include <LibWeb/Fetch/Engine/NetworkActivity.h>
-#include <LibWeb/Fetch/Engine/RequestEnd.h>
#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>
namespace Web::Fetch::Engine::Event {
@@ -66,10 +65,10 @@ struct RequestTransmissionStarted {
TransmissionGeneration generation;
};
+// A timing update: the network phases a load of the fetch's request settled as it finished. Only a load that completes
+// sends one.
struct RequestTransmissionEnded {
- TransmissionId transmission_id;
- TransmissionGeneration generation;
- RequestEnd request_end;
+ FetchNetworkPhases network_phases;
};
// The length of one more chunk of a request's body.
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchTimingSeed.h b/Libraries/LibWeb/Fetch/Engine/FetchTimingSeed.h
index 9299f779c08..8134950e092 100644
--- a/Libraries/LibWeb/Fetch/Engine/FetchTimingSeed.h
+++ b/Libraries/LibWeb/Fetch/Engine/FetchTimingSeed.h
@@ -6,7 +6,6 @@
#pragma once
-#include <AK/Optional.h>
#include <AK/String.h>
#include <AK/Vector.h>
#include <LibWebCommon/Fetch/Infrastructure/ConnectionTimingInfo.h>
@@ -14,19 +13,22 @@
namespace Web::Fetch::Engine {
-// The timing fields settled at final response handover.
+// The timing fields a response handover gives the agent that started the fetch.
struct FetchTimingSeed {
HighResolutionTime::DOMHighResTimeStamp start_time { 0 };
HighResolutionTime::DOMHighResTimeStamp redirect_start_time { 0 };
HighResolutionTime::DOMHighResTimeStamp redirect_end_time { 0 };
HighResolutionTime::DOMHighResTimeStamp post_redirect_start_time { 0 };
HighResolutionTime::DOMHighResTimeStamp final_service_worker_start_time { 0 };
- HighResolutionTime::DOMHighResTimeStamp final_network_request_start_time { 0 };
- HighResolutionTime::DOMHighResTimeStamp first_interim_network_response_start_time { 0 };
- HighResolutionTime::DOMHighResTimeStamp final_network_response_start_time { 0 };
- Optional<Infrastructure::ConnectionTimingInfo> final_connection_timing_info;
Vector<String> server_timing_headers;
bool render_blocking { false };
};
+// The timing fields a load of a fetch's request settles once it has finished.
+struct FetchNetworkPhases {
+ Infrastructure::ConnectionTimingInfo final_connection_timing_info;
+ HighResolutionTime::DOMHighResTimeStamp final_network_request_start_time { 0 };
+ HighResolutionTime::DOMHighResTimeStamp final_network_response_start_time { 0 };
+};
+
}
diff --git a/Libraries/LibWeb/Fetch/Engine/Ids.h b/Libraries/LibWeb/Fetch/Engine/Ids.h
index 3da90bdb42c..35eb7a3dbdc 100644
--- a/Libraries/LibWeb/Fetch/Engine/Ids.h
+++ b/Libraries/LibWeb/Fetch/Engine/Ids.h
@@ -17,7 +17,6 @@ AK_TYPEDEF_DISTINCT_ORDERED_ID(u64, DeliveryId);
AK_TYPEDEF_DISTINCT_ORDERED_ID(u64, ContinuationId);
AK_TYPEDEF_DISTINCT_ORDERED_ID(u64, TransmissionId);
AK_TYPEDEF_DISTINCT_ORDERED_ID(u64, TransmissionGeneration);
-AK_TYPEDEF_DISTINCT_ORDERED_ID(u64, AttemptId);
// Identifies one wait for a body's bytes, and travels with the wake that ends it.
AK_TYPEDEF_DISTINCT_ORDERED_ID(u64, WakeTicket);
diff --git a/Libraries/LibWeb/Fetch/Engine/RequestEnd.h b/Libraries/LibWeb/Fetch/Engine/RequestEnd.h
deleted file mode 100644
index f6522570b32..00000000000
--- a/Libraries/LibWeb/Fetch/Engine/RequestEnd.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Time.h>
-#include <AK/Variant.h>
-#include <LibRequests/ALPNHttpVersion.h>
-#include <LibRequests/NetworkError.h>
-#include <LibWeb/Fetch/Engine/Ids.h>
-
-namespace Web::Fetch::Engine {
-
-// One arm per way a request can end.
-struct RequestEnd {
- struct NetworkSuccess {
- AttemptId attempt_id;
- u64 encoded_body_size { 0 };
- Requests::ALPNHttpVersion alpn { Requests::ALPNHttpVersion::None };
- };
- struct LocalSuccess {
- u64 encoded_body_size { 0 };
- };
- struct AttemptFailedBeforeHeaders {
- AttemptId attempt_id;
- Requests::NetworkError error;
- };
- struct CommittedAttemptFailed {
- AttemptId attempt_id;
- Requests::NetworkError error;
- u64 encoded_body_size { 0 };
- };
- struct LocalFailed {
- Requests::NetworkError error;
- u64 encoded_body_size { 0 };
- };
- struct FailedBeforeTransport {
- Requests::NetworkError error;
- };
-
- using Outcome = Variant<NetworkSuccess, LocalSuccess, AttemptFailedBeforeHeaders, CommittedAttemptFailed, LocalFailed, FailedBeforeTransport>;
-
- RequestId request_id;
- TransportEpoch transport_epoch;
- MonotonicTime transport_complete_at;
- Outcome outcome;
-};
-
-}
diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.cpp b/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.cpp
index 4c12d5fffdc..0958b37d540 100644
--- a/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.cpp
@@ -162,6 +162,9 @@ void FetchEventSink::handle_event(Engine::EngineEvent event)
[&](Engine::Event::NetworkActivity const& network_activity) {
controller->page()->did_receive_network_activity(network_activity);
},
+ [&](Engine::Event::RequestTransmissionEnded const& ended) {
+ controller->control_block().settle_network_phases(ended.network_phases);
+ },
[&](Engine::Event::EndOfBody const& end_of_body) {
controller->did_end_body(end_of_body);
},
@@ -169,8 +172,7 @@ void FetchEventSink::handle_event(Engine::EngineEvent event)
[](Engine::Event::ConsumeBodyResult const&) { VERIFY_NOT_REACHED(); },
[](Engine::Event::BodyChannelReadable const&) { VERIFY_NOT_REACHED(); },
[](Engine::Event::DeliveryEnd const&) { VERIFY_NOT_REACHED(); },
- [](Engine::Event::RequestTransmissionStarted const&) { VERIFY_NOT_REACHED(); },
- [](Engine::Event::RequestTransmissionEnded const&) { VERIFY_NOT_REACHED(); });
+ [](Engine::Event::RequestTransmissionStarted const&) { VERIFY_NOT_REACHED(); });
}
}
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index d0ce3ca5daa..fc15fb37761 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -1074,7 +1074,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
auto internal_response = response.unsafe_response();
WebDriver::BiDi::network_response_started(fetch_params, *internal_response);
if (fetch_params.request()->is_navigation_request() && !internal_response->network_transport().has_value())
- WebDriver::BiDi::network_response_completed(fetch_params, *internal_response);
+ WebDriver::BiDi::network_response_completed(fetch_params, *internal_response, *timing_info);
}
}
@@ -1095,6 +1095,11 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
timing_info->set_server_timing_headers(server_timing_headers.release_value());
}
+ // AD-HOC: timingInfo belongs to the fetch's engine, so the steps below use the agent's own copy of it, made of the
+ // fields settled so far, the network phases settled last and the end time last set for the fetch. Those
+ // settled or set later reach the latest handover's copy.
+ auto agent_timing_info = fetch_params.control_block().hand_over_timing(timing_info->seed());
+
// https://html.spec.whatwg.org/multipage/document-lifecycle.html#initialise-the-document-object
// NOTE: The create and initialize a Document object algorithm extracts full timing info for navigation requests
// whose destination can also be "embed", "frame", "iframe", or "object".
@@ -1102,7 +1107,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
// 3. If fetchParams's request's destination is "document", then set fetchParams's controller's full timing info
// to fetchParams's timing info.
if (fetch_params.request()->is_navigation_request())
- fetch_params.control_block().set_full_timing_info(fetch_params.timing_info());
+ fetch_params.control_block().set_full_timing_info(agent_timing_info);
// 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
@@ -1112,7 +1117,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
// 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, HighResolutionTime::DOMHighResTimeStamp unsafe_end_time) {
+ auto setup_report_timing_steps = GC::create_function(GC::Heap::the(), GC::captures(response_view->record(), NonnullRefPtr { fetch_params }, controller, agent_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.
@@ -1130,6 +1135,9 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
// it always a negative value approximately the value of the time origin.
// https://github.com/whatwg/fetch/issues/1812
timing_info->set_end_time(unsafe_end_time);
+ // AD-HOC: The agent keeps this as the end time last set for the fetch, which later handovers and WebDriver
+ // BiDi's events take.
+ fetch_params->control_block().set_end_time(unsafe_end_time);
// 3. Let cacheState be response’s cache state.
auto cache_state = response->cache_state();
@@ -1194,14 +1202,14 @@ 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) {
+ auto process_response_end_of_body = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { fetch_params }, controller, response_view, agent_timing_info, setup_report_timing_steps, report_timing_if_appropriate), [](auto& fetch_params, auto& controller, auto& response_view, auto& agent_timing_info, auto& setup_report_timing_steps, auto& report_timing_if_appropriate) {
// 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());
+ WebDriver::BiDi::network_response_completed(fetch_params, *response_view->record()->unsafe_response(), *agent_timing_info);
// 3. Let processResponseEndOfBodyTask be the following steps:
auto process_response_end_of_body_task = GC::create_function(GC::Heap::the(), GC::captures(fetch_params, controller, response_view, report_timing_if_appropriate), [](auto& fetch_params, auto& controller, auto& response_view, auto& report_timing_if_appropriate) {
@@ -1238,11 +1246,11 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
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) {
+ network_completion_steps = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { fetch_params }, response_view, agent_timing_info, setup_report_timing_steps, report_timing_if_appropriate), [](auto& fetch_params, auto& response_view, auto& agent_timing_info, 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());
+ WebDriver::BiDi::network_response_completed(*fetch_params, *response_view->record()->unsafe_response(), *agent_timing_info);
});
}
auto run_network_completion_steps_now = [&] {
@@ -1917,7 +1925,7 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParam
// 6. If internalResponse’s status is a redirect status:
if (Infrastructure::is_redirect_status(internal_response->status())) {
if (WebDriver::BiDi::network_events_enabled())
- WebDriver::BiDi::network_response_completed(fetch_params, *internal_response);
+ WebDriver::BiDi::network_response_completed(fetch_params, *internal_response, *fetch_params->timing_info());
// 1. If request is a navigation request, then append to request's navigation timing allow values list
// given request and internalResponse.
if (request->is_navigation_request())
@@ -3060,11 +3068,16 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
body_pump->set_cached_response_body(move(data));
});
- auto complete_load = GC::create_function(GC::Heap::the(), GC::captures(realm, pending_response, body_pump, request, fetch_timing_info, cross_origin_isolated_capability), [](auto& realm, auto& pending_response, auto& body_pump, auto& request, auto& fetch_timing_info, auto& cross_origin_isolated_capability, bool success, Requests::RequestTimingInfo const& timing_info, Optional<StringView> error_message) {
+ // A CORS preflight's network phases are those of its own timing info, not the fetch's.
+ auto reports_network_phases = !fetch_params.is_cors_preflight();
+ auto complete_load = GC::create_function(GC::Heap::the(), GC::captures(realm, pending_response, body_pump, request, fetch_timing_info, cross_origin_isolated_capability, NonnullRefPtr { *engine_record }, reports_network_phases), [](auto& realm, auto& pending_response, auto& body_pump, auto& request, auto& fetch_timing_info, auto& cross_origin_isolated_capability, auto& engine_record, auto& reports_network_phases, bool success, Requests::RequestTimingInfo const& timing_info, Optional<StringView> error_message) {
HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
if (success) {
- fetch_timing_info->update_final_timings(timing_info, cross_origin_isolated_capability);
+ auto network_phases = fetch_timing_info->final_network_phases(timing_info, cross_origin_isolated_capability);
+ fetch_timing_info->set_network_phases(network_phases);
+ if (reports_network_phases)
+ engine_record->event_sink().handle_event(Engine::Event::RequestTransmissionEnded { move(network_phases) });
body_pump->handle_network_complete(Infrastructure::is_http_or_https_scheme(request->current_url().scheme()) ? Optional<i64>(timing_info.encoded_body_size) : Optional<i64> {});
} else {
auto error = Utf16String::formatted("Load failed: {}", error_message.value_or("Unknown error"sv));
@@ -3252,7 +3265,7 @@ GC::Ref<PendingResponse> cors_preflight_fetch(JS::Realm& realm, Infrastructure::
if (response->is_network_error())
WebDriver::BiDi::network_fetch_error(*preflight_fetch_params, response->network_error_message().value_or("Preflight failed"_string));
else
- WebDriver::BiDi::network_response_completed(*preflight_fetch_params, *response);
+ WebDriver::BiDi::network_response_completed(*preflight_fetch_params, *response, *preflight_fetch_params->timing_info());
}
// NB: Only the preflight response's headers are read.
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchControlBlock.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchControlBlock.h
index ddfd555dba8..436b3518fd6 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchControlBlock.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchControlBlock.h
@@ -9,9 +9,11 @@
#include <AK/AtomicRefCounted.h>
#include <AK/Badge.h>
#include <AK/NonnullRefPtr.h>
+#include <AK/Optional.h>
#include <AK/RefPtr.h>
#include <LibGC/Forward.h>
#include <LibWeb/Fetch/Engine/BodyIntent.h>
+#include <LibWeb/Fetch/Engine/FetchTimingSeed.h>
#include <LibWeb/Fetch/Infrastructure/FetchTimingInfo.h>
namespace Web::Fetch::Infrastructure {
@@ -55,6 +57,37 @@ public:
[[nodiscard]] RefPtr<FetchTimingInfo> full_timing_info() const { return m_full_timing_info; }
void set_full_timing_info(NonnullRefPtr<FetchTimingInfo> full_timing_info) { m_full_timing_info = move(full_timing_info); }
+ // The agent's timing state, which only the thread of the agent that started the fetch reads and writes.
+
+ // The timing info the agent has of its latest response handover.
+ [[nodiscard]] RefPtr<FetchTimingInfo> agent_timing_info() const { return m_agent_timing_info; }
+ // Makes the agent's timing info from the fields a response handover gives it, the network phases settled last and
+ // the fetch's end time.
+ NonnullRefPtr<FetchTimingInfo> hand_over_timing(Engine::FetchTimingSeed const& seed)
+ {
+ auto timing_info = FetchTimingInfo::create(seed);
+ if (m_network_phases.has_value())
+ timing_info->set_network_phases(*m_network_phases);
+ timing_info->set_end_time(m_end_time);
+ m_agent_timing_info = timing_info;
+ return timing_info;
+ }
+ // Gives the network phases a load of the fetch settled to the agent's timing info, and to that of later handovers.
+ void settle_network_phases(Engine::FetchNetworkPhases network_phases)
+ {
+ if (m_agent_timing_info)
+ m_agent_timing_info->set_network_phases(network_phases);
+ m_network_phases = move(network_phases);
+ }
+ // The end time last set for the fetch, or 0, which the agent's timing info has, as do those of later handovers.
+ [[nodiscard]] HighResolutionTime::DOMHighResTimeStamp end_time() const { return m_end_time; }
+ void set_end_time(HighResolutionTime::DOMHighResTimeStamp end_time)
+ {
+ if (m_agent_timing_info)
+ m_agent_timing_info->set_end_time(end_time);
+ m_end_time = end_time;
+ }
+
[[nodiscard]] Engine::BodyIntent body_intent() const { return m_body_intent; }
void set_body_intent(Badge<FetchController>, Engine::BodyIntent body_intent)
{
@@ -86,6 +119,11 @@ private:
// Null or a fetch timing info.
RefPtr<FetchTimingInfo> m_full_timing_info;
+ // The agent's timing state, which only the thread of the agent that started the fetch reads and writes.
+ RefPtr<FetchTimingInfo> m_agent_timing_info;
+ Optional<Engine::FetchNetworkPhases> m_network_phases;
+ HighResolutionTime::DOMHighResTimeStamp m_end_time { 0 };
+
Engine::BodyIntent m_body_intent { Engine::BodyIntent::DrainAndDiscard };
bool m_response_arrived { false };
bool m_has_started_request { false };
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchTimingInfo.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchTimingInfo.cpp
index 0e3e456dd4b..8dd5269a04f 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchTimingInfo.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchTimingInfo.cpp
@@ -17,6 +17,32 @@ NonnullRefPtr<FetchTimingInfo> FetchTimingInfo::create()
return adopt_ref(*new FetchTimingInfo);
}
+NonnullRefPtr<FetchTimingInfo> FetchTimingInfo::create(Engine::FetchTimingSeed const& seed)
+{
+ auto timing_info = create();
+ timing_info->m_start_time = seed.start_time;
+ timing_info->m_redirect_start_time = seed.redirect_start_time;
+ timing_info->m_redirect_end_time = seed.redirect_end_time;
+ timing_info->m_post_redirect_start_time = seed.post_redirect_start_time;
+ timing_info->m_final_service_worker_start_time = seed.final_service_worker_start_time;
+ timing_info->m_server_timing_headers = seed.server_timing_headers;
+ timing_info->m_render_blocking = seed.render_blocking;
+ return timing_info;
+}
+
+Engine::FetchTimingSeed FetchTimingInfo::seed() const
+{
+ return {
+ .start_time = m_start_time,
+ .redirect_start_time = m_redirect_start_time,
+ .redirect_end_time = m_redirect_end_time,
+ .post_redirect_start_time = m_post_redirect_start_time,
+ .final_service_worker_start_time = m_final_service_worker_start_time,
+ .server_timing_headers = m_server_timing_headers,
+ .render_blocking = m_render_blocking,
+ };
+}
+
// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info
NonnullRefPtr<FetchTimingInfo> create_opaque_timing_info(FetchTimingInfo const& timing_info)
{
@@ -32,7 +58,7 @@ NonnullRefPtr<FetchTimingInfo> create_opaque_timing_info(FetchTimingInfo const&
return new_timing_info;
}
-void FetchTimingInfo::update_final_timings(Requests::RequestTimingInfo const& final_timings, HTML::CanUseCrossOriginIsolatedAPIs cross_origin_isolated_capability)
+Engine::FetchNetworkPhases FetchTimingInfo::final_network_phases(Requests::RequestTimingInfo const& final_timings, HTML::CanUseCrossOriginIsolatedAPIs cross_origin_isolated_capability) const
{
// RequestServer measures each hop from the start of its own request, so the final hop's offsets are relative to
// the post-redirect start time.
@@ -58,22 +84,36 @@ void FetchTimingInfo::update_final_timings(Requests::RequestTimingInfo const& fi
coarsened_secure_connection_start_time = HighResolutionTime::coarsen_time(secure_connect_start_time_milliseconds, cross_origin_isolated_capability);
}
- m_final_connection_timing_info = ConnectionTimingInfo {
- .domain_lookup_start_time = coarsened_domain_lookup_start_time,
- .domain_lookup_end_time = coarsened_domain_lookup_end_time,
- .connection_start_time = coarsened_connection_start_time,
- .connection_end_time = coarsened_connection_end_time,
- .secure_connection_start_time = coarsened_secure_connection_start_time,
- .alpn_negotiated_protocol = alpn_http_version_to_byte_string(final_timings.http_version_alpn_identifier),
- };
-
auto request_start_time_milliseconds = final_request_start_time + (static_cast<HighResolutionTime::DOMHighResTimeStamp>(final_timings.request_start_microseconds) / 1000.0);
auto coarsened_request_start_time = HighResolutionTime::coarsen_time(request_start_time_milliseconds, cross_origin_isolated_capability);
- m_final_network_request_start_time = coarsened_request_start_time;
auto response_start_time_milliseconds = final_request_start_time + (static_cast<HighResolutionTime::DOMHighResTimeStamp>(final_timings.response_start_microseconds) / 1000.0);
auto coarsened_response_start_time = HighResolutionTime::coarsen_time(response_start_time_milliseconds, cross_origin_isolated_capability);
- m_final_network_response_start_time = coarsened_response_start_time;
+
+ return {
+ .final_connection_timing_info = {
+ .domain_lookup_start_time = coarsened_domain_lookup_start_time,
+ .domain_lookup_end_time = coarsened_domain_lookup_end_time,
+ .connection_start_time = coarsened_connection_start_time,
+ .connection_end_time = coarsened_connection_end_time,
+ .secure_connection_start_time = coarsened_secure_connection_start_time,
+ .alpn_negotiated_protocol = alpn_http_version_to_byte_string(final_timings.http_version_alpn_identifier),
+ },
+ .final_network_request_start_time = coarsened_request_start_time,
+ .final_network_response_start_time = coarsened_response_start_time,
+ };
+}
+
+void FetchTimingInfo::set_network_phases(Engine::FetchNetworkPhases network_phases)
+{
+ m_final_connection_timing_info = move(network_phases.final_connection_timing_info);
+ m_final_network_request_start_time = network_phases.final_network_request_start_time;
+ m_final_network_response_start_time = network_phases.final_network_response_start_time;
+}
+
+void FetchTimingInfo::update_final_timings(Requests::RequestTimingInfo const& final_timings, HTML::CanUseCrossOriginIsolatedAPIs cross_origin_isolated_capability)
+{
+ set_network_phases(final_network_phases(final_timings, cross_origin_isolated_capability));
}
// The values of a FetchTimingInfo, as Bindings/Rust/src/fetch/infrastructure/fetch_timing_info.rs reads them.
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchTimingInfo.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchTimingInfo.h
index 4e2c2cac9d1..09b3ac98961 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchTimingInfo.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchTimingInfo.h
@@ -12,6 +12,7 @@
#include <AK/Vector.h>
#include <LibRequests/Forward.h>
#include <LibWeb/Export.h>
+#include <LibWeb/Fetch/Engine/FetchTimingSeed.h>
#include <LibWebCommon/Fetch/Infrastructure/ConnectionTimingInfo.h>
#include <LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.h>
#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>
@@ -24,6 +25,9 @@ public:
GC_HOLDS_NO_CELL_EDGES;
[[nodiscard]] static NonnullRefPtr<FetchTimingInfo> create();
+ [[nodiscard]] static NonnullRefPtr<FetchTimingInfo> create(Engine::FetchTimingSeed const&);
+
+ [[nodiscard]] Engine::FetchTimingSeed seed() const;
[[nodiscard]] HighResolutionTime::DOMHighResTimeStamp start_time() const { return m_start_time; }
void set_start_time(HighResolutionTime::DOMHighResTimeStamp start_time) { m_start_time = start_time; }
@@ -62,6 +66,8 @@ public:
[[nodiscard]] bool render_blocking() const { return m_render_blocking; }
void set_render_blocking(bool render_blocking) { m_render_blocking = render_blocking; }
+ [[nodiscard]] Engine::FetchNetworkPhases final_network_phases(Requests::RequestTimingInfo const& final_timings, HTML::CanUseCrossOriginIsolatedAPIs cross_origin_isolated_capability) const;
+ void set_network_phases(Engine::FetchNetworkPhases);
void update_final_timings(Requests::RequestTimingInfo const& final_timings, HTML::CanUseCrossOriginIsolatedAPIs cross_origin_isolated_capability);
private:
diff --git a/Libraries/LibWeb/WebDriver/BiDi/Network.cpp b/Libraries/LibWeb/WebDriver/BiDi/Network.cpp
index c074912a25f..e2542d813ac 100644
--- a/Libraries/LibWeb/WebDriver/BiDi/Network.cpp
+++ b/Libraries/LibWeb/WebDriver/BiDi/Network.cpp
@@ -368,7 +368,7 @@ static u64 headers_size(HTTP::HeaderList const& headers)
}
// https://w3c.github.io/webdriver-bidi/#get-the-fetch-timings
-static JsonObject get_the_fetch_timings(FetchTimingInfo const& timings, Optional<double> time_origin, double epoch_origin)
+static JsonObject get_the_fetch_timings(FetchTimingInfo const& timings, HighResolutionTime::DOMHighResTimeStamp end_time, Optional<double> time_origin, double epoch_origin)
{
JsonObject result;
result.set("timeOrigin"sv, epoch_origin);
@@ -389,20 +389,26 @@ static JsonObject get_the_fetch_timings(FetchTimingInfo const& timings, Optional
result.set("tlsStart"sv, convert(connection.secure_connection_start_time));
result.set("requestStart"sv, convert(timings.final_network_request_start_time()));
result.set("responseStart"sv, convert(timings.final_network_response_start_time()));
- result.set("responseEnd"sv, convert(timings.end_time()));
+ result.set("responseEnd"sv, convert(end_time));
return result;
}
-static JsonObject get_the_fetch_timings(Request const& request, FetchTimingInfo const& timings)
+static JsonObject get_the_fetch_timings(Request const& request, FetchTimingInfo const& timings, HighResolutionTime::DOMHighResTimeStamp end_time)
{
auto const& client = request.client_snapshot();
if (!client)
- return get_the_fetch_timings(timings, {}, 0);
- return get_the_fetch_timings(timings, client->time_origin, client->time_origin - HighResolutionTime::estimated_monotonic_time_of_the_unix_epoch());
+ return get_the_fetch_timings(timings, end_time, {}, 0);
+ return get_the_fetch_timings(timings, end_time, client->time_origin, client->time_origin - HighResolutionTime::estimated_monotonic_time_of_the_unix_epoch());
+}
+
+// A fetch's events report the end time last set for it, which the agent that started it keeps.
+static HighResolutionTime::DOMHighResTimeStamp end_time_of(FetchParams const& fetch_params)
+{
+ return fetch_params.control_block().end_time();
}
// https://w3c.github.io/webdriver-bidi/#get-the-request-data
-static JsonObject get_the_request_data(NetworkRequest const& state, Request const& request, FetchTimingInfo const& timings)
+static JsonObject get_the_request_data(NetworkRequest const& state, Request const& request, FetchTimingInfo const& timings, HighResolutionTime::DOMHighResTimeStamp end_time)
{
JsonObject result;
result.set("request"sv, state.id);
@@ -426,7 +432,7 @@ static JsonObject get_the_request_data(NetworkRequest const& state, Request cons
result.set("bodySize"sv, move(body_size));
result.set("destination"sv, request.destination().has_value() ? request_destination_to_string(*request.destination()) : ""sv);
result.set("initiatorType"sv, request.initiator_type().has_value() ? JsonValue(initiator_type_to_string(*request.initiator_type()).to_utf16_string().to_utf8()) : JsonValue {});
- result.set("timings"sv, get_the_fetch_timings(request, timings));
+ result.set("timings"sv, get_the_fetch_timings(request, timings, end_time));
return result;
}
@@ -527,7 +533,7 @@ static JsonObject get_the_response_data(Response const& response, FetchTimingInf
}
// https://w3c.github.io/webdriver-bidi/#process-a-network-event
-static JsonObject process_a_network_event(HTML::Navigable const& navigable, NetworkRequest const& state, Request const& request, FetchTimingInfo const& timing_info)
+static JsonObject process_a_network_event(HTML::Navigable const& navigable, NetworkRequest const& state, Request const& request, FetchTimingInfo const& timing_info, HighResolutionTime::DOMHighResTimeStamp end_time)
{
JsonObject params;
params.set("context"sv, navigable_id(navigable));
@@ -542,8 +548,8 @@ static JsonObject process_a_network_event(HTML::Navigable const& navigable, Netw
if (auto cached = state.request_data.get(request.redirect_count()); cached.has_value())
request_data = *cached;
else
- request_data = get_the_request_data(state, request, timing_info);
- request_data.set("timings"sv, get_the_fetch_timings(request, timing_info));
+ request_data = get_the_request_data(state, request, timing_info, end_time);
+ request_data.set("timings"sv, get_the_fetch_timings(request, timing_info, end_time));
params.set("request"sv, move(request_data));
params.set("timestamp"sv, UnixDateTime::now().milliseconds_since_epoch());
return params;
@@ -652,7 +658,7 @@ static ErrorOr<JsonValue, Error> continue_network_request_impl(StringView method
request->header_list()->set({ "Content-Length"sv, ByteString::number(*body.length()) });
}
- state->request_data.set(request->redirect_count(), get_the_request_data(*state, *request, *blocked->fetch_params->timing_info()));
+ state->request_data.set(request->redirect_count(), get_the_request_data(*state, *request, *blocked->fetch_params->timing_info(), end_time_of(*blocked->fetch_params)));
if (params.has("url"sv) || params.has("method"sv) || params.has("headers"sv) || params.has("body"sv) || params.has("cookies"sv))
action = NetworkContinuationAction::ContinueWithModifiedRequest;
} else if (method == "network.failRequest"sv) {
@@ -744,9 +750,9 @@ void network_before_request_sent(FetchParams const& fetch_params)
// 4. Let redirect count be request's redirect count.
// 5. Add redirect count to before request sent map[request].
state->before_request_sent.set(request->redirect_count());
- state->request_data.set(request->redirect_count(), get_the_request_data(*state, *request, *fetch_params.timing_info()));
+ state->request_data.set(request->redirect_count(), get_the_request_data(*state, *request, *fetch_params.timing_info(), end_time_of(fetch_params)));
if (is_event_enabled("network.beforeRequestSent"sv))
- emit_event(*navigable, "network.beforeRequestSent"_string, process_a_network_event(*navigable, *state, *fetch_params.request(), *fetch_params.timing_info()));
+ emit_event(*navigable, "network.beforeRequestSent"_string, process_a_network_event(*navigable, *state, *fetch_params.request(), *fetch_params.timing_info(), end_time_of(fetch_params)));
}
// https://w3c.github.io/webdriver-bidi/#event-network-responseStarted
@@ -763,7 +769,7 @@ void network_response_started(FetchParams const& fetch_params, Response& respons
state->response_started.set(request->redirect_count());
// 5. Let sessions be the set of sessions for which an event is enabled given "network.responseStarted" and related navigables.
if (is_event_enabled("network.responseStarted"sv)) {
- auto params = process_a_network_event(*navigable, *state, *fetch_params.request(), *fetch_params.timing_info());
+ auto params = process_a_network_event(*navigable, *state, *fetch_params.request(), *fetch_params.timing_info(), end_time_of(fetch_params));
params.set("response"sv, get_the_response_data(response, *fetch_params.timing_info()));
emit_event(*navigable, "network.responseStarted"_string, move(params));
}
@@ -778,13 +784,13 @@ void network_auth_required(FetchParams const& fetch_params, Response const& resp
auto navigable = navigable_of(*state);
if (!navigable)
return;
- auto params = process_a_network_event(*navigable, *state, *fetch_params.request(), *fetch_params.timing_info());
+ auto params = process_a_network_event(*navigable, *state, *fetch_params.request(), *fetch_params.timing_info(), end_time_of(fetch_params));
params.set("response"sv, get_the_response_data(response, *fetch_params.timing_info()));
emit_event(*navigable, "network.authRequired"_string, move(params));
}
// https://w3c.github.io/webdriver-bidi/#event-network-responseCompleted
-void network_response_completed(FetchParams const& fetch_params, Response const& response)
+void network_response_completed(FetchParams const& fetch_params, Response const& response, FetchTimingInfo const& timing_info)
{
auto request = fetch_params.request();
auto state = network_request_of(fetch_params);
@@ -794,13 +800,14 @@ void network_response_completed(FetchParams const& fetch_params, Response const&
if (!navigable)
return;
state->completed.set(request->redirect_count());
- if (!fetch_params.timing_info()->end_time())
- fetch_params.timing_info()->set_end_time(HighResolutionTime::unsafe_shared_current_time());
+ auto& control_block = fetch_params.control_block();
+ if (!control_block.end_time())
+ control_block.set_end_time(HighResolutionTime::unsafe_shared_current_time());
// 5. Let sessions be the set of sessions for which an event is enabled given "network.responseCompleted" and related navigables.
if (!is_event_enabled("network.responseCompleted"sv))
return;
- auto params = process_a_network_event(*navigable, *state, *fetch_params.request(), *fetch_params.timing_info());
- params.set("response"sv, get_the_response_data(response, *fetch_params.timing_info()));
+ auto params = process_a_network_event(*navigable, *state, *fetch_params.request(), timing_info, end_time_of(fetch_params));
+ params.set("response"sv, get_the_response_data(response, timing_info));
emit_event(*navigable, "network.responseCompleted"_string, move(params));
}
@@ -822,7 +829,7 @@ void network_fetch_error(FetchParams const& fetch_params, StringView error_text)
return;
if (!is_event_enabled("network.fetchError"sv))
return;
- auto params = process_a_network_event(*navigable, *state, *fetch_params.request(), *fetch_params.timing_info());
+ auto params = process_a_network_event(*navigable, *state, *fetch_params.request(), *fetch_params.timing_info(), end_time_of(fetch_params));
// 4.2. Set the errorText field of params to an implementation-defined string describing the error which caused the request to be aborted.
params.set("errorText"sv, String::from_utf8_with_replacement_character(error_text));
emit_event(*navigable, "network.fetchError"_string, move(params));
@@ -841,7 +848,7 @@ Optional<JsonObject> network_response_for_navigation(Request const& request, Fet
return {};
state->transferred.set(request.redirect_count());
JsonObject result;
- result.set("parameters"sv, process_a_network_event(*navigable, *state, request, timing_info));
+ result.set("parameters"sv, process_a_network_event(*navigable, *state, request, timing_info, timing_info.end_time()));
result.set("response"sv, get_the_response_data(response, timing_info));
result.set("postRedirectStartTime"sv, timing_info.post_redirect_start_time());
auto const& client = request.client_snapshot();
@@ -868,7 +875,7 @@ void network_navigation_response_finished(HTML::Navigable const& navigable, Json
auto old_timings = request->get_object("timings"sv);
auto epoch_origin = old_timings->get("timeOrigin"sv)->get_double_with_precision_loss().value();
auto origin = metadata.get("timeOrigin"sv);
- request->set("timings"sv, get_the_fetch_timings(timings, origin->is_null() ? Optional<double> {} : origin->get_double_with_precision_loss(), epoch_origin));
+ request->set("timings"sv, get_the_fetch_timings(timings, timings.end_time(), origin->is_null() ? Optional<double> {} : origin->get_double_with_precision_loss(), epoch_origin));
}
params.set("response"sv, get_the_response_data(response, timings));
}
diff --git a/Libraries/LibWeb/WebDriver/BiDi/Network.h b/Libraries/LibWeb/WebDriver/BiDi/Network.h
index d5dfa350fad..aeb177f5401 100644
--- a/Libraries/LibWeb/WebDriver/BiDi/Network.h
+++ b/Libraries/LibWeb/WebDriver/BiDi/Network.h
@@ -110,7 +110,7 @@ void initialize_network_request_with_its_navigable(Fetch::Infrastructure::FetchP
void network_before_request_sent(Fetch::Infrastructure::FetchParams const&);
void network_response_started(Fetch::Infrastructure::FetchParams const&, Fetch::Infrastructure::Response&);
void network_auth_required(Fetch::Infrastructure::FetchParams const&, Fetch::Infrastructure::Response const&);
-void network_response_completed(Fetch::Infrastructure::FetchParams const&, Fetch::Infrastructure::Response const&);
+void network_response_completed(Fetch::Infrastructure::FetchParams const&, Fetch::Infrastructure::Response const&, Fetch::Infrastructure::FetchTimingInfo const&);
void network_fetch_error(Fetch::Infrastructure::FetchParams const&, StringView);
Optional<JsonObject> network_response_for_navigation(Fetch::Infrastructure::Request const&, Fetch::Infrastructure::FetchTimingInfo const&,
diff --git a/Tests/LibWeb/TestFetchAlgorithms.cpp b/Tests/LibWeb/TestFetchAlgorithms.cpp
index 9f6ec69d498..1ecb4d51afc 100644
--- a/Tests/LibWeb/TestFetchAlgorithms.cpp
+++ b/Tests/LibWeb/TestFetchAlgorithms.cpp
@@ -48,6 +48,7 @@
#include <LibWeb/HTML/Scripting/Agent.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
+#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Loader/ResourceLoader.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Streams/ReadableStream.h>
@@ -68,6 +69,7 @@ using Web::Fetch::Engine::Event::ReadRequestBodyStream;
using Web::Fetch::Engine::Event::RequestBodyEndOfBody;
using Web::Fetch::Engine::Event::RequestBodyProgress;
using Web::Fetch::Engine::Event::RequestBodySentFromSource;
+using Web::Fetch::Engine::Event::RequestTransmissionEnded;
using Web::Fetch::Fetching::FetchEventSink;
using Web::Fetch::Fetching::NetworkBodyPump;
using Web::Fetch::Infrastructure::FetchAlgorithms;
@@ -1175,9 +1177,10 @@ TEST_CASE(a_body_that_ends_after_its_response_is_handed_over_reports_the_end_tim
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);
+ auto agent_timing_info = delivered.controller->control_block().agent_timing_info();
+ VERIFY(agent_timing_info);
+ EXPECT_EQ(agent_timing_info->end_time(), 1);
+ EXPECT_EQ(delivered.controller->control_block().end_time(), 1);
}
TEST_CASE(a_stopped_fetch_no_longer_awaits_the_end_of_its_body)
@@ -1233,6 +1236,27 @@ struct ReportedNetworkEvents : RefCounted<ReportedNetworkEvents> {
Vector<String> request_ids;
};
+// A WebDriver BiDi session with the given events enabled, whose events reach the callback, until it goes.
+class WebDriverBiDiSession {
+public:
+ using OnEvent = Function<void(Web::HTML::Navigable const&, String const&, JsonValue)>;
+
+ WebDriverBiDiSession(Vector<String> enabled_events, OnEvent on_event)
+ {
+ Web::WebDriver::BiDi::set_event_sink({ .on_event = move(on_event), .on_navigation_event = {} });
+ Web::WebDriver::BiDiSessionState session_state;
+ session_state.is_active = true;
+ session_state.enabled_events = move(enabled_events);
+ Web::WebDriver::BiDi::set_session_state(move(session_state));
+ }
+
+ ~WebDriverBiDiSession()
+ {
+ Web::WebDriver::BiDi::set_session_state({});
+ Web::WebDriver::BiDi::set_event_sink({});
+ }
+};
+
}
TEST_CASE(a_request_fetched_again_keeps_its_webdriver_bidi_request_id)
@@ -1242,20 +1266,12 @@ TEST_CASE(a_request_fetched_again_keeps_its_webdriver_bidi_request_id)
FetchHarness harness;
auto events = make_ref_counted<ReportedNetworkEvents>();
- Web::WebDriver::BiDi::set_event_sink({
- .on_event = [events](Web::HTML::Navigable const&, String const& name, JsonValue params) {
+ WebDriverBiDiSession session {
+ { "network.beforeRequestSent"_string, "network.fetchError"_string },
+ [events](Web::HTML::Navigable const&, String const& name, JsonValue params) {
events->names.append(name);
events->request_ids.append(*params.as_object().get_object("request"sv)->get_string("request"sv));
},
- .on_navigation_event = {},
- });
- Web::WebDriver::BiDiSessionState session_state;
- session_state.is_active = true;
- session_state.enabled_events = { "network.beforeRequestSent"_string, "network.fetchError"_string };
- Web::WebDriver::BiDi::set_session_state(move(session_state));
- ScopeGuard end_session = [] {
- Web::WebDriver::BiDi::set_session_state({});
- Web::WebDriver::BiDi::set_event_sink({});
};
auto& heap = harness.realm->heap();
@@ -1297,23 +1313,15 @@ TEST_CASE(a_request_that_starts_after_its_fetch_was_stopped_reports_the_stop)
FetchHarness harness;
auto events = make_ref_counted<ReachedSteps>();
- Web::WebDriver::BiDi::set_event_sink({
- .on_event = [events](Web::HTML::Navigable const&, String const& name, JsonValue params) {
+ WebDriverBiDiSession session {
+ { "network.beforeRequestSent"_string, "network.fetchError"_string },
+ [events](Web::HTML::Navigable const&, String const& name, JsonValue params) {
auto const& object = params.as_object();
auto event = ByteString::formatted("{} {}", name, object.get_u32("redirectCount"sv).value());
if (auto error_text = object.get_string("errorText"sv); error_text.has_value())
event = ByteString::formatted("{}: {}", event, *error_text);
events->steps.append(move(event));
},
- .on_navigation_event = {},
- });
- Web::WebDriver::BiDiSessionState session_state;
- session_state.is_active = true;
- session_state.enabled_events = { "network.beforeRequestSent"_string, "network.fetchError"_string };
- Web::WebDriver::BiDi::set_session_state(move(session_state));
- ScopeGuard end_session = [] {
- Web::WebDriver::BiDi::set_session_state({});
- Web::WebDriver::BiDi::set_event_sink({});
};
auto request = harness.create_request_for("http://localhost/"sv);
@@ -1333,7 +1341,7 @@ TEST_CASE(a_request_that_starts_after_its_fetch_was_stopped_reports_the_stop)
namespace {
-// A page client that records the network activity reported to it.
+// A page client that records the network activity reported to it, and opens the files its page asks for.
class NetworkActivityPageClient final : public Web::PageClient {
GC_CELL(NetworkActivityPageClient, Web::PageClient);
GC_DECLARE_ALLOCATOR(NetworkActivityPageClient);
@@ -1363,9 +1371,18 @@ public:
virtual void report_finished_handling_input_event(Web::PageId, u64, Web::EventResult) override { }
virtual Web::HTML::CrossProcessId allocate_cross_process_id() override { return { 2, s_next_cross_process_id++ }; }
virtual void request_frame() override { }
- virtual void request_file(Web::FileRequest) override { }
virtual bool is_headless() const override { return true; }
+ virtual void request_file(Web::FileRequest request) override
+ {
+ auto file = Core::File::open(request.path(), Core::File::OpenMode::Read);
+ if (file.is_error()) {
+ request.on_file_request_finish(file.release_error());
+ return;
+ }
+ request.on_file_request_finish(file.value()->leak_fd());
+ }
+
virtual void page_did_start_network_request(u64 request_id, URL::URL const& url, ByteString const& method, Vector<HTTP::Header> const& request_headers, ReadonlyBytes request_body, Optional<String> initiator_type, String const& referrer_policy, bool is_navigation_request, Web::Fetch::Infrastructure::Request::Priority priority) override
{
VERIFY(request_headers.size() == 1);
@@ -1562,6 +1579,366 @@ TEST_CASE(a_fetch_reads_the_network_activity_observers_of_its_agent)
EXPECT(!fetch_params->engine_record()->network_activity_observers().has_devtools_client());
}
+static void expect_network_phases_of(Web::Fetch::Infrastructure::FetchTimingInfo const& timing_info, Requests::RequestTimingInfo const& finished)
+{
+ auto expected = timing_info.final_network_phases(finished, Web::HTML::CanUseCrossOriginIsolatedAPIs::No);
+ EXPECT(timing_info.final_connection_timing_info().has_value());
+ if (!timing_info.final_connection_timing_info().has_value())
+ return;
+ EXPECT_EQ(timing_info.final_connection_timing_info()->domain_lookup_start_time, expected.final_connection_timing_info.domain_lookup_start_time);
+ EXPECT_EQ(timing_info.final_connection_timing_info()->connection_end_time, expected.final_connection_timing_info.connection_end_time);
+ EXPECT_EQ(timing_info.final_network_request_start_time(), expected.final_network_request_start_time);
+ EXPECT_EQ(timing_info.final_network_response_start_time(), expected.final_network_response_start_time);
+}
+
+static Web::Fetch::Engine::FetchNetworkPhases network_phases(double request_start_time)
+{
+ Web::Fetch::Infrastructure::ConnectionTimingInfo connection_timing_info;
+ connection_timing_info.connection_start_time = request_start_time - 1;
+ return {
+ .final_connection_timing_info = move(connection_timing_info),
+ .final_network_request_start_time = request_start_time,
+ .final_network_response_start_time = request_start_time + 1,
+ };
+}
+
+TEST_CASE(a_load_that_finishes_before_its_response_is_handed_over_gives_the_agent_its_network_phases)
+{
+ 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/finished-before-handover"sv);
+ 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, { { "Access-Control-Allow-Origin"sv, "*"sv } });
+ request_server.send_finished(request_id, finished_timing_info(1000));
+ run_until_responses(harness, record, 1);
+
+ auto agent_timing_info = controller->control_block().agent_timing_info();
+ VERIFY(agent_timing_info);
+ expect_network_phases_of(*agent_timing_info, finished_timing_info(1000));
+}
+
+TEST_CASE(a_load_that_finishes_after_its_response_is_handed_over_gives_the_agent_its_network_phases)
+{
+ 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/finished-after-handover"sv);
+ auto agent_timing_info = delivered.controller->control_block().agent_timing_info();
+ VERIFY(agent_timing_info);
+ EXPECT(!agent_timing_info->final_connection_timing_info().has_value());
+
+ request_server.send_finished(delivered.request_id, finished_timing_info(1000));
+ run_until_encoded_size(harness, delivered.response, 1234);
+ expect_network_phases_of(*agent_timing_info, finished_timing_info(1000));
+ EXPECT_EQ(delivered.controller->control_block().agent_timing_info().ptr(), agent_timing_info.ptr());
+}
+
+TEST_CASE(network_phases_heard_before_a_handover_reach_each_timing_info_it_makes)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+ auto controller = FetchController::create(Web::HTML::surrounding_agent().fetch_controller_registry);
+ FetchEventSink event_sink { controller };
+ auto& control_block = controller->control_block();
+
+ event_sink.handle_event(RequestTransmissionEnded { network_phases(10) });
+ EXPECT(!control_block.agent_timing_info());
+
+ Web::Fetch::Engine::FetchTimingSeed seed;
+ seed.post_redirect_start_time = 5;
+ auto first = control_block.hand_over_timing(seed);
+ EXPECT_EQ(first->post_redirect_start_time(), 5);
+ EXPECT_EQ(first->final_network_request_start_time(), 10);
+
+ // The next response of a manual redirect starts from the phases settled last. Phases settled later reach only the
+ // newest handover's timing info.
+ auto next = control_block.hand_over_timing(seed);
+ EXPECT_NE(next.ptr(), first.ptr());
+ EXPECT_EQ(next->final_network_request_start_time(), 10);
+ event_sink.handle_event(RequestTransmissionEnded { network_phases(20) });
+ EXPECT_EQ(next->final_network_request_start_time(), 20);
+ EXPECT_EQ(first->final_network_request_start_time(), 10);
+}
+
+TEST_CASE(a_handover_gives_its_timing_info_each_field_of_the_seed_and_the_end_time_last_set_for_the_fetch)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+ auto controller = FetchController::create(Web::HTML::surrounding_agent().fetch_controller_registry);
+ auto& control_block = controller->control_block();
+
+ auto timing_info = Web::Fetch::Infrastructure::FetchTimingInfo::create();
+ timing_info->set_start_time(1);
+ timing_info->set_redirect_start_time(2);
+ timing_info->set_redirect_end_time(3);
+ timing_info->set_post_redirect_start_time(4);
+ timing_info->set_final_service_worker_start_time(5);
+ timing_info->set_server_timing_headers({ "total;dur=6"_string });
+ timing_info->set_render_blocking(true);
+ control_block.set_end_time(7);
+
+ auto handed_over = control_block.hand_over_timing(timing_info->seed());
+ EXPECT_EQ(handed_over->start_time(), 1);
+ EXPECT_EQ(handed_over->redirect_start_time(), 2);
+ EXPECT_EQ(handed_over->redirect_end_time(), 3);
+ EXPECT_EQ(handed_over->post_redirect_start_time(), 4);
+ EXPECT_EQ(handed_over->final_service_worker_start_time(), 5);
+ EXPECT_EQ(handed_over->server_timing_headers(), (Vector<String> { "total;dur=6"_string }));
+ EXPECT(handed_over->render_blocking());
+ EXPECT_EQ(handed_over->end_time(), 7);
+
+ // An end time set later reaches it too.
+ control_block.set_end_time(8);
+ EXPECT_EQ(handed_over->end_time(), 8);
+}
+
+namespace {
+
+// What the steps awaiting a body's end saw when they ran.
+struct EndOfBodySteps : RefCounted<EndOfBodySteps> {
+ GC_HOLDS_NO_CELL_EDGES;
+
+ Vector<double> end_times;
+ bool had_network_phases { false };
+};
+
+}
+
+TEST_CASE(the_network_phases_of_a_load_reach_the_agent_before_the_end_of_its_body)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+ auto controller = FetchController::create(Web::HTML::surrounding_agent().fetch_controller_registry);
+ FetchEventSink event_sink { controller };
+ auto agent_timing_info = controller->control_block().hand_over_timing({});
+ auto response = Response::create();
+
+ auto steps = make_ref_counted<EndOfBodySteps>();
+ controller->when_body_ends(Web::Fetch::Engine::DeliveryId(1), response, GC::create_function(harness.realm->heap(), GC::captures(steps, agent_timing_info), [](auto& steps, auto& agent_timing_info, double end_time) {
+ steps->end_times.append(end_time);
+ steps->had_network_phases = agent_timing_info->final_connection_timing_info().has_value();
+ }));
+
+ event_sink.handle_event(RequestTransmissionEnded { network_phases(10) });
+ EXPECT(steps->end_times.is_empty());
+ EXPECT_EQ(agent_timing_info->final_network_request_start_time(), 10);
+
+ EndOfBody end_of_body {
+ .delivery_id = Web::Fetch::Engine::DeliveryId(1),
+ .final_sizes = { .encoded_body_size = 3, .decoded_body_size = 4 },
+ .end_time = 30,
+ };
+ event_sink.handle_event(move(end_of_body));
+ EXPECT_EQ(steps->end_times, (Vector<double> { 30 }));
+ EXPECT(steps->had_network_phases);
+ EXPECT_EQ(response->body_info().encoded_size, 3u);
+ EXPECT_EQ(response->body_info().decoded_size, 4u);
+}
+
+namespace {
+
+// The WebDriver BiDi responseCompleted events that reached the event sink, by redirect count.
+struct CompletedResponses : RefCounted<CompletedResponses> {
+ GC_HOLDS_NO_CELL_EDGES;
+
+ Vector<u32> redirect_counts;
+ Vector<double> request_starts;
+ Vector<double> response_ends;
+};
+
+}
+
+TEST_CASE(a_redirected_fetch_reports_the_end_time_of_its_final_body_to_webdriver_bidi_and_resource_timing)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+ StandInRequestServer request_server { harness };
+
+ auto completed = make_ref_counted<CompletedResponses>();
+ WebDriverBiDiSession session {
+ { "network.responseCompleted"_string },
+ [completed](Web::HTML::Navigable const&, String const&, JsonValue params) {
+ auto const& object = params.as_object();
+ completed->redirect_counts.append(object.get_u32("redirectCount"sv).value());
+ auto timings = object.get_object("request"sv)->get_object("timings"sv);
+ completed->request_starts.append(timings->get_double_with_precision_loss("requestStart"sv).value());
+ completed->response_ends.append(timings->get_double_with_precision_loss("responseEnd"sv).value());
+ },
+ };
+
+ auto record = make_ref_counted<AlgorithmCalls>();
+ auto request = harness.create_request_for("http://127.0.0.1:8000/redirect"sv);
+ request->set_initiator_type(Request::InitiatorType::Fetch);
+ auto controller = GC::make_root(harness.fetch(request, recording_responses(harness.realm->heap(), record)));
+ auto& control_block = controller->control_block();
+
+ // The redirect completes, and WebDriver BiDi sets the fetch's end time.
+ auto redirect_id = request_server.wait_for_request("GET"sv);
+ request_server.send_headers(redirect_id, 302, { { "Location"sv, "/final"sv } });
+ request_server.send_finished(redirect_id, finished_timing_info(1000));
+ auto final_id = request_server.wait_for_request("GET"sv);
+ auto redirect_end_time = control_block.end_time();
+ EXPECT_NE(redirect_end_time, 0);
+
+ // The final body ends once the clock is past the redirect's end time by more than a coarsening interval.
+ request_server.send_headers(final_id, 200);
+ run_until_responses(harness, record, 1);
+ auto clock_tick = Core::Timer::create_repeating(AK::Duration::from_milliseconds(1), [] { });
+ clock_tick->start();
+ harness.run_tasks_until(GC::create_function(harness.realm->heap(), GC::captures(redirect_end_time), [](auto& redirect_end_time) {
+ return Web::HighResolutionTime::unsafe_shared_current_time() > redirect_end_time + 1;
+ }));
+ clock_tick->stop();
+ request_server.send_finished(final_id, finished_timing_info(2000));
+ auto response = record->responses[0]->record()->unsafe_response();
+ run_until_encoded_size(harness, response, 1234);
+
+ // The timing report and WebDriver BiDi share the fetch's end time, which is the final body's.
+ auto agent_timing_info = control_block.agent_timing_info();
+ VERIFY(agent_timing_info);
+ EXPECT(agent_timing_info->end_time() > redirect_end_time + 1);
+ EXPECT_EQ(control_block.end_time(), agent_timing_info->end_time());
+ EXPECT_EQ(completed->redirect_counts, (Vector<u32> { 0, 1 }));
+ VERIFY(completed->response_ends.size() == 2);
+ auto time_origin = request->client_snapshot()->time_origin;
+ EXPECT_EQ(completed->response_ends[0], Web::HighResolutionTime::coarsen_time(redirect_end_time) - time_origin);
+ EXPECT_EQ(completed->response_ends[1], Web::HighResolutionTime::coarsen_time(agent_timing_info->end_time()) - time_origin);
+ EXPECT_NE(completed->response_ends[1], completed->response_ends[0]);
+
+ // The final body's completion reports the network phases of the final load.
+ EXPECT_EQ(completed->request_starts[1], Web::HighResolutionTime::coarsen_time(agent_timing_info->final_network_request_start_time()) - time_origin);
+}
+
+TEST_CASE(the_next_response_of_a_manual_redirect_takes_the_end_time_last_set_for_the_fetch)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+ StandInRequestServer request_server { harness };
+ WebDriverBiDiSession session { { "network.responseCompleted"_string }, [](Web::HTML::Navigable const&, String const&, JsonValue) { } };
+
+ auto record = make_ref_counted<AlgorithmCalls>();
+ auto request = harness.create_request_for("http://127.0.0.1:8000/manual-redirect"sv);
+ request->set_mode(Request::Mode::Navigate);
+ request->set_destination(Request::Destination::Document);
+ request->set_redirect_mode(Request::RedirectMode::Manual);
+ auto controller = GC::make_root(harness.fetch(request, recording_responses(harness.realm->heap(), record)));
+ auto& control_block = controller->control_block();
+
+ // WebDriver BiDi completes the redirect, which sets the fetch's end time before the redirect is handed over.
+ auto redirect_id = request_server.wait_for_request("GET"sv);
+ request_server.send_headers(redirect_id, 302, { { "Location"sv, "/final"sv } });
+ run_until_responses(harness, record, 1);
+ auto redirect_end_time = control_block.end_time();
+ EXPECT_NE(redirect_end_time, 0);
+ auto redirect_timing_info = control_block.agent_timing_info();
+ VERIFY(redirect_timing_info);
+ EXPECT_EQ(redirect_timing_info->end_time(), redirect_end_time);
+
+ {
+ Web::HTML::TemporaryExecutionContext execution_context { *harness.realm, Web::HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ controller->process_next_manual_redirect();
+ }
+ auto final_id = request_server.wait_for_request("GET"sv);
+ request_server.send_headers(final_id, 200);
+ request_server.send_finished(final_id, finished_timing_info(2000));
+ run_until_responses(harness, record, 2);
+ run_until_encoded_size(harness, record->responses[1]->record()->unsafe_response(), 1234);
+
+ // The final response's timing info takes the fetch's end time, and the redirect and network fields of its own hop.
+ auto final_timing_info = control_block.agent_timing_info();
+ VERIFY(final_timing_info);
+ EXPECT_NE(final_timing_info.ptr(), redirect_timing_info.ptr());
+ EXPECT_EQ(final_timing_info->end_time(), redirect_end_time);
+ auto fetch_params = controller->original_fetch_params();
+ VERIFY(fetch_params);
+ auto const& engine_timing_info = *fetch_params->timing_info();
+ EXPECT_NE(engine_timing_info.redirect_end_time(), redirect_timing_info->redirect_end_time());
+ EXPECT_EQ(final_timing_info->redirect_start_time(), engine_timing_info.redirect_start_time());
+ EXPECT_EQ(final_timing_info->redirect_end_time(), engine_timing_info.redirect_end_time());
+ EXPECT_EQ(final_timing_info->post_redirect_start_time(), engine_timing_info.post_redirect_start_time());
+ expect_network_phases_of(*final_timing_info, finished_timing_info(2000));
+}
+
+TEST_CASE(a_cors_preflight_reports_none_of_its_network_phases_to_its_fetch)
+{
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+ StandInRequestServer request_server { harness };
+
+ auto record = make_ref_counted<AlgorithmCalls>();
+ auto request = harness.create_request_for("http://127.0.0.1:8000/preflighted"sv);
+ request->set_method("PUT");
+ request->set_mode(Request::Mode::CORS);
+ request->set_unsafe_request(true);
+ auto controller = GC::make_root(harness.fetch(request, recording_responses(harness.realm->heap(), record)));
+
+ // The preflight's request ends right after its headers.
+ auto preflight_id = request_server.wait_for_request("OPTIONS"sv);
+ request_server.send_headers(preflight_id, 200, { { "Access-Control-Allow-Origin"sv, "*"sv }, { "Access-Control-Allow-Methods"sv, "PUT"sv } });
+ request_server.send_finished(preflight_id, finished_timing_info(9000));
+ auto request_id = request_server.wait_for_request("PUT"sv);
+ request_server.send_headers(request_id, 200, { { "Access-Control-Allow-Origin"sv, "*"sv } });
+ run_until_responses(harness, record, 1);
+
+ auto agent_timing_info = controller->control_block().agent_timing_info();
+ VERIFY(agent_timing_info);
+ EXPECT(!agent_timing_info->final_connection_timing_info().has_value());
+
+ request_server.send_finished(request_id, finished_timing_info(1000));
+ run_until_encoded_size(harness, record->responses[0]->record()->unsafe_response(), 1234);
+ expect_network_phases_of(*agent_timing_info, finished_timing_info(1000));
+}
+
+TEST_CASE(a_file_navigation_keeps_the_network_phases_of_its_load)
+{
+ auto const path = ByteString::formatted("{}/TestFetchAlgorithms-{:016x}.html", Core::StandardPaths::tempfile_directory(), get_random<u64>());
+ {
+ auto file = MUST(Core::File::open(path, Core::File::OpenMode::Write | Core::File::OpenMode::MustBeNew));
+ MUST(file->write_until_depleted("<p>file</p>"sv.bytes()));
+ }
+ ScopeGuard remove_file = [&path] { MUST(FileSystem::remove(path, FileSystem::RecursionMode::Disallowed)); };
+
+ Core::EventLoop event_loop;
+ install_font_plugin();
+ FetchHarness harness;
+ ResourceLoaderWithoutRequestServer resource_loader { harness.realm->heap() };
+ auto page_client = NetworkActivityPageClient::create(harness.realm->heap(), Web::PageId { 1 });
+ auto document = create_document_of_page(page_client->page());
+
+ auto record = make_ref_counted<AlgorithmCalls>();
+ auto url = URL::create_with_file_scheme(path);
+ VERIFY(url.has_value());
+ auto request = harness.create_request_for(url->serialize());
+ // A traversal back to a file: entry, which fetches it with the client of the document it replaces.
+ request->set_mode(Request::Mode::Navigate);
+ request->set_destination(Request::Destination::Document);
+ request->set_redirect_mode(Request::RedirectMode::Manual);
+ request->set_history_navigation(true);
+ auto controller = GC::make_root(harness.fetch(request, recording_responses(harness.realm->heap(), record), document));
+ run_until_responses(harness, record, 1);
+ auto response = record->responses[0]->record()->unsafe_response();
+ run_until_encoded_size(harness, response, 11);
+
+ // A load without a RequestServer request has its network phases at its post-redirect start time.
+ auto full_timing_info = controller->full_timing_info();
+ VERIFY(full_timing_info);
+ EXPECT_EQ(full_timing_info.ptr(), controller->control_block().agent_timing_info().ptr());
+ expect_network_phases_of(*full_timing_info, {});
+}
+
TEST_CASE(algorithms_that_consume_a_body_need_a_consuming_intent)
{
Core::EventLoop event_loop;
diff --git a/Tests/LibWeb/TestFetchEngineMessages.cpp b/Tests/LibWeb/TestFetchEngineMessages.cpp
index 2e463d01a4b..5c8e71ef4f6 100644
--- a/Tests/LibWeb/TestFetchEngineMessages.cpp
+++ b/Tests/LibWeb/TestFetchEngineMessages.cpp
@@ -128,14 +128,14 @@ TEST_CASE(events_round_trip_their_payloads)
events.append(Event::BodyChannelReadable { .delivery_id = DeliveryId(4), .ticket = WakeTicket(7) });
events.append(Event::DeliveryEnd { .delivery_id = DeliveryId(5), .outcome = Event::DeliveryEnd::Revoked {} });
events.append(Event::RequestTransmissionStarted { .transmission_id = TransmissionId(6), .generation = TransmissionGeneration(1) });
+ Web::Fetch::Infrastructure::ConnectionTimingInfo connection_timing_info;
+ connection_timing_info.connection_start_time = 3;
+ connection_timing_info.alpn_negotiated_protocol = "h2";
events.append(Event::RequestTransmissionEnded {
- .transmission_id = TransmissionId(7),
- .generation = TransmissionGeneration(2),
- .request_end = {
- .request_id = RequestId(70),
- .transport_epoch = TransportEpoch(3),
- .transport_complete_at = MonotonicTime::now(),
- .outcome = RequestEnd::CommittedAttemptFailed { .attempt_id = AttemptId(4), .error = Requests::NetworkError::IncompleteContent, .encoded_body_size = 512 },
+ .network_phases = {
+ .final_connection_timing_info = move(connection_timing_info),
+ .final_network_request_start_time = 4,
+ .final_network_response_start_time = 5,
},
});
events.append(Event::RequestBodyProgress { .length = 8 });
@@ -178,6 +178,7 @@ TEST_CASE(events_round_trip_their_payloads)
});
Vector<u64> seen_ids;
+ bool seen_network_phases = false;
Vector<StringView> seen_request_body_events;
Vector<u64> seen_network_request_ids;
for (auto const& event : events) {
@@ -206,11 +207,12 @@ TEST_CASE(events_round_trip_their_payloads)
},
[&](Event::RequestTransmissionStarted const& started) { seen_ids.append(started.transmission_id.value()); },
[&](Event::RequestTransmissionEnded const& ended) {
- EXPECT_EQ(ended.request_end.request_id, RequestId(70));
- auto const& failed = ended.request_end.outcome.get<RequestEnd::CommittedAttemptFailed>();
- EXPECT_EQ(failed.error, Requests::NetworkError::IncompleteContent);
- EXPECT_EQ(failed.encoded_body_size, 512u);
- seen_ids.append(ended.transmission_id.value());
+ auto const& phases = ended.network_phases;
+ EXPECT_EQ(phases.final_connection_timing_info.connection_start_time, 3);
+ EXPECT_EQ(phases.final_connection_timing_info.alpn_negotiated_protocol, "h2"sv);
+ EXPECT_EQ(phases.final_network_request_start_time, 4);
+ EXPECT_EQ(phases.final_network_response_start_time, 5);
+ seen_network_phases = true;
},
[&](Event::RequestBodyProgress const& progress) {
EXPECT_EQ(progress.length, 8u);
@@ -255,7 +257,8 @@ TEST_CASE(events_round_trip_their_payloads)
seen_network_request_ids.append(network_activity.request_id.value());
});
}
- EXPECT_EQ(seen_ids, (Vector<u64> { 1, 2, 3, 4, 5, 6, 7 }));
+ EXPECT_EQ(seen_ids, (Vector<u64> { 1, 2, 3, 4, 5, 6 }));
+ EXPECT(seen_network_phases);
EXPECT_EQ(seen_request_body_events, (Vector<StringView> { "progress"sv, "end of body"sv, "read stream"sv, "sent from source"sv }));
EXPECT_EQ(seen_network_request_ids, (Vector<u64> { 8, 9, 10, 11 }));
}
diff --git a/Tests/LibWebView/test-webdriver-bidi.py b/Tests/LibWebView/test-webdriver-bidi.py
index cbc89a0739d..4565697fac7 100755
--- a/Tests/LibWebView/test-webdriver-bidi.py
+++ b/Tests/LibWebView/test-webdriver-bidi.py
@@ -185,6 +185,18 @@ class ReloadHandler(http.server.BaseHTTPRequestHandler):
# The connection closes with the body unfinished, which fails the body.
self.close_connection = True
return
+ if self.path == "/network-events/whole-body":
+ body = b"BiDi whole body\n"
+ self.send_response(200)
+ self.send_header("Content-Type", "text/plain")
+ self.send_header("Content-Length", str(len(body)))
+ self.send_header("Cache-Control", "no-store")
+ self.end_headers()
+ try:
+ self.wfile.write(body)
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+ return
if self.path.startswith("/network-interception/"):
# NB: Preserve duplicate fields for assertions even if the transport combines their length values.
# A stale length on the redirected GET is an assertion failure, not a reason for the fixture to wait.
@@ -1473,6 +1485,44 @@ def check_network_body_error_after_late_subscription(bidi, context, server):
bidi.command("session.unsubscribe", {"subscriptions": [subscription]})
+def check_network_end_time_after_late_subscription(bidi, context, server):
+ url = f"http://127.0.0.1:{server.server_port}/network-events/whole-body"
+ # The page leaves the body unread, and the fetch reports its timing once the network has delivered it.
+ bidi.evaluate(
+ context,
+ "window.endTimeAbort = new AbortController(); "
+ f"fetch({json.dumps(url)}, {{signal: endTimeAbort.signal}}).then(response => {{ window.endTimeResponse = response; }}); 0",
+ )
+ subscription = None
+ try:
+ entry_response_end_expression = (
+ f"performance.getEntriesByName({json.dumps(url)}).map(entry => entry.responseEnd).concat([0])[0]"
+ )
+ deadline = time.monotonic() + 30
+ while (entry_response_end := bidi.evaluate(context, entry_response_end_expression)["result"]["value"]) == 0:
+ assert time.monotonic() < deadline, "The fetch did not report its timing"
+ time.sleep(0.01)
+
+ # Network events are subscribed only after the timing report, and the abort then reports the request.
+ subscription = bidi.command(
+ "session.subscribe", {"events": ["network.beforeRequestSent", "network.fetchError"]}
+ )["subscription"]
+ bidi.evaluate(context, "0")
+ bidi.evaluate(context, "endTimeAbort.abort(); 0")
+ events = [
+ next_network_event(bidi, url, ["network.beforeRequestSent"]),
+ next_network_event(bidi, url, ["network.fetchError"]),
+ ]
+ response_ends = [event["params"]["request"]["timings"]["responseEnd"] for event in events]
+ assert all(response_end > 0 for response_end in response_ends), response_ends
+ assert response_ends[0] == response_ends[1], response_ends
+ assert abs(response_ends[0] - entry_response_end) < 1, (response_ends, entry_response_end)
+ drop_network_events(bidi, url)
+ finally:
+ if sys.exc_info()[0] is None and subscription is not None:
+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})
+
+
def check_network_continue_after_gc(bidi, context, server):
subscription = bidi.command(
"session.subscribe",
@@ -1846,6 +1896,8 @@ def check_network_interception(bidi, context, server, case="all"):
check_network_stopped_fetch_reports_error(bidi, context, server)
if case in ["all", "late-events-body-error"]:
check_network_body_error_after_late_subscription(bidi, context, server)
+ if case in ["all", "late-events-end-time"]:
+ check_network_end_time_after_late_subscription(bidi, context, server)
if case in ["all", "continue-after-gc"]:
check_network_continue_after_gc(bidi, context, server)
if case in ["all", "preflight-body"]:
@@ -3126,6 +3178,7 @@ if __name__ == "__main__":
"events-off-stop",
"events-on-stop",
"late-events-body-error",
+ "late-events-end-time",
"continue-after-gc",
"preflight-body",
"adopted-navigation-continue",