Truly independent web browser
LibWeb+LibHTTP: Evict least recently used HTTP memory cache entries
Andreas Kling9bf49ededb15
diff --git a/Libraries/LibHTTP/Cache/MemoryCache.cpp b/Libraries/LibHTTP/Cache/MemoryCache.cppindex 2879992af89..b60bcee261c 100644--- a/Libraries/LibHTTP/Cache/MemoryCache.cpp+++ b/Libraries/LibHTTP/Cache/MemoryCache.cpp@@ -10,9 +10,56 @@namespace HTTP {-NonnullRefPtr<MemoryCache> MemoryCache::create()+NonnullRefPtr<MemoryCache> MemoryCache::create(NonnullRefPtr<MemoryCacheUsage> usage){- return adopt_ref(*new MemoryCache());+ return adopt_ref(*new MemoryCache(move(usage)));+}++MemoryCache::MemoryCache(NonnullRefPtr<MemoryCacheUsage> usage)+ : m_usage(move(usage))+{+}++MemoryCache::~MemoryCache()+{+ for (auto const& it : m_complete_entries) {+ for (auto const& entry : it.value)+ remove_from_usage(entry);+ }+}++// NB: A cache is only used on one thread, so a counter per thread orders the uses of all caches that share a usage.+static u64 next_use()+{+ static thread_local u64 s_last_use = 0;+ return ++s_last_use;+}++static size_t bytes_in_memory_of(MemoryCache::Entry const& entry)+{+ size_t size = sizeof(entry) + entry.reason_phrase.length();+ if (!entry.body_is_mapped)+ size += entry.response_body.size();+ for (auto const& header : *entry.response_headers)+ size += sizeof(header) + header.name.length() + header.value.length();+ return size;+}++void MemoryCache::add_to_usage(Entry const& entry)+{+ m_usage->bytes_in_memory += entry.bytes_in_memory;+ if (entry.body_is_mapped)+ ++m_usage->mapped_bodies;+}++void MemoryCache::remove_from_usage(Entry const& entry)+{+ VERIFY(m_usage->bytes_in_memory >= entry.bytes_in_memory);+ m_usage->bytes_in_memory -= entry.bytes_in_memory;+ if (entry.body_is_mapped) {+ VERIFY(m_usage->mapped_bodies > 0);+ --m_usage->mapped_bodies;+ }}// A stored response satisfies a request only if the request header fields nominated by the response's Vary header@@ -44,9 +91,9 @@ Optional<MemoryCache::Entry const&> MemoryCache::open_entry(URL::URL const& url,}// - request header fields nominated by the stored response (if any) match those presented (see Section 4.1), and- Optional<Entry const&> cache_entry;+ Optional<Entry&> cache_entry;- for (auto const& entry : *cache_entries) {+ for (auto& entry : *cache_entries) {if (!entry_matches_request(request_headers, entry))continue;@@ -77,7 +124,8 @@ Optional<MemoryCache::Entry const&> MemoryCache::open_entry(URL::URL const& url,switch (cache_lifetime_status(request_headers, cache_entry->response_headers, freshness_lifetime, current_age)) {case CacheLifetimeStatus::Fresh:dbgln_if(HTTP_MEMORY_CACHE_DEBUG, "\033[37m[memory]\033[0m \033[32;1mOpened cache entry for\033[0m {} (lifetime={}s age={}s) ({} bytes)", url, freshness_lifetime.to_seconds(), current_age.to_seconds(), cache_entry->response_body.size());- return cache_entry;+ cache_entry->last_use = next_use();+ return *cache_entry;case CacheLifetimeStatus::Expired:case CacheLifetimeStatus::MustRevalidate:@@ -86,11 +134,12 @@ Optional<MemoryCache::Entry const&> MemoryCache::open_entry(URL::URL const& url,// staleness", which includes responses that must be revalidated. Other engines behave the same way.if (cache_mode_permits_stale_responses(cache_mode)) {dbgln_if(HTTP_MEMORY_CACHE_DEBUG, "\033[37m[memory]\033[0m \033[32;1mOpened expired cache entry for\033[0m {} (lifetime={}s age={}s) ({} bytes)", url, freshness_lifetime.to_seconds(), current_age.to_seconds(), cache_entry->response_body.size());- return cache_entry;+ cache_entry->last_use = next_use();+ return *cache_entry;}dbgln_if(HTTP_MEMORY_CACHE_DEBUG, "\033[37m[memory]\033[0m \033[33;1mCache entry expired for\033[0m {} (lifetime={}s age={}s)", url, freshness_lifetime.to_seconds(), current_age.to_seconds());- m_complete_entries.remove(cache_key);+ remove_complete_entries(cache_key, [](auto const&) { return true; });return {};}@@ -115,12 +164,7 @@ void MemoryCache::create_entry(URL::URL const& url, StringView method, HeaderLisauto vary_key = create_vary_key(request_headers, response_headers);if (!vary_key.has_value() || !is_cacheable(status_code, response_headers)) {// A non-storable replacement must still retire the old response.- if (auto cache_entries = m_complete_entries.get(cache_key); cache_entries.has_value()) {- cache_entries->remove_all_matching([&](auto const& entry) { return entry_matches_request(request_headers, entry); });- if (cache_entries->is_empty())- m_complete_entries.remove(cache_key);- }-+ remove_complete_entries(cache_key, [&](auto const& entry) { return entry_matches_request(request_headers, entry); });return;}@@ -143,15 +187,15 @@ void MemoryCache::create_entry(URL::URL const& url, StringView method, HeaderLis// FIXME: It would be nicer if create_entry just returned the cache and vary keys. But the call sites of create_entry and// finalize_entry are pretty far apart, so passing that information along is rather awkward in Fetch.-bool MemoryCache::finalize_entry(URL::URL const& url, StringView method, HeaderList const& request_headers, u32 status_code, HeaderList const& received_response_headers, Core::ImmutableBytes response_body)+void MemoryCache::finalize_entry(URL::URL const& url, StringView method, HeaderList const& request_headers, u32 status_code, HeaderList const& received_response_headers, Core::ImmutableBytes response_body){auto response_headers_without_connection_specific_fields = remove_connection_specific_fields(received_response_headers);auto const& response_headers = *response_headers_without_connection_specific_fields;if (!is_cacheable(method, request_headers))- return false;+ return;if (!is_cacheable(status_code, response_headers))- return false;+ return;auto serialized_url = serialize_url_for_cache_storage(url);auto cache_key = create_cache_key(serialized_url, method);@@ -159,18 +203,21 @@ bool MemoryCache::finalize_entry(URL::URL const& url, StringView method, HeaderLauto cache_entry = take_pending_entry(cache_key, vary_key);if (!cache_entry.has_value())- return false;+ return;dbgln_if(HTTP_MEMORY_CACHE_DEBUG, "\033[37m[memory]\033[0m \033[34;1mFinished caching\033[0m {} ({} bytes)", url, response_body.size());+ cache_entry->body_is_mapped = response_body.is_file_backed() || response_body.is_readonly_mapped();cache_entry->response_body = move(response_body);+ // NB: The response headers are shared with the responses made from this entry, so this is counted once.+ cache_entry->bytes_in_memory = bytes_in_memory_of(*cache_entry);+ cache_entry->last_use = next_use();- auto& complete_entries = m_complete_entries.ensure(cache_key);- complete_entries.remove_all_matching([&](auto const& entry) { return entry.vary_key == cache_entry->vary_key; });- complete_entries.append(cache_entry.release_value());- return true;+ remove_complete_entries(cache_key, [&](auto const& entry) { return entry.vary_key == cache_entry->vary_key; });+ add_to_usage(*cache_entry);+ m_complete_entries.ensure(cache_key).append(cache_entry.release_value());}-void MemoryCache::abandon_entry(URL::URL const& url, StringView method, HeaderList const& request_headers, HeaderList const& received_response_headers)+void MemoryCache::abandon_entry(URL::URL const& url, StringView method, HeaderList const& request_headers, HeaderList const& received_response_headers, StoredResponse stored_response){auto response_headers_without_connection_specific_fields = remove_connection_specific_fields(received_response_headers);auto const& response_headers = *response_headers_without_connection_specific_fields;@@ -184,6 +231,9 @@ void MemoryCache::abandon_entry(URL::URL const& url, StringView method, HeaderLiif (take_pending_entry(cache_key, vary_key).has_value())dbgln_if(HTTP_MEMORY_CACHE_DEBUG, "\033[37m[memory]\033[0m \033[33;1mAbandoned cache entry for\033[0m {}", url);++ if (stored_response == StoredResponse::Retire)+ remove_complete_entries(cache_key, [&](auto const& entry) { return entry_matches_request(request_headers, entry); });}Optional<MemoryCache::Entry> MemoryCache::take_pending_entry(u64 cache_key, Optional<u64> vary_key)@@ -216,9 +266,41 @@ void MemoryCache::invalidate(URL::URL const& url)auto cache_key = create_cache_key(serialized_url, method);dbgln_if(HTTP_MEMORY_CACHE_DEBUG, "\033[37m[memory]\033[0m \033[33;1mInvalidated cache entries for\033[0m {} {}", method, url);- m_complete_entries.remove(cache_key);+ remove_complete_entries(cache_key, [](auto const&) { return true; });m_pending_entries.remove(cache_key);}}+void MemoryCache::remove_complete_entries(u64 cache_key, Function<bool(Entry const&)> const& predicate)+{+ auto cache_entries = m_complete_entries.get(cache_key);+ if (!cache_entries.has_value())+ return;++ cache_entries->remove_all_matching([&](auto const& entry) {+ if (!predicate(entry))+ return false;+ remove_from_usage(entry);+ return true;+ });+ if (cache_entries->is_empty())+ m_complete_entries.remove(cache_key);+}++Vector<MemoryCache::EntryUse> MemoryCache::complete_entry_uses() const+{+ Vector<EntryUse> uses;+ for (auto const& [cache_key, cache_entries] : m_complete_entries) {+ for (auto const& entry : cache_entries)+ uses.append({ .cache_key = cache_key, .vary_key = entry.vary_key, .body_is_mapped = entry.body_is_mapped, .last_use = entry.last_use });+ }+ return uses;+}++void MemoryCache::evict_complete_entry(u64 cache_key, u64 vary_key)+{+ dbgln_if(HTTP_MEMORY_CACHE_DEBUG, "\033[37m[memory]\033[0m \033[33;1mEvicted cache entry\033[0m {}", cache_key);+ remove_complete_entries(cache_key, [&](auto const& entry) { return entry.vary_key == vary_key; });+}+}diff --git a/Libraries/LibHTTP/Cache/MemoryCache.h b/Libraries/LibHTTP/Cache/MemoryCache.hindex 6fe3e7fcd3a..ae67b1e36a4 100644--- a/Libraries/LibHTTP/Cache/MemoryCache.h+++ b/Libraries/LibHTTP/Cache/MemoryCache.h@@ -7,10 +7,12 @@#pragma once#include <AK/ByteString.h>+#include <AK/Function.h>#include <AK/HashMap.h>#include <AK/NonnullRefPtr.h>#include <AK/RefCounted.h>#include <AK/Time.h>+#include <AK/Vector.h>#include <LibCore/ImmutableBytes.h>#include <LibHTTP/Cache/CacheMode.h>#include <LibHTTP/Forward.h>@@ -18,6 +20,14 @@namespace HTTP {+// What the complete entries of a group of caches hold together.+struct MemoryCacheUsage : public RefCounted<MemoryCacheUsage> {+ // The memory the entries take up, including the response bodies that are not mapped files.+ size_t bytes_in_memory { 0 };+ // The response bodies that are mapped files, whose pages the kernel can drop and read again.+ size_t mapped_bodies { 0 };+};+class MemoryCache : public RefCounted<MemoryCache> {public:struct Entry {@@ -30,30 +40,52 @@ public:UnixDateTime request_time;UnixDateTime response_time;++ // Set when the entry is complete.+ size_t bytes_in_memory { 0 };+ bool body_is_mapped { false };+ u64 last_use { 0 };};- static NonnullRefPtr<MemoryCache> create();+ static NonnullRefPtr<MemoryCache> create(NonnullRefPtr<MemoryCacheUsage> = adopt_ref(*new MemoryCacheUsage));+ ~MemoryCache();Optional<Entry const&> open_entry(URL::URL const&, StringView method, HeaderList const& request_headers, CacheMode);void create_entry(URL::URL const&, StringView method, HeaderList const& request_headers, UnixDateTime request_time, u32 status_code, ByteString reason_phrase, HeaderList const& response_headers);- // Returns whether the response was stored.- bool finalize_entry(URL::URL const&, StringView method, HeaderList const& request_headers, u32 status_code, HeaderList const& response_headers, Core::ImmutableBytes response_body);+ void finalize_entry(URL::URL const&, StringView method, HeaderList const& request_headers, u32 status_code, HeaderList const& response_headers, Core::ImmutableBytes response_body);// Drops the oldest pending entry with the request's cache and vary keys, for a response whose body will not be- // finalized.- void abandon_entry(URL::URL const&, StringView method, HeaderList const& request_headers, HeaderList const& response_headers);+ // finalized. A response that is not stored can still be meant to replace the stored one.+ enum class StoredResponse : u8 {+ Keep,+ Retire,+ };+ void abandon_entry(URL::URL const&, StringView method, HeaderList const& request_headers, HeaderList const& response_headers, StoredResponse);void invalidate(URL::URL const&);- // Removes the complete entries, and keeps the pending ones for the responses that are still arriving.- void clear_complete_entries() { m_complete_entries.clear(); }- bool has_pending_entries() const { return !m_pending_entries.is_empty(); }+ bool is_empty() const { return m_complete_entries.is_empty() && m_pending_entries.is_empty(); }++ struct EntryUse {+ u64 cache_key { 0 };+ u64 vary_key { 0 };+ bool body_is_mapped { false };+ u64 last_use { 0 };+ };+ Vector<EntryUse> complete_entry_uses() const;+ void evict_complete_entry(u64 cache_key, u64 vary_key);private:+ explicit MemoryCache(NonnullRefPtr<MemoryCacheUsage>);++ void add_to_usage(Entry const&);+ void remove_from_usage(Entry const&);Optional<Entry> take_pending_entry(u64 cache_key, Optional<u64> vary_key);+ void remove_complete_entries(u64 cache_key, Function<bool(Entry const&)> const& predicate);HashMap<u64, Vector<Entry>, IdentityHashTraits<u64>> m_pending_entries;HashMap<u64, Vector<Entry>, IdentityHashTraits<u64>> m_complete_entries;+ NonnullRefPtr<MemoryCacheUsage> m_usage;};}diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex 7288b59da78..8534156a56c 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -11,6 +11,7 @@#include <AK/Base64.h>#include <AK/Debug.h>+#include <AK/QuickSort.h>#include <AK/ScopeGuard.h>#include <AK/kmalloc.h>#include <LibGC/Heap.h>@@ -186,8 +187,10 @@ public:HTTP::MemoryCache& get(Utf16String const& key){- return *m_cache.ensure(key, [] {- return HTTP::MemoryCache::create();+ return *m_cache.ensure(key, [this] {+ if (!m_usage)+ m_usage = adopt_ref(*new HTTP::MemoryCacheUsage);+ return HTTP::MemoryCache::create(*m_usage);});}@@ -209,37 +212,58 @@ public:void clear_cache(){m_cache.clear();- m_responses_stored_since_clear = 0;- m_bytes_in_memory_stored_since_clear = 0;+ // NB: A fetch that is still running may hold a partition that is now gone, which must not count towards the+ // limits of the partitions that replace it. This allocates nothing, as the cache of an agent that shuts+ // down is never destroyed.+ m_usage = nullptr;}- // Drops the stored responses once there may be more than a limit, as the cache otherwise keeps every response for- // a URL that is not fetched again for as long as the agent lives. A response body that is a mapped file costs a- // mapping, and others cost their size in memory.- void did_store_response(Core::ImmutableBytes const& body)+ static bool can_hold_body_in_memory(size_t size) { return size <= largest_body_in_memory; }++ // Evicts the least recently used responses of all partitions, once they hold more than a limit, down to three+ // quarters of it. A response for a URL that is not fetched again would otherwise stay for as long as the agent does.+ // NB: A response body that is a mapped file costs a mapping, while the kernel can drop its pages and read them again,+ // so those are limited by count. The memory of all else, which every entry has some of, is limited by size.+ void evict_until_within_limits(){- ++m_responses_stored_since_clear;- if (!body.is_file_backed() && !body.is_readonly_mapped())- m_bytes_in_memory_stored_since_clear += body.size();- if (m_responses_stored_since_clear <= stored_response_limit && m_bytes_in_memory_stored_since_clear <= stored_bytes_in_memory_limit)+ if (!m_usage)+ return;+ bool too_many_bytes = m_usage->bytes_in_memory > bytes_in_memory_limit;+ bool too_many_mapped_bodies = m_usage->mapped_bodies > mapped_body_limit;+ if (!too_many_bytes && !too_many_mapped_bodies)return;- // NB: A fetch that is still running holds its partition and has a pending entry in it, which must stay the- // partition for its key.- for (auto& it : m_cache)- it.value->clear_complete_entries();- m_cache.remove_all_matching([](auto const&, auto const& cache) { return !cache->has_pending_entries() && cache->ref_count() == 1; });- m_responses_stored_since_clear = 0;- m_bytes_in_memory_stored_since_clear = 0;+ struct Candidate {+ HTTP::MemoryCache* cache { nullptr };+ HTTP::MemoryCache::EntryUse use;+ };+ Vector<Candidate> candidates;+ for (auto const& it : m_cache) {+ for (auto const& use : it.value->complete_entry_uses())+ candidates.append({ .cache = it.value.ptr(), .use = use });+ }+ quick_sort(candidates, [](auto const& a, auto const& b) { return a.use.last_use < b.use.last_use; });++ for (auto const& candidate : candidates) {+ too_many_bytes = too_many_bytes && m_usage->bytes_in_memory > bytes_in_memory_limit / 4 * 3;+ too_many_mapped_bodies = too_many_mapped_bodies && m_usage->mapped_bodies > mapped_body_limit / 4 * 3;+ if (!too_many_bytes && !too_many_mapped_bodies)+ break;+ if (too_many_bytes || (candidate.use.body_is_mapped && too_many_mapped_bodies))+ candidate.cache->evict_complete_entry(candidate.use.cache_key, candidate.use.vary_key);+ }++ // NB: A fetch that is still running may hold a partition, which must then stay the one for its key.+ m_cache.remove_all_matching([](auto const&, auto const& cache) { return cache->is_empty() && cache->ref_count() == 1; });}private:- static constexpr size_t stored_response_limit = 1024;- static constexpr size_t stored_bytes_in_memory_limit = 32 * MiB;+ static constexpr size_t bytes_in_memory_limit = 16 * MiB;+ static constexpr size_t largest_body_in_memory = bytes_in_memory_limit / 4;+ static constexpr size_t mapped_body_limit = 1024;+ RefPtr<HTTP::MemoryCacheUsage> m_usage;HashMap<Utf16String, NonnullRefPtr<HTTP::MemoryCache>> m_cache;- size_t m_responses_stored_since_clear { 0 };- size_t m_bytes_in_memory_stored_since_clear { 0 };};Optional<Utf16String> http_cache_partition(Infrastructure::Request const& request)@@ -3025,7 +3049,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(delivery_gate->attach_transport(*network_transport);network_transport->set_on_teardown([delivery_gate, channel, body_pump = GC::Root { body_pump }](Requests::Request::TeardownReason reason) {tear_down_network_body(*delivery_gate, *channel, reason);- body_pump->abandon_cache_entry();+ body_pump->abandon_cache_entry(HTTP::MemoryCache::StoredResponse::Keep);});if (request->destination() == Infrastructure::Request::Destination::Font) {network_transport->set_on_requires_network([control_block = NonnullRefPtr { fetch_params.control_block() }] {@@ -3605,9 +3629,14 @@ bool http_memory_cache_enabled()return g_http_memory_cache_enabled;}-void did_store_response_in_http_memory_cache(Core::ImmutableBytes const& body)+bool http_memory_cache_can_hold_body_in_memory(size_t size)+{+ return HTTPCache::can_hold_body_in_memory(size);+}++void evict_http_memory_cache_entries_over_limits(){- HTTPCache::the().did_store_response(body);+ HTTPCache::the().evict_until_within_limits();}void clear_http_memory_cache()diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.h b/Libraries/LibWeb/Fetch/Fetching/Fetching.hindex 4c483d5c1e5..170b281f1dc 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.h+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.h@@ -76,7 +76,8 @@ void append_user_agent_client_hints_for_request(Infrastructure::Request&);WEB_API void set_http_memory_cache_enabled(bool enabled);WEB_API bool http_memory_cache_enabled();WEB_API void clear_http_memory_cache();-void did_store_response_in_http_memory_cache(Core::ImmutableBytes const&);+bool http_memory_cache_can_hold_body_in_memory(size_t);+void evict_http_memory_cache_entries_over_limits();WEB_API Optional<Utf16String> http_cache_partition(Infrastructure::Request const&);WEB_API void set_disk_cache_enabled_for_navigations_for_testing(bool enabled);WEB_API bool disk_cache_enabled_for_navigations_for_testing();diff --git a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cppindex 5085dd52345..a9cd65c5ef9 100644--- a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp@@ -96,10 +96,15 @@ void NetworkBodyPump::handle_network_data(Requests::ResponseData data)m_channel->write_copy(bytes);}- if (m_http_cache && !m_cache_body_replaces_network_buffer) {+ if (m_http_cache && !m_cache_body_replaces_network_buffer && !m_cache_body_too_large_for_memory) {if (file_backed && m_cache_buffer.is_empty()) {if (!m_cache_body.has_value())m_cache_body = file_backed->payload;+ } else if (!http_memory_cache_can_hold_body_in_memory(m_decoded_body_size)) {+ // NB: A mapped file of the whole body may still arrive, which the cache can hold.+ m_cache_body_too_large_for_memory = true;+ m_cache_buffer.clear();+ m_cache_body.clear();} else {if (m_cache_body.has_value()) {m_cache_buffer.append(m_cache_body->bytes());@@ -128,7 +133,7 @@ void NetworkBodyPump::handle_network_error(StringView error_message){if (WebDriver::BiDi::network_events_enabled() && m_fetch_params)WebDriver::BiDi::network_fetch_error(*m_fetch_params, error_message);- abandon_cache_entry();+ abandon_cache_entry(HTTP::MemoryCache::StoredResponse::Keep);m_channel->error({ .message = MUST(ByteBuffer::copy(error_message.bytes())) });}@@ -140,6 +145,7 @@ void NetworkBodyPump::set_cached_response_body(Core::ImmutableBytes body)m_cache_buffer.clear();m_cache_body = move(body);m_cache_body_replaces_network_buffer = true;+ m_cache_body_too_large_for_memory = false;}void NetworkBodyPump::finalize_cache_entry()@@ -148,25 +154,33 @@ void NetworkBodyPump::finalize_cache_entry()return;auto request = m_fetch_params->request();- if (!m_fetch_params->is_canceled() && m_response && request->cache_mode() != HTTP::CacheMode::NoStore) {- auto response_body = m_cache_body.has_value()- ? m_cache_body.release_value()- : Core::ImmutableBytes::adopt(move(m_cache_buffer));- if (m_http_cache->finalize_entry(request->current_url(), request->method(), request->header_list(), m_response->status(), m_response->header_list(), response_body))- did_store_response_in_http_memory_cache(response_body);+ if (m_fetch_params->is_canceled() || !m_response || request->cache_mode() == HTTP::CacheMode::NoStore) {+ abandon_cache_entry(HTTP::MemoryCache::StoredResponse::Keep);+ return;}+ // NB: The cache cannot hold this response, which still replaces the one it has stored.+ if (m_cache_body_too_large_for_memory) {+ abandon_cache_entry(HTTP::MemoryCache::StoredResponse::Retire);+ return;+ }++ auto response_body = m_cache_body.has_value()+ ? m_cache_body.release_value()+ : Core::ImmutableBytes::adopt(move(m_cache_buffer));+ m_http_cache->finalize_entry(request->current_url(), request->method(), request->header_list(), m_response->status(), m_response->header_list(), move(response_body));+ evict_http_memory_cache_entries_over_limits();+m_http_cache.clear();m_cache_body.clear();}-void NetworkBodyPump::abandon_cache_entry()+void NetworkBodyPump::abandon_cache_entry(HTTP::MemoryCache::StoredResponse stored_response){- if (!m_http_cache || !m_fetch_params || !m_response)- return;-- auto request = m_fetch_params->request();- m_http_cache->abandon_entry(request->current_url(), request->method(), request->header_list(), m_response->header_list());+ if (m_http_cache && m_fetch_params && m_response) {+ auto request = m_fetch_params->request();+ m_http_cache->abandon_entry(request->current_url(), request->method(), request->header_list(), m_response->header_list(), stored_response);+ }m_http_cache.clear();m_cache_buffer.clear();diff --git a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.hindex 1b7c477ae5a..1fb2cfbdbe1 100644--- a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h+++ b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.h@@ -11,7 +11,7 @@#include <AK/ByteBuffer.h>#include <LibCore/ImmutableBytes.h>#include <LibGC/CellAllocator.h>-#include <LibHTTP/Forward.h>+#include <LibHTTP/Cache/MemoryCache.h>#include <LibJS/Heap/Cell.h>#include <LibRequests/Request.h>#include <LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h>@@ -38,7 +38,7 @@ public:void set_cached_response_body(Core::ImmutableBytes);// Drops a pending memory-cache entry that matches the response's request, for a body that will not finish arriving.- void abandon_cache_entry();+ void abandon_cache_entry(HTTP::MemoryCache::StoredResponse);private:NetworkBodyPump(RefPtr<Infrastructure::FetchParams const>, NonnullRefPtr<Engine::FetchByteChannel>, NonnullRefPtr<Engine::FetchBodyDeliveryGate>, RefPtr<HTTP::MemoryCache>);@@ -62,6 +62,7 @@ private:ByteBuffer m_cache_buffer;Optional<Core::ImmutableBytes> m_cache_body;bool m_cache_body_replaces_network_buffer { false };+ bool m_cache_body_too_large_for_memory { false };u64 m_encoded_body_size { 0 };u64 m_decoded_body_size { 0 };diff --git a/Tests/LibHTTP/TestMemoryCache.cpp b/Tests/LibHTTP/TestMemoryCache.cppindex ec47e40033c..ce288b3860c 100644--- a/Tests/LibHTTP/TestMemoryCache.cpp+++ b/Tests/LibHTTP/TestMemoryCache.cpp@@ -121,7 +121,7 @@ TEST_CASE(abandoned_response_is_not_stored)auto response_headers = create_cacheable_response_headers();cache->create_entry(url, "GET"sv, *request_headers, UnixDateTime::now(), 200, "OK"sv, *response_headers);- cache->abandon_entry(url, "GET"sv, *request_headers, *response_headers);+ cache->abandon_entry(url, "GET"sv, *request_headers, *response_headers, HTTP::MemoryCache::StoredResponse::Keep);cache->finalize_entry(url, "GET"sv, *request_headers, 200, *response_headers, immutable_bytes("partial"sv));EXPECT(!cache->open_entry(url, "GET"sv, *request_headers, HTTP::CacheMode::Default).has_value());@@ -136,7 +136,7 @@ TEST_CASE(abandoning_a_response_leaves_other_pending_responses)cache->create_entry(url, "GET"sv, *request_headers, UnixDateTime::now(), 200, "OK"sv, *response_headers);cache->create_entry(url, "GET"sv, *request_headers, UnixDateTime::now(), 200, "OK"sv, *response_headers);- cache->abandon_entry(url, "GET"sv, *request_headers, *response_headers);+ cache->abandon_entry(url, "GET"sv, *request_headers, *response_headers, HTTP::MemoryCache::StoredResponse::Keep);cache->finalize_entry(url, "GET"sv, *request_headers, 200, *response_headers, immutable_bytes("complete"sv));auto entry = cache->open_entry(url, "GET"sv, *request_headers, HTTP::CacheMode::Default);@@ -160,7 +160,7 @@ TEST_CASE(abandoning_a_response_matches_its_vary_headers)cache->create_entry(url, "GET"sv, *abandoned_request_headers, UnixDateTime::now(), 200, "OK"sv, *response_headers);cache->create_entry(url, "GET"sv, *completed_request_headers, UnixDateTime::now(), 200, "OK"sv, *response_headers);- cache->abandon_entry(url, "GET"sv, *abandoned_request_headers, *response_headers);+ cache->abandon_entry(url, "GET"sv, *abandoned_request_headers, *response_headers, HTTP::MemoryCache::StoredResponse::Keep);cache->finalize_entry(url, "GET"sv, *abandoned_request_headers, 200, *response_headers, immutable_bytes("partial"sv));cache->finalize_entry(url, "GET"sv, *completed_request_headers, 200, *response_headers, immutable_bytes("complete"sv));