Truly independent web browser
LibWeb: Make FetchParams reference-counted instead of GC-allocated
Luke Wilde4029a4b61f66
diff --git a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cppindex dd6cfd192c1..b9ad352e3ce 100644--- a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp@@ -10,7 +10,6 @@#include <LibJS/Runtime/Error.h>#include <LibWeb/Fetch/Fetching/BodyStreamPullSource.h>#include <LibWeb/Fetch/Infrastructure/FetchController.h>-#include <LibWeb/Fetch/Infrastructure/FetchParams.h>#include <LibWeb/Fetch/Infrastructure/Task.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>@@ -75,9 +74,9 @@ void BodyStreamWakeSink::wake(Engine::WakeTicket ticket)});}-BodyStreamPullSource::BodyStreamPullSource(JS::Realm& realm, GC::Ptr<Infrastructure::FetchParams const> fetch_params, GC::Ref<Streams::ReadableStream> stream, NonnullRefPtr<Engine::FetchByteChannel> channel, BodyStreamWakeSink const& wake_sink)+BodyStreamPullSource::BodyStreamPullSource(JS::Realm& realm, GC::Ptr<Infrastructure::FetchController> fetch_controller, GC::Ref<Streams::ReadableStream> stream, NonnullRefPtr<Engine::FetchByteChannel> channel, BodyStreamWakeSink const& wake_sink): m_realm(realm)- , m_fetch_params(fetch_params)+ , m_fetch_controller(fetch_controller), m_stream(stream), m_channel(move(channel)), m_registry_token(wake_sink.registry_token())@@ -90,7 +89,7 @@ void BodyStreamPullSource::visit_edges(Visitor& visitor){Base::visit_edges(visitor);visitor.visit(m_realm);- visitor.visit(m_fetch_params);+ visitor.visit(m_fetch_controller);visitor.visit(m_stream);visitor.visit(m_pending_pull_promise);visitor.visit(m_on_resource_header);@@ -137,8 +136,8 @@ GC::Ref<WebIDL::Promise> BodyStreamPullSource::cancel(JS::Value reason)on_resource_header->function()({}, Infrastructure::Body::SniffOutcome::Failed);// cancelAlgorithm: abort fetchParams's controller with reason, given reason.- if (m_fetch_params)- m_fetch_params->controller()->abort(realm, reason);+ if (m_fetch_controller)+ m_fetch_controller->abort(realm, reason);return WebIDL::create_resolved_promise(realm, JS::js_undefined());}@@ -223,8 +222,8 @@ void BodyStreamPullSource::on_pull_wake()auto steps = GC::create_function(heap(), [this] {run_pull_task();});- if (m_fetch_params) {- Infrastructure::queue_fetch_task(m_fetch_params->controller()->task_destination(), steps);+ if (m_fetch_controller) {+ Infrastructure::queue_fetch_task(m_fetch_controller->task_destination(), steps);return;}@@ -241,7 +240,7 @@ void BodyStreamPullSource::push_while_paused(){if (m_detached || m_pending_pull_promise || m_push_ticket.has_value() || !HTML::main_thread_event_loop().execution_paused())return;- if (!m_fetch_params || m_fetch_params->control_block().body_intent() != Engine::BodyIntent::SyncAccumulate)+ if (!m_fetch_controller || m_fetch_controller->control_block().body_intent() != Engine::BodyIntent::SyncAccumulate)return;m_push_ticket = arm_waiter(Engine::FetchByteChannel::BufferedAtLeast { 1 });}@@ -338,8 +337,8 @@ void BodyStreamPullSource::drain_into_stream()auto error = WebIDL::exception_to_throw_completion(realm.vm(), realm, pull_result.release_error());if (m_stream->is_readable())m_stream->error(error.value());- if (m_fetch_params)- m_fetch_params->controller()->terminate();+ if (m_fetch_controller)+ m_fetch_controller->terminate();m_channel->cancel();m_detached = true;return;@@ -347,8 +346,8 @@ void BodyStreamPullSource::drain_into_stream()}// 2. If stream is errored, then terminate fetchParams’s controller.- if (m_stream->is_errored() && m_fetch_params)- m_fetch_params->controller()->terminate();+ if (m_stream->is_errored() && m_fetch_controller)+ m_fetch_controller->terminate();settle_stream(result);if (result.state.has<Engine::FetchByteChannel::ConsumerCancelled>() || result.state.has<Engine::FetchByteChannel::Transferred>())@@ -357,7 +356,7 @@ void BodyStreamPullSource::drain_into_stream()// https://fetch.spec.whatwg.org/#concept-http-network-fetch// NB: Steps 10 to 13 of HTTP-network fetch.-GC::Ref<Infrastructure::Body> create_body_from_channel(JS::Realm& realm, GC::Ptr<Infrastructure::FetchParams const> fetch_params, NonnullRefPtr<Engine::FetchByteChannel> channel)+GC::Ref<Infrastructure::Body> create_body_from_channel(JS::Realm& realm, GC::Ptr<Infrastructure::FetchController> fetch_controller, NonnullRefPtr<Engine::FetchByteChannel> channel){HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };@@ -366,7 +365,7 @@ GC::Ref<Infrastructure::Body> create_body_from_channel(JS::Realm& realm, GC::Ptr// 10. Let stream be a new ReadableStream.auto stream = Streams::ReadableStream::create(realm);- auto pull_source = GC::Heap::the().allocate<BodyStreamPullSource>(realm, fetch_params, stream, move(channel), *wake_sink);+ auto pull_source = GC::Heap::the().allocate<BodyStreamPullSource>(realm, fetch_controller, stream, move(channel), *wake_sink);// 11. Let pullAlgorithm be the following steps:auto pull_algorithm = GC::create_function(GC::Heap::the(), [pull_source]() {diff --git a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.hindex 6ccd7b3f678..1aea4e95bc4 100644--- a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h+++ b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.h@@ -45,7 +45,7 @@ class BodyStreamPullSource final : public JS::Cell {GC_DECLARE_ALLOCATOR(BodyStreamPullSource);public:- BodyStreamPullSource(JS::Realm&, GC::Ptr<Infrastructure::FetchParams const>, GC::Ref<Streams::ReadableStream>, NonnullRefPtr<Engine::FetchByteChannel>, BodyStreamWakeSink const&);+ BodyStreamPullSource(JS::Realm&, GC::Ptr<Infrastructure::FetchController>, GC::Ref<Streams::ReadableStream>, NonnullRefPtr<Engine::FetchByteChannel>, BodyStreamWakeSink const&);virtual ~BodyStreamPullSource() override;GC::Ref<WebIDL::Promise> pull();@@ -81,7 +81,7 @@ private:// The realm the stream is set up in.GC::Ref<JS::Realm> m_realm;// Null for a navigation body adopted from another process.- GC::Ptr<Infrastructure::FetchParams const> m_fetch_params;+ GC::Ptr<Infrastructure::FetchController> m_fetch_controller;GC::Ref<Streams::ReadableStream> m_stream;NonnullRefPtr<Engine::FetchByteChannel> m_channel;BodyStreamWakeToken const m_registry_token { 0 };@@ -99,6 +99,6 @@ private:};// The view of a body whose bytes arrive through the channel; its stream's pull source is the channel's consumer.-WEB_API GC::Ref<Infrastructure::Body> create_body_from_channel(JS::Realm&, GC::Ptr<Infrastructure::FetchParams const>, NonnullRefPtr<Engine::FetchByteChannel>);+WEB_API GC::Ref<Infrastructure::Body> create_body_from_channel(JS::Realm&, GC::Ptr<Infrastructure::FetchController>, NonnullRefPtr<Engine::FetchByteChannel>);}diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex ad502bfc728..35a0bbd833e 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -164,7 +164,7 @@ private:GC_DEFINE_ALLOCATOR(ResponseBodyForwardingReadRequest);// The view of the body of response, which takes the channel the body's bytes arrive through.-static GC::Ptr<Infrastructure::Body> create_body_view(JS::Realm& realm, Infrastructure::Response& response, GC::Ptr<Infrastructure::FetchParams const> fetch_params)+static GC::Ptr<Infrastructure::Body> create_body_view(JS::Realm& realm, Infrastructure::Response& response, GC::Ptr<Infrastructure::FetchController> fetch_controller){auto body = response.body();if (!body.has_value())@@ -176,7 +176,7 @@ static GC::Ptr<Infrastructure::Body> create_body_view(JS::Realm& realm, Infrastrauto channel = body->bytes().get<NonnullRefPtr<Engine::FetchByteChannel>>();auto length = body->length();response.set_body(Infrastructure::ResponseBody { Infrastructure::ResponseBody::ReadThroughStream {}, length });- return create_body_from_channel(realm, fetch_params, move(channel));+ return create_body_from_channel(realm, fetch_controller, move(channel));}class HTTPCache {@@ -366,12 +366,11 @@ GC::Ref<Infrastructure::FetchController> fetch(JS::Realm& realm, Infrastructure:// 2. Let onPreloadedResponseAvailable be an algorithm that runs the following step given a response// response: set fetchParams’s preloaded response candidate to response.- auto on_preloaded_response_available = GC::create_function(GC::Heap::the(), [fetch_params](NonnullRefPtr<Infrastructure::Response> response) {+ auto on_preloaded_response_available = GC::create_function(GC::Heap::the(), [fetch_params, controller](NonnullRefPtr<Infrastructure::Response> response) {fetch_params->set_preloaded_response_candidate(response);// NB: main fetch may already be parked on this preload result.// Resolve that waiter here instead of spinning the event loop.- auto controller = fetch_params->controller();if (auto pending_preloaded_response = controller->pending_preloaded_response()) {controller->set_pending_preloaded_response(nullptr);pending_preloaded_response->resolve(response);@@ -488,7 +487,7 @@ GC::Ref<Infrastructure::FetchController> fetch(JS::Realm& realm, Infrastructure:}if (Core::StatsLog::the() && client_window && request.is_subresource_request())- begin_rendering_pending_operation(fetch_params->controller().ptr(), client_window->associated_document(), RenderingPendingReason::ResourceFetchesInFlight);+ begin_rendering_pending_operation(controller.ptr(), client_window->associated_document(), RenderingPendingReason::ResourceFetchesInFlight);// 15. Run main fetch given fetchParams.(void)main_fetch(realm, fetch_params);@@ -632,34 +631,33 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParamrequest->current_url().set_scheme("https"sv);}- auto get_response = GC::create_function(GC::Heap::the(), [&realm, &fetch_params, request]() -> GC::Ref<PendingResponse> {+ auto get_response = GC::create_function(GC::Heap::the(), [&realm, fetch_params = NonnullRefPtr { fetch_params }, controller = fetch_params.controller(), request]() -> GC::Ref<PendingResponse> {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' get_response() function");auto const* origin = request->origin().get_pointer<URL::Origin>();// -> fetchParams’s preloaded response candidate is not null- if (!fetch_params.preloaded_response_candidate().has<Empty>()) {+ if (!fetch_params->preloaded_response_candidate().has<Empty>()) {// 1. Wait until fetchParams's preloaded response candidate is not "pending".- if (fetch_params.preloaded_response_candidate().has<Infrastructure::FetchParams::PreloadedResponseCandidatePendingTag>()) {+ if (fetch_params->preloaded_response_candidate().has<Infrastructure::FetchParams::PreloadedResponseCandidatePendingTag>()) {// NB: The spec says to wait here. Spinning the main-thread event// loop strands the queued preload callback behind nested work,// so we park a PendingResponse and let that callback resolve it.- auto controller = fetch_params.controller();// NB: Reuse the parked response if this branch is re-entered// before the preload callback runs.if (auto pending_preloaded_response = controller->pending_preloaded_response())return *pending_preloaded_response;- auto pending_preloaded_response = PendingResponse::create(fetch_params);+ auto pending_preloaded_response = PendingResponse::create(controller);controller->set_pending_preloaded_response(pending_preloaded_response);return pending_preloaded_response;}// 2. Assert: fetchParams’s preloaded response candidate is a response.- VERIFY(fetch_params.preloaded_response_candidate().has<NonnullRefPtr<Infrastructure::Response>>());+ VERIFY(fetch_params->preloaded_response_candidate().has<NonnullRefPtr<Infrastructure::Response>>());// 3. Return fetchParams’s preloaded response candidate.- return PendingResponse::create(fetch_params, fetch_params.preloaded_response_candidate().get<NonnullRefPtr<Infrastructure::Response>>());+ return PendingResponse::create(controller, fetch_params->preloaded_response_candidate().get<NonnullRefPtr<Infrastructure::Response>>());}// -> request’s current URL’s origin is same origin with request’s origin, and request’s response tainting is "basic"@@ -682,7 +680,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParamrequest->set_response_tainting(Infrastructure::Request::ResponseTainting::Basic);// 2. Return the result of running scheme fetch given fetchParams.- return scheme_fetch(realm, fetch_params);+ return scheme_fetch(realm, *fetch_params);// NOTE: HTML assigns any documents and workers created from URLs whose scheme is "data" a unique// opaque origin. Service workers can only be created from URLs whose scheme is an HTTP(S) scheme.@@ -691,20 +689,20 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam// -> request’s mode is "same-origin"if (request->mode() == Infrastructure::Request::Mode::SameOrigin) {// Return a network error.- return PendingResponse::create(fetch_params, Infrastructure::Response::network_error("Request with 'same-origin' mode must have same URL and request origin"_string));+ return PendingResponse::create(controller, Infrastructure::Response::network_error("Request with 'same-origin' mode must have same URL and request origin"_string));}// -> request’s mode is "no-cors"if (request->mode() == Infrastructure::Request::Mode::NoCORS) {// 1. If request’s redirect mode is not "follow", then return a network error.if (request->redirect_mode() != Infrastructure::Request::RedirectMode::Follow)- return PendingResponse::create(fetch_params, Infrastructure::Response::network_error("Request with 'no-cors' mode must have redirect mode set to 'follow'"_string));+ return PendingResponse::create(controller, Infrastructure::Response::network_error("Request with 'no-cors' mode must have redirect mode set to 'follow'"_string));// 2. Set request’s response tainting to "opaque".request->set_response_tainting(Infrastructure::Request::ResponseTainting::Opaque);// 3. Return the result of running scheme fetch given fetchParams.- return scheme_fetch(realm, fetch_params);+ return scheme_fetch(realm, *fetch_params);}// -> request’s current URL’s scheme is not an HTTP(S) scheme@@ -715,7 +713,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParamVERIFY(request->mode() == Infrastructure::Request::Mode::CORS);// Return a network error.- return PendingResponse::create(fetch_params, Infrastructure::Response::network_error("Request with 'cors' mode must have URL with HTTP or HTTPS scheme"_string));+ return PendingResponse::create(controller, Infrastructure::Response::network_error("Request with 'cors' mode must have URL with HTTP or HTTPS scheme"_string));}// -> request’s use-CORS-preflight flag is set@@ -729,10 +727,10 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam// 1. Set request’s response tainting to "cors".request->set_response_tainting(Infrastructure::Request::ResponseTainting::CORS);- auto returned_pending_response = PendingResponse::create(fetch_params);+ auto returned_pending_response = PendingResponse::create(controller);// 2. Let corsWithPreflightResponse be the result of running HTTP fetch given fetchParams and true.- auto cors_with_preflight_response = http_fetch(realm, fetch_params, MakeCORSPreflight::Yes);+ auto cors_with_preflight_response = http_fetch(realm, *fetch_params, MakeCORSPreflight::Yes);cors_with_preflight_response->when_loaded([request, returned_pending_response](NonnullRefPtr<Infrastructure::Response> cors_with_preflight_response) {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' cors_with_preflight_response load callback");// 3. If corsWithPreflightResponse is a network error, then clear cache entries using request.@@ -752,7 +750,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParamrequest->set_response_tainting(Infrastructure::Request::ResponseTainting::CORS);// 2. Return the result of running HTTP fetch given fetchParams.- return http_fetch(realm, fetch_params);+ return http_fetch(realm, *fetch_params);});if (recursive == Recursive::Yes) {@@ -767,21 +765,21 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam}// 11. If recursive is false, then run the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, &fetch_params, request, response, get_response] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, fetch_params = NonnullRefPtr { fetch_params }, controller = fetch_params.controller(), request, response, get_response] {// 12. If response is null, then set response to the result of running the steps corresponding to the first// matching statement:- auto pending_response = PendingResponse::create(fetch_params, Infrastructure::Response::create());+ auto pending_response = PendingResponse::create(controller, Infrastructure::Response::create());if (!response) {pending_response = get_response->function()();}- pending_response->when_loaded([&realm, &fetch_params, request, response, response_was_null = !response](NonnullRefPtr<Infrastructure::Response> resolved_response) mutable {+ pending_response->when_loaded([&realm, fetch_params, controller, request, response, response_was_null = !response](NonnullRefPtr<Infrastructure::Response> resolved_response) mutable {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' pending_response load callback");// AD-HOC: From here on, response processing captures fetchParams's task destination as it schedules work// (the fully-read in step 22, and fetch response handover's tasks, body pipe and body read). Record// that the response has arrived (a network response was recorded as its headers came in) — so// consume_a_preloaded_resource() re-targets an in-flight preload's fetch only til then.- fetch_params.control_block().set_response_arrived();+ fetch_params->control_block().set_response_arrived();if (response_was_null)response = resolved_response;@@ -866,7 +864,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam// - should internalResponse to request be blocked due to nosniff|| Infrastructure::should_response_to_request_be_blocked_due_to_nosniff(internal_response, request) == Infrastructure::RequestOrResponseBlocking::Blocked)) {// then set response and internalResponse to a network error.- stop_discarded_response_body(*fetch_params.controller(), *internal_response);+ stop_discarded_response_body(*controller, *internal_response);response = internal_response = Infrastructure::Response::network_error("Response was blocked"_string);}@@ -880,7 +878,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam&& internal_response->status() == 206&& internal_response->range_requested()&& !request->header_list()->contains("Range"sv)) {- stop_discarded_response_body(*fetch_params.controller(), *internal_response);+ stop_discarded_response_body(*controller, *internal_response);response = internal_response = Infrastructure::Response::network_error("Response has status 206 and 'range-requested' flag set, but request has no 'Range' header"_string);}@@ -895,8 +893,8 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParamif (!request->integrity_metadata().is_empty()) {// 1. Let processBodyError be this step: run fetch response handover given fetchParams and a network// error.- auto process_body_error = GC::create_function(GC::Heap::the(), [&realm, &fetch_params](JS::Value) {- fetch_response_handover(realm, fetch_params, Infrastructure::Response::network_error("Response body could not be processed"_string));+ auto process_body_error = GC::create_function(GC::Heap::the(), [&realm, fetch_params, controller](JS::Value) {+ fetch_response_handover(realm, *fetch_params, controller, Infrastructure::Response::network_error("Response body could not be processed"_string));});// 2. If response’s body is null, then run processBodyError and abort these steps.@@ -906,7 +904,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam}// 3. Let processBody given bytes be these steps:- auto process_body = GC::create_function(GC::Heap::the(), [&realm, request, response, &fetch_params, process_body_error](ByteBuffer bytes) {+ auto process_body = GC::create_function(GC::Heap::the(), [&realm, request, response, fetch_params, controller, process_body_error](ByteBuffer bytes) {// 1. If bytes do not match request’s integrity metadata, then run processBodyError and abort these steps.if (!TRY_OR_IGNORE(SRI::do_bytes_match_metadata_list(bytes, request->integrity_metadata()))) {process_body_error->function()({});@@ -917,16 +915,16 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParamresponse->set_body(Infrastructure::ResponseBody::from_bytes(Core::ImmutableBytes::adopt(move(bytes))));// 3. Run fetch response handover given fetchParams and response.- fetch_response_handover(realm, fetch_params, *response);+ fetch_response_handover(realm, *fetch_params, controller, *response);});// 4. Fully read response’s body given processBody and processBodyError.- auto body_view = create_body_view(realm, *response, &fetch_params);- body_view->fully_read(realm, process_body, process_body_error, fetch_params.controller()->task_destination());+ auto body_view = create_body_view(realm, *response, controller);+ body_view->fully_read(realm, process_body, process_body_error, controller->task_destination());}// 24. Otherwise, run fetch response handover given fetchParams and response.else {- fetch_response_handover(realm, fetch_params, *response);+ fetch_response_handover(realm, *fetch_params, controller, *response);}});}));@@ -970,13 +968,14 @@ static StorageAPI::StorageKey obtain_a_storage_key_for_non_storage_purposes(Requ}// https://fetch.spec.whatwg.org/#fetch-finale-void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, Infrastructure::Response& response)+void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, GC::Ref<Infrastructure::FetchController> controller, Infrastructure::Response& response){dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'fetch response handover' with: fetch_params @ {}, response @ {}", &fetch_params, &response);+ VERIFY(&controller->control_block() == &fetch_params.control_block());// NB: The body view takes the channel that the internal response's body arrives through.auto internal_body = response.unsafe_response()->body().copy();- auto body_view = create_body_view(realm, *response.unsafe_response(), &fetch_params);+ auto body_view = create_body_view(realm, *response.unsafe_response(), controller);auto response_view = Infrastructure::ResponseView::create(response, body_view);// 1. Let timingInfo be fetchParams’s timing info.@@ -1026,19 +1025,19 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const// within processResponseConsumeBody. So we ensure report_timing_steps is set on error too, which allows// reportTiming to work without asserting, and still produces useful timing data for failed fetches.auto timing_reported = RefCountedFlag::create(false);- auto setup_report_timing_steps = [response = response_view->record(), &fetch_params, timing_info, timing_reported] {+ auto setup_report_timing_steps = [response = response_view->record(), fetch_params = NonnullRefPtr { fetch_params }, controller, timing_info, timing_reported] {// 1. Let unsafeEndTime be the unsafe shared current time.auto unsafe_end_time = HighResolutionTime::unsafe_shared_current_time();// 2. Set fetchParams’s controller’s report timing steps to the following steps given a global object global:- fetch_params.controller()->set_report_timing_steps([response, &fetch_params, timing_info, unsafe_end_time, timing_reported](JS::Object& global) mutable {+ controller->set_report_timing_steps([response, fetch_params, timing_info, unsafe_end_time, timing_reported](JS::Object& global) mutable {// NB: Network completion and consuming the response body can both request a timing report.if (timing_reported->value())return;timing_reported->set_value(true);// 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return.- if (!Infrastructure::is_http_or_https_scheme(fetch_params.request()->url().scheme()))+ if (!Infrastructure::is_http_or_https_scheme(fetch_params->request()->url().scheme()))return;// 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global.@@ -1068,7 +1067,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams constauto response_status = 0;// 7. If fetchParams’s request’s mode is not "navigate" or response’s redirect taint is "same-origin":- if (fetch_params.request()->mode() != Infrastructure::Request::Mode::Navigate || response->redirect_taint() == Infrastructure::RedirectTaint::SameOrigin) {+ if (fetch_params->request()->mode() != Infrastructure::Request::Mode::Navigate || response->redirect_taint() == Infrastructure::RedirectTaint::SameOrigin) {// 1. Set responseStatus to response’s status.response_status = response->status();@@ -1082,15 +1081,15 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const// 8. If fetchParams’s request’s initiator type is not null, then mark resource timing given timingInfo,// request’s URL, request’s initiator type, global, cacheState, bodyInfo, and responseStatus.- if (fetch_params.request()->initiator_type().has_value()) {- auto initiator_type = Infrastructure::initiator_type_to_string(fetch_params.request()->initiator_type().value());- ResourceTiming::PerformanceResourceTiming::mark_resource_timing(timing_info, utf16_string_from_url_ascii(fetch_params.request()->url().serialize()), initiator_type, global, cache_state, body_info, response_status);+ if (fetch_params->request()->initiator_type().has_value()) {+ auto initiator_type = Infrastructure::initiator_type_to_string(fetch_params->request()->initiator_type().value());+ ResourceTiming::PerformanceResourceTiming::mark_resource_timing(timing_info, utf16_string_from_url_ascii(fetch_params->request()->url().serialize()), initiator_type, global, cache_state, body_info, response_status);}});};// NB: Share step 3 of processResponseEndOfBodyTask with the network-completion timing path.- auto report_timing_if_appropriate = [&fetch_params] {+ auto report_timing_if_appropriate = [fetch_params = NonnullRefPtr { fetch_params }, controller] {// 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s global// object is fetchParams’s task destination, then run fetchParams’s controller’s report timing steps// given fetchParams’s request’s client’s global object.@@ -1098,34 +1097,34 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const// entry for a preloaded resource and its consumer.// AD-HOC: The global object of a client another process hosts is in that process, so the fetch reports its// timing to the global object of the realm that started it.- auto const* task_destination_global_object = fetch_params.controller()->task_destination().get_pointer<GC::Ref<JS::Object>>();- if (task_destination_global_object != nullptr && fetch_params.request()->initiator_type().has_value() && !fetch_params.preload_reports_timing()) {- auto client = resolve_fetch_client(fetch_params.request());+ auto const* task_destination_global_object = controller->task_destination().get_pointer<GC::Ref<JS::Object>>();+ if (task_destination_global_object != nullptr && fetch_params->request()->initiator_type().has_value() && !fetch_params->preload_reports_timing()) {+ auto client = resolve_fetch_client(fetch_params->request());auto client_global_is_task_destination = client.has_value()&& client->visit([&](GC::Ref<HTML::EnvironmentSettingsObject> const& settings_object) { return &settings_object->global_object() == task_destination_global_object->ptr(); },[](NonnullRefPtr<HTML::RemoteEnvironmentSettings const> const&) { return true; });if (client_global_is_task_destination)- fetch_params.controller()->report_timing(**task_destination_global_object);+ controller->report_timing(**task_destination_global_object);}};// 4. Let processResponseEndOfBody be the following steps:- auto process_response_end_of_body = [&fetch_params, response_view, setup_report_timing_steps, report_timing_if_appropriate] {+ auto process_response_end_of_body = [fetch_params = NonnullRefPtr { fetch_params }, controller, response_view, setup_report_timing_steps, report_timing_if_appropriate] {// 1-2. (See setup_report_timing_steps above)setup_report_timing_steps();if (WebDriver::BiDi::g_network_events_enabled && !response_view->is_network_error())WebDriver::BiDi::network_response_completed(fetch_params, *response_view->record()->unsafe_response());// 3. Let processResponseEndOfBodyTask be the following steps:- auto process_response_end_of_body_task = GC::create_function(GC::Heap::the(), [&fetch_params, response_view, report_timing_if_appropriate] {+ auto process_response_end_of_body_task = GC::create_function(GC::Heap::the(), [fetch_params, controller, response_view, report_timing_if_appropriate] {// 1. Set fetchParams’s request’s done flag.- fetch_params.request()->set_done(true);- end_rendering_pending_operation(fetch_params.controller().ptr());+ fetch_params->request()->set_done(true);+ end_rendering_pending_operation(controller.ptr());// 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process response// end-of-body given response.- auto algorithms = fetch_params.controller()->algorithms();+ auto algorithms = controller->algorithms();if (algorithms->process_response_end_of_body())(algorithms->process_response_end_of_body())(response_view);@@ -1133,14 +1132,14 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const});// 4. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination.- Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.controller()->task_destination(), move(process_response_end_of_body_task));+ Infrastructure::queue_fetch_task(controller, controller->task_destination(), move(process_response_end_of_body_task));};// 5. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s process response// given response, with fetchParams’s task destination.- if (fetch_params.controller()->algorithms()->process_response()) {- Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.controller()->task_destination(), GC::create_function(GC::Heap::the(), [&fetch_params, response_view]() {- fetch_params.controller()->algorithms()->process_response()(response_view);+ if (controller->algorithms()->process_response()) {+ Infrastructure::queue_fetch_task(controller, controller->task_destination(), GC::create_function(GC::Heap::the(), [controller, response_view]() {+ controller->algorithms()->process_response()(response_view);}));}@@ -1150,11 +1149,11 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const// AD-HOC: Report a body's timing once the network has delivered it. Fetch reports it from the flush of the// transform the body is piped through, which backpressure on an unread body can hold back.if (internal_body.has_value() && (fetch_params.request()->initiator_type().has_value() || (WebDriver::BiDi::g_network_events_enabled && !fetch_params.request()->is_navigation_request()))) {- auto network_completion_steps = GC::create_function(GC::Heap::the(), [&fetch_params, response_view, setup_report_timing_steps, report_timing_if_appropriate] {+ auto network_completion_steps = GC::create_function(GC::Heap::the(), [fetch_params = NonnullRefPtr { fetch_params }, response_view, setup_report_timing_steps, report_timing_if_appropriate] {setup_report_timing_steps();report_timing_if_appropriate();if (WebDriver::BiDi::g_network_events_enabled)- WebDriver::BiDi::network_response_completed(fetch_params, *response_view->record()->unsafe_response());+ WebDriver::BiDi::network_response_completed(*fetch_params, *response_view->record()->unsafe_response());});internal_body->bytes().visit([&](Core::ImmutableBytes const&) { network_completion_steps->function()(); },@@ -1162,15 +1161,15 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams constif (channel->peek_up_to(0).state.has<Engine::FetchByteChannel::Closed>())network_completion_steps->function()();else- fetch_params.controller()->when_network_completes_body(*channel, network_completion_steps);+ controller->when_network_completes_body(*channel, network_completion_steps);},[](Infrastructure::ResponseBody::ReadThroughStream) { });}if (Core::StatsLog::the() && body_view)- track_rendering_pending_stream(fetch_params.controller().ptr(), *body_view->stream());+ track_rendering_pending_stream(controller.ptr(), *body_view->stream());- auto algorithms = fetch_params.controller()->algorithms();+ auto algorithms = controller->algorithms();// NB: Nobody reads the body of a fetch stopped before its handover.auto body_intent = fetch_params.control_block().state() == Infrastructure::FetchControlBlock::State::Stopped@@ -1270,7 +1269,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams constprocess_response_end_of_body();});auto discard_error = GC::create_function(GC::Heap::the(), [](JS::Value) { });- body_view->incrementally_read(realm, discard_chunk, end_of_body, discard_error, fetch_params.controller()->task_destination());+ body_view->incrementally_read(realm, discard_chunk, end_of_body, discard_error, controller->task_destination());break;}case Engine::BodyIntent::SyncAccumulate:@@ -1319,7 +1318,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams constif (read_body_in_parallel) {(algorithms->process_response_consume_body())(response_view, Empty {});} else {- Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.controller()->task_destination(), GC::create_function(GC::Heap::the(), [algorithms, response_view]() {+ Infrastructure::queue_fetch_task(controller, controller->task_destination(), GC::create_function(GC::Heap::the(), [algorithms, response_view]() {// NB: We have to provide fully_read a callback which accepts a ByteBuffer. Since that's not// nullable, we just invoke process_response_consume_body with a null value manually here.(algorithms->process_response_consume_body())(response_view, Empty {});@@ -1359,7 +1358,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const}}} else {- body_view->fully_read(realm, process_body, process_body_error, fetch_params.controller()->task_destination());+ body_view->fully_read(realm, process_body, process_body_error, controller->task_destination());}}}@@ -1744,7 +1743,7 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParam// fetch is to ensure the fetched resource is familiar with the CORS protocol. The cache is there to// minimize the number of CORS-preflight fetches.- auto fetch_main_content = GC::create_function(GC::Heap::the(), [request, realm = GC::Ref { realm }, fetch_params = GC::Ref { fetch_params }]() -> GC::Ref<PendingResponse> {+ auto fetch_main_content = GC::create_function(GC::Heap::the(), [request, realm = GC::Ref { realm }, fetch_params = NonnullRefPtr { fetch_params }]() -> GC::Ref<PendingResponse> {// 2. If request’s redirect mode is "follow", then set request’s service-workers mode to "none".// NOTE: Redirects coming from the network (as opposed to from a service worker) are not to be exposed to a// service worker.@@ -1779,7 +1778,7 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParampending_actual_response = PendingResponse::create(fetch_params, Infrastructure::Response::create());}- pending_actual_response->when_loaded([&realm, &fetch_params, request, response, internal_response, returned_pending_response, response_was_null = !response](NonnullRefPtr<Infrastructure::Response> resolved_actual_response) mutable {+ pending_actual_response->when_loaded([&realm, fetch_params = NonnullRefPtr { fetch_params }, controller = fetch_params.controller(), request, response, internal_response, returned_pending_response, response_was_null = !response](NonnullRefPtr<Infrastructure::Response> resolved_actual_response) mutable {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_actual_response load callback");if (response_was_null) {response = internal_response = resolved_actual_response;@@ -1789,7 +1788,7 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParam// a service worker for that matter, it is applied here.if (request->response_tainting() == Infrastructure::Request::ResponseTainting::CORS&& !cors_check(request, *response)) {- stop_discarded_response_body(*fetch_params.controller(), *response);+ stop_discarded_response_body(*controller, *response);returned_pending_response->resolve(Infrastructure::Response::network_error("Request with 'cors' response tainting failed CORS check"_string));return;}@@ -1810,7 +1809,7 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParamauto const& client_embedder_policy = request->policy_container().get<NonnullRefPtr<HTML::PolicyContainer const>>()->embedder_policy;if ((request->response_tainting() == Infrastructure::Request::ResponseTainting::Opaque || response->type() == Infrastructure::Response::Type::Opaque)&& cross_origin_resource_policy_check(request->origin().get<URL::Origin>(), client_embedder_policy, *internal_response) == Infrastructure::RequestOrResponseBlocking::Blocked) {- stop_discarded_response_body(*fetch_params.controller(), *internal_response);+ stop_discarded_response_body(*controller, *internal_response);returned_pending_response->resolve(Infrastructure::Response::network_error("Response was blocked by cross-origin resource policy check"_string));return;}@@ -1842,8 +1841,8 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParam// 1. If request’s mode is "navigate", then set fetchParams’s controller’s next manual redirect steps// to run HTTP-redirect fetch given fetchParams and response.if (request->mode() == Infrastructure::Request::Mode::Navigate) {- fetch_params.controller()->set_next_manual_redirect_steps([&realm, &fetch_params, response] {- (void)http_redirect_fetch(realm, fetch_params, *response);+ controller->set_next_manual_redirect_steps([&realm, fetch_params, response] {+ (void)http_redirect_fetch(realm, *fetch_params, *response);});}// 2. Otherwise, set response to an opaque-redirect filtered response whose internal response is@@ -1855,7 +1854,7 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParam// -> "follow"case Infrastructure::Request::RedirectMode::Follow:// 1. Set response to the result of running HTTP-redirect fetch given fetchParams and response.- inner_pending_response = http_redirect_fetch(realm, fetch_params, *response);+ inner_pending_response = http_redirect_fetch(realm, *fetch_params, *response);break;default:VERIFY_NOT_REACHED();@@ -2100,15 +2099,15 @@ static void process_http_network_or_cache_response(JS::Object& global_object, Inif (WebDriver::BiDi::g_network_events_enabled && authentication_handled == AuthenticationHandled::No) {auto intercepts = WebDriver::BiDi::get_network_intercepts(fetch_params, "authRequired"sv);if (!intercepts.is_empty()) {- WebDriver::BiDi::block_network_request(fetch_params, response, "authRequired"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), [&realm, &fetch_params, http_request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials](WebDriver::BiDi::NetworkContinuationAction action, RefPtr<Infrastructure::Response> continued_response) {+ WebDriver::BiDi::block_network_request(fetch_params, response, "authRequired"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), [&realm, fetch_params = NonnullRefPtr { fetch_params }, http_request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials](WebDriver::BiDi::NetworkContinuationAction action, RefPtr<Infrastructure::Response> continued_response) {if (action == WebDriver::BiDi::NetworkContinuationAction::ProvideCredentials) {- stop_discarded_response_body(*fetch_params.controller(), *continued_response);- auto pending_response = http_network_or_cache_fetch(realm, fetch_params, IsAuthenticationFetch::Yes);+ stop_discarded_response_body(*fetch_params->controller(), *continued_response);+ auto pending_response = http_network_or_cache_fetch(realm, *fetch_params, IsAuthenticationFetch::Yes);pending_response->when_loaded([returned_pending_response](auto response) { returned_pending_response->resolve(response); });} else if (first_is_one_of(action, WebDriver::BiDi::NetworkContinuationAction::CancelAuthentication, WebDriver::BiDi::NetworkContinuationAction::Fail, WebDriver::BiDi::NetworkContinuationAction::ProvideResponse)) {returned_pending_response->resolve(*continued_response);} else {- process_http_network_or_cache_response(realm.global_object(), fetch_params, http_request, *continued_response, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials, action == WebDriver::BiDi::NetworkContinuationAction::RetryAuthentication ? AuthenticationHandled::No : AuthenticationHandled::Yes);+ process_http_network_or_cache_response(realm.global_object(), *fetch_params, http_request, *continued_response, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials, action == WebDriver::BiDi::NetworkContinuationAction::RetryAuthentication ? AuthenticationHandled::No : AuthenticationHandled::Yes);}}));return;@@ -2131,7 +2130,7 @@ static void process_http_network_or_cache_response(JS::Object& global_object, Ininner_pending_response = http_network_or_cache_fetch(realm, fetch_params, IsAuthenticationFetch::Yes);}- inner_pending_response->when_loaded([&realm, &fetch_params, request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch](NonnullRefPtr<Infrastructure::Response> response) {+ inner_pending_response->when_loaded([&realm, fetch_params = NonnullRefPtr { fetch_params }, request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch](NonnullRefPtr<Infrastructure::Response> response) {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP network-or-cache fetch' inner_pending_response load callback");// 15. If response’s status is 407, then:if (response->status() == 407) {@@ -2146,8 +2145,8 @@ static void process_http_network_or_cache_response(JS::Object& global_object, In// (Red box in the spec, no-op)// 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.- if (fetch_params.is_canceled()) {- returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(fetch_params));+ if (fetch_params->is_canceled()) {+ returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(*fetch_params));return;}@@ -2159,7 +2158,7 @@ static void process_http_network_or_cache_response(JS::Object& global_object, In// (Doing this without step 4 would potentially lead to an infinite request cycle.)}- auto inner_pending_response = PendingResponse::create(fetch_params, *response);+ auto inner_pending_response = PendingResponse::create(*fetch_params, *response);// 16. If all of the following are trueif (@@ -2172,13 +2171,13 @@ static void process_http_network_or_cache_response(JS::Object& global_object, In// then:) {// 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.- if (fetch_params.is_canceled()) {- returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(fetch_params));+ if (fetch_params->is_canceled()) {+ returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(*fetch_params));return;}// 2. Set response to the result of running HTTP-network-or-cache fetch given fetchParams,// isAuthenticationFetch, and true.- inner_pending_response = http_network_or_cache_fetch(realm, fetch_params, is_authentication_fetch, IsNewConnectionFetch::Yes);+ inner_pending_response = http_network_or_cache_fetch(realm, *fetch_params, is_authentication_fetch, IsNewConnectionFetch::Yes);}inner_pending_response->when_loaded([returned_pending_response, is_authentication_fetch](NonnullRefPtr<Infrastructure::Response> response) {@@ -2194,7 +2193,7 @@ static void process_http_network_or_cache_response(JS::Object& global_object, In}// https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch-static GC::Ref<PendingResponse> continue_http_network_or_cache_fetch(JS::Object& global_object, Infrastructure::FetchParams const& fetch_params, GC::Ref<Infrastructure::FetchParams const> http_fetch_params, RefPtr<Infrastructure::Response> response, RefPtr<Infrastructure::Response> stored_response, RefPtr<HTTP::MemoryCache> http_cache, IsAuthenticationFetch is_authentication_fetch, IsNewConnectionFetch is_new_connection_fetch, HTTP::Cookie::IncludeCredentials include_credentials)+static GC::Ref<PendingResponse> continue_http_network_or_cache_fetch(JS::Object& global_object, Infrastructure::FetchParams const& fetch_params, NonnullRefPtr<Infrastructure::FetchParams const> http_fetch_params, RefPtr<Infrastructure::Response> response, RefPtr<Infrastructure::Response> stored_response, RefPtr<HTTP::MemoryCache> http_cache, IsAuthenticationFetch is_authentication_fetch, IsNewConnectionFetch is_new_connection_fetch, HTTP::Cookie::IncludeCredentials include_credentials){auto& realm = HTML::relevant_realm(global_object);auto request = fetch_params.request();@@ -2221,7 +2220,7 @@ static GC::Ref<PendingResponse> continue_http_network_or_cache_fetch(JS::Object&auto returned_pending_response = PendingResponse::create(fetch_params);- pending_forward_response->when_loaded([&realm, &fetch_params, response, stored_response, http_request, http_fetch_params, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials, response_was_null = !response, http_cache](NonnullRefPtr<Infrastructure::Response> resolved_forward_response) mutable {+ pending_forward_response->when_loaded([&realm, fetch_params = NonnullRefPtr { fetch_params }, response, stored_response, http_request, http_fetch_params, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials, response_was_null = !response, http_cache](NonnullRefPtr<Infrastructure::Response> resolved_forward_response) mutable {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-network-or-cache fetch' pending_forward_response load callback");if (response_was_null) {auto forward_response = resolved_forward_response;@@ -2265,17 +2264,17 @@ static GC::Ref<PendingResponse> continue_http_network_or_cache_fetch(JS::Object&if (WebDriver::BiDi::g_network_events_enabled) {// NB: Instrumentation may have been enabled after httpRequest was cloned. The controller's original// request must share the identity reported by the prepared request, including on cancellation.- WebDriver::BiDi::synchronize_network_request(*fetch_params.request(), *http_request);+ WebDriver::BiDi::synchronize_network_request(*fetch_params->request(), *http_request);auto intercepts = WebDriver::BiDi::get_network_intercepts(*http_fetch_params, "responseStarted"sv);if (!response->is_network_error() && !intercepts.is_empty()) {- WebDriver::BiDi::block_network_request(*http_fetch_params, response, "responseStarted"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), [&realm, &fetch_params, http_request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials](WebDriver::BiDi::NetworkContinuationAction, RefPtr<Infrastructure::Response> continued_response) {- process_http_network_or_cache_response(realm.global_object(), fetch_params, *http_request, *continued_response, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials);+ WebDriver::BiDi::block_network_request(*http_fetch_params, response, "responseStarted"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), [&realm, fetch_params, http_request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials](WebDriver::BiDi::NetworkContinuationAction, RefPtr<Infrastructure::Response> continued_response) {+ process_http_network_or_cache_response(realm.global_object(), *fetch_params, *http_request, *continued_response, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials);}));return;}WebDriver::BiDi::network_response_started(*http_fetch_params, *response);}- process_http_network_or_cache_response(realm.global_object(), fetch_params, *http_request, *response, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials);+ process_http_network_or_cache_response(realm.global_object(), *fetch_params, *http_request, *response, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials);});// 18. Return response.@@ -2299,7 +2298,7 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, InfrastruWebDriver::BiDi::apply_network_cache_behavior(*request);// 2. Let httpFetchParams be null.- GC::Ptr<Infrastructure::FetchParams const> http_fetch_params;+ RefPtr<Infrastructure::FetchParams const> http_fetch_params;// 3. Let httpRequest be null.RefPtr<Infrastructure::Request> http_request;@@ -2598,13 +2597,13 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastruauto intercepts = WebDriver::BiDi::get_network_intercepts(*http_fetch_params, "beforeRequestSent"sv);if (!intercepts.is_empty()) {auto returned_pending_response = PendingResponse::create(fetch_params);- WebDriver::BiDi::block_network_request(*http_fetch_params, nullptr, "beforeRequestSent"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), [&realm, &fetch_params, http_fetch_params, response, stored_response, http_cache, is_authentication_fetch, is_new_connection_fetch, include_credentials, returned_pending_response](WebDriver::BiDi::NetworkContinuationAction action, RefPtr<Infrastructure::Response> continued_response) {+ WebDriver::BiDi::block_network_request(*http_fetch_params, nullptr, "beforeRequestSent"_string, move(intercepts), WebDriver::BiDi::NetworkContinuation::create(realm.heap(), [&realm, fetch_params = NonnullRefPtr { fetch_params }, http_fetch_params, response, stored_response, http_cache, is_authentication_fetch, is_new_connection_fetch, include_credentials, returned_pending_response](WebDriver::BiDi::NetworkContinuationAction action, RefPtr<Infrastructure::Response> continued_response) {// AD-HOC: The fetch can be canceled while its request is blocked.- if (fetch_params.is_canceled()) {- returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(fetch_params));+ if (fetch_params->is_canceled()) {+ returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(*fetch_params));return;}- auto pending_response = continue_http_network_or_cache_fetch(realm.global_object(), fetch_params, *http_fetch_params, action == WebDriver::BiDi::NetworkContinuationAction::Continue ? response : continued_response, stored_response, http_cache, is_authentication_fetch, is_new_connection_fetch, include_credentials);+ auto pending_response = continue_http_network_or_cache_fetch(realm.global_object(), *fetch_params, *http_fetch_params, action == WebDriver::BiDi::NetworkContinuationAction::Continue ? response : continued_response, stored_response, http_cache, is_authentication_fetch, is_new_connection_fetch, include_credentials);pending_response->when_loaded([returned_pending_response](auto response) { returned_pending_response->resolve(response); });}),request);@@ -2662,7 +2661,7 @@ struct NetworkBody {// https://fetch.spec.whatwg.org/#concept-http-network-fetch// NB: Step 9 of HTTP-network fetch. Steps 10 to 13 run in create_body_from_channel(), where the body is first read.-static NetworkBody create_network_body(GC::Ptr<Infrastructure::FetchParams const> fetch_params, Engine::FetchBodyDeliveryGate::NavigationHold navigation_hold, RefPtr<HTTP::MemoryCache> http_cache)+static NetworkBody create_network_body(RefPtr<Infrastructure::FetchParams const> fetch_params, Engine::FetchBodyDeliveryGate::NavigationHold navigation_hold, RefPtr<HTTP::MemoryCache> http_cache){// 9. Let buffer be an empty byte sequence.// NB: The buffer is the FetchByteChannel; its watermarks are the user-agent-chosen lower and upper limits.@@ -2671,7 +2670,7 @@ static NetworkBody create_network_body(GC::Ptr<Infrastructure::FetchParams constauto channel = Engine::FetchByteChannel::create(network_body_watermarks, delivery_gate->create_channel_sink());delivery_gate->grant_credit(channel->initial_credit());- auto body_pump = GC::Heap::the().allocate<NetworkBodyPump>(fetch_params, channel, delivery_gate, move(http_cache));+ auto body_pump = GC::Heap::the().allocate<NetworkBodyPump>(move(fetch_params), channel, delivery_gate, move(http_cache));return { move(channel), move(delivery_gate), body_pump };}@@ -2844,7 +2843,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(// A load without a RequestServer request, such as one for a file: URL, hands over its whole body at once.auto whole_body_transport = create_whole_body_transport(*delivery_gate, *channel);- auto on_headers_received = GC::create_function(GC::Heap::the(), [&fetch_params, pending_response, request, body_pump, channel, delivery_gate, whole_body_transport, http_cache](Engine::NetworkTransportHandle* network_transport, HTTP::HeaderList const& response_headers, Optional<u32> status_code, Optional<String> const& reason_phrase, Optional<Core::ImmutableBytes> javascript_bytecode, Optional<u64> javascript_bytecode_cache_vary_key, Requests::CacheState cache_state) {+ auto on_headers_received = GC::create_function(GC::Heap::the(), [fetch_params = NonnullRefPtr { fetch_params }, pending_response, request, body_pump, channel, delivery_gate, whole_body_transport, http_cache](Engine::NetworkTransportHandle* network_transport, HTTP::HeaderList const& response_headers, Optional<u32> status_code, Optional<String> const& reason_phrase, Optional<Core::ImmutableBytes> javascript_bytecode, Optional<u64> javascript_bytecode_cache_vary_key, Requests::CacheState cache_state) {if (pending_response->is_resolved()) {// RequestServer will send us the response headers twice, the second time being for HTTP trailers. This// fetch algorithm is not interested in trailers, so just drop them here.@@ -2853,7 +2852,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(// AD-HOC: From here on, the response's body delivery is scheduled against the event loop (see// BodyStreamPullSource::on_wake()); record that, for consume_a_preloaded_resource().- fetch_params.control_block().set_response_arrived();+ fetch_params->control_block().set_response_arrived();auto response = Infrastructure::Response::create();response->set_status(status_code.value_or(200));@@ -2990,8 +2989,8 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(// fetchParams’s process request end-of-body and fetchParams’s task destination.if (request->body().has<Empty>()) {if (fetch_params.controller()->algorithms()->process_request_end_of_body()) {- Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.controller()->task_destination(), GC::create_function(GC::Heap::the(), [&fetch_params]() {- fetch_params.controller()->algorithms()->process_request_end_of_body()();+ Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.controller()->task_destination(), GC::create_function(GC::Heap::the(), [fetch_params = NonnullRefPtr { fetch_params }]() {+ fetch_params->controller()->algorithms()->process_request_end_of_body()();}));}}@@ -2999,9 +2998,9 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(else if (auto const* body = request->body().get_pointer<Infrastructure::FetchBody>()) {// 1. Let processBodyChunk given bytes be these steps:// NB: The steps read only bytes's length, so they are given it.- auto process_body_chunk = [&fetch_params](u64 length) {+ auto process_body_chunk = [fetch_params = NonnullRefPtr { fetch_params }, controller = fetch_params.controller()](u64 length) {// 1. If fetchParams is canceled, then abort these steps.- if (fetch_params.is_canceled())+ if (fetch_params->is_canceled())return;// 2. Run this step in parallel: transmit bytes.@@ -3009,35 +3008,35 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(// 3. If fetchParams’s process request body chunk length is non-null, then run fetchParams’s process// request body chunk length given bytes’s length.- if (fetch_params.controller()->algorithms()->process_request_body_chunk_length())- fetch_params.controller()->algorithms()->process_request_body_chunk_length()(length);+ if (controller->algorithms()->process_request_body_chunk_length())+ controller->algorithms()->process_request_body_chunk_length()(length);};// 2. Let processEndOfBody be these steps:- auto process_end_of_body = GC::create_function(GC::Heap::the(), [&fetch_params]() {+ auto process_end_of_body = GC::create_function(GC::Heap::the(), [fetch_params = NonnullRefPtr { fetch_params }, controller = fetch_params.controller()]() {// 1. If fetchParams is canceled, then abort these steps.- if (fetch_params.is_canceled())+ if (fetch_params->is_canceled())return;// 2. If fetchParams’s process request end-of-body is non-null, then run fetchParams’s process request// end-of-body.- if (fetch_params.controller()->algorithms()->process_request_end_of_body())- fetch_params.controller()->algorithms()->process_request_end_of_body()();+ if (controller->algorithms()->process_request_end_of_body())+ controller->algorithms()->process_request_end_of_body()();});// 3. Let processBodyError given e be these steps:- auto process_body_error = GC::create_function(GC::Heap::the(), [&realm, &fetch_params](JS::Value error) {+ auto process_body_error = GC::create_function(GC::Heap::the(), [&realm, fetch_params = NonnullRefPtr { fetch_params }, controller = fetch_params.controller()](JS::Value error) {// 1. If fetchParams is canceled, then abort these steps.- if (fetch_params.is_canceled())+ if (fetch_params->is_canceled())return;// 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.auto const* exception = error.is_object() ? Bindings::dom_exception_from_object(error.as_object()) : nullptr;if (exception && exception->name() == "AbortError"_utf16_fly_string)- fetch_params.controller()->abort(realm, {});+ controller->abort(realm, {});// 3. Otherwise, terminate fetchParams’s controller.else- fetch_params.controller()->terminate();+ controller->terminate();});// 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, processBodyError, and@@ -3114,15 +3113,16 @@ GC::Ref<PendingResponse> cors_preflight_fetch(JS::Realm& realm, Infrastructure::// FIXME: The spec doesn't say anything about timing_info here, but FetchParams requires a non-null FetchTimingInfo object.auto timing_info = Infrastructure::FetchTimingInfo::create();auto& controller_registry = HTML::relevant_agent(realm.global_object()).fetch_controller_registry;- auto preflight_controller = Infrastructure::FetchController::create(controller_registry);+ // NB: The preflight's controller stays alive until the preflight's pending response holds it.+ auto preflight_controller = GC::make_root(Infrastructure::FetchController::create(controller_registry));auto preflight_algorithms = Infrastructure::FetchAlgorithms::create(Infrastructure::FetchAlgorithms::Input { Engine::BodyIntent::DrainAndDiscard });- auto preflight_fetch_params = Infrastructure::FetchParams::create(preflight_controller, preflight, preflight_algorithms, timing_info, fetch_params.loader_config_snapshot());+ auto preflight_fetch_params = Infrastructure::FetchParams::create(*preflight_controller, preflight, preflight_algorithms, timing_info, fetch_params.loader_config_snapshot());auto returned_pending_response = PendingResponse::create(fetch_params);auto preflight_response = http_network_or_cache_fetch(realm, preflight_fetch_params);- preflight_response->when_loaded([request = fetch_params.request(), returned_pending_response, preflight_controller, preflight_fetch_params](NonnullRefPtr<Infrastructure::Response> response) {+ preflight_response->when_loaded([request = fetch_params.request(), returned_pending_response, preflight_controller = GC::Ref { *preflight_controller }, preflight_fetch_params](NonnullRefPtr<Infrastructure::Response> response) {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'CORS-preflight fetch' preflight_response load callback");if (WebDriver::BiDi::g_network_events_enabled) {diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.h b/Libraries/LibWeb/Fetch/Fetching/Fetching.hindex 67c352bcda2..0fec644b340 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.h+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.h@@ -50,7 +50,7 @@ ENUMERATE_BOOL_PARAMSWEB_API GC::Ref<Infrastructure::FetchController> fetch(JS::Realm&, Infrastructure::Request&, Infrastructure::FetchAlgorithms const&, UseParallelQueue use_parallel_queue = UseParallelQueue::No, CreateResponseBodyTransferLease = CreateResponseBodyTransferLease::No);GC::Ptr<PendingResponse> main_fetch(JS::Realm&, Infrastructure::FetchParams const&, Recursive recursive = Recursive::No);void populate_request_from_client(Infrastructure::Request&, Optional<HTML::FetchClient> const& client);-void fetch_response_handover(JS::Realm&, Infrastructure::FetchParams const&, Infrastructure::Response&);+void fetch_response_handover(JS::Realm&, Infrastructure::FetchParams const&, GC::Ref<Infrastructure::FetchController>, Infrastructure::Response&);GC::Ref<PendingResponse> scheme_fetch(JS::Realm&, Infrastructure::FetchParams const&);GC::Ref<PendingResponse> http_fetch(JS::Realm&, Infrastructure::FetchParams const&, MakeCORSPreflight make_cors_preflight = MakeCORSPreflight::No);WEB_API GC::Ptr<PendingResponse> http_redirect_fetch(JS::Realm&, Infrastructure::FetchParams const&, Infrastructure::Response&);diff --git a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cppindex 36c56c96d09..b404f4f2bae 100644--- a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp@@ -18,8 +18,9 @@ namespace Web::Fetch::Fetching {GC_DEFINE_ALLOCATOR(NetworkBodyPump);-NetworkBodyPump::NetworkBodyPump(GC::Ptr<Infrastructure::FetchParams const> fetch_params, NonnullRefPtr<Engine::FetchByteChannel> channel, NonnullRefPtr<Engine::FetchBodyDeliveryGate> delivery_gate, RefPtr<HTTP::MemoryCache> http_cache)- : m_fetch_params(fetch_params)+NetworkBodyPump::NetworkBodyPump(RefPtr<Infrastructure::FetchParams const> fetch_params, NonnullRefPtr<Engine::FetchByteChannel> channel, NonnullRefPtr<Engine::FetchBodyDeliveryGate> delivery_gate, RefPtr<HTTP::MemoryCache> http_cache)+ : m_fetch_params(move(fetch_params))+ , m_fetch_controller(m_fetch_params ? m_fetch_params->controller().ptr() : nullptr), m_channel(move(channel)), m_delivery_gate(move(delivery_gate)), m_http_cache(move(http_cache))@@ -46,7 +47,7 @@ void NetworkBodyPump::update_response_body_info()void NetworkBodyPump::visit_edges(Visitor& visitor){Base::visit_edges(visitor);- visitor.visit(m_fetch_params);+ visitor.visit(m_fetch_controller);}// This implements the transmission steps of HTTP-network fetch.@@ -118,8 +119,8 @@ void NetworkBodyPump::handle_network_complete(Optional<u64> encoded_body_size)update_response_body_info();finalize_cache_entry();m_channel->close();- if (m_fetch_params)- m_fetch_params->controller()->did_complete_network_body(*m_channel);+ if (m_fetch_controller)+ m_fetch_controller->did_complete_network_body(*m_channel);}void NetworkBodyPump::handle_network_error(StringView error_message)diff --git a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.hindex 6fadb86dc5d..1e6c4b165bc 100644--- a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h+++ b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h@@ -41,14 +41,16 @@ public:void abandon_cache_entry();private:- NetworkBodyPump(GC::Ptr<Infrastructure::FetchParams const>, NonnullRefPtr<Engine::FetchByteChannel>, NonnullRefPtr<Engine::FetchBodyDeliveryGate>, RefPtr<HTTP::MemoryCache>);+ NetworkBodyPump(RefPtr<Infrastructure::FetchParams const>, NonnullRefPtr<Engine::FetchByteChannel>, NonnullRefPtr<Engine::FetchBodyDeliveryGate>, RefPtr<HTTP::MemoryCache>);virtual void visit_edges(Visitor& visitor) override;void finalize_cache_entry();void update_response_body_info();- GC::Ptr<Infrastructure::FetchParams const> m_fetch_params;+ RefPtr<Infrastructure::FetchParams const> m_fetch_params;+ // The controller of m_fetch_params, which the pump keeps alive with them.+ GC::Ptr<Infrastructure::FetchController> m_fetch_controller;RefPtr<Fetch::Infrastructure::Response> m_response;NonnullRefPtr<Engine::FetchByteChannel> m_channel;diff --git a/Libraries/LibWeb/Fetch/Fetching/PendingResponse.cpp b/Libraries/LibWeb/Fetch/Fetching/PendingResponse.cppindex 896c75bc7a5..4ec7eed5c0b 100644--- a/Libraries/LibWeb/Fetch/Fetching/PendingResponse.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/PendingResponse.cpp@@ -15,14 +15,24 @@ namespace Web::Fetch::Fetching {GC_DEFINE_ALLOCATOR(PendingResponse);+GC::Ref<PendingResponse> PendingResponse::create(GC::Ref<Infrastructure::FetchController> fetch_controller)+{+ return GC::Heap::the().allocate<PendingResponse>(fetch_controller);+}++GC::Ref<PendingResponse> PendingResponse::create(GC::Ref<Infrastructure::FetchController> fetch_controller, NonnullRefPtr<Infrastructure::Response> response)+{+ return GC::Heap::the().allocate<PendingResponse>(fetch_controller, move(response));+}+GC::Ref<PendingResponse> PendingResponse::create(Infrastructure::FetchParams const& fetch_params){- return GC::Heap::the().allocate<PendingResponse>(fetch_params.controller());+ return create(fetch_params.controller());}GC::Ref<PendingResponse> PendingResponse::create(Infrastructure::FetchParams const& fetch_params, NonnullRefPtr<Infrastructure::Response> response){- return GC::Heap::the().allocate<PendingResponse>(fetch_params.controller(), move(response));+ return create(fetch_params.controller(), move(response));}PendingResponse::PendingResponse(GC::Ref<Infrastructure::FetchController> fetch_controller, RefPtr<Infrastructure::Response> response)diff --git a/Libraries/LibWeb/Fetch/Fetching/PendingResponse.h b/Libraries/LibWeb/Fetch/Fetching/PendingResponse.hindex 3d33b4463ce..9b0dd80aa58 100644--- a/Libraries/LibWeb/Fetch/Fetching/PendingResponse.h+++ b/Libraries/LibWeb/Fetch/Fetching/PendingResponse.h@@ -24,6 +24,8 @@ class PendingResponse : public JS::Cell {public:using Callback = Function<void(NonnullRefPtr<Infrastructure::Response>)>;+ [[nodiscard]] static GC::Ref<PendingResponse> create(GC::Ref<Infrastructure::FetchController>);+ [[nodiscard]] static GC::Ref<PendingResponse> create(GC::Ref<Infrastructure::FetchController>, NonnullRefPtr<Infrastructure::Response>);[[nodiscard]] static GC::Ref<PendingResponse> create(Infrastructure::FetchParams const&);[[nodiscard]] static GC::Ref<PendingResponse> create(Infrastructure::FetchParams const&, NonnullRefPtr<Infrastructure::Response>);diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cppindex 1915bb3aebe..96478bdebf2 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp@@ -79,7 +79,7 @@ void FetchController::report_webdriver_bidi_fetch_error(StringView error_text) c{if (!WebDriver::BiDi::g_network_events_enabled)return;- if (auto fetch_params = m_original_fetch_params.ptr())+ if (auto fetch_params = m_original_fetch_params.strong_ref())WebDriver::BiDi::network_fetch_error(*fetch_params, error_text);}@@ -91,9 +91,9 @@ void FetchController::cancel_webdriver_bidi_network_interception() constWebDriver::BiDi::cancel_network_interception(*fetch_params);}-GC::Ptr<FetchParams> FetchController::original_fetch_params() const+RefPtr<FetchParams> FetchController::original_fetch_params() const{- return m_original_fetch_params.ptr();+ return m_original_fetch_params.strong_ref();}GC::Ref<FetchAlgorithms const> FetchController::algorithms() constdiff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.hindex 20ab4583517..2fcfc385bae 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h@@ -11,7 +11,6 @@#include <AK/WeakPtr.h>#include <LibGC/Function.h>#include <LibGC/Ptr.h>-#include <LibGC/Weak.h>#include <LibJS/Forward.h>#include <LibJS/Heap/Cell.h>#include <LibJS/Runtime/VM.h>@@ -45,6 +44,7 @@ public:[[nodiscard]] static GC::Ref<FetchController> create(FetchControllerRegistry&);[[nodiscard]] FetchControllerToken token() const { return m_token; }+ [[nodiscard]] WeakPtr<FetchControllerRegistry> const& registry() const { return m_registry; }[[nodiscard]] FetchControlBlock& control_block() const { return *m_control_block; }void set_report_timing_steps(Function<void(JS::Object&)> report_timing_steps);@@ -70,7 +70,7 @@ public:// The fetch params created with the controller, for which WebDriver BiDi reports errors and intercepts requests.void set_original_fetch_params(Badge<FetchParams>, FetchParams const&);- [[nodiscard]] GC::Ptr<FetchParams> original_fetch_params() const;+ [[nodiscard]] RefPtr<FetchParams> original_fetch_params() const;[[nodiscard]] TaskDestination const& task_destination() const { return m_task_destination; }void set_task_destination(TaskDestination task_destination) { m_task_destination = move(task_destination); }@@ -116,7 +116,7 @@ private:WeakPtr<FetchControllerRegistry> m_registry;FetchControllerToken m_token;NonnullRefPtr<FetchControlBlock> m_control_block;- GC::Weak<FetchParams> m_original_fetch_params;+ WeakPtr<FetchParams> m_original_fetch_params;// https://fetch.spec.whatwg.org/#fetch-controller-report-timing-steps// report timing steps (default null)diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cppindex 2c51222f9d4..716e6d020f9 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp@@ -4,30 +4,29 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>-#include <LibJS/Runtime/VM.h>#include <LibWeb/Fetch/Infrastructure/FetchParams.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>namespace Web::Fetch::Infrastructure {-GC_DEFINE_ALLOCATOR(FetchParams);--FetchParams::FetchParams(NonnullRefPtr<Request> request, GC::Ref<FetchAlgorithms const> algorithms, GC::Ref<FetchController> controller, NonnullRefPtr<FetchTimingInfo> timing_info, NonnullRefPtr<LoaderConfigSnapshot const> loader_config)+FetchParams::FetchParams(NonnullRefPtr<Request> request, GC::Ref<FetchAlgorithms const> algorithms, FetchController& controller, NonnullRefPtr<FetchTimingInfo> timing_info, NonnullRefPtr<LoaderConfigSnapshot const> loader_config): m_request(move(request))- , m_controller(controller)- , m_control_block(controller->control_block())+ , m_controller_token(controller.token())+ , m_controller_registry(controller.registry())+ , m_control_block(controller.control_block()), m_timing_info(move(timing_info)), m_loader_config(move(loader_config)){- m_controller->set_algorithms({}, algorithms);- m_controller->set_original_fetch_params({}, *this);+ controller.set_algorithms({}, algorithms);+ controller.set_original_fetch_params({}, *this);}FetchParams::FetchParams(FetchParams const& params)- : m_request(params.m_request)+ : RefCounted()+ , m_request(params.m_request), m_cross_origin_isolated_capability(params.m_cross_origin_isolated_capability)- , m_controller(params.m_controller)+ , m_controller_token(params.m_controller_token)+ , m_controller_registry(params.m_controller_registry), m_control_block(params.m_control_block), m_timing_info(params.m_timing_info), m_preloaded_response_candidate(params.m_preloaded_response_candidate)@@ -37,20 +36,22 @@ FetchParams::FetchParams(FetchParams const& params){}-GC::Ref<FetchParams> FetchParams::create(FetchController& controller, NonnullRefPtr<Request> request, GC::Ref<FetchAlgorithms const> algorithms, NonnullRefPtr<FetchTimingInfo> timing_info, NonnullRefPtr<LoaderConfigSnapshot const> loader_config)+NonnullRefPtr<FetchParams> FetchParams::create(FetchController& controller, NonnullRefPtr<Request> request, GC::Ref<FetchAlgorithms const> algorithms, NonnullRefPtr<FetchTimingInfo> timing_info, NonnullRefPtr<LoaderConfigSnapshot const> loader_config){- return GC::Heap::the().allocate<FetchParams>(move(request), algorithms, controller, move(timing_info), move(loader_config));+ return adopt_ref(*new FetchParams(move(request), algorithms, controller, move(timing_info), move(loader_config)));}-GC::Ref<FetchParams> FetchParams::copy(FetchParams const& params)+NonnullRefPtr<FetchParams> FetchParams::copy(FetchParams const& params){- return GC::Heap::the().allocate<FetchParams>(params);+ return adopt_ref(*new FetchParams(params));}-void FetchParams::visit_edges(JS::Cell::Visitor& visitor)+GC::Ref<FetchController> FetchParams::controller() const{- Base::visit_edges(visitor);- visitor.visit(m_controller);+ VERIFY(m_controller_registry);+ auto controller = m_controller_registry->find(m_controller_token);+ VERIFY(controller);+ return *controller;}// https://fetch.spec.whatwg.org/#fetch-params-aborteddiff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.hindex ec97c1345f0..ccc8e849960 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h@@ -7,9 +7,10 @@#pragma once#include <AK/Forward.h>+#include <AK/RefCounted.h>+#include <AK/WeakPtr.h>+#include <AK/Weakable.h>#include <LibGC/Ptr.h>-#include <LibJS/Forward.h>-#include <LibJS/Heap/Cell.h>#include <LibWeb/Export.h>#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>#include <LibWeb/Fetch/Infrastructure/FetchController.h>@@ -22,20 +23,19 @@namespace Web::Fetch::Infrastructure {// https://fetch.spec.whatwg.org/#fetch-params-class WEB_API FetchParams : public JS::Cell {- GC_CELL(FetchParams, JS::Cell);- GC_DECLARE_ALLOCATOR(FetchParams);-+class WEB_API FetchParams+ : public RefCounted<FetchParams>+ , public Weakable<FetchParams> {public:struct PreloadedResponseCandidatePendingTag { };using PreloadedResponseCandidate = Variant<Empty, PreloadedResponseCandidatePendingTag, NonnullRefPtr<Response>>;- [[nodiscard]] static GC::Ref<FetchParams> create(FetchController&, NonnullRefPtr<Request>, GC::Ref<FetchAlgorithms const>, NonnullRefPtr<FetchTimingInfo>, NonnullRefPtr<LoaderConfigSnapshot const>);- [[nodiscard]] static GC::Ref<FetchParams> copy(FetchParams const&);+ [[nodiscard]] static NonnullRefPtr<FetchParams> create(FetchController&, NonnullRefPtr<Request>, GC::Ref<FetchAlgorithms const>, NonnullRefPtr<FetchTimingInfo>, NonnullRefPtr<LoaderConfigSnapshot const>);+ [[nodiscard]] static NonnullRefPtr<FetchParams> copy(FetchParams const&);[[nodiscard]] NonnullRefPtr<Request> request() const { return m_request; }void set_request(NonnullRefPtr<Request> request) { m_request = move(request); }- [[nodiscard]] GC::Ref<FetchController> controller() const { return m_controller; }+ [[nodiscard]] GC::Ref<FetchController> controller() const;[[nodiscard]] FetchControlBlock& control_block() const { return *m_control_block; }[[nodiscard]] NonnullRefPtr<FetchTimingInfo> timing_info() const { return m_timing_info; }[[nodiscard]] LoaderConfig const& loader_config() const { return m_loader_config->config; }@@ -61,11 +61,9 @@ public:void set_blob_url_entry(Optional<FileAPI::SerializedBlobURLEntry> blob_url_entry) { m_blob_url_entry = move(blob_url_entry); }private:- FetchParams(NonnullRefPtr<Request>, GC::Ref<FetchAlgorithms const>, GC::Ref<FetchController>, NonnullRefPtr<FetchTimingInfo>, NonnullRefPtr<LoaderConfigSnapshot const>);+ FetchParams(NonnullRefPtr<Request>, GC::Ref<FetchAlgorithms const>, FetchController&, NonnullRefPtr<FetchTimingInfo>, NonnullRefPtr<LoaderConfigSnapshot const>);FetchParams(FetchParams const&);- virtual void visit_edges(JS::Cell::Visitor&) override;-// https://fetch.spec.whatwg.org/#fetch-params-request// request// A request.@@ -79,7 +77,8 @@ private:// https://fetch.spec.whatwg.org/#fetch-params-controller// controller (default a new fetch controller)// A fetch controller.- GC::Ref<FetchController> m_controller;+ FetchControllerToken m_controller_token;+ WeakPtr<FetchControllerRegistry> m_controller_registry;NonnullRefPtr<FetchControlBlock> m_control_block;// https://fetch.spec.whatwg.org/#fetch-params-timing-infodiff --git a/Libraries/LibWeb/WebDriver/BiDi/Network.cpp b/Libraries/LibWeb/WebDriver/BiDi/Network.cppindex e5c88d3cf6e..e23c646186b 100644--- a/Libraries/LibWeb/WebDriver/BiDi/Network.cpp+++ b/Libraries/LibWeb/WebDriver/BiDi/Network.cpp@@ -49,7 +49,7 @@ void NetworkContinuation::finalize()void NetworkContinuation::visit_edges(JS::Cell::Visitor& visitor){Base::visit_edges(visitor);- visitor.visit(fetch_params);+ visitor.visit(controller);visitor.visit_possible_values(m_callback.raw_capture_range());}@@ -68,6 +68,7 @@ void NetworkContinuation::clear_blocked_state()phase = {};intercepts = {};fetch_params = nullptr;+ controller = nullptr;original_request = nullptr;response = nullptr;}@@ -93,7 +94,7 @@ static GC::Ptr<NetworkContinuation> blocked_request(FetchController const& contrif (!fetch_params)return nullptr;auto blocked = blocked_request(*fetch_params->request());- return blocked && blocked->fetch_params->controller().ptr() == &controller ? blocked : nullptr;+ return blocked && blocked->controller.ptr() == &controller ? blocked : nullptr;}static void share_blocked_request_identity(FetchParams const& fetch_params)@@ -102,10 +103,10 @@ static void share_blocked_request_identity(FetchParams const& fetch_params)fetch_params.request()->set_webdriver_bidi_network_request(blocked->fetch_params->request()->webdriver_bidi_network_request());}-static void stop_response_transport(FetchParams const& fetch_params, Response const& response)+static void stop_response_transport(FetchController& controller, Response const& response){response.release_request_transfer_lease();- fetch_params.controller()->stop_body_transport();+ controller.stop_body_transport();}static void resume_blocked_request(String id, NetworkContinuationAction action, RefPtr<Fetch::Infrastructure::Response> response)@@ -114,13 +115,13 @@ static void resume_blocked_request(String id, NetworkContinuationAction action,if (it == blocked_requests().end())return;GC::Ptr<NetworkContinuation> continuation = it->value.ptr();- auto fetch_params = continuation->fetch_params;+ auto controller = continuation->controller;auto original_response = continuation->response;// NB: Remove the entry before stopping transport or invoking a continuation, which can reenter Fetch.blocked_requests().remove(it);continuation->clear_blocked_state();if (action == NetworkContinuationAction::Fail && original_response)- stop_response_transport(*fetch_params, *original_response);+ stop_response_transport(*controller, *original_response);continuation->invoke(action, response);}@@ -535,7 +536,7 @@ void block_network_request(FetchParams const& fetch_params, RefPtr<Fetch::Infrasauto state = request->webdriver_bidi_network_request();if (fetch_params.is_canceled() || fetch_params.control_block().state() == FetchControlBlock::State::Stopped) {if (response)- stop_response_transport(fetch_params, *response);+ stop_response_transport(*fetch_params.controller(), *response);continuation->invoke(NetworkContinuationAction::Fail, Response::network_error("Intercepted fetch was stopped"_string));return;}@@ -550,6 +551,7 @@ void block_network_request(FetchParams const& fetch_params, RefPtr<Fetch::Infrascontinuation->phase = move(phase);continuation->intercepts = move(intercepts);continuation->fetch_params = fetch_params;+ continuation->controller = fetch_params.controller();continuation->original_request = original_request;continuation->response = response;if (original_request)@@ -667,7 +669,7 @@ static ErrorOr<JsonValue, Error> continue_network_request_impl(StringView method// NB: A replacement body has no RequestServer transport to transfer to a new navigation process.if (blocked->response) {blocked->response->release_request_transfer_lease();- blocked->fetch_params->controller()->stop_body_transport();+ blocked->controller->stop_body_transport();}auto replacement = Response::create();replacement->set_url_list(response->url_list());diff --git a/Libraries/LibWeb/WebDriver/BiDi/Network.h b/Libraries/LibWeb/WebDriver/BiDi/Network.hindex 185247c2cfd..c595fd73192 100644--- a/Libraries/LibWeb/WebDriver/BiDi/Network.h+++ b/Libraries/LibWeb/WebDriver/BiDi/Network.h@@ -52,7 +52,8 @@ public:String request_id;String phase;JsonArray intercepts;- GC::Ptr<Fetch::Infrastructure::FetchParams const> fetch_params;+ RefPtr<Fetch::Infrastructure::FetchParams const> fetch_params;+ GC::Ptr<Fetch::Infrastructure::FetchController> controller;RefPtr<Fetch::Infrastructure::Request> original_request;RefPtr<Fetch::Infrastructure::Response> response;diff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txtindex 5b7a1564bc8..330fe3bda3f 100644--- a/Tests/LibWeb/CMakeLists.txt+++ b/Tests/LibWeb/CMakeLists.txt@@ -30,6 +30,7 @@ set(TEST_SOURCESTestFetchBodyDeliveryGate.cppTestFetchBodyStream.cppTestFetchByteChannel.cpp+ TestFetchController.cppTestFetchControllerRegistry.cppTestFetchTaskDestination.cppTestFetchEngineMessages.cpp@@ -99,6 +100,7 @@ target_link_libraries(TestFetchAlgorithms PRIVATE LibCore LibGC LibJS LibURL)target_link_libraries(TestFetchBodyDeliveryGate PRIVATE LibCore LibThreading)target_link_libraries(TestFetchBodyStream PRIVATE LibCore LibGC LibJS)target_link_libraries(TestFetchByteChannel PRIVATE LibThreading)+target_link_libraries(TestFetchController PRIVATE LibGC)target_link_libraries(TestFetchControllerRegistry PRIVATE LibGC)target_link_libraries(TestFetchTaskDestination PRIVATE LibCore LibGC LibJS LibURL)target_link_libraries(TestFetchResponse PRIVATE LibGC LibHTTP LibJS LibRequests LibURL)diff --git a/Tests/LibWeb/TestFetchAlgorithms.cpp b/Tests/LibWeb/TestFetchAlgorithms.cppindex b0aad63add2..858fa4eb749 100644--- a/Tests/LibWeb/TestFetchAlgorithms.cpp+++ b/Tests/LibWeb/TestFetchAlgorithms.cpp@@ -8,6 +8,7 @@#include <LibCore/EventLoop.h>#include <LibCore/Timer.h>#include <LibGC/RootVector.h>+#include <LibGC/Testing.h>#include <LibTest/TestCase.h>#include <LibURL/Parser.h>#include <LibWeb/Fetch/Fetching/Fetching.h>@@ -193,3 +194,37 @@ TEST_CASE(a_stop_leaves_the_algorithms_for_the_next_fetch)harness.run_tasks_until([&] { return call_count == 3; });EXPECT_EQ(call_count, 3u);}++static NEVER_INLINE void start_fetch_without_holding_its_controller(FetchHarness const& harness, Request& request, FetchAlgorithms::Input input)+{+ (void)harness.fetch(request, move(input));+}++static NEVER_INLINE void run_a_fetch_whose_controller_nothing_holds()+{+ Core::EventLoop event_loop;+ install_font_plugin();+ IGNORE_USE_IN_ESCAPING_LAMBDA FetchHarness harness;++ IGNORE_USE_IN_ESCAPING_LAMBDA bool consumed_body = false;+ FetchAlgorithms::Input input { Web::Fetch::Engine::BodyIntent::ConsumeForCallback };+ input.process_response_consume_body = [&](GC::Ref<ResponseView>, FetchAlgorithms::BodyBytes) { consumed_body = true; };++ // A worker's script fetch has no fetch record, so only its own steps hold its controller.+ auto request = harness.create_request();+ request->set_destination(Request::Destination::Worker);+ start_fetch_without_holding_its_controller(harness, request, move(input));+ GC::scrub_stack_for_testing();+ harness.run_tasks_until([&] {+ harness.realm->heap().collect_garbage();+ return consumed_body;+ });++ EXPECT(consumed_body);+}++TEST_CASE(a_fetch_whose_controller_nothing_holds_still_runs_its_algorithms)+{+ GC::scrub_stack_for_testing();+ run_a_fetch_whose_controller_nothing_holds();+}diff --git a/Tests/LibWeb/TestFetchBodyStream.cpp b/Tests/LibWeb/TestFetchBodyStream.cppindex 826459f52c8..18d59ae5c0c 100644--- a/Tests/LibWeb/TestFetchBodyStream.cpp+++ b/Tests/LibWeb/TestFetchBodyStream.cpp@@ -70,7 +70,7 @@ private:GC_DEFINE_ALLOCATOR(RecordingReadRequest);-GC::Ref<FetchParams> create_sync_xhr_fetch_params(Web::Fetch::Infrastructure::FetchController& controller)+NonnullRefPtr<FetchParams> create_sync_xhr_fetch_params(Web::Fetch::Infrastructure::FetchController& controller){auto algorithms = FetchAlgorithms::create(FetchAlgorithms::Input { Web::Fetch::Engine::BodyIntent::SyncAccumulate });auto request = Web::Fetch::Infrastructure::Request::create();@@ -88,7 +88,7 @@ struct BodyStreamHarness {void create_stream(FetchByteChannel::Watermarks watermarks = { .low = 16, .high = 64 }){channel = FetchByteChannel::create(watermarks, adopt_ref(*new IgnoringProducerSink));- body = Web::Fetch::Fetching::create_body_from_channel(*realm, fetch_params, *channel);+ body = Web::Fetch::Fetching::create_body_from_channel(*realm, fetch_controller, *channel);stream = body->stream();}@@ -124,7 +124,8 @@ struct BodyStreamHarness {GC::Ref<JS::Realm> realm;Web::HTML::TemporaryExecutionContext execution_context;- GC::Ptr<FetchParams const> fetch_params;+ RefPtr<FetchParams const> fetch_params;+ GC::Ptr<Web::Fetch::Infrastructure::FetchController> fetch_controller;RefPtr<FetchByteChannel> channel;GC::Ptr<Body> body;GC::Ptr<Web::Streams::ReadableStream> stream;@@ -230,7 +231,8 @@ TEST_CASE(bytes_reach_a_stream_while_the_event_loop_is_paused)install_font_plugin();BodyStreamHarness harness;auto& controller_registry = static_cast<Web::HTML::Agent&>(*harness.realm->vm().agent()).fetch_controller_registry;- harness.fetch_params = create_sync_xhr_fetch_params(Web::Fetch::Infrastructure::FetchController::create(controller_registry));+ harness.fetch_controller = Web::Fetch::Infrastructure::FetchController::create(controller_registry);+ harness.fetch_params = create_sync_xhr_fetch_params(*harness.fetch_controller);auto pause = Web::HTML::main_thread_event_loop().pause(Web::HTML::EventLoop::UpdateTheRendering::No);harness.create_stream();diff --git a/Tests/LibWeb/TestFetchController.cpp b/Tests/LibWeb/TestFetchController.cppnew file mode 100644index 00000000000..623c2b36494--- /dev/null+++ b/Tests/LibWeb/TestFetchController.cpp@@ -0,0 +1,55 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/NeverDestroyed.h>+#include <LibGC/Heap.h>+#include <LibGC/Root.h>+#include <LibTest/TestCase.h>+#include <LibWeb/Fetch/Engine/WholeBodyTransport.h>+#include <LibWeb/Fetch/Infrastructure/FetchController.h>+#include <LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h>++using Web::Fetch::Engine::WholeBodyTransport;+using Web::Fetch::Infrastructure::FetchController;+using Web::Fetch::Infrastructure::FetchControllerRegistry;++static GC::Heap& test_heap()+{+ static AK::NeverDestroyed<GC::Heap> heap([](auto&) { });+ return *heap;+}++TEST_SETUP+{+ GC::Heap::set_default_heap_for_testing(test_heap());+}++TEST_CASE(a_terminated_fetch_stops_a_body_transport_without_a_request)+{+ FetchControllerRegistry registry;+ auto controller = GC::make_root(FetchController::create(registry));+ auto transport = WholeBodyTransport::create();+ bool stopped = false;+ transport->set_on_stop([&] { stopped = true; });+ controller->set_body_transport(transport);++ controller->terminate();+ EXPECT(stopped);+}++TEST_CASE(stopping_the_body_transport_leaves_the_fetch_ongoing)+{+ FetchControllerRegistry registry;+ auto controller = GC::make_root(FetchController::create(registry));+ auto transport = WholeBodyTransport::create();+ bool stopped = false;+ transport->set_on_stop([&] { stopped = true; });+ controller->set_body_transport(transport);++ controller->stop_body_transport();+ EXPECT(stopped);+ EXPECT_EQ(controller->state(), FetchController::State::Ongoing);+}diff --git a/Tests/LibWeb/TestFetchControllerRegistry.cpp b/Tests/LibWeb/TestFetchControllerRegistry.cppindex b4e0075a023..cf767d478a7 100644--- a/Tests/LibWeb/TestFetchControllerRegistry.cpp+++ b/Tests/LibWeb/TestFetchControllerRegistry.cpp@@ -7,6 +7,7 @@#include <AK/NeverDestroyed.h>#include <LibGC/Heap.h>#include <LibGC/Root.h>+#include <LibGC/Testing.h>#include <LibTest/TestCase.h>#include <LibWeb/Fetch/Infrastructure/FetchController.h>#include <LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h>@@ -52,8 +53,9 @@ TEST_CASE(a_collected_controller_is_not_found){FetchControllerRegistry registry;auto token = create_unreferenced_controller(registry);+ GC::scrub_stack_for_testing();- test_heap().collect_garbage(GC::Heap::CollectionType::CollectEverything);+ test_heap().collect_garbage();EXPECT(!registry.find(token));}diff --git a/Tests/LibWeb/TestFetchResponse.cpp b/Tests/LibWeb/TestFetchResponse.cppindex 3ce55a36a5f..80a35039440 100644--- a/Tests/LibWeb/TestFetchResponse.cpp+++ b/Tests/LibWeb/TestFetchResponse.cpp@@ -70,8 +70,8 @@ TEST_CASE(http_redirect_fetch_releases_intermediate_response_transfer_lease)auto algorithms = Web::Fetch::Infrastructure::FetchAlgorithms::create(Web::Fetch::Infrastructure::FetchAlgorithms::Input { Web::Fetch::Engine::BodyIntent::DeliverStreamToConsumerAgent });Web::Fetch::Infrastructure::FetchControllerRegistry controller_registry;- auto controller = Web::Fetch::Infrastructure::FetchController::create(controller_registry);- auto fetch_params = Web::Fetch::Infrastructure::FetchParams::create(controller, request, algorithms, Web::Fetch::Infrastructure::FetchTimingInfo::create(), Web::current_loader_config());+ auto controller = GC::make_root(Web::Fetch::Infrastructure::FetchController::create(controller_registry));+ auto fetch_params = Web::Fetch::Infrastructure::FetchParams::create(*controller, request, algorithms, Web::Fetch::Infrastructure::FetchTimingInfo::create(), Web::current_loader_config());auto response = TransferTrackingResponse::create();response->set_status(302);response->set_header_list(HTTP::HeaderList::create({ { "Location"sv, "/redirected"sv } }));diff --git a/Tests/LibWeb/Text/expected/Fetch/document-with-fetches-stopped-before-their-response-is-collectable.txt b/Tests/LibWeb/Text/expected/Fetch/document-with-fetches-stopped-before-their-response-is-collectable.txtnew file mode 100644index 00000000000..2d4b739e4c6--- /dev/null+++ b/Tests/LibWeb/Text/expected/Fetch/document-with-fetches-stopped-before-their-response-is-collectable.txt@@ -0,0 +1 @@+collected 5 of 5 documents with fetches stopped before their responsediff --git a/Tests/LibWeb/Text/expected/Fetch/dropped-fetch-reports-resource-timing.txt b/Tests/LibWeb/Text/expected/Fetch/dropped-fetch-reports-resource-timing.txtnew file mode 100644index 00000000000..c02b7be50b9--- /dev/null+++ b/Tests/LibWeb/Text/expected/Fetch/dropped-fetch-reports-resource-timing.txt@@ -0,0 +1 @@+The fetch reported its resource timingdiff --git a/Tests/LibWeb/Text/expected/Fetch/fetch-request-body-stream-survives-garbage-collection.txt b/Tests/LibWeb/Text/expected/Fetch/fetch-request-body-stream-survives-garbage-collection.txtnew file mode 100644index 00000000000..d9432ad8482--- /dev/null+++ b/Tests/LibWeb/Text/expected/Fetch/fetch-request-body-stream-survives-garbage-collection.txt@@ -0,0 +1,2 @@+fetch: response+The stream was read after the responsediff --git a/Tests/LibWeb/Text/expected/Fetch/object-fetch-survives-garbage-collection.txt b/Tests/LibWeb/Text/expected/Fetch/object-fetch-survives-garbage-collection.txtnew file mode 100644index 00000000000..5a3f19405c5--- /dev/null+++ b/Tests/LibWeb/Text/expected/Fetch/object-fetch-survives-garbage-collection.txt@@ -0,0 +1 @@+The object fired loaddiff --git a/Tests/LibWeb/Text/expected/XHR/XMLHttpRequest-sync-body-larger-than-high-watermark.txt b/Tests/LibWeb/Text/expected/XHR/XMLHttpRequest-sync-body-larger-than-high-watermark.txtnew file mode 100644index 00000000000..0fe57a08773--- /dev/null+++ b/Tests/LibWeb/Text/expected/XHR/XMLHttpRequest-sync-body-larger-than-high-watermark.txt@@ -0,0 +1 @@+Status 200, 4194304 bytes, intactdiff --git a/Tests/LibWeb/Text/expected/navigation/redirected-navigation-survives-garbage-collection.txt b/Tests/LibWeb/Text/expected/navigation/redirected-navigation-survives-garbage-collection.txtnew file mode 100644index 00000000000..802cc2aa70b--- /dev/null+++ b/Tests/LibWeb/Text/expected/navigation/redirected-navigation-survives-garbage-collection.txt@@ -0,0 +1 @@+The redirected navigation loadeddiff --git a/Tests/LibWeb/Text/input/Fetch/document-with-fetches-stopped-before-their-response-is-collectable.html b/Tests/LibWeb/Text/input/Fetch/document-with-fetches-stopped-before-their-response-is-collectable.htmlnew file mode 100644index 00000000000..7c8b9993a08--- /dev/null+++ b/Tests/LibWeb/Text/input/Fetch/document-with-fetches-stopped-before-their-response-is-collectable.html@@ -0,0 +1,74 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // Navigating away from a document stops its fetch() and XMLHttpRequest fetches, and a fetch stopped before its+ // response arrived keeps nothing of the document alive.+ promiseTest(async () => {+ const server = httpTestServer();+ const token = `document-with-fetches-stopped-before-their-response-${uniqueID()}`;++ // The response arrives only once the token is unblocked, which happens after the documents are counted.+ const blockedURL = await server.createEcho("GET", "/document-with-fetches-stopped-before-their-response-blocked", {+ status: 200,+ headers: { "Access-Control-Allow-Origin": "*", "Content-Type": "text/plain", "Cache-Control": "no-store" },+ body: "xx",+ wait_for_unblock: token,+ });++ // The page starts a fetch and an XMLHttpRequest of that response, and tells its parent once both are sent.+ const pageURL = await server.createEcho("GET", "/document-with-fetches-stopped-before-their-response", {+ status: 200,+ headers: { "Content-Type": "text/html" },+ body: `<!DOCTYPE html>+<script>+ const url = ${JSON.stringify(blockedURL)} + "?page=" + location.search.slice(1) + "&request=";+ fetch(url + "fetch");+ const xhr = new XMLHttpRequest();+ xhr.open("GET", url + "xhr");+ xhr.send();+ parent.postMessage("requests started", "*");+<\/script>`,+ });++ const iframe = document.createElement("iframe");+ document.body.append(iframe);++ const navigate = async page => {+ await new Promise(resolve => {+ window.addEventListener("message", resolve, { once: true });+ iframe.src = `${pageURL}?${page}`;+ });+ for (const request of ["fetch", "xhr"])+ await server.waitForRequest(`${blockedURL}?page=${page}&request=${request}`);+ await internals.gcAsync();+ };++ // The first document reuses the initial about:blank document's window, so the recording starts with the+ // second. It runs in a nested function so that no document lingers in this function's frame.+ const weakDocuments = await (async () => {+ const weakDocuments = [];+ await navigate(0);+ await navigate(1);+ for (let page = 2; page <= 6; page++) {+ const unloadedDocument = iframe.contentDocument;+ unloadedDocument.preserveWrapper = true;+ weakDocuments.push(new WeakRef(unloadedDocument));+ await navigate(page);+ }+ return weakDocuments;+ })();++ const maximumGcRoundsWhileRequestTeardownTasksDrain = 100;+ for (let round = 0; round < maximumGcRoundsWhileRequestTeardownTasksDrain; ++round) {+ await timeout(0);+ await internals.gcAsync();+ if (weakDocuments.every(weak => weak.deref() === undefined))+ break;+ }++ const collected = weakDocuments.filter(weak => weak.deref() === undefined).length;+ println(`collected ${collected} of ${weakDocuments.length} documents with fetches stopped before their response`);+ await fetch(`${server.baseURL}/unblock/${token}`);+ iframe.remove();+ });+</script>diff --git a/Tests/LibWeb/Text/input/Fetch/document-with-fetches-stopped-before-their-response-is-collectable.html.headers b/Tests/LibWeb/Text/input/Fetch/document-with-fetches-stopped-before-their-response-is-collectable.html.headersnew file mode 100644index 00000000000..156209f9c81--- /dev/null+++ b/Tests/LibWeb/Text/input/Fetch/document-with-fetches-stopped-before-their-response-is-collectable.html.headers@@ -0,0 +1 @@+Content-Type: text/htmldiff --git a/Tests/LibWeb/Text/input/Fetch/dropped-fetch-reports-resource-timing.html b/Tests/LibWeb/Text/input/Fetch/dropped-fetch-reports-resource-timing.htmlnew file mode 100644index 00000000000..aaafdb3dc84--- /dev/null+++ b/Tests/LibWeb/Text/input/Fetch/dropped-fetch-reports-resource-timing.html@@ -0,0 +1,40 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // The page keeps nothing of this fetch, its response or the read of its body, so only the fetch's own steps and its+ // fetch record keep it going until it reports its resource timing.+ promiseTest(async () => {+ const server = httpTestServer();+ const token = `dropped-fetch-reports-resource-timing-${uniqueID()}`;+ const url = await server.createEcho("GET", "/dropped-fetch-reports-resource-timing", {+ status: 200,+ headers: { "Access-Control-Allow-Origin": "*", "Content-Type": "text/plain", "Cache-Control": "no-store" },+ body: "xx",+ });++ // The response's first byte arrives at once, and the rest once the token is unblocked.+ const requestURL = `${url}?chunks=1&chunk_unblock_tokens=${token}`;+ const reported = new Promise(resolve => {+ new PerformanceObserver((list, observer) => {+ if (list.getEntries().some(entry => entry.name === requestURL)) {+ observer.disconnect();+ resolve();+ }+ }).observe({ type: "resource" });+ });++ (() => {+ fetch(requestURL).then(response => {+ response.text();+ });+ })();++ await server.waitForRequest(url);+ for (let i = 0; i < 5; ++i)+ await internals.gcAsync();+ await fetch(`${server.baseURL}/unblock/${token}`);++ await reported;+ println("The fetch reported its resource timing");+ });+</script>diff --git a/Tests/LibWeb/Text/input/Fetch/fetch-request-body-stream-survives-garbage-collection.html b/Tests/LibWeb/Text/input/Fetch/fetch-request-body-stream-survives-garbage-collection.htmlnew file mode 100644index 00000000000..ba0e9ddfe21--- /dev/null+++ b/Tests/LibWeb/Text/input/Fetch/fetch-request-body-stream-survives-garbage-collection.html@@ -0,0 +1,33 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A request body streamed from a ReadableStream can still be read after its response has arrived and nothing+ // else holds the fetch.+ promiseTest(async () => {+ const url = await httpTestServer().createEcho("POST", "/fetch-request-body-stream-survives-garbage-collection", {+ status: 200,+ headers: { "Access-Control-Allow-Origin": "*", "Cache-Control": "no-store" },+ body: "response",+ });++ let streamController;+ const stream = new ReadableStream({+ start(controller) {+ streamController = controller;+ },+ });++ const text = await fetch(url, { method: "POST", body: stream, duplex: "half" }).then(response => response.text());+ println(`fetch: ${text}`);++ for (let i = 0; i < 5; ++i)+ await internals.gcAsync();++ streamController.enqueue(new Uint8Array([1, 2, 3]));+ streamController.close();+ for (let i = 0; i < 5; ++i)+ await new Promise(resolve => setTimeout(resolve, 0));++ println("The stream was read after the response");+ });+</script>diff --git a/Tests/LibWeb/Text/input/Fetch/object-fetch-survives-garbage-collection.html b/Tests/LibWeb/Text/input/Fetch/object-fetch-survives-garbage-collection.htmlnew file mode 100644index 00000000000..f79aad59ef0--- /dev/null+++ b/Tests/LibWeb/Text/input/Fetch/object-fetch-survives-garbage-collection.html@@ -0,0 +1,33 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // An <object> element keeps nothing of its fetch, so only the fetch's own steps keep it going while its response+ // is outstanding.+ promiseTest(async () => {+ const server = httpTestServer();+ const token = `object-fetch-survives-garbage-collection-${uniqueID()}`;+ const url = await server.createEcho("GET", "/object-fetch-survives-garbage-collection", {+ status: 200,+ headers: { "Content-Type": "text/plain", "Cache-Control": "no-store" },+ body: "xx",+ });++ const object = document.createElement("object");+ const loaded = new Promise(resolve => {+ object.onload = () => resolve("load");+ object.onerror = () => resolve("error");+ });++ // The response's first byte arrives at once, and the rest once the token is unblocked.+ object.data = `${url}?chunks=1&chunk_unblock_tokens=${token}`;+ document.body.append(object);++ await server.waitForRequest(url);+ for (let i = 0; i < 5; ++i)+ await internals.gcAsync();+ await fetch(`${server.baseURL}/unblock/${token}`);++ println(`The object fired ${await loaded}`);+ object.remove();+ });+</script>diff --git a/Tests/LibWeb/Text/input/XHR/XMLHttpRequest-sync-body-larger-than-high-watermark.html b/Tests/LibWeb/Text/input/XHR/XMLHttpRequest-sync-body-larger-than-high-watermark.htmlnew file mode 100644index 00000000000..ec518e78c6f--- /dev/null+++ b/Tests/LibWeb/Text/input/XHR/XMLHttpRequest-sync-body-larger-than-high-watermark.html@@ -0,0 +1,20 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A sync request reads a body several times the size its fetch buffers at once.+ promiseTest(async () => {+ const server = httpTestServer();+ const body = "x".repeat(4 * 1024 * 1024);+ const url = await server.createEcho("GET", "/sync-xhr-body-larger-than-high-watermark", {+ status: 200,+ headers: { "Access-Control-Allow-Origin": "*", "Content-Type": "text/plain", "Cache-Control": "no-store" },+ body,+ });++ const xhr = new XMLHttpRequest();+ xhr.open("GET", url, false);+ xhr.send();++ println(`Status ${xhr.status}, ${xhr.responseText.length} bytes, ${xhr.responseText === body ? "intact" : "corrupted"}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/include.js b/Tests/LibWeb/Text/input/include.jsindex 9a305c50d20..ea5fc446781 100644--- a/Tests/LibWeb/Text/input/include.js+++ b/Tests/LibWeb/Text/input/include.js@@ -257,6 +257,16 @@ class HTTPTestServer {recordedRequestHeadersURL(echoURL) {return `${this.baseURL}/recorded-request-headers${new URL(echoURL).pathname}`;}+ // Resolves once the echo server has seen a request for echoURL, query included.+ async waitForRequest(echoURL) {+ const url = new URL(echoURL);+ const recordedURL = `${this.baseURL}/recorded-request-headers${url.pathname}${url.search}`;+ for (;;) {+ const response = await fetch(recordedURL).catch(() => null);+ if (response?.ok) return;+ await timeout(10);+ }+ }getStaticURL(path) {return `${this.baseURL}/static/${path}`;}diff --git a/Tests/LibWeb/Text/input/navigation/redirected-navigation-survives-garbage-collection.html b/Tests/LibWeb/Text/input/navigation/redirected-navigation-survives-garbage-collection.htmlnew file mode 100644index 00000000000..b78425eb670--- /dev/null+++ b/Tests/LibWeb/Text/input/navigation/redirected-navigation-survives-garbage-collection.html@@ -0,0 +1,36 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A navigation follows its redirects one hop at a time, and its fetch keeps going across a garbage collection+ // while the next hop is under way.+ promiseTest(async () => {+ const server = httpTestServer();+ const token = `redirected-navigation-survives-garbage-collection-${uniqueID()}`;+ const targetURL = await server.createEcho("GET", "/redirected-navigation-survives-garbage-collection-target", {+ status: 200,+ headers: { "Content-Type": "text/html", "Cache-Control": "no-store" },+ body: `<!DOCTYPE html><script>parent.postMessage("loaded", "*");<\/script>`,+ wait_for_unblock: token,+ });+ const redirectURL = await server.createEcho("GET", "/redirected-navigation-survives-garbage-collection", {+ status: 302,+ headers: { "Location": targetURL, "Cache-Control": "no-store" },+ body: "",+ });++ const loaded = new Promise(resolve => {+ window.addEventListener("message", event => resolve(event.data), { once: true });+ });+ const iframe = document.createElement("iframe");+ document.body.append(iframe);+ iframe.src = redirectURL;++ await server.waitForRequest(targetURL);+ for (let i = 0; i < 5; ++i)+ await internals.gcAsync();+ await fetch(`${server.baseURL}/unblock/${token}`);++ println(`The redirected navigation ${await loaded}`);+ iframe.remove();+ });+</script>diff --git a/Tests/LibWebView/test-webdriver-bidi.py b/Tests/LibWebView/test-webdriver-bidi.pyindex cefa86b1416..35ba563780c 100755--- a/Tests/LibWebView/test-webdriver-bidi.py+++ b/Tests/LibWebView/test-webdriver-bidi.py@@ -209,6 +209,8 @@ class ReloadHandler(http.server.BaseHTTPRequestHandler):body = b"authentication required"else:self.send_response(200)+ if self.path.startswith("/network-interception/cors/"):+ self.send_header("Access-Control-Allow-Origin", "*")with server.interception_lock:body = json.dumps(server.interception_requests).encode()self.send_header("Content-Type", "application/json")@@ -284,7 +286,8 @@ class ReloadHandler(http.server.BaseHTTPRequestHandler):passreturnif self.path.startswith("/network-document/"):- truncated = self.path.rsplit("/", 1)[-1] == "truncated"+ kind = self.path.rsplit("/", 1)[-1]+ truncated = kind == "truncated"body = server.document_bodyself.send_response(200)self.send_header("Content-Type", "text/html")@@ -299,6 +302,15 @@ class ReloadHandler(http.server.BaseHTTPRequestHandler):self.wfile.write(body[:held_from])self.wfile.flush()server.document_headers_sent.set()+ if kind in ["intercepted-fail", "intercepted-provide"]:+ # A failed or replaced response's transport closes while the rest of its body is held.+ self.connection.settimeout(30)+ try:+ if not self.connection.recv(1):+ server.interception_transport_closed.set()+ except ConnectionResetError:+ server.interception_transport_closed.set()+ returnif not server.release_document.wait(30):raise TimeoutError("The test did not release the document response")if not truncated:@@ -1087,6 +1099,156 @@ def check_network_cancel_with_events_off(bidi, context, server, kind):bidi.evaluate(context, "objectFrame.remove(); 0")+def check_network_continue_after_gc(bidi, context, server):+ subscription = bidi.command(+ "session.subscribe",+ {"events": ["network.beforeRequestSent", "network.responseStarted", "network.authRequired"]},+ )["subscription"]+ continue_commands = {+ "beforeRequestSent": "network.continueRequest",+ "responseStarted": "network.continueResponse",+ "authRequired": "network.continueWithAuth",+ }+ server.release_preflight.set()+ try:+ for phase in [*continue_commands, "preflight"]:+ if phase == "preflight":+ # A cross-origin PUT blocks first for its preflight, then for itself.+ url = f"http://localhost:{server.server_port}/network-interception/cors/continue-after-gc"+ options = {"method": "PUT", "headers": {"X-BiDi": "1"}}+ blocked = [("beforeRequestSent", "OPTIONS"), ("beforeRequestSent", "PUT")]+ else:+ auth = "auth/" if phase == "authRequired" else ""+ url = f"http://127.0.0.1:{server.server_port}/network-interception/{auth}continue-after-gc-{phase}"+ options = None+ blocked = [(phase, "GET")]+ intercept = bidi.command(+ "network.addIntercept",+ {+ "phases": sorted({blocked_phase for blocked_phase, _ in blocked}),+ "urlPatterns": [{"type": "string", "pattern": url}],+ },+ )["intercept"]+ with server.interception_lock:+ server.interception_requests.clear()+ pending = send_fetch(bidi, context, url, options)+ for blocked_phase, method in blocked:+ event = intercepted_event(bidi, f"network.{blocked_phase}", url)+ assert event["request"]["method"] == method, event+ # A collection while the request is blocked keeps what its continuation needs.+ bidi.evaluate(context, "internals.gc(); undefined")+ params = {"request": event["request"]["request"]}+ if blocked_phase == "authRequired":+ params["action"] = "provideCredentials"+ params["credentials"] = {"type": "password", "username": "user", "password": "pass"}+ bidi.command(continue_commands[blocked_phase], params)+ records = fetch_records(bidi, pending)+ path = urllib.parse.urlsplit(url).path+ expected = (+ [(path, "PUT")] if phase == "preflight" else [(path, "GET")] * (2 if phase == "authRequired" else 1)+ )+ assert [(record["path"], record["method"]) for record in records] == expected, records+ if phase == "authRequired":+ authorization = [value for key, value in records[-1]["headers"] if key.lower() == "authorization"]+ assert authorization == ["Basic dXNlcjpwYXNz"], records+ bidi.command("network.removeIntercept", {"intercept": intercept})+ finally:+ if sys.exc_info()[0] is None:+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})+++def check_network_intercepted_adopted_navigation(bidi, context, server, action):+ # A cross-site navigation blocked at responseStarted commits its document in another process once continued.+ terminal_methods = {"network.responseCompleted", "network.fetchError"}+ origin = f"http://127.0.0.1:{server.server_port}"+ url = f"http://localhost:{server.server_port}/network-document/intercepted-{action}"+ provided = "<!doctype html><title>Provided document</title><p>Provided"+ server.document_headers_sent.clear()+ server.release_document.clear()+ server.interception_transport_closed.clear()+ subscription = bidi.command(+ "session.subscribe",+ {"events": ["network.responseStarted", *sorted(terminal_methods)], "contexts": [context]},+ )["subscription"]+ intercept = bidi.command(+ "network.addIntercept",+ {"phases": ["responseStarted"], "urlPatterns": [{"type": "string", "pattern": url}]},+ )["intercept"]++ def is_our_terminal_event(event):+ return event["method"] in terminal_methods and event["params"].get("request", {}).get("url") == url++ def next_terminal_event():+ while True:+ for index, event in enumerate(bidi.events):+ if is_our_terminal_event(event):+ return bidi.events.pop(index)+ bidi.read_message()++ def wait_for_commit():+ deadline = time.monotonic() + 10+ while True:+ result = bidi.response(+ bidi.send(+ "script.evaluate",+ {"target": {"context": context}, "expression": "document.URL", "awaitPromise": False},+ )+ )+ if result["type"] == "success" and result["result"]["result"].get("value") == url:+ return+ assert time.monotonic() < deadline, "The navigation did not commit its document"++ try:+ navigation = bidi.send("browsingContext.navigate", {"context": context, "url": url, "wait": "none"})+ event = intercepted_event(bidi, "network.responseStarted", url)+ request_id = event["request"]["request"]+ assert server.document_headers_sent.wait(10)+ expected_size = len(provided) if action == "provide" else len(server.document_body)+ if action == "continue":+ bidi.command("network.continueResponse", {"request": request_id})+ wait_for_commit()+ server.release_document.set()+ elif action == "fail":+ bidi.command("network.failRequest", {"request": request_id})+ else:+ bidi.command(+ "network.provideResponse",+ {"request": request_id, "body": {"type": "string", "value": provided}},+ )+ wait_for_commit()+ assert bidi.evaluate(context, "document.title")["result"]["value"] == "Provided document"+ # A failed navigation settles too, with an error document, before the next navigation starts.+ result = bidi.response(navigation)+ if action != "fail":+ assert result["type"] == "success", result++ terminal = next_terminal_event()+ params = terminal["params"]+ assert params["request"]["request"] == request_id, params+ if action == "fail":+ assert terminal["method"] == "network.fetchError", terminal+ else:+ assert terminal["method"] == "network.responseCompleted", terminal+ assert params["response"]["bodySize"] == expected_size, params+ assert params["response"]["content"]["size"] == expected_size, params+ if action != "continue":+ assert server.interception_transport_closed.wait(30), "The original response's transport stayed open"++ # The navigation's body ends once, in whichever process holds it, and the process that handed it over reports+ # nothing more for it, so a reply from the document that holds it follows every event of the request.+ bidi.evaluate(context, "0")+ assert not any(is_our_terminal_event(event) for event in bidi.events), bidi.events+ finally:+ server.release_document.set()+ if sys.exc_info()[0] is None:+ bidi.command("network.removeIntercept", {"intercept": intercept})+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})+ bidi.command(+ "browsingContext.navigate",+ {"context": context, "url": f"{origin}/interception-page", "wait": "complete"},+ )++def check_network_provided_body_at_response_started(bidi, context, server):url = f"http://127.0.0.1:{server.server_port}/network-interception/fail-body"provided = "provided body"@@ -1272,6 +1434,11 @@ def check_network_interception(bidi, context, server, case="all"):for kind in ["abort", "stop"]:if case in ["all", f"events-off-{kind}"]:check_network_cancel_with_events_off(bidi, context, server, kind)+ if case in ["all", "continue-after-gc"]:+ check_network_continue_after_gc(bidi, context, server)+ for action in ["continue", "fail", "provide"]:+ if case in ["all", f"adopted-navigation-{action}"]:+ check_network_intercepted_adopted_navigation(bidi, context, server, action)for action in ["cancel", "default"]:if case in ["all", "auth-response-matrix", "auth-action-extras", f"auth-{action}-extra"]:for credentials in [{"type": "password", "username": "user", "password": "pass"}, {}]:@@ -2423,6 +2590,10 @@ if __name__ == "__main__":"abort-after-gc","events-off-abort","events-off-stop",+ "continue-after-gc",+ "adopted-navigation-continue",+ "adopted-navigation-fail",+ "adopted-navigation-provide","auth-gates","auth-omit","auth-cors",