Truly independent web browser
LibWeb: Account for in-flight keepalive bytes per fetch group
Luke Wilde8d3bcc23d039
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex f8c69ead5bf..e511aeeac16 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -375,6 +375,7 @@ set(SOURCESFetch/Infrastructure/HTTP/Requests.cppFetch/Infrastructure/HTTP/Responses.cppFetch/Infrastructure/IncrementalReadLoopReadRequest.cpp+ Fetch/Infrastructure/KeepaliveQuotaAccountant.cppFetch/Infrastructure/MimeTypeBlocking.cppFetch/Infrastructure/NetworkPartitionKey.cppFetch/Infrastructure/NoSniffBlocking.cppdiff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex dd83cb11521..31fe7c3a230 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -436,6 +436,16 @@ GC::Ref<Infrastructure::FetchController> fetch(JS::Realm& realm, Infrastructure:// 2. Append record to request’s client’s fetch group’s fetch records.request.client()->fetch_group().append(record);++ // AD-HOC: A keepalive request's body length counts toward its fetch group's keepalive quota from here until+ // its done flag is set or its body is null, since its fetch record can be collected before then.+ if (request.keepalive()) {+ auto body_length = request.body().visit(+ [](Empty) -> u64 { return 0; },+ [](ByteBuffer const& buffer) -> u64 { return buffer.size(); },+ [](GC::Ref<Infrastructure::Body> body) -> u64 { return body->length().value_or(0); });+ request.set_keepalive_quota_reservation(request.client()->keepalive_quota_accountant().reserve(body_length));+ }}if (Core::StatsLog::the() && client_window && request.is_subresource_request())@@ -2007,31 +2017,14 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru// 10. If contentLength is non-null and httpRequest’s keepalive is true, then:if (content_length.has_value() && http_request->keepalive()) {// 1. Let inflightKeepaliveBytes be 0.- u64 inflight_keep_alive_bytes = 0;-// 2. Let group be httpRequest’s client’s fetch group.- auto& group = http_request->client()->fetch_group();-// 3. Let inflightRecords be the set of fetch records in group whose request’s keepalive is true and done flag is unset.- GC::RootVector<GC::Ref<Infrastructure::FetchRecord>> in_flight_records;- for (auto& fetch_record : group) {- if (fetch_record.request()->keepalive() && !fetch_record.request()->done())- in_flight_records.append(fetch_record);- }-// 4. For each fetchRecord of inflightRecords:- for (auto const& fetch_record : in_flight_records) {- // 1. Let inflightRequest be fetchRecord’s request.- auto const& in_flight_request = fetch_record->request();-- // 2. Increment inflightKeepaliveBytes by inflightRequest’s body’s length.- inflight_keep_alive_bytes += in_flight_request->body().visit(- [](Empty) -> u64 { return 0; },- [](ByteBuffer const& buffer) -> u64 { return buffer.size(); },- [](GC::Ref<Infrastructure::Body> body) -> u64 {- return body->length().has_value() ? body->length().value() : 0;- });- }+ // 1. Let inflightRequest be fetchRecord’s request.+ // 2. Increment inflightKeepaliveBytes by inflightRequest’s body’s length.+ // AD-HOC: The fetch group's keepalive quota accountant holds this sum, so a request whose fetch record was+ // collected still counts.+ auto inflight_keep_alive_bytes = http_request->client()->keepalive_quota_accountant().in_flight_byte_count();// 5. If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.if ((content_length.value() + inflight_keep_alive_bytes) > keepalive_maximum_size)diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.hindex 9e45049e100..e1de48b6aaf 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h@@ -28,6 +28,7 @@#include <LibWeb/Export.h>#include <LibWeb/Fetch/Infrastructure/HTTP.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>+#include <LibWeb/Fetch/Infrastructure/KeepaliveQuotaAccountant.h>#include <LibWeb/Forward.h>#include <LibWebCommon/Fetch/Infrastructure/HTTP/RequestPriority.h>#include <LibWebCommon/Fetch/Infrastructure/HTTP/RequestReferrer.h>@@ -188,7 +189,12 @@ public:[[nodiscard]] BodyType const& body() const { return m_body; }[[nodiscard]] BodyType& body() { return m_body; }- void set_body(BodyType body) { m_body = move(body); }+ void set_body(BodyType body)+ {+ if (body.has<Empty>())+ m_keepalive_quota_reservation.clear();+ m_body = move(body);+ }[[nodiscard]] GC::Ptr<HTML::EnvironmentSettingsObject const> client() const { return m_client; }[[nodiscard]] GC::Ptr<HTML::EnvironmentSettingsObject> client() { return m_client; }@@ -302,7 +308,14 @@ public:void set_prevent_no_cache_cache_control_header_modification(bool prevent_no_cache_cache_control_header_modification) { m_prevent_no_cache_cache_control_header_modification = prevent_no_cache_cache_control_header_modification; }[[nodiscard]] bool done() const { return m_done; }- void set_done(bool done) { m_done = done; }+ void set_done(bool done)+ {+ m_done = done;+ if (done)+ m_keepalive_quota_reservation.clear();+ }++ void set_keepalive_quota_reservation(KeepaliveQuotaAccountant::Reservation reservation) { m_keepalive_quota_reservation = move(reservation); }[[nodiscard]] bool timing_allow_failed() const { return m_timing_allow_failed; }void set_timing_allow_failed(bool timing_allow_failed) { m_timing_allow_failed = timing_allow_failed; }@@ -556,6 +569,9 @@ private:// A request has an associated done flag. Unless stated otherwise, it is unset.bool m_done { false };+ // Counts this request's body against its client's keepalive quota until its done flag is set or its body is null.+ Optional<KeepaliveQuotaAccountant::Reservation> m_keepalive_quota_reservation;+// https://fetch.spec.whatwg.org/#timing-allow-failed// A request has an associated timing allow failed flag. Unless stated otherwise, it is unset.bool m_timing_allow_failed { false };diff --git a/Libraries/LibWeb/Fetch/Infrastructure/KeepaliveQuotaAccountant.cpp b/Libraries/LibWeb/Fetch/Infrastructure/KeepaliveQuotaAccountant.cppnew file mode 100644index 00000000000..45bab5b3219--- /dev/null+++ b/Libraries/LibWeb/Fetch/Infrastructure/KeepaliveQuotaAccountant.cpp@@ -0,0 +1,59 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibWeb/Fetch/Infrastructure/KeepaliveQuotaAccountant.h>++namespace Web::Fetch::Infrastructure {++NonnullRefPtr<KeepaliveQuotaAccountant> KeepaliveQuotaAccountant::create()+{+ return adopt_ref(*new KeepaliveQuotaAccountant);+}++KeepaliveQuotaAccountant::Reservation KeepaliveQuotaAccountant::reserve(u64 byte_count)+{+ m_in_flight_byte_count.fetch_add(byte_count);+ return Reservation { *this, byte_count };+}++KeepaliveQuotaAccountant::Reservation::Reservation(NonnullRefPtr<KeepaliveQuotaAccountant> accountant, u64 byte_count)+ : m_accountant(move(accountant))+ , m_byte_count(byte_count)+{+}++KeepaliveQuotaAccountant::Reservation::Reservation(Reservation&& other)+ : m_accountant(move(other.m_accountant))+ , m_byte_count(exchange(other.m_byte_count, 0))+{+}++KeepaliveQuotaAccountant::Reservation& KeepaliveQuotaAccountant::Reservation::operator=(Reservation&& other)+{+ if (this != &other) {+ release();+ m_accountant = move(other.m_accountant);+ m_byte_count = exchange(other.m_byte_count, 0);+ }+ return *this;+}++KeepaliveQuotaAccountant::Reservation::~Reservation()+{+ release();+}++void KeepaliveQuotaAccountant::Reservation::release()+{+ if (!m_accountant)+ return;+ auto byte_count = exchange(m_byte_count, 0);+ auto previous_byte_count = m_accountant->m_in_flight_byte_count.fetch_sub(byte_count);+ VERIFY(previous_byte_count >= byte_count);+ m_accountant = nullptr;+}++}diff --git a/Libraries/LibWeb/Fetch/Infrastructure/KeepaliveQuotaAccountant.h b/Libraries/LibWeb/Fetch/Infrastructure/KeepaliveQuotaAccountant.hnew file mode 100644index 00000000000..d274b6c49f7--- /dev/null+++ b/Libraries/LibWeb/Fetch/Infrastructure/KeepaliveQuotaAccountant.h@@ -0,0 +1,53 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Atomic.h>+#include <AK/AtomicRefCounted.h>+#include <AK/Noncopyable.h>+#include <AK/NonnullRefPtr.h>+#include <AK/RefPtr.h>+#include <LibWeb/Export.h>++namespace Web::Fetch::Infrastructure {++// The sum of the body lengths of a fetch group's keepalive requests whose done flag is unset.+class WEB_API KeepaliveQuotaAccountant final : public AtomicRefCounted<KeepaliveQuotaAccountant> {+public:+ // Keeps its byte count in the accountant's sum until it is destroyed.+ class Reservation {+ AK_MAKE_NONCOPYABLE(Reservation);++ public:+ Reservation(Reservation&&);+ Reservation& operator=(Reservation&&);+ ~Reservation();++ private:+ friend class KeepaliveQuotaAccountant;++ Reservation(NonnullRefPtr<KeepaliveQuotaAccountant>, u64 byte_count);++ void release();++ RefPtr<KeepaliveQuotaAccountant> m_accountant;+ u64 m_byte_count { 0 };+ };++ [[nodiscard]] static NonnullRefPtr<KeepaliveQuotaAccountant> create();++ [[nodiscard]] Reservation reserve(u64 byte_count);++ [[nodiscard]] u64 in_flight_byte_count() const { return m_in_flight_byte_count.load(); }++private:+ KeepaliveQuotaAccountant() = default;++ Atomic<u64> m_in_flight_byte_count { 0 };+};++}diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex afaf82310b2..804571740f6 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -572,6 +572,7 @@ class FetchParams;class FetchRecord;class FetchTimingInfo;class IncrementalReadLoopReadRequest;+class KeepaliveQuotaAccountant;class Request;class Response;diff --git a/Libraries/LibWeb/HTML/Scripting/Environments.cpp b/Libraries/LibWeb/HTML/Scripting/Environments.cppindex abaceef0013..0cc613cd1e4 100644--- a/Libraries/LibWeb/HTML/Scripting/Environments.cpp+++ b/Libraries/LibWeb/HTML/Scripting/Environments.cpp@@ -63,6 +63,7 @@ Environment::~Environment() = default;EnvironmentSettingsObject::EnvironmentSettingsObject(NonnullOwnPtr<JS::ExecutionContext> realm_execution_context): m_realm_execution_context(move(realm_execution_context))+ , m_keepalive_quota_accountant(Fetch::Infrastructure::KeepaliveQuotaAccountant::create()){m_module_map = GC::Heap::the().allocate<ModuleMap>();diff --git a/Libraries/LibWeb/HTML/Scripting/Environments.h b/Libraries/LibWeb/HTML/Scripting/Environments.hindex bd9836baada..74205900d69 100644--- a/Libraries/LibWeb/HTML/Scripting/Environments.h+++ b/Libraries/LibWeb/HTML/Scripting/Environments.h@@ -16,6 +16,7 @@#include <LibURL/URL.h>#include <LibWeb/Export.h>#include <LibWeb/Fetch/Infrastructure/FetchRecord.h>+#include <LibWeb/Fetch/Infrastructure/KeepaliveQuotaAccountant.h>#include <LibWeb/Forward.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/Scripting/ModuleMap.h>@@ -134,6 +135,7 @@ public:// https://fetch.spec.whatwg.org/#concept-fetch-groupauto& fetch_group() { return m_fetch_group; }+ Fetch::Infrastructure::KeepaliveQuotaAccountant& keepalive_quota_accountant() { return m_keepalive_quota_accountant; }SerializedEnvironmentSettingsObject serialize();@@ -187,6 +189,7 @@ private:// https://fetch.spec.whatwg.org/#concept-fetch-record// A fetch group holds an ordered list of fetch recordsFetch::Infrastructure::FetchRecord::List m_fetch_group;+ NonnullRefPtr<Fetch::Infrastructure::KeepaliveQuotaAccountant> m_keepalive_quota_accountant;// https://storage.spec.whatwg.org/#api// Each environment settings object has an associated StorageManager object.diff --git a/Tests/LibWeb/Text/expected/Fetch/fetch-keepalive-quota.txt b/Tests/LibWeb/Text/expected/Fetch/fetch-keepalive-quota.txtnew file mode 100644index 00000000000..b0f2ceef91d--- /dev/null+++ b/Tests/LibWeb/Text/expected/Fetch/fetch-keepalive-quota.txt@@ -0,0 +1,7 @@+1000 bytes beside 40000 in flight: sent+30000 bytes beside 40000 in flight: rejected+30000 bytes beside 40000 in flight after garbage collection: rejected+40000 bytes once unblocked: sent, sent+30000 bytes after that: sent+20000 bytes beside 30000 redirected to a GET in flight: sent+30000 bytes redirected to a GET once unblocked: sentdiff --git a/Tests/LibWeb/Text/input/Fetch/fetch-keepalive-quota.html b/Tests/LibWeb/Text/input/Fetch/fetch-keepalive-quota.htmlnew file mode 100644index 00000000000..b295cc96e61--- /dev/null+++ b/Tests/LibWeb/Text/input/Fetch/fetch-keepalive-quota.html@@ -0,0 +1,73 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const server = httpTestServer();+ const token = crypto.randomUUID();+ const createHeldEcho = name =>+ server.createEcho("POST", `/fetch-keepalive-quota-${name}-${token}`, {+ status: 200,+ headers: { "Access-Control-Allow-Origin": "*" },+ wait_for_unblock: token,+ });+ const firstHeldURL = await createHeldEcho("first-held");+ const secondHeldURL = await createHeldEcho("second-held");+ const url = await server.createEcho("POST", `/fetch-keepalive-quota-${token}`, {+ status: 200,+ headers: { "Access-Control-Allow-Origin": "*" },+ });++ const sendKeepalive = async (url, byteCount) => {+ try {+ const response = await fetch(url, { method: "POST", keepalive: true, body: "*".repeat(byteCount) });+ await response.text();+ return "sent";+ } catch {+ return "rejected";+ }+ };+ const nextTask = () => new Promise(resolve => setTimeout(resolve, 0));++ const held = [sendKeepalive(firstHeldURL, 20000), sendKeepalive(secondHeldURL, 20000)];+ println(`1000 bytes beside 40000 in flight: ${await sendKeepalive(url, 1000)}`);+ println(`30000 bytes beside 40000 in flight: ${await sendKeepalive(url, 30000)}`);++ internals.gc();+ println(`30000 bytes beside 40000 in flight after garbage collection: ${await sendKeepalive(url, 30000)}`);++ await fetch(`${server.baseURL}/unblock/${token}`);+ println(`40000 bytes once unblocked: ${(await Promise.all(held)).join(", ")}`);+ await nextTask();+ println(`30000 bytes after that: ${await sendKeepalive(url, 30000)}`);++ const redirectToken = crypto.randomUUID();+ const redirectedURL = await server.createEcho("GET", `/fetch-keepalive-quota-redirected-${redirectToken}`, {+ status: 200,+ headers: { "Access-Control-Allow-Origin": "*" },+ wait_for_unblock: redirectToken,+ });+ const redirectingURL = await server.createEcho("POST", `/fetch-keepalive-quota-redirecting-${redirectToken}`, {+ status: 303,+ headers: { "Access-Control-Allow-Origin": "*", "Location": redirectedURL },+ });+ const redirected = sendKeepalive(redirectingURL, 30000);+ const recordedRedirectedRequestURL = `${server.baseURL}/recorded-request-headers${new URL(redirectedURL).pathname}`;+ const redirectedRequestArrived = () =>+ fetch(recordedRedirectedRequestURL, { cache: "no-store" }).then(+ response => response.ok,+ () => false+ );+ const arrivalDeadline = performance.now() + 10000;+ while (!(await redirectedRequestArrived())) {+ if (performance.now() > arrivalDeadline) {+ println("the redirected request never arrived");+ return;+ }+ await nextTask();+ }+ println(`20000 bytes beside 30000 redirected to a GET in flight: ${await sendKeepalive(url, 20000)}`);++ await fetch(`${server.baseURL}/unblock/${redirectToken}`);+ println(`30000 bytes redirected to a GET once unblocked: ${await redirected}`);+ });+</script>