Truly independent web browser
LibWeb: Post navigation body controls to the agent's fetch executor
Luke Wildeb1ce8e8cc77d
diff --git a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cpp b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cppindex c69f34db743..0fcc575050c 100644--- a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cpp+++ b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cpp@@ -4,6 +4,9 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/StdLibExtras.h>+#include <LibWeb/Fetch/Engine/EngineCommand.h>+#include <LibWeb/Fetch/Engine/FetchExecutor.h>#include <LibWeb/Fetch/Engine/NetworkTransportHandle.h>namespace Web::Fetch::Engine {@@ -53,6 +56,50 @@ void NetworkTransportHandle::release_transfer_lease()m_request->release_transfer_lease();}+void NetworkTransportHandle::post_transport_control(FetchExecutor& executor, auto operation)+{+ Command::TransportControl control {+ .request_id = request_id(),+ .transport_epoch = transport_epoch(),+ .operation = move(operation),+ };+ executor.post(move(control));+}++void NetworkTransportHandle::post_stop(FetchExecutor& executor)+{+ NonnullRefPtr protector = *this;+ ASSERT(is_on_owner_thread());+ m_stop_requested = true;+ if (auto on_stop_requested = exchange(m_on_stop_requested, nullptr))+ on_stop_requested();+ post_transport_control(executor, Command::TransportControl::StopTransport {});+}++void NetworkTransportHandle::post_release_navigation_hold(FetchExecutor& executor)+{+ ASSERT(is_on_owner_thread());+ post_transport_control(executor, Command::TransportControl::ReleaseNavigationHold {});+}++void NetworkTransportHandle::post_release_navigation_hold_up_to(FetchExecutor& executor, u64 byte_count)+{+ ASSERT(is_on_owner_thread());+ post_transport_control(executor, Command::TransportControl::ReleaseNavigationHoldUpTo { .byte_count = byte_count });+}++void NetworkTransportHandle::set_on_stop_requested(Function<void()> on_stop_requested)+{+ ASSERT(is_on_owner_thread());+ m_on_stop_requested = move(on_stop_requested);+}++Function<void()> NetworkTransportHandle::take_on_stop_requested()+{+ ASSERT(is_on_owner_thread());+ return exchange(m_on_stop_requested, nullptr);+}+void NetworkTransportHandle::set_on_requires_network(Function<void()> on_requires_network){ASSERT(is_on_owner_thread());diff --git a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.hindex 1b6c040f0da..ad265d4dea2 100644--- a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h+++ b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h@@ -15,6 +15,8 @@namespace Web::Fetch::Engine {+class FetchExecutor;+// Controls the RequestServer request a fetch's response arrives through. Every method, and the handle's destruction,// runs on the loop the handle was created on.class WEB_API NetworkTransportHandle final : public FetchBodyDeliveryGate::Transport {@@ -37,6 +39,17 @@ public:void release_transfer_lease();+ // The agent's controls, which reach the transport through the given executor. A stop is requested from the moment+ // it is posted.+ void post_stop(FetchExecutor&);+ [[nodiscard]] bool is_stop_requested() const { return m_stop_requested; }+ void post_release_navigation_hold(FetchExecutor&);+ void post_release_navigation_hold_up_to(FetchExecutor&, u64 byte_count);++ // Runs in the first post_stop(), unless it was taken before.+ void set_on_stop_requested(Function<void()>);+ [[nodiscard]] Function<void()> take_on_stop_requested();+void set_on_requires_network(Function<void()>);void set_on_upload_progress(Function<void(u64 bytes_sent)>);void set_on_teardown(Function<void(Requests::Request::TeardownReason)>);@@ -45,9 +58,12 @@ private:explicit NetworkTransportHandle(NonnullRefPtr<Requests::Request>);[[nodiscard]] bool is_on_owner_thread() const { return m_owner_thread.is_current_thread(); }+ void post_transport_control(FetchExecutor&, auto operation);NonnullRefPtr<Requests::Request> m_request;AK::ThreadID m_owner_thread { AK::ThreadID::current() };+ bool m_stop_requested { false };+ Function<void()> m_on_stop_requested;};}diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex c812491cd5d..693cb18510f 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -2756,25 +2756,52 @@ GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, IEngine::Command::NavigationBodyAdopted adopted { network_transport, body_pump->delivery_gate() };fetch_executor.post(move(adopted));- // The observer hears the body's end at most once.+ // The observer hears the body's end at most once. A stop the agent requests is reported in the call, unless the+ // body ended first.auto network_settled = GC::make_root(on_network_settled);- network_transport->set_on_teardown([body_pump, network_settled](Requests::Request::TeardownReason reason) {+ network_transport->set_on_stop_requested([network_settled] {+ network_settled->function()("Transferred navigation response was stopped"sv);+ });+ auto weak_network_transport = network_transport->make_weak_ptr<Engine::NetworkTransportHandle>();+ auto take_stopped_report = [weak_network_transport]() -> Function<void()> {+ auto handle = weak_network_transport.strong_ref();+ if (!handle)+ return {};+ return handle->take_on_stop_requested();+ };+ network_transport->set_on_teardown([body_pump, take_stopped_report](Requests::Request::TeardownReason reason) {body_pump->handle_network_teardown(reason);+ auto report_stopped = take_stopped_report();// A body that moves to another owner is reported there.- if (reason == Requests::Request::TeardownReason::Stopped)- network_settled->function()("Transferred navigation response was stopped"sv);+ if (reason == Requests::Request::TeardownReason::Stopped && report_stopped)+ report_stopped();});+ // Until a stop the agent requested reaches the request, the body takes none of its data, and ends as stopped if the+ // request finishes first.+ auto is_stop_requested = [weak_network_transport] {+ auto handle = weak_network_transport.strong_ref();+ return handle && handle->is_stop_requested();+ };+auto cross_origin_isolated_capability = Bindings::principal_host_defined_environment_settings_object(realm).cross_origin_isolated_capability();request->set_unbuffered_request_callbacks([](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Requests::CacheState) { },- [body_pump](Requests::ResponseData data) {+ [body_pump, is_stop_requested](Requests::ResponseData data) {+ if (is_stop_requested())+ return;body_pump->handle_network_data(move(data));},[body_pump](Core::ImmutableBytes data) {body_pump->set_cached_response_body(move(data));},- [body_pump, timing_info, cross_origin_isolated_capability, network_settled](u64, Requests::RequestTimingInfo const& request_timing_info, Optional<Requests::NetworkError> network_error) {+ [body_pump, timing_info, cross_origin_isolated_capability, network_settled, is_stop_requested, take_stopped_report](u64, Requests::RequestTimingInfo const& request_timing_info, Optional<Requests::NetworkError> network_error) {+ // A stop requested after the body ended reports nothing.+ (void)take_stopped_report();+ if (is_stop_requested()) {+ body_pump->handle_network_teardown(Requests::Request::TeardownReason::Stopped);+ return;+ }if (network_error.has_value()) {network_settled->function()("Transferred navigation response failed"sv);body_pump->handle_network_error("Transferred navigation response failed"sv);diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.h b/Libraries/LibWeb/Fetch/Fetching/Fetching.hindex 847fb0ea8ff..3e430c05fa6 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.h+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.h@@ -64,7 +64,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(GC::Ref<PendingResponse> cors_preflight_fetch(JS::Realm&, Infrastructure::FetchParams const&);// on_network_settled runs at most once: when the network completes the body, or with an error when the body fails// or is stopped.-GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm&, Infrastructure::Response&, Optional<Utf16String> const& request_server_top_level_site, Requests::RequestTransferLeaseKey, RefPtr<Infrastructure::FetchTimingInfo>, GC::Ref<GC::Function<void(Optional<StringView> error)>> on_network_settled);+WEB_API GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm&, Infrastructure::Response&, Optional<Utf16String> const& request_server_top_level_site, Requests::RequestTransferLeaseKey, RefPtr<Infrastructure::FetchTimingInfo>, GC::Ref<GC::Function<void(Optional<StringView> error)>> on_network_settled);// Stopping the transport also cancels the channel.WEB_API NonnullRefPtr<Engine::WholeBodyTransport> create_whole_body_transport(Engine::FetchBodyDeliveryGate&, Engine::FetchByteChannel&);void set_sec_fetch_dest_header(Infrastructure::Request&);diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.hindex 21b953017e5..c7b802cb842 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h@@ -57,8 +57,8 @@ public:[[nodiscard]] GC::Ref<ResponseView> clone(JS::Realm&) const;void release_request_transfer_lease() const { m_record->release_request_transfer_lease(); }- void resume_body_delivery() const { m_record->resume_body_delivery(); }- void resume_body_delivery_up_to(size_t byte_count) const { m_record->resume_body_delivery_up_to(byte_count); }+ void resume_body_delivery(Engine::FetchExecutor& executor) const { m_record->resume_body_delivery(executor); }+ void release_navigation_hold_up_to(Engine::FetchExecutor& executor, size_t byte_count) const { m_record->release_navigation_hold_up_to(executor, byte_count); }[[nodiscard]] Vector<Core::ImmutableBytes> release_body_for_transfer() const { return m_record->release_body_for_transfer(); }private:diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cppindex 196e1df79c3..f17909594f2 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp@@ -95,17 +95,17 @@ void Response::release_request_transfer_lease() constm_network_transport->handle->release_transfer_lease();}-void Response::resume_body_delivery() const+void Response::resume_body_delivery(Engine::FetchExecutor& executor) const{release_request_transfer_lease();if (m_network_transport.has_value())- m_network_transport->body_delivery_gate->release_hold();+ m_network_transport->handle->post_release_navigation_hold(executor);}-void Response::resume_body_delivery_up_to(size_t byte_count) const+void Response::release_navigation_hold_up_to(Engine::FetchExecutor& executor, size_t byte_count) const{if (m_network_transport.has_value())- m_network_transport->body_delivery_gate->release_hold_up_to(byte_count);+ m_network_transport->handle->post_release_navigation_hold_up_to(executor, byte_count);}Vector<Core::ImmutableBytes> Response::release_body_for_transfer() constdiff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.hindex 2c0b75d12c7..3d3d425c651 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h@@ -138,8 +138,9 @@ public:[[nodiscard]] virtual Optional<NetworkTransport> const& network_transport() const { return m_network_transport; }virtual void set_network_transport(NetworkTransport network_transport) { m_network_transport = move(network_transport); }virtual void release_request_transfer_lease() const;- virtual void resume_body_delivery() const;- virtual void resume_body_delivery_up_to(size_t) const;+ // Releases the request's transfer lease, and posts the release of the body's navigation hold to the given executor.+ virtual void resume_body_delivery(Engine::FetchExecutor&) const;+ virtual void release_navigation_hold_up_to(Engine::FetchExecutor&, size_t) const;// Stops this process taking the body, and returns the bytes that a process adopting its request reads before the// rest.@@ -277,8 +278,8 @@ public:[[nodiscard]] virtual Optional<NetworkTransport> const& network_transport() const override { return m_internal_response->network_transport(); }virtual void set_network_transport(NetworkTransport network_transport) override { m_internal_response->set_network_transport(move(network_transport)); }virtual void release_request_transfer_lease() const override { m_internal_response->release_request_transfer_lease(); }- virtual void resume_body_delivery() const override { m_internal_response->resume_body_delivery(); }- virtual void resume_body_delivery_up_to(size_t byte_count) const override { m_internal_response->resume_body_delivery_up_to(byte_count); }+ virtual void resume_body_delivery(Engine::FetchExecutor& executor) const override { m_internal_response->resume_body_delivery(executor); }+ virtual void release_navigation_hold_up_to(Engine::FetchExecutor& executor, size_t byte_count) const override { m_internal_response->release_navigation_hold_up_to(executor, byte_count); }virtual Vector<Core::ImmutableBytes> release_body_for_transfer() const override { return m_internal_response->release_body_for_transfer(); }[[nodiscard]] NonnullRefPtr<Response const> internal_response() const { return m_internal_response; }diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cppindex 1b60edd1623..ee7a74874fb 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp@@ -72,6 +72,7 @@#include <LibWeb/HTML/Parser/HTMLParser.h>#include <LibWeb/HTML/PolicyContainers.h>#include <LibWeb/HTML/RemoteNavigable.h>+#include <LibWeb/HTML/Scripting/Agent.h>#include <LibWeb/HTML/Scripting/ClassicScript.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h>@@ -526,7 +527,8 @@ void LocalNavigable::start_download_for_response(GC::Ref<Fetch::Infrastructure::// https://fetch.spec.whatwg.org/#body-incrementally-readauto reader = response->body()->incrementally_read(process_body_chunk, process_end_of_body, process_body_error, GC::Ref { realm.global_object() });page().client().page_did_register_download_reader(*download_id, reader);- response->resume_body_delivery();+ if (response->network_transport().has_value())+ response->resume_body_delivery(*surrounding_agent().fetch_executor);}// https://html.spec.whatwg.org/multipage/links.html#handle-as-a-download@@ -3145,7 +3147,8 @@ GC::Ref<DOM::Document> DocumentToCreate::create_document()auto document = m_load_steps->function()(*m_navigation_params);if (m_origin.has_value())document->set_origin(*m_origin);- m_navigation_params->response->resume_body_delivery();+ if (m_navigation_params->response->network_transport().has_value())+ m_navigation_params->response->resume_body_delivery(*surrounding_agent().fetch_executor);m_navigation_params = nullptr;m_load_steps = nullptr;return document;@@ -3405,7 +3408,7 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_entauto sniff_bytes = body ? body->sniff_bytes_if_available() : Optional<Fetch::Infrastructure::Body::SniffBytes> { Fetch::Infrastructure::Body::SniffBytes {} };if (!sniff_bytes.has_value()) {// Async path: bytes not yet available, wait for them- nav_params->response->resume_body_delivery_up_to(Fetch::Infrastructure::MAX_SNIFF_BYTES);+ nav_params->response->release_navigation_hold_up_to(*surrounding_agent().fetch_executor, Fetch::Infrastructure::MAX_SNIFF_BYTES);body->wait_for_sniff_bytes(GC::create_function(self.heap(), GC::captures(output, nav_params, navigation_params, completion_steps, source_allows_downloading, source_interface_origin, url, navigation_id, is_reload_traversal), [](auto& output, auto& nav_params, auto& navigation_params, auto& completion_steps, auto& source_allows_downloading, auto& source_interface_origin, auto& url, auto& navigation_id, auto& is_reload_traversal, Fetch::Infrastructure::Body::SniffBytes sniff_bytes) {// AD-HOC: The document may have been destroyed between when the fetch started and when the// bytes arrived. A response that failed mid-sniff must not be loaded as a documentdiff --git a/Libraries/LibWeb/HTML/NavigationParams.cpp b/Libraries/LibWeb/HTML/NavigationParams.cppindex d65259e887d..02dc37cd8d6 100644--- a/Libraries/LibWeb/HTML/NavigationParams.cpp+++ b/Libraries/LibWeb/HTML/NavigationParams.cpp@@ -13,6 +13,7 @@#include <LibWeb/HTML/BrowsingContext.h>#include <LibWeb/HTML/LocalNavigable.h>#include <LibWeb/HTML/NavigationParams.h>+#include <LibWeb/HTML/Scripting/Agent.h>#include <LibWeb/HTML/Scripting/Environments.h>namespace Web::HTML {@@ -51,7 +52,7 @@ bool stop_body_delivery(NavigationParams::BodyDelivery const& body_delivery)return true;},[](NonnullRefPtr<Fetch::Engine::NetworkTransportHandle> const& network_transport) {- network_transport->stop();+ network_transport->post_stop(*surrounding_agent().fetch_executor);return true;});}diff --git a/Libraries/LibWeb/HTML/NavigationParams.h b/Libraries/LibWeb/HTML/NavigationParams.hindex 465cc1e06e0..237ef4c3a76 100644--- a/Libraries/LibWeb/HTML/NavigationParams.h+++ b/Libraries/LibWeb/HTML/NavigationParams.h@@ -14,6 +14,7 @@#include <LibGC/Ptr.h>#include <LibURL/Origin.h>#include <LibWeb/Bindings/PerformanceNavigationTiming.h>+#include <LibWeb/Export.h>#include <LibWeb/Fetch/Infrastructure/FetchTimingInfo.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>@@ -229,7 +230,7 @@ protected:using NavigationParamsVariant = Variant<NavigationParamsNullOrError, GC::Ref<NavigationParams>, GC::Ref<NonFetchSchemeNavigationParams>>;// Returns whether a fetch controller or network transport was stopped.-bool stop_body_delivery(NavigationParams::BodyDelivery const&);+WEB_API bool stop_body_delivery(NavigationParams::BodyDelivery const&);bool check_a_navigation_responses_adherence_to_x_frame_options(GC::Ptr<Fetch::Infrastructure::ResponseView> response, LocalNavigable* navigable, ContentSecurityPolicy::PolicyList const& csp_list, URL::Origin destination_origin);diff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txtindex ad7a4f4dd41..d55e6bb8998 100644--- a/Tests/LibWeb/CMakeLists.txt+++ b/Tests/LibWeb/CMakeLists.txt@@ -68,7 +68,7 @@ target_sources(TestLibWeb PRIVATE${LADYBIRD_SOURCE_DIR}/Libraries/LibWeb/DOM/IDLEventListener.cpp${LADYBIRD_SOURCE_DIR}/Libraries/LibWeb/WebIDL/CallbackType.cpp)-target_link_libraries(TestLibWeb PRIVATE LibCompositing LibCrypto LibGC LibGfx LibHTTP LibIPC LibJS LibRequests LibThreading LibURL LibWeb LibWebCommon LibWebView)+target_link_libraries(TestLibWeb PRIVATE LibCompositing LibCrypto LibFileSystem LibGC LibGfx LibHTTP LibIPC LibJS LibRequests LibThreading LibURL LibWeb LibWebCommon LibWebView)# NB: This one needs a process of its own: its agents must not share one with the persistent main-thread VM of the suite.ladybird_test(TestAgentThreads.cpp LibWeb LIBS LibCore LibGC LibGfx LibIPC LibJS LibThreading LibURL LibWeb LibWebCommon)diff --git a/Tests/LibWeb/TestFetchAlgorithms.cpp b/Tests/LibWeb/TestFetchAlgorithms.cppindex e36a69c7ae1..e162eb3b86d 100644--- a/Tests/LibWeb/TestFetchAlgorithms.cpp+++ b/Tests/LibWeb/TestFetchAlgorithms.cpp@@ -6,14 +6,21 @@#include "FetchTestDocument.h"#include <AK/JsonObject.h>+#include <AK/Random.h>#include <AK/RefCounted.h>#include <AK/ScopeGuard.h>#include <LibCore/EventLoop.h>+#include <LibCore/File.h>+#include <LibCore/StandardPaths.h>#include <LibCore/Timer.h>+#include <LibFileSystem/FileSystem.h>#include <LibGC/Function.h>#include <LibGC/Root.h>#include <LibGC/Testing.h>+#include <LibIPC/File.h>+#include <LibIPC/Transport.h>#include <LibJS/Runtime/Error.h>+#include <LibRequests/RequestClient.h>#include <LibTest/TestCase.h>#include <LibURL/Parser.h>#include <LibWeb/Fetch/Engine/EngineCommand.h>@@ -22,6 +29,7 @@#include <LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h>#include <LibWeb/Fetch/Engine/FetchByteChannel.h>#include <LibWeb/Fetch/Engine/InlineFetchExecutor.h>+#include <LibWeb/Fetch/Engine/NetworkTransportHandle.h>#include <LibWeb/Fetch/Engine/WholeBodyTransport.h>#include <LibWeb/Fetch/Fetching/FetchEngine.h>#include <LibWeb/Fetch/Fetching/FetchEventSink.h>@@ -35,6 +43,7 @@#include <LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h>#include <LibWeb/Fetch/Infrastructure/Task.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>+#include <LibWeb/HTML/NavigationParams.h>#include <LibWeb/HTML/Scripting/Agent.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>@@ -49,7 +58,9 @@ using Web::Fetch::Engine::EngineCommand;using Web::Fetch::Engine::EngineCommandSink;using Web::Fetch::Engine::FetchBodyDeliveryGate;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::NetworkActivity;using Web::Fetch::Engine::Event::ReadRequestBodyStream;using Web::Fetch::Engine::Event::RequestBodyEndOfBody;@@ -267,11 +278,26 @@ struct ReachedSteps : RefCounted<ReachedSteps> {bool marker_reached { false };};-// Records each stop that reaches the fetch engine.-class StopRecordingEngine final : public EngineCommandSink {+// The commands posted to an engine that applies none of them, for the test to hand on.+struct PostedCommands : RefCounted<PostedCommands> {+ Vector<EngineCommand> commands;+};++ByteString describe_transport_control(TransportControl::Operation const& operation, Web::Fetch::Engine::RequestId request_id, Web::Fetch::Engine::TransportEpoch transport_epoch)+{+ auto description = operation.visit(+ [](TransportControl::StopTransport) { return ByteString { "stop transport"sv }; },+ [](TransportControl::ReleaseNavigationHold) { return ByteString { "release navigation hold"sv }; },+ [](TransportControl::ReleaseNavigationHoldUpTo const& release) { return ByteString::formatted("release navigation hold up to {}", release.byte_count); });+ return ByteString::formatted("{} of request {} of epoch {}", description, request_id.value(), transport_epoch.value());+}++// Records each command that reaches the fetch engine, and applies none of them.+class CommandRecordingEngine final : public EngineCommandSink {public:- explicit StopRecordingEngine(NonnullRefPtr<ReachedSteps> reached)+ explicit CommandRecordingEngine(NonnullRefPtr<ReachedSteps> reached, RefPtr<PostedCommands> posted_commands = {}): m_reached(move(reached))+ , m_posted_commands(move(posted_commands)){}@@ -281,11 +307,16 @@ public:[&](Web::Fetch::Engine::Command::Abort const& abort) { m_reached->steps.append(ByteString::formatted("abort {}", abort.fetch_id.value())); },[&](Web::Fetch::Engine::Command::Terminate const& terminate) { m_reached->steps.append(ByteString::formatted("terminate {}", terminate.fetch_id.value())); },[&](Web::Fetch::Engine::Command::Stop const& stop) { m_reached->steps.append(ByteString::formatted("stop {}", stop.fetch_id.value())); },+ [&](Web::Fetch::Engine::Command::NavigationBodyAdopted const&) { m_reached->steps.append("navigation body adopted"); },+ [&](TransportControl const& control) { m_reached->steps.append(describe_transport_control(control.operation, control.request_id, control.transport_epoch)); },[](auto const&) { FAIL("unexpected command"); });+ if (m_posted_commands)+ m_posted_commands->commands.append(move(command));}private:NonnullRefPtr<ReachedSteps> m_reached;+ RefPtr<PostedCommands> m_posted_commands;};// A fetch that has run to its end, with a response body whose transport the fetch's engine record keeps.@@ -338,7 +369,7 @@ TEST_CASE(each_stop_of_a_started_fetch_reaches_the_engine_for_its_fetch_id)auto reached = make_ref_counted<ReachedSteps>();Web::Fetch::Engine::FetchExecutorServices services { .event_loop = Core::EventLoop::current_weak() };- auto fetch_executor = Web::Fetch::Engine::InlineFetchExecutor::create(move(services), make<StopRecordingEngine>(reached));+ auto fetch_executor = Web::Fetch::Engine::InlineFetchExecutor::create(move(services), make<CommandRecordingEngine>(reached));auto& registry = Web::HTML::surrounding_agent().fetch_controller_registry;auto create_controller = [&](Optional<u64> fetch_id) {@@ -653,6 +684,28 @@ 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)+ {+ Web::ResourceLoader::initialize(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());+ }++ ~ResourceLoaderWithStandInRequestServer()+ {+ // The client can hear of its RequestServer's death after the resource loader is gone.+ client->on_request_server_died = nullptr;+ Web::ResourceLoader::shut_down();+ }++ RefPtr<Requests::RequestClient> client;+ OwnPtr<IPC::Transport> request_server;+};+}TEST_CASE(a_request_body_sent_without_a_network_request_is_one_chunk_before_the_response)@@ -730,6 +783,200 @@ TEST_CASE(a_null_request_body_ends_before_the_response)namespace {+// A navigation body adopted from a RequestServer that the test stands in for. The commands posted to the agent's+// executor are recorded, and reach a fetch engine only when the test applies them.+class AdoptedNavigationBody {+public:+ explicit AdoptedNavigationBody(FetchHarness const& harness)+ : m_harness(harness)+ , m_resource_loader(harness.realm->heap())+ {+ auto& agent = Web::HTML::surrounding_agent();+ Web::Fetch::Engine::FetchExecutorServices services { .event_loop = Core::EventLoop::current_weak() };+ auto recording_engine = make<CommandRecordingEngine>(commands, m_posted_commands);+ agent.fetch_executor = Web::Fetch::Engine::InlineFetchExecutor::create(move(services), move(recording_engine));+ m_engine_executor = Web::Fetch::Fetching::create_inline_fetch_executor(agent.network_activity_observers);++ auto on_network_settled = GC::create_function(harness.realm->heap(), GC::captures(settled), [](auto& settled, Optional<StringView> error) {+ settled->steps.append(error.has_value() ? ByteString { *error } : ByteString { "completed"sv });+ });+ Requests::RequestTransferLeaseKey transfer_lease { .source_client_id = 2, .source_request_id = 3 };+ auto body = Web::Fetch::Fetching::adopt_navigation_response_body(*harness.realm, *response, {}, transfer_lease, nullptr, on_network_settled);+ VERIFY(body);+ m_body = GC::make_root(*body);+ }++ NetworkTransportHandle& handle() const { return *response->network_transport()->handle; }+ Web::Fetch::Engine::FetchExecutor& agent_executor() const { return *Web::HTML::surrounding_agent().fetch_executor; }+ FetchByteChannel::TakeResult peek_body(u64 limit) const { return response->network_transport()->body_channel->peek_up_to(limit); }++ // 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));+ 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, Vector<HTTP::Header> {}, Optional<u32> {}, Optional<String> {}, Requests::CacheState::NotCached, marker));+ MUST(marker_message.transfer_message(*m_resource_loader.request_server));++ 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) {+ auto handle = weak_handle.strong_ref();+ return handle && handle->http_version() == marker;+ }));+ }++ void finish_request()+ {+ auto request_id = handle().request_id().value();+ receive(MUST(Messages::RequestClient::RequestFinished::static_encode(request_id, 0, Requests::RequestTimingInfo {}, Optional<Requests::NetworkError> {})));+ }++ // Hands the commands posted so far to a fetch engine, and runs them.+ void apply_posted_commands()+ {+ run_queued_invocations(m_harness);+ for (auto& command : m_posted_commands->commands)+ m_engine_executor->post(move(command));+ m_posted_commands->commands.clear();+ run_queued_invocations(m_harness);+ }++ ByteString describe(TransportControl::Operation const& operation) const+ {+ return describe_transport_control(operation, handle().request_id(), handle().transport_epoch());+ }++ NonnullRefPtr<ReachedSteps> commands { make_ref_counted<ReachedSteps>() };+ NonnullRefPtr<ReachedSteps> settled { make_ref_counted<ReachedSteps>() };+ NonnullRefPtr<Web::Fetch::Infrastructure::Response> response { Web::Fetch::Infrastructure::Response::create() };++private:+ FetchHarness const& m_harness;+ ResourceLoaderWithStandInRequestServer m_resource_loader;+ 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;+ u64 m_received_count { 0 };+};++}++TEST_CASE(an_adopted_navigation_body_completes_when_its_request_finishes)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;+ AdoptedNavigationBody adopted { harness };++ adopted.finish_request();+ EXPECT_EQ(adopted.settled->steps, (Vector<ByteString> { "completed" }));+ EXPECT(adopted.peek_body(0).state.has<FetchByteChannel::Closed>());+ EXPECT_EQ(adopted.commands->steps, (Vector<ByteString> { "navigation body adopted" }));+}++TEST_CASE(a_stop_of_an_adopted_navigation_body_is_reported_as_it_is_requested_and_once)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;+ AdoptedNavigationBody adopted { harness };++ adopted.handle().post_stop(adopted.agent_executor());+ EXPECT_EQ(adopted.settled->steps, (Vector<ByteString> { "Transferred navigation response was stopped" }));++ // The stop reaches the request, whose teardown ends the body.+ adopted.apply_posted_commands();+ EXPECT_EQ(adopted.settled->steps, (Vector<ByteString> { "Transferred navigation response was stopped" }));+ EXPECT(adopted.peek_body(0).state.has<FetchByteChannel::ConsumerCancelled>());+ auto stop = adopted.describe(TransportControl::StopTransport {});+ EXPECT_EQ(adopted.commands->steps, (Vector<ByteString> { "navigation body adopted", stop }));+}++TEST_CASE(an_adopted_navigation_body_whose_request_finishes_before_a_requested_stop_reaches_it_ends_as_stopped_once)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;+ AdoptedNavigationBody adopted { harness };++ adopted.handle().post_stop(adopted.agent_executor());+ adopted.finish_request();+ EXPECT(adopted.peek_body(0).state.has<FetchByteChannel::ConsumerCancelled>());++ // The stop reaches the request once it has finished.+ adopted.apply_posted_commands();+ EXPECT_EQ(adopted.settled->steps, (Vector<ByteString> { "Transferred navigation response was stopped" }));+ EXPECT(adopted.peek_body(0).state.has<FetchByteChannel::ConsumerCancelled>());+}++TEST_CASE(a_stop_requested_after_an_adopted_navigation_body_ended_reports_nothing)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;+ AdoptedNavigationBody adopted { harness };++ adopted.finish_request();+ adopted.handle().post_stop(adopted.agent_executor());+ adopted.apply_posted_commands();+ EXPECT_EQ(adopted.settled->steps, (Vector<ByteString> { "completed" }));+ EXPECT(adopted.peek_body(0).state.has<FetchByteChannel::Closed>());+}++TEST_CASE(an_adopted_navigation_body_takes_none_of_its_data_once_its_stop_is_requested)+{+ auto const payload = "adopted body bytes"sv;+ auto const path = ByteString::formatted("{}/TestFetchAlgorithms-{:016x}", 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(payload.bytes()));+ }+ // A file that is still mapped cannot be removed on Windows, so this runs last, once the request has unmapped it.+ ScopeGuard remove_file = [&path] { MUST(FileSystem::remove(path, FileSystem::RecursionMode::Disallowed)); };++ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;+ AdoptedNavigationBody adopted { harness };++ // The body flows, as once its document is created.+ adopted.response->network_transport()->body_delivery_gate->release_hold();+ adopted.handle().post_stop(adopted.agent_executor());++ auto request_id = adopted.handle().request_id().value();+ auto file = IPC::File::adopt_file(MUST(Core::File::open(path, Core::File::OpenMode::Read)));+ adopted.receive(MUST(Messages::RequestClient::RequestBodyFileAvailable::static_encode(request_id, file, 0, payload.length())));+ auto buffered = adopted.peek_body(payload.length());+ EXPECT(buffered.taken.is_empty());+ EXPECT(buffered.state.has<FetchByteChannel::Open>());++ adopted.finish_request();+ run_queued_invocations(harness);+ EXPECT(adopted.peek_body(0).state.has<FetchByteChannel::ConsumerCancelled>());+}++TEST_CASE(the_holders_of_an_adopted_navigation_body_post_its_controls_to_the_agents_fetch_executor)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;+ AdoptedNavigationBody adopted { harness };++ adopted.response->resume_body_delivery(adopted.agent_executor());+ adopted.response->release_navigation_hold_up_to(adopted.agent_executor(), 512);+ EXPECT(Web::HTML::stop_body_delivery(NonnullRefPtr { adopted.handle() }));+ EXPECT_EQ(adopted.settled->steps, (Vector<ByteString> { "Transferred navigation response was stopped" }));++ run_queued_invocations(harness);+ auto release = adopted.describe(TransportControl::ReleaseNavigationHold {});+ auto release_up_to = adopted.describe(TransportControl::ReleaseNavigationHoldUpTo { .byte_count = 512 });+ auto stop = adopted.describe(TransportControl::StopTransport {});+ EXPECT_EQ(adopted.commands->steps, (Vector<ByteString> { "navigation body adopted", release, release_up_to, stop }));+}++namespace {+// The WebDriver BiDi network events that reached the event sink, by name and request id.struct ReportedNetworkEvents : RefCounted<ReportedNetworkEvents> {GC_HOLDS_NO_CELL_EDGES;diff --git a/Tests/LibWebView/test-webdriver-bidi.py b/Tests/LibWebView/test-webdriver-bidi.pyindex 4d8f73ae633..cbc89a0739d 100755--- a/Tests/LibWebView/test-webdriver-bidi.py+++ b/Tests/LibWebView/test-webdriver-bidi.py@@ -1991,7 +1991,12 @@ def check_network_adopted_navigation_events(bidi, context, server):subscription = bidi.command("session.subscribe",{- "events": ["network.beforeRequestSent", "network.responseStarted", *sorted(terminal_methods)],+ "events": [+ "browsingContext.navigationAborted",+ "network.beforeRequestSent",+ "network.responseStarted",+ *sorted(terminal_methods),+ ],"contexts": [context],},)["subscription"]@@ -2038,8 +2043,28 @@ def check_network_adopted_navigation_events(bidi, context, server):)if kind == "stopped":- # A stop in the document's process ends the adopted body with a fetch error.+ # A stop in the document's process ends the adopted body with a fetch error, reported before the+ # stop aborts the document's navigation.bidi.evaluate(context, "window.stop()")++ def is_our_navigation_abort(event, navigation=started["navigation"]):+ return (+ event["method"] == "browsingContext.navigationAborted"+ and event["params"].get("navigation") == navigation+ )++ while True:+ reported = [+ event["method"]+ for event in bidi.events+ if (event["method"] in terminal_methods and is_our_event(event))+ or is_our_navigation_abort(event)+ ]+ if len(reported) >= 2:+ break+ bidi.read_message()+ assert reported[:2] == ["network.fetchError", "browsingContext.navigationAborted"], reported+ bidi.events = [event for event in bidi.events if not is_our_navigation_abort(event)]else:server.release_document.set()terminal = next_event(terminal_methods)