Truly independent web browser
RequestServer+LibHTTP: Remove cache associated data
Andreas Kling5931e4633fa0
diff --git a/Libraries/LibHTTP/Cache/CacheEntry.cpp b/Libraries/LibHTTP/Cache/CacheEntry.cppindex 4a1c9a4386b..e2de8d30815 100644--- a/Libraries/LibHTTP/Cache/CacheEntry.cpp+++ b/Libraries/LibHTTP/Cache/CacheEntry.cpp@@ -89,8 +89,6 @@ void CacheEntry::remove()return;(void)FileSystem::remove(m_path->string(), FileSystem::RecursionMode::Disallowed);- for (auto associated_data : CACHE_ENTRY_ASSOCIATED_DATA_TYPES)- (void)FileSystem::remove(path_for_cache_entry_associated_data(m_disk_cache.cache_directory(), m_cache_key, m_vary_key, associated_data).string(), FileSystem::RecursionMode::Disallowed);m_index.remove_entry(m_cache_key, m_vary_key);}@@ -271,11 +269,6 @@ ErrorOr<void> CacheEntryWriter::flush_impl(NonnullRefPtr<HeaderList> request_heabody_file->size = m_cache_footer.data_size;}- // Drop any sidecars left over from an older entry at the same (cache_key, vary_key). They are tied to the previous- // response body, so reusing them with the freshly written one would mismatch the source they were generated for.- for (auto associated_data : CACHE_ENTRY_ASSOCIATED_DATA_TYPES)- (void)FileSystem::remove(path_for_cache_entry_associated_data(m_disk_cache.cache_directory(), m_cache_key, m_vary_key, associated_data).string(), FileSystem::RecursionMode::Disallowed);-if (auto result = m_index.create_entry(m_cache_key, m_vary_key, m_url, move(request_headers), m_response_headers.release_nonnull(), m_cache_footer.data_size, m_request_time, m_response_time); result.is_error()) {dbgln_if(HTTP_DISK_CACHE_DEBUG, "\033[36m[disk]\033[0m \033[31;1mUnable to flush cache entry for\033[0m {} ({} bytes): {}", m_url, m_cache_footer.data_size, result.error());remove();diff --git a/Libraries/LibHTTP/Cache/CacheEntry.h b/Libraries/LibHTTP/Cache/CacheEntry.hindex 4079cf6c8ac..31bcb08291d 100644--- a/Libraries/LibHTTP/Cache/CacheEntry.h+++ b/Libraries/LibHTTP/Cache/CacheEntry.h@@ -67,7 +67,6 @@ public:virtual ~CacheEntry() = default;u64 cache_key() const { return m_cache_key; }- u64 vary_key() const { return m_vary_key; }u64 body_size() const { return m_cache_footer.data_size; }void remove();diff --git a/Libraries/LibHTTP/Cache/CacheIndex.cpp b/Libraries/LibHTTP/Cache/CacheIndex.cppindex 367e689ab17..6fd0a33ab97 100644--- a/Libraries/LibHTTP/Cache/CacheIndex.cpp+++ b/Libraries/LibHTTP/Cache/CacheIndex.cpp@@ -22,6 +22,7 @@ namespace HTTP {static constexpr u32 INDEX_SCHEMA_BASELINE_VERSION = 1u;static constexpr u32 INDEX_SCHEMA_PARTITIONED_CACHE_KEYS_VERSION = 2u;static constexpr u32 INDEX_SCHEMA_VARY_KEY_VERSION = 3u;+static constexpr u32 INDEX_SCHEMA_RESPONSES_ONLY_VERSION = 4u;// Persist full-range hashes as signed bit patterns; keys are only compared for equality.static i64 encode_cache_key_for_database(u64 key)@@ -71,8 +72,6 @@ static NonnullRefPtr<HeaderList> deserialize_headers(StringView serialized_headestatic void remove_cache_entry_files(LexicalPath const& cache_directory, u64 cache_key, u64 vary_key){(void)FileSystem::remove(path_for_cache_entry(cache_directory, cache_key, vary_key).string(), FileSystem::RecursionMode::Disallowed);- for (auto associated_data : CACHE_ENTRY_ASSOCIATED_DATA_TYPES)- (void)FileSystem::remove(path_for_cache_entry_associated_data(cache_directory, cache_key, vary_key, associated_data).string(), FileSystem::RecursionMode::Disallowed);}template<typename Callback>@@ -173,6 +172,19 @@ ErrorOr<Database::MigrationOutcome> CacheIndex::migrate_schema(Database::Databasreturn {};},},+ {+ // The cache now holds responses only. Stored responses stay valid, but the JavaScript bytecode files beside+ // them, and any such file left half-written, are no longer read or accounted for.+ .version = INDEX_SCHEMA_RESPONSES_ONLY_VERSION,+ .sql = "ALTER TABLE CacheIndex DROP COLUMN associated_data_size;"sv,+ .backfill = [](Database::Database& database) -> ErrorOr<void> {+ for_each_cache_entry_file(database, [](LexicalPath const& cache_entry) {+ if (cache_entry.basename().contains('.'))+ (void)FileSystem::remove(cache_entry.string(), FileSystem::RecursionMode::Disallowed);+ });+ return {};+ },+ },});return database.migrate("CacheIndex"sv, migrations, mode);@@ -185,29 +197,28 @@ ErrorOr<CacheIndex> CacheIndex::create(Database::Database& database, LexicalPath#endifStatements statements {};- statements.insert_entry = TRY(database.prepare_statement("INSERT OR REPLACE INTO CacheIndex (cache_key, vary_key, url, request_headers, response_headers, data_size, associated_data_size, request_time, response_time, last_access_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"sv));+ statements.insert_entry = TRY(database.prepare_statement("INSERT OR REPLACE INTO CacheIndex (cache_key, vary_key, url, request_headers, response_headers, data_size, request_time, response_time, last_access_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);"sv));statements.remove_entry = TRY(database.prepare_statement(R"#(DELETE FROM CacheIndexWHERE cache_key = ? AND vary_key = ?- RETURNING MAX(data_size, 0) + MAX(associated_data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers);+ RETURNING MAX(data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers);)#"sv));statements.remove_entries_accessed_since = TRY(database.prepare_statement(R"#(DELETE FROM CacheIndexWHERE last_access_time >= ?- RETURNING cache_key, vary_key, MAX(data_size, 0) + MAX(associated_data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers);+ RETURNING cache_key, vary_key, MAX(data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers);)#"sv));statements.remove_entries_accessed_before = TRY(database.prepare_statement(R"#(DELETE FROM CacheIndexWHERE last_access_time < ?- RETURNING cache_key, vary_key, MAX(data_size, 0) + MAX(associated_data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers);+ RETURNING cache_key, vary_key, MAX(data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers);)#"sv));statements.remove_all_entries = TRY(database.prepare_statement(R"#(DELETE FROM CacheIndexRETURNING cache_key, vary_key;)#"sv));- statements.select_entries = TRY(database.prepare_statement("SELECT vary_key, url, request_headers, response_headers, data_size, associated_data_size, request_time, response_time, last_access_time FROM CacheIndex WHERE cache_key = ?;"sv));+ statements.select_entries = TRY(database.prepare_statement("SELECT vary_key, url, request_headers, response_headers, data_size, request_time, response_time, last_access_time FROM CacheIndex WHERE cache_key = ?;"sv));statements.update_response_headers = TRY(database.prepare_statement("UPDATE CacheIndex SET response_headers = ?, last_access_time = ? WHERE cache_key = ? AND vary_key = ?;"sv));- statements.update_associated_data_size = TRY(database.prepare_statement("UPDATE CacheIndex SET associated_data_size = ? WHERE cache_key = ? AND vary_key = ?;"sv));statements.update_last_access_time = TRY(database.prepare_statement("UPDATE CacheIndex SET last_access_time = ? WHERE cache_key = ? AND vary_key = ?;"sv));statements.remove_entries_exceeding_cache_limit = TRY(database.prepare_statement(R"#(@@ -215,7 +226,7 @@ ErrorOr<CacheIndex> CacheIndex::create(Database::Database& database, LexicalPathSELECTcache_key,vary_key,- SUM(MAX(data_size, 0) + MAX(associated_data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers))+ SUM(MAX(data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers))OVER (ORDER BY last_access_time DESC)AS cumulative_estimated_sizeFROM CacheIndex@@ -226,22 +237,22 @@ ErrorOr<CacheIndex> CacheIndex::create(Database::Database& database, LexicalPathFROM RankedCacheIndexWHERE cumulative_estimated_size > ?)- RETURNING cache_key, vary_key, MAX(data_size, 0) + MAX(associated_data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers);+ RETURNING cache_key, vary_key, MAX(data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers);)#"sv));statements.estimate_cache_size_accessed_since = TRY(database.prepare_statement(R"#(- SELECT COALESCE(SUM(MAX(data_size, 0) + MAX(associated_data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers)), 0)+ SELECT COALESCE(SUM(MAX(data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers)), 0)FROM CacheIndexWHERE last_access_time >= ?;)#"sv));statements.select_total_estimated_size = TRY(database.prepare_statement(R"#(- SELECT COALESCE(SUM(MAX(data_size, 0) + MAX(associated_data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers)), 0)+ SELECT COALESCE(SUM(MAX(data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers)), 0)FROM CacheIndex;)#"sv));statements.select_access_profile = TRY(database.prepare_statement(R"#(- SELECT last_access_time / ?1 * ?1 AS bucket, SUM(MAX(data_size, 0) + MAX(associated_data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers))+ SELECT last_access_time / ?1 * ?1 AS bucket, SUM(MAX(data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers))FROM CacheIndexGROUP BY bucketORDER BY bucket DESC;@@ -260,9 +271,8 @@ ErrorOr<CacheIndex> CacheIndex::create(Database::Database& database, LexicalPathDELETE FROM CacheIndexWHERE typeof(cache_key) != 'integer' OR typeof(vary_key) != 'integer' OR typeof(url) != 'text'OR typeof(request_headers) != 'blob' OR typeof(response_headers) != 'blob'- OR typeof(data_size) != 'integer' OR typeof(associated_data_size) != 'integer'- OR typeof(request_time) != 'integer' OR typeof(response_time) != 'integer' OR typeof(last_access_time) != 'integer'- OR data_size NOT BETWEEN 0 AND ?1 OR associated_data_size NOT BETWEEN 0 AND ?1+ OR typeof(data_size) != 'integer' OR typeof(request_time) != 'integer' OR typeof(response_time) != 'integer' OR typeof(last_access_time) != 'integer'+ OR data_size NOT BETWEEN 0 AND ?1RETURNING cache_key, vary_key;)#"sv));@@ -324,7 +334,6 @@ ErrorOr<void> CacheIndex::create_entry(u64 cache_key, u64 vary_key, String url,.request_headers = move(request_headers),.response_headers = move(response_headers),.data_size = data_size,- .associated_data_size = 0,.serialized_request_headers_size = static_cast<u64>(serialized_request_headers.length()),.serialized_response_headers_size = static_cast<u64>(serialized_response_headers.length()),.request_time = request_time,@@ -332,7 +341,6 @@ ErrorOr<void> CacheIndex::create_entry(u64 cache_key, u64 vary_key, String url,.last_access_time = now,};Checked<u64> checked_entry_size = entry.data_size;- checked_entry_size += entry.associated_data_size;checked_entry_size += entry.serialized_request_headers_size;checked_entry_size += entry.serialized_response_headers_size;@@ -355,7 +363,7 @@ ErrorOr<void> CacheIndex::create_entry(u64 cache_key, u64 vary_key, String url,return existing_entry.vary_key == vary_key;});- if (auto result = m_database->try_execute_statement(m_statements.insert_entry, {}, encode_cache_key_for_database(cache_key), encode_cache_key_for_database(vary_key), entry.url, serialized_request_headers, serialized_response_headers, static_cast<i64>(entry.data_size), static_cast<i64>(entry.associated_data_size), entry.request_time, entry.response_time, entry.last_access_time); result.is_error()) {+ if (auto result = m_database->try_execute_statement(m_statements.insert_entry, {}, encode_cache_key_for_database(cache_key), encode_cache_key_for_database(vary_key), entry.url, serialized_request_headers, serialized_response_headers, static_cast<i64>(entry.data_size), entry.request_time, entry.response_time, entry.last_access_time); result.is_error()) {// The row of the entry this one replaces is gone already, so the index no longer holds that entry either.delete_entry(cache_key, vary_key);return result.release_error();@@ -525,7 +533,6 @@ ErrorOr<void> CacheIndex::update_response_headers(u64 cache_key, u64 vary_key, Nauto serialized_response_headers_size = static_cast<u64>(serialized_response_headers.length());Checked<u64> checked_entry_size = entry->data_size;- checked_entry_size += entry->associated_data_size;checked_entry_size += entry->serialized_request_headers_size;checked_entry_size += serialized_response_headers_size;@@ -544,23 +551,6 @@ ErrorOr<void> CacheIndex::update_response_headers(u64 cache_key, u64 vary_key, Nreturn {};}-ErrorOr<void> CacheIndex::update_associated_data_size(u64 cache_key, u64 vary_key, u64 associated_data_size)-{- auto entry = get_entry(cache_key, vary_key);- if (!entry.has_value())- return {};-- if (associated_data_size > static_cast<u64>(NumericLimits<i64>::max()))- return Error::from_string_literal("Associated data size exceeds the representable maximum");-- TRY(m_database->try_execute_statement(m_statements.update_associated_data_size, {}, static_cast<i64>(associated_data_size), encode_cache_key_for_database(cache_key), encode_cache_key_for_database(vary_key)));-- adjust_total_estimated_size(-static_cast<i64>(entry->associated_data_size));- adjust_total_estimated_size(static_cast<i64>(associated_data_size));- entry->associated_data_size = associated_data_size;- return {};-}-void CacheIndex::update_last_access_time(u64 cache_key, u64 vary_key){auto entry = get_entry(cache_key, vary_key);@@ -613,15 +603,14 @@ Vector<CacheIndex::Entry>& CacheIndex::entries_for_cache_key(u64 cache_key)auto request_headers = m_database->result_column<ByteString>(statement_id, column++);auto response_headers = m_database->result_column<ByteString>(statement_id, column++);auto data_size = m_database->result_column<i64>(statement_id, column++);- auto associated_data_size = m_database->result_column<i64>(statement_id, column++);auto request_time = m_database->result_column<UnixDateTime>(statement_id, column++);auto response_time = m_database->result_column<UnixDateTime>(statement_id, column++);auto last_access_time = m_database->result_column<UnixDateTime>(statement_id, column++);- if (data_size < 0 || associated_data_size < 0)+ if (data_size < 0)return {};- entries.empend(vary_key, move(url), deserialize_headers(request_headers), deserialize_headers(response_headers), static_cast<u64>(data_size), static_cast<u64>(associated_data_size), request_headers.length(), response_headers.length(), request_time, response_time, last_access_time);+ entries.empend(vary_key, move(url), deserialize_headers(request_headers), deserialize_headers(response_headers), static_cast<u64>(data_size), request_headers.length(), response_headers.length(), request_time, response_time, last_access_time);return {};},encode_cache_key_for_database(cache_key));diff --git a/Libraries/LibHTTP/Cache/CacheIndex.h b/Libraries/LibHTTP/Cache/CacheIndex.hindex ebb3c68a119..3be0939f5bc 100644--- a/Libraries/LibHTTP/Cache/CacheIndex.h+++ b/Libraries/LibHTTP/Cache/CacheIndex.h@@ -27,7 +27,6 @@ class CacheIndex {NonnullRefPtr<HeaderList> request_headers;NonnullRefPtr<HeaderList> response_headers;u64 data_size { 0 };- u64 associated_data_size { 0 };u64 serialized_request_headers_size { 0 };u64 serialized_response_headers_size { 0 };@@ -37,7 +36,7 @@ class CacheIndex {u64 estimated_size() const{- return data_size + associated_data_size + serialized_request_headers_size + serialized_response_headers_size;+ return data_size + serialized_request_headers_size + serialized_response_headers_size;}};@@ -58,7 +57,6 @@ public:bool has_entry(u64 cache_key, u64 vary_key);ErrorOr<void> update_response_headers(u64 cache_key, u64 vary_key, NonnullRefPtr<HeaderList>);- ErrorOr<void> update_associated_data_size(u64 cache_key, u64 vary_key, u64 associated_data_size);void update_last_access_time(u64 cache_key, u64 vary_key);Requests::CacheSizes estimate_cache_size_accessed_since(UnixDateTime since);@@ -80,7 +78,6 @@ private:Database::StatementID remove_all_entries { 0 };Database::StatementID select_entries { 0 };Database::StatementID update_response_headers { 0 };- Database::StatementID update_associated_data_size { 0 };Database::StatementID update_last_access_time { 0 };Database::StatementID estimate_cache_size_accessed_since { 0 };Database::StatementID select_total_estimated_size { 0 };diff --git a/Libraries/LibHTTP/Cache/DiskCache.cpp b/Libraries/LibHTTP/Cache/DiskCache.cppindex fe12432f80d..ed83567ea2a 100644--- a/Libraries/LibHTTP/Cache/DiskCache.cpp+++ b/Libraries/LibHTTP/Cache/DiskCache.cpp@@ -4,14 +4,10 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/Checked.h>#include <AK/Debug.h>-#include <AK/ScopeGuard.h>#include <AK/Utf16String.h>#include <LibCore/Directory.h>#include <LibCore/EventLoop.h>-#include <LibCore/File.h>-#include <LibCore/System.h>#include <LibFileSystem/FileSystem.h>#include <LibHTTP/Cache/CacheRequest.h>#include <LibHTTP/Cache/DiskCache.h>@@ -22,28 +18,6 @@ namespace HTTP {static constexpr auto INDEX_DATABASE = "INDEX"sv;-static ErrorOr<u64> compute_associated_data_size(LexicalPath const& cache_directory, u64 cache_key, u64 vary_key)-{- Checked<u64> associated_data_size = 0;- for (auto associated_data : CACHE_ENTRY_ASSOCIATED_DATA_TYPES) {- auto path = path_for_cache_entry_associated_data(cache_directory, cache_key, vary_key, associated_data);- auto size = FileSystem::size_from_stat(path.string());- if (size.is_error()) {- if (size.error().is_errno() && size.error().code() == ENOENT)- continue;- return size.release_error();- }-- if (size.value() < 0)- return Error::from_errno(EINVAL);- associated_data_size += static_cast<u64>(size.value());- }-- if (associated_data_size.has_overflow())- return Error::from_errno(EOVERFLOW);- return associated_data_size.value();-}-static constexpr StringView cache_directory_for_mode(DiskCache::Mode mode){switch (mode) {@@ -246,136 +220,6 @@ Variant<Optional<CacheEntryReader&>, DiskCache::CacheHasOpenEntry> DiskCache::opreturn Optional<CacheEntryReader&> { *cache_entry_pointer };}-ErrorOr<bool> DiskCache::create_synthetic_entry(Utf16String const& partition, URL::URL const& url, StringView method)-{- auto request_headers = HeaderList::create();- if (!is_cacheable(method, *request_headers))- return false;-- auto serialized_url = serialize_url_for_cache_storage(url);- auto cache_key = create_cache_key(partition, serialized_url, method);- constexpr u64 synthetic_vary_key = 0;-- if (m_index.has_entry(cache_key, synthetic_vary_key))- return true;-- auto response_headers = HeaderList::create();- auto now = UnixDateTime::now();- TRY(m_index.create_entry(cache_key, synthetic_vary_key, serialized_url, request_headers, response_headers, 0, now, now));-- // Include associated data already on disk in the size limit.- TRY(count_associated_data_or_remove_entry(cache_key, synthetic_vary_key));- remove_entries_exceeding_cache_limit();- return m_index.has_entry(cache_key, synthetic_vary_key);-}--// The associated data file at path, opened for reading, or nothing when there is no such file. The caller owns the fd.-static ErrorOr<Optional<CacheEntryBodyFile>> open_associated_data_file(LexicalPath const& path)-{- auto file = Core::File::open(path.string(), Core::File::OpenMode::Read);- if (file.is_error()) {- if (file.error().is_errno() && file.error().code() == ENOENT)- return Optional<CacheEntryBodyFile> {};- return file.release_error();- }-- auto size = TRY(file.value()->size());- if (!AK::is_within_range<u64>(size))- return Error::from_errno(EOVERFLOW);-- return CacheEntryBodyFile {- .fd = file.value()->leak_fd(),- .offset = 0,- .size = static_cast<u64>(size),- };-}--ErrorOr<Optional<CacheEntryBodyFile>> DiskCache::store_associated_data(Utf16String const& partition, URL::URL const& url, StringView method, HeaderList const& request_headers, Optional<u64> vary_key, CacheEntryAssociatedData associated_data, ReadonlyBytes data)-{- if (!is_cacheable(method, request_headers))- return Optional<CacheEntryBodyFile> {};-- auto serialized_url = serialize_url_for_cache_storage(url);- auto cache_key = create_cache_key(partition, serialized_url, method);- if (!vary_key.has_value()) {- auto index_entry = m_index.find_entry(cache_key, request_headers);- if (!index_entry.has_value())- return Optional<CacheEntryBodyFile> {};- vary_key = index_entry->vary_key;- }-- if (!m_index.has_entry(cache_key, *vary_key))- return Optional<CacheEntryBodyFile> {};-- auto path = path_for_cache_entry_associated_data(m_cache_directory, cache_key, *vary_key, associated_data);- auto temporary_path = LexicalPath::join(m_cache_directory.string(), ByteString::formatted("{}.tmp", path.basename()));- ArmedScopeGuard remove_temporary_file = [&]() {- (void)FileSystem::remove(temporary_path.string(), FileSystem::RecursionMode::Disallowed);- };-- {- auto file = TRY(Core::File::open(temporary_path.string(), Core::File::OpenMode::Write));- TRY(file->write_until_depleted(data));- }-- TRY(FileSystem::move_file(path.string(), temporary_path.string()));- remove_temporary_file.disarm();- TRY(count_associated_data_or_remove_entry(cache_key, *vary_key));- remove_entries_exceeding_cache_limit();- if (!m_index.has_entry(cache_key, *vary_key))- return Optional<CacheEntryBodyFile> {};- return open_associated_data_file(path);-}--ErrorOr<Optional<ByteBuffer>> DiskCache::retrieve_associated_data(Utf16String const& partition, URL::URL const& url, StringView method, HeaderList const& request_headers, Optional<u64> vary_key, CacheEntryAssociatedData associated_data)-{- if (!is_cacheable(method, request_headers))- return Optional<ByteBuffer> {};-- auto serialized_url = serialize_url_for_cache_storage(url);- auto cache_key = create_cache_key(partition, serialized_url, method);- if (!vary_key.has_value()) {- auto index_entry = m_index.find_entry(cache_key, request_headers);- if (!index_entry.has_value())- return Optional<ByteBuffer> {};- vary_key = index_entry->vary_key;- }-- if (!m_index.has_entry(cache_key, *vary_key))- return Optional<ByteBuffer> {};-- auto path = path_for_cache_entry_associated_data(m_cache_directory, cache_key, *vary_key, associated_data);- auto file = Core::File::open(path.string(), Core::File::OpenMode::Read);- if (file.is_error()) {- if (file.error().is_errno() && file.error().code() == ENOENT)- return Optional<ByteBuffer> {};- return file.release_error();- }-- return TRY(file.value()->read_until_eof());-}--ErrorOr<Optional<CacheEntryBodyFile>> DiskCache::retrieve_associated_data_file(Utf16String const& partition, URL::URL const& url, StringView method, HeaderList const& request_headers, Optional<u64> vary_key, CacheEntryAssociatedData associated_data)-{- if (!is_cacheable(method, request_headers))- return Optional<CacheEntryBodyFile> {};-- auto serialized_url = serialize_url_for_cache_storage(url);- auto cache_key = create_cache_key(partition, serialized_url, method);- if (!vary_key.has_value()) {- auto index_entry = m_index.find_entry(cache_key, request_headers);- if (!index_entry.has_value())- return Optional<CacheEntryBodyFile> {};- vary_key = index_entry->vary_key;- }-- if (!m_index.has_entry(cache_key, *vary_key))- return Optional<CacheEntryBodyFile> {};-- auto path = path_for_cache_entry_associated_data(m_cache_directory, cache_key, *vary_key, associated_data);- return open_associated_data_file(path);-}-bool DiskCache::check_if_cache_has_open_entry(CacheRequest& request, u64 cache_key, URL::URL const& url, CheckReaderEntries check_reader_entries){// FIXME: We purposefully do not use the vary key here, as we do not yet have it when creating a CacheEntryWriter@@ -548,21 +392,6 @@ void DiskCache::close_entry(CacheEntry const& cache_entry)}}-// Counts the associated data on disk for an entry toward the size limit. An entry whose files the index can't count-// would escape that limit, so when counting fails, the entry leaves the index, and its files are deleted.-ErrorOr<void> DiskCache::count_associated_data_or_remove_entry(u64 cache_key, u64 vary_key)-{- auto result = [&]() -> ErrorOr<void> {- auto associated_data_size = TRY(compute_associated_data_size(m_cache_directory, cache_key, vary_key));- return m_index.update_associated_data_size(cache_key, vary_key, associated_data_size);- }();- if (result.is_error()) {- m_index.remove_entry(cache_key, vary_key);- delete_entry(cache_key, vary_key);- }- return result;-}-void DiskCache::delete_entry(u64 cache_key, u64 vary_key){if (auto open_entries = m_open_cache_entries.get(cache_key); open_entries.has_value()) {@@ -577,8 +406,6 @@ void DiskCache::remove_entry_files(u64 cache_key, u64 vary_key){auto cache_path = path_for_cache_entry(m_cache_directory, cache_key, vary_key);(void)FileSystem::remove(cache_path.string(), FileSystem::RecursionMode::Disallowed);- for (auto associated_data : CACHE_ENTRY_ASSOCIATED_DATA_TYPES)- (void)FileSystem::remove(path_for_cache_entry_associated_data(m_cache_directory, cache_key, vary_key, associated_data).string(), FileSystem::RecursionMode::Disallowed);}}diff --git a/Libraries/LibHTTP/Cache/DiskCache.h b/Libraries/LibHTTP/Cache/DiskCache.hindex e95364c1d5c..7f493e39cfc 100644--- a/Libraries/LibHTTP/Cache/DiskCache.h+++ b/Libraries/LibHTTP/Cache/DiskCache.h@@ -6,7 +6,6 @@#pragma once-#include <AK/ByteBuffer.h>#include <AK/Error.h>#include <AK/LexicalPath.h>#include <AK/Optional.h>@@ -53,13 +52,6 @@ public:};Variant<Optional<CacheEntryReader&>, CacheHasOpenEntry> open_entry(CacheRequest&, Utf16String const& partition, URL::URL const&, StringView method, HeaderList const& request_headers, CacheMode, OpenMode);- ErrorOr<Optional<CacheEntryBodyFile>> store_associated_data(Utf16String const& partition, URL::URL const&, StringView method, HeaderList const& request_headers, Optional<u64> vary_key, CacheEntryAssociatedData, ReadonlyBytes);- ErrorOr<Optional<ByteBuffer>> retrieve_associated_data(Utf16String const& partition, URL::URL const&, StringView method, HeaderList const& request_headers, Optional<u64> vary_key, CacheEntryAssociatedData);- ErrorOr<Optional<CacheEntryBodyFile>> retrieve_associated_data_file(Utf16String const& partition, URL::URL const&, StringView method, HeaderList const& request_headers, Optional<u64> vary_key, CacheEntryAssociatedData);-- // Ensure an index row exists for url+method so the shelf has something to attach to even if there are no real HTTP requests in flight.- ErrorOr<bool> create_synthetic_entry(Utf16String const& partition, URL::URL const&, StringView method);-void remove_entries_exceeding_cache_limit();void remove_variants_exceeding_limit(Badge<CacheEntryWriter>, u64 cache_key, u64 vary_key_to_keep);void set_maximum_disk_cache_size(u64 maximum_disk_cache_size);@@ -96,7 +88,6 @@ private:bool check_if_cache_has_open_entry(CacheRequest&, u64 cache_key, URL::URL const&, CheckReaderEntries);void close_entry(CacheEntry const&);- ErrorOr<void> count_associated_data_or_remove_entry(u64 cache_key, u64 vary_key);void delete_entry(u64 cache_key, u64 vary_key);void remove_entry_files(u64 cache_key, u64 vary_key);diff --git a/Libraries/LibHTTP/Cache/Utilities.cpp b/Libraries/LibHTTP/Cache/Utilities.cppindex 5accde76b49..c3b144ab70c 100644--- a/Libraries/LibHTTP/Cache/Utilities.cpp+++ b/Libraries/LibHTTP/Cache/Utilities.cpp@@ -5,6 +5,7 @@*/#include <AK/AllOf.h>+#include <AK/Array.h>#include <AK/CharacterTypes.h>#include <AK/GenericLexer.h>#include <AK/NumericLimits.h>@@ -222,36 +223,11 @@ LexicalPath path_for_cache_entry(LexicalPath const& cache_directory, u64 cache_kreturn cache_directory.append(file);}-static constexpr StringView cache_entry_associated_data_suffix(CacheEntryAssociatedData associated_data)-{- switch (associated_data) {- case CacheEntryAssociatedData::JavaScriptBytecode:- return "jsbc"sv;- }- VERIFY_NOT_REACHED();-}--static constexpr Optional<CacheEntryAssociatedData> cache_entry_associated_data_from_suffix(StringView suffix)-{- if (suffix == "jsbc"sv)- return CacheEntryAssociatedData::JavaScriptBytecode;- return {};-}--LexicalPath path_for_cache_entry_associated_data(LexicalPath const& cache_directory, u64 cache_key, u64 vary_key, CacheEntryAssociatedData associated_data)-{- auto file = vary_key == 0- ? ByteString::formatted("{:016x}.{}", cache_key, cache_entry_associated_data_suffix(associated_data))- : ByteString::formatted("{:016x}_{:016x}.{}", cache_key, vary_key, cache_entry_associated_data_suffix(associated_data));-- return cache_directory.append(file);-}-Optional<CacheEntryData> cache_entry_data_for_file(LexicalPath const& cache_file){CacheEntryData result;- if (auto file_name = cache_file.basename(LexicalPath::StripExtension::Yes); file_name.contains('_')) {+ if (auto file_name = cache_file.basename(); file_name.contains('_')) {auto parts = file_name.split_view('_', SplitBehavior::KeepEmpty);if (parts.size() != 2)return {};@@ -271,12 +247,6 @@ Optional<CacheEntryData> cache_entry_data_for_file(LexicalPath const& cache_fileresult.cache_key = *cache_key;}- if (auto extension = cache_file.extension(); !extension.is_empty()) {- result.associated_data = cache_entry_associated_data_from_suffix(extension);- if (!result.associated_data.has_value())- return {};- }-return result;}diff --git a/Libraries/LibHTTP/Cache/Utilities.h b/Libraries/LibHTTP/Cache/Utilities.hindex 673b386f187..b4818fb88c2 100644--- a/Libraries/LibHTTP/Cache/Utilities.h+++ b/Libraries/LibHTTP/Cache/Utilities.h@@ -6,7 +6,6 @@#pragma once-#include <AK/Array.h>#include <AK/LexicalPath.h>#include <AK/StringView.h>#include <AK/Time.h>@@ -27,13 +26,6 @@ constexpr inline u64 DEFAULT_MAXIMUM_DISK_CACHE_SIZE = 5 * GiB;constexpr inline size_t MAXIMUM_VARY_FIELD_COUNT = 32;constexpr inline size_t MAXIMUM_CACHE_ENTRY_VARIANT_COUNT = 16;-enum class CacheEntryAssociatedData {- JavaScriptBytecode,-};-constexpr inline Array CACHE_ENTRY_ASSOCIATED_DATA_TYPES {- CacheEntryAssociatedData::JavaScriptBytecode,-};-i64 compute_maximum_disk_cache_size(u64 free_bytes, u64 limit_maximum_disk_cache_size = DEFAULT_MAXIMUM_DISK_CACHE_SIZE);i64 compute_maximum_disk_cache_entry_size(i64 maximum_disk_cache_size);@@ -45,12 +37,10 @@ u64 create_cache_key(StringView url, StringView method);Optional<Vector<ByteString>> vary_field_names(HeaderList const& response_headers);Optional<u64> create_vary_key(HeaderList const& request_headers, HeaderList const& response_headers);LexicalPath path_for_cache_entry(LexicalPath const& cache_directory, u64 cache_key, u64 vary_key);-LexicalPath path_for_cache_entry_associated_data(LexicalPath const& cache_directory, u64 cache_key, u64 vary_key, CacheEntryAssociatedData);struct CacheEntryData {u64 cache_key { 0 };u64 vary_key { 0 };- Optional<CacheEntryAssociatedData> associated_data;};Optional<CacheEntryData> cache_entry_data_for_file(LexicalPath const&);diff --git a/Libraries/LibRequests/Request.cpp b/Libraries/LibRequests/Request.cppindex 1be7744fa6d..bd1e39f25e1 100644--- a/Libraries/LibRequests/Request.cpp+++ b/Libraries/LibRequests/Request.cpp@@ -270,12 +270,10 @@ void Request::set_buffered_request_finished_callback(BufferedRequestFinished on_m_internal_buffered_data = make<InternalBufferedData>();- on_headers_received = [this](auto headers, auto response_code, auto const& reason_phrase, auto javascript_bytecode, auto javascript_bytecode_cache_vary_key, auto cache_state) {+ on_headers_received = [this](auto headers, auto response_code, auto const& reason_phrase, auto cache_state) {m_internal_buffered_data->response_headers = move(headers);m_internal_buffered_data->response_code = move(response_code);m_internal_buffered_data->reason_phrase = reason_phrase;- m_internal_buffered_data->javascript_bytecode = move(javascript_bytecode);- m_internal_buffered_data->javascript_bytecode_cache_vary_key = javascript_bytecode_cache_vary_key;m_internal_buffered_data->cache_state = cache_state;};@@ -296,8 +294,6 @@ void Request::set_buffered_request_finished_callback(BufferedRequestFinished on_m_internal_buffered_data->response_headers,m_internal_buffered_data->response_code,m_internal_buffered_data->reason_phrase,- move(m_internal_buffered_data->javascript_bytecode),- m_internal_buffered_data->javascript_bytecode_cache_vary_key,m_internal_buffered_data->cache_state,move(payload));};@@ -334,11 +330,11 @@ void Request::did_finish(Badge<RequestClient>, u64 total_size, RequestTimingInfoon_finish(total_size, timing_info, effective_network_error);}-void Request::did_receive_headers(Badge<RequestClient>, NonnullRefPtr<HTTP::HeaderList> response_headers, Optional<u32> response_code, Optional<String> const& reason_phrase, Optional<Core::ImmutableBytes> javascript_bytecode, Optional<u64> javascript_bytecode_cache_vary_key, CacheState cache_state, ByteString http_version)+void Request::did_receive_headers(Badge<RequestClient>, NonnullRefPtr<HTTP::HeaderList> response_headers, Optional<u32> response_code, Optional<String> const& reason_phrase, CacheState cache_state, ByteString http_version){m_http_version = move(http_version);if (on_headers_received)- on_headers_received(move(response_headers), response_code, reason_phrase, move(javascript_bytecode), javascript_bytecode_cache_vary_key, cache_state);+ on_headers_received(move(response_headers), response_code, reason_phrase, cache_state);}void Request::did_transfer(Badge<RequestClient>)diff --git a/Libraries/LibRequests/Request.h b/Libraries/LibRequests/Request.hindex 89920fded2b..adf957789f6 100644--- a/Libraries/LibRequests/Request.h+++ b/Libraries/LibRequests/Request.h@@ -107,13 +107,13 @@ public:// body delivery is paused.[[nodiscard]] bool is_finished() const { return m_finished; }- using BufferedRequestFinished = Function<void(u64 total_size, RequestTimingInfo const& timing_info, Optional<NetworkError> const& network_error, NonnullRefPtr<HTTP::HeaderList> response_headers, Optional<u32> response_code, Optional<String> reason_phrase, Optional<Core::ImmutableBytes> javascript_bytecode, Optional<u64> javascript_bytecode_cache_vary_key, CacheState cache_state, Core::ImmutableBytes payload)>;+ using BufferedRequestFinished = Function<void(u64 total_size, RequestTimingInfo const& timing_info, Optional<NetworkError> const& network_error, NonnullRefPtr<HTTP::HeaderList> response_headers, Optional<u32> response_code, Optional<String> reason_phrase, CacheState cache_state, Core::ImmutableBytes payload)>;// Configure the request such that the entirety of the response data is buffered. The callback receives that data and// the response headers all at once. Using this method is mutually exclusive with `set_unbuffered_data_received_callback`.void set_buffered_request_finished_callback(BufferedRequestFinished);- using HeadersReceived = Function<void(NonnullRefPtr<HTTP::HeaderList> response_headers, Optional<u32> response_code, Optional<String> const& reason_phrase, Optional<Core::ImmutableBytes> javascript_bytecode, Optional<u64> javascript_bytecode_cache_vary_key, CacheState cache_state)>;+ using HeadersReceived = Function<void(NonnullRefPtr<HTTP::HeaderList> response_headers, Optional<u32> response_code, Optional<String> const& reason_phrase, CacheState cache_state)>;using DataReceived = Function<void(ResponseData data)>;using CachedBodyAvailable = Function<void(Core::ImmutableBytes data)>;using RequestFinished = Function<void(u64 total_size, RequestTimingInfo const& timing_info, Optional<NetworkError> network_error)>;@@ -136,7 +136,7 @@ public:Function<void(TeardownReason)> on_teardown;void did_finish(Badge<RequestClient>, u64 total_size, RequestTimingInfo const& timing_info, Optional<NetworkError> const& network_error);- void did_receive_headers(Badge<RequestClient>, NonnullRefPtr<HTTP::HeaderList> response_headers, Optional<u32> response_code, Optional<String> const& reason_phrase, Optional<Core::ImmutableBytes> javascript_bytecode, Optional<u64> javascript_bytecode_cache_vary_key, CacheState cache_state, ByteString http_version);+ void did_receive_headers(Badge<RequestClient>, NonnullRefPtr<HTTP::HeaderList> response_headers, Optional<u32> response_code, Optional<String> const& reason_phrase, CacheState cache_state, ByteString http_version);void did_transfer(Badge<RequestClient>);RefPtr<Core::Notifier>& write_notifier(Badge<RequestClient>) { return m_write_notifier; }@@ -182,8 +182,6 @@ private:NonnullRefPtr<HTTP::HeaderList> response_headers;Optional<u32> response_code;Optional<String> reason_phrase;- Optional<Core::ImmutableBytes> javascript_bytecode;- Optional<u64> javascript_bytecode_cache_vary_key;CacheState cache_state { CacheState::NotCached };Optional<Core::ImmutableBytes> payload;};diff --git a/Libraries/LibRequests/RequestClient.cpp b/Libraries/LibRequests/RequestClient.cppindex 931459d99a0..536b837a02a 100644--- a/Libraries/LibRequests/RequestClient.cpp+++ b/Libraries/LibRequests/RequestClient.cpp@@ -4,7 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/ScopeGuard.h>#include <LibCore/EventLoop.h>#include <LibCore/Promise.h>#include <LibCore/System.h>@@ -13,27 +12,6 @@namespace Requests {-static Optional<Core::ImmutableBytes> map_cache_associated_data_file(int fd, u64 size)-{- ArmedScopeGuard close_fd = [fd] {- (void)Core::System::close(fd);- };-- if (!AK::is_within_range<size_t>(size)) {- dbgln("RequestClient: Received cache associated data file outside mappable range");- return {};- }-- close_fd.disarm();- auto payload = Core::ImmutableBytes::map_from_fd_range_and_close(fd, "cache associated data"sv, 0, static_cast<size_t>(size));- if (payload.is_error()) {- dbgln("RequestClient: Failed to map cache associated data file: {}", payload.error());- return {};- }-- return payload.release_value();-}-RequestClient::RequestClient(NonnullOwnPtr<IPC::Transport> transport): IPC::ConnectionToServer<RequestClientEndpoint, RequestServerEndpoint>(*this, move(transport)){@@ -132,28 +110,6 @@ RefPtr<Request> RequestClient::import_request(ExportedRequest exported, Transferreturn request;}-ErrorOr<Optional<Core::ImmutableBytes>> RequestClient::store_cache_associated_data(Optional<HTTP::NetworkIsolationKey> const& network_isolation_key, URL::URL const& url, ByteString const& method, Optional<HTTP::HeaderList const&> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData associated_data, ReadonlyBytes data)-{- auto buffer = TRY(Core::AnonymousBuffer::create_with_size(data.size()));- memcpy(buffer.data<void>(), data.data(), data.size());- return store_cache_associated_data(network_isolation_key, url, method, request_headers, vary_key, associated_data, move(buffer));-}--ErrorOr<Optional<Core::ImmutableBytes>> RequestClient::store_cache_associated_data(Optional<HTTP::NetworkIsolationKey> const& network_isolation_key, URL::URL const& url, ByteString const& method, Optional<HTTP::HeaderList const&> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData associated_data, Core::AnonymousBuffer data)-{- auto headers = request_headers.map([](auto const& headers) { return headers.headers(); }).value_or({});- auto response = IPCProxy::store_cache_associated_data(network_isolation_key, url, method, headers, vary_key, associated_data, move(data));- if (!response.file().has_value())- return Optional<Core::ImmutableBytes> {};- return map_cache_associated_data_file(response.take_file()->take_fd(), response.size());-}--ErrorOr<Optional<Core::AnonymousBuffer>> RequestClient::retrieve_cache_associated_data(Optional<HTTP::NetworkIsolationKey> const& network_isolation_key, URL::URL const& url, ByteString const& method, Optional<HTTP::HeaderList const&> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData associated_data)-{- auto headers = request_headers.map([](auto const& headers) { return headers.headers(); }).value_or({});- return IPCProxy::retrieve_cache_associated_data(network_isolation_key, url, method, headers, vary_key, associated_data);-}-bool RequestClient::stop_request(Badge<Request>, Request& request){auto stopped_request = m_requests.take(request.id());@@ -268,15 +224,11 @@ void RequestClient::request_finished(u64 request_id, u64 total_size, RequestTimim_requests.remove(request_id);}-void RequestClient::headers_became_available(u64 request_id, Vector<HTTP::Header> response_headers, Optional<u32> status_code, Optional<String> reason_phrase, Optional<IPC::File> javascript_bytecode_file, u64 javascript_bytecode_size, Optional<u64> javascript_bytecode_cache_vary_key, CacheState cache_state, ByteString http_version)+void RequestClient::headers_became_available(u64 request_id, Vector<HTTP::Header> response_headers, Optional<u32> status_code, Optional<String> reason_phrase, CacheState cache_state, ByteString http_version){- Optional<Core::ImmutableBytes> javascript_bytecode;- if (javascript_bytecode_file.has_value())- javascript_bytecode = map_cache_associated_data_file(javascript_bytecode_file->take_fd(), javascript_bytecode_size);-RefPtr<Request> request = m_requests.get(request_id).value_or(nullptr);if (request)- request->did_receive_headers({}, HTTP::HeaderList::create(move(response_headers)), status_code, reason_phrase, move(javascript_bytecode), javascript_bytecode_cache_vary_key, cache_state, move(http_version));+ request->did_receive_headers({}, HTTP::HeaderList::create(move(response_headers)), status_code, reason_phrase, cache_state, move(http_version));elsewarnln("Received headers for non-existent request {}", request_id);}diff --git a/Libraries/LibRequests/RequestClient.h b/Libraries/LibRequests/RequestClient.hindex b6deea21a3c..31fde3b2817 100644--- a/Libraries/LibRequests/RequestClient.h+++ b/Libraries/LibRequests/RequestClient.h@@ -8,7 +8,6 @@#include <AK/HashMap.h>#include <LibCore/AnonymousBuffer.h>-#include <LibCore/ImmutableBytes.h>#include <LibHTTP/Cache/CacheMode.h>#include <LibHTTP/Cache/Utilities.h>#include <LibHTTP/Cookie/IncludeCredentials.h>@@ -69,9 +68,6 @@ public:RefPtr<WebSocket> websocket_connect(URL::URL const&, Optional<HTTP::NetworkIsolationKey> const&, ByteString const& origin, Vector<ByteString> const& protocols, Vector<ByteString> const& extensions, HTTP::HeaderList const& request_headers);// Stores the data in the HTTP cache, and returns it mapped read-only from the cache's file, or nothing when it wasn't stored.- ErrorOr<Optional<Core::ImmutableBytes>> store_cache_associated_data(Optional<HTTP::NetworkIsolationKey> const&, URL::URL const&, ByteString const& method, Optional<HTTP::HeaderList const&> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData, ReadonlyBytes);- ErrorOr<Optional<Core::ImmutableBytes>> store_cache_associated_data(Optional<HTTP::NetworkIsolationKey> const&, URL::URL const&, ByteString const& method, Optional<HTTP::HeaderList const&> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData, Core::AnonymousBuffer);- ErrorOr<Optional<Core::AnonymousBuffer>> retrieve_cache_associated_data(Optional<HTTP::NetworkIsolationKey> const&, URL::URL const&, ByteString const& method, Optional<HTTP::HeaderList const&> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData);Function<void()> on_request_server_died;@@ -84,7 +80,7 @@ private:virtual void request_body_file_available(u64 request_id, IPC::File, u64 offset, u64 size) override;virtual void request_cached_body_file_available(u64 request_id, IPC::File, u64 offset, u64 size) override;virtual void request_finished(u64 request_id, u64, RequestTimingInfo, Optional<NetworkError>) override;- virtual void headers_became_available(u64 request_id, Vector<HTTP::Header>, Optional<u32>, Optional<String>, Optional<IPC::File>, u64 javascript_bytecode_size, Optional<u64>, CacheState, ByteString http_version) override;+ virtual void headers_became_available(u64 request_id, Vector<HTTP::Header>, Optional<u32>, Optional<String>, CacheState, ByteString http_version) override;virtual void request_transferred(u64 request_id) override;virtual void host_resolved(u64 lookup_id, Vector<ByteString> addresses) override;diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex 83385ae2fec..f1ae7f22f84 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -2737,7 +2737,7 @@ GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, Iauto body_pump = GC::make_root(network_body.body_pump);auto cross_origin_isolated_capability = Bindings::principal_host_defined_environment_settings_object(realm).cross_origin_isolated_capability();request->set_unbuffered_request_callbacks(- [](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Optional<Core::ImmutableBytes>, Optional<u64>, Requests::CacheState) { },+ [](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Requests::CacheState) { },[body_pump](Requests::ResponseData data) {body_pump->handle_network_data(move(data));},diff --git a/Libraries/LibWeb/Loader/ResourceLoader.cpp b/Libraries/LibWeb/Loader/ResourceLoader.cppindex 785aae1eb55..6e53ad101e1 100644--- a/Libraries/LibWeb/Loader/ResourceLoader.cpp+++ b/Libraries/LibWeb/Loader/ResourceLoader.cpp@@ -552,7 +552,7 @@ RefPtr<Fetch::Engine::NetworkTransportHandle> ResourceLoader::load(LoadRequest&auto network_transport = Fetch::Engine::NetworkTransportHandle::create(*protocol_request);- auto protocol_headers_received = [on_headers_received = move(on_headers_received), request, &protocol_request = *protocol_request, network_transport](auto const& response_headers, auto status_code, auto const& reason_phrase, auto, auto, auto cache_state) {+ auto protocol_headers_received = [on_headers_received = move(on_headers_received), request, &protocol_request = *protocol_request, network_transport](auto const& response_headers, auto status_code, auto const& reason_phrase, auto cache_state) {if (auto page = request.page())page->client().page_did_receive_network_response_headers(protocol_request.id(), status_code.value_or(0), reason_phrase, response_headers->headers(), cache_state);diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cppindex 24d0188be37..9bdc4f70381 100644--- a/Libraries/LibWebView/Application.cpp+++ b/Libraries/LibWebView/Application.cpp@@ -966,7 +966,7 @@ void Application::start_next_content_blocker_list_update()timeout->start();m_content_blocker_list_update_request->set_unbuffered_request_callbacks(- [this](NonnullRefPtr<HTTP::HeaderList> headers, Optional<u32> response_code, Optional<String> const& reason_phrase, Optional<Core::ImmutableBytes>, Optional<u64>, Requests::CacheState) {+ [this](NonnullRefPtr<HTTP::HeaderList> headers, Optional<u32> response_code, Optional<String> const& reason_phrase, Requests::CacheState) {if (m_content_blocker_list_update_cancelled)return;if (response_code.has_value() && Web::Fetch::Infrastructure::is_redirect_status(*response_code)) {diff --git a/Libraries/LibWebView/Autocomplete.cpp b/Libraries/LibWebView/Autocomplete.cppindex 66264d5b137..776ff6ef253 100644--- a/Libraries/LibWebView/Autocomplete.cpp+++ b/Libraries/LibWebView/Autocomplete.cpp@@ -384,7 +384,7 @@ void Autocomplete::start_remote_query(AutocompleteQueryID query_id, SearchEnginem_request = client.value()->start_request("GET"sv, *url);m_request->set_buffered_request_finished_callback(- [this, query_id, engine, query = move(query)](u64, Requests::RequestTimingInfo const&, Optional<Requests::NetworkError> const& network_error, HTTP::HeaderList const& response_headers, Optional<u32> response_code, Optional<String> const& reason_phrase, Optional<Core::ImmutableBytes>, Optional<u64>, Requests::CacheState, Core::ImmutableBytes payload) {+ [this, query_id, engine, query = move(query)](u64, Requests::RequestTimingInfo const&, Optional<Requests::NetworkError> const& network_error, HTTP::HeaderList const& response_headers, Optional<u32> response_code, Optional<String> const& reason_phrase, Requests::CacheState, Core::ImmutableBytes payload) {Core::deferred_invoke([self = make_weak_ptr(), query_id] {if (self && self->m_query_id == query_id)self->m_request.clear();diff --git a/Libraries/LibWebView/FileDownloader.cpp b/Libraries/LibWebView/FileDownloader.cppindex b28d7c2ccc2..99ce1923184 100644--- a/Libraries/LibWebView/FileDownloader.cpp+++ b/Libraries/LibWebView/FileDownloader.cpp@@ -351,7 +351,7 @@ void FileDownloader::attach_request_to_download(u64 download_id, size_t segment_request->set_body_delivery_paused(true);request->set_unbuffered_request_callbacks(- [this, download_id, segment_index, request_generation](NonnullRefPtr<HTTP::HeaderList> response_headers, Optional<u32> response_code, Optional<String> const& reason_phrase, Optional<Core::ImmutableBytes>, Optional<u64>, Requests::CacheState cache_state) {+ [this, download_id, segment_index, request_generation](NonnullRefPtr<HTTP::HeaderList> response_headers, Optional<u32> response_code, Optional<String> const& reason_phrase, Requests::CacheState cache_state) {handle_segment_headers(download_id, segment_index, request_generation, *response_headers, response_code, reason_phrase, cache_state);},[this, download_id, segment_index, request_generation](Requests::ResponseData data) {diff --git a/Libraries/LibWebView/NavigationLoader.cpp b/Libraries/LibWebView/NavigationLoader.cppindex 2bda19c155c..edaa748ed51 100644--- a/Libraries/LibWebView/NavigationLoader.cpp+++ b/Libraries/LibWebView/NavigationLoader.cpp@@ -369,7 +369,7 @@ void NavigationLoader::set_response_body_callbacks(Requests::Request& request){auto weak_this = make_weak_ptr();request.set_unbuffered_request_callbacks(- [weak_this](NonnullRefPtr<HTTP::HeaderList> response_header_list, Optional<u32>, Optional<String> const&, Optional<Core::ImmutableBytes>, Optional<u64>, Requests::CacheState) {+ [weak_this](NonnullRefPtr<HTTP::HeaderList> response_header_list, Optional<u32>, Optional<String> const&, Requests::CacheState) {if (auto* loader = weak_this.ptr()) {loader->m_response_header_list = move(response_header_list);loader->did_acquire(true);diff --git a/Libraries/LibWebView/ReportSubmission.cpp b/Libraries/LibWebView/ReportSubmission.cppindex 5457567a448..7d713ef8cb1 100644--- a/Libraries/LibWebView/ReportSubmission.cpp+++ b/Libraries/LibWebView/ReportSubmission.cpp@@ -400,7 +400,7 @@ void ReportSubmission::post(StringView path, StringView activity, StringView conon_success = move(on_success)](u64, Requests::RequestTimingInfo const&,Optional<Requests::NetworkError> const& network_error, HTTP::HeaderList const& response_headers,Optional<u32> response_code, Optional<String> const&,- Optional<Core::ImmutableBytes>, Optional<u64>, Requests::CacheState,+ Requests::CacheState,Core::ImmutableBytes payload) {auto self = weak_this.strong_ref();if (!self || !self->m_request)diff --git a/Services/RequestServer/ConnectionFromClient.cpp b/Services/RequestServer/ConnectionFromClient.cppindex bdd829975ab..bc3ebf79762 100644--- a/Services/RequestServer/ConnectionFromClient.cpp+++ b/Services/RequestServer/ConnectionFromClient.cpp@@ -267,12 +267,6 @@ static bool is_fetchable_url(URL::URL const& url)return !url.port().has_value() || !HTTP::is_bad_port(*url.port());}-// IPC does not validate enum values; the cache requires a known associated-data kind.-static bool is_valid_associated_data(HTTP::CacheEntryAssociatedData associated_data)-{- return HTTP::CACHE_ENTRY_ASSOCIATED_DATA_TYPES.contains_slow(associated_data);-}-// Headers go verbatim on the wire; newlines would allow request injection.static bool are_valid_headers(Vector<HTTP::Header> const& headers){@@ -840,81 +834,6 @@ void ConnectionFromClient::ensure_connection(u64 request_id, URL::URL url, ::Reqm_active_requests.set(request_id, move(request));}-// The partition of this RequestServer's disk cache that a key reaches, if any.-static Optional<Utf16String> disk_cache_partition_for(Optional<HTTP::NetworkIsolationKey> const& network_isolation_key)-{- if (!network_isolation_key.has_value() || !process_keeps_responses_under(network_isolation_key->top_level_site))- return {};- return network_isolation_key->disk_cache_partition();-}--Messages::RequestServer::StoreCacheAssociatedDataResponse ConnectionFromClient::store_cache_associated_data(Optional<HTTP::NetworkIsolationKey> network_isolation_key, URL::URL url, ByteString method, Vector<HTTP::Header> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData associated_data, Core::AnonymousBuffer data)-{- if (!is_valid_associated_data(associated_data)) {- did_misbehave("invalid cache associated data kind");- return { Optional<IPC::File> {}, 0 };- }-- if (!are_valid_headers(request_headers)) {- did_misbehave("invalid request header");- return { Optional<IPC::File> {}, 0 };- }-- if (network_isolation_key.has_value() && !may_use_network_isolation_key(*network_isolation_key))- return { Optional<IPC::File> {}, 0 };-- auto partition = disk_cache_partition_for(network_isolation_key);- if (!m_disk_cache.has_value() || !partition.has_value() || !data.is_valid())- return { Optional<IPC::File> {}, 0 };-- auto result = m_disk_cache->store_associated_data(*partition, url, method, *HTTP::HeaderList::create(move(request_headers)), vary_key, associated_data, data.bytes());- if (result.is_error()) {- dbgln("Failed to store cache associated data for {}: {}", url, result.error());- return { Optional<IPC::File> {}, 0 };- }-- if (!result.value().has_value())- return { Optional<IPC::File> {}, 0 };- return { IPC::File::adopt_fd(result.value()->fd), result.value()->size };-}--Messages::RequestServer::RetrieveCacheAssociatedDataResponse ConnectionFromClient::retrieve_cache_associated_data(Optional<HTTP::NetworkIsolationKey> network_isolation_key, URL::URL url, ByteString method, Vector<HTTP::Header> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData associated_data)-{- if (!is_valid_associated_data(associated_data)) {- did_misbehave("invalid cache associated data kind");- return Optional<Core::AnonymousBuffer> {};- }-- if (!are_valid_headers(request_headers)) {- did_misbehave("invalid request header");- return Optional<Core::AnonymousBuffer> {};- }-- if (network_isolation_key.has_value() && !may_use_network_isolation_key(*network_isolation_key))- return Optional<Core::AnonymousBuffer> {};-- auto partition = disk_cache_partition_for(network_isolation_key);- if (!m_disk_cache.has_value() || !partition.has_value())- return Optional<Core::AnonymousBuffer> {};-- auto data = m_disk_cache->retrieve_associated_data(*partition, url, method, *HTTP::HeaderList::create(move(request_headers)), vary_key, associated_data);- if (data.is_error()) {- dbgln("Failed to retrieve cache associated data for {}: {}", url, data.error());- return Optional<Core::AnonymousBuffer> {};- }- if (!data.value().has_value())- return Optional<Core::AnonymousBuffer> {};-- auto buffer = Core::AnonymousBuffer::create_with_size(data.value()->size());- if (buffer.is_error()) {- dbgln("Failed to allocate cache associated data buffer for {}: {}", url, buffer.error());- return Optional<Core::AnonymousBuffer> {};- }-- memcpy(buffer.value().data<void>(), data.value()->data(), data.value()->size());- return Optional<Core::AnonymousBuffer> { buffer.release_value() };-}-size_t ConnectionFromClient::websocket_count() const{return m_pending_websockets.size() + m_websockets.size();diff --git a/Services/RequestServer/ConnectionFromClient.h b/Services/RequestServer/ConnectionFromClient.hindex f176441328c..e03c57ca5fc 100644--- a/Services/RequestServer/ConnectionFromClient.h+++ b/Services/RequestServer/ConnectionFromClient.h@@ -95,9 +95,6 @@ private:virtual void ensure_connection(u64 request_id, URL::URL url, ::RequestServer::CacheLevel cache_level) override;virtual void resolve_host(u64 lookup_id, ByteString host) override;- virtual Messages::RequestServer::StoreCacheAssociatedDataResponse store_cache_associated_data(Optional<HTTP::NetworkIsolationKey>, URL::URL, ByteString method, Vector<HTTP::Header> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData, Core::AnonymousBuffer) override;- virtual Messages::RequestServer::RetrieveCacheAssociatedDataResponse retrieve_cache_associated_data(Optional<HTTP::NetworkIsolationKey>, URL::URL, ByteString method, Vector<HTTP::Header> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData) override;-virtual void websocket_connect(u64 websocket_id, URL::URL, Optional<HTTP::NetworkIsolationKey>, ByteString, Vector<ByteString>, Vector<ByteString>, Vector<HTTP::Header>) override;virtual void websocket_send(u64 websocket_id, bool, ByteBuffer) override;virtual void websocket_send_shared(u64 websocket_id, bool, Core::AnonymousBuffer) override;diff --git a/Services/RequestServer/Request.cpp b/Services/RequestServer/Request.cppindex 06471100cca..314e60eb7e8 100644--- a/Services/RequestServer/Request.cpp+++ b/Services/RequestServer/Request.cpp@@ -1712,9 +1712,8 @@ void Request::handle_complete_state()auto timing_info = acquire_timing_info();transfer_headers_to_client_if_needed();- // Finalize the disk cache entry before notifying WebContent that the request is complete: WebContent may- // immediately fire off a JavaScript bytecode cache store against this entry, and that store needs the cache- // index row to already exist. If we notified first the store would race the index write and be rejected.+ // Finalize the disk cache entry before notifying WebContent that the request is complete, so that a large body+ // can be handed over as a file from the cache.Optional<HTTP::CacheEntryBodyFile> cached_body_file;if (m_cache_entry_writer.has_value()) {if (m_cache_entry_writer->body_size() >= static_cast<u64>(PAGE_SIZE)) {@@ -2304,22 +2303,7 @@ void Request::transfer_headers_to_client_if_needed()}}- Optional<IPC::File> javascript_bytecode;- u64 javascript_bytecode_size { 0 };- Optional<u64> javascript_bytecode_cache_vary_key;- if (m_cache_status == CacheStatus::ReadFromCache && m_disk_cache.has_value()) {- VERIFY(m_cache_entry_reader.has_value());- javascript_bytecode_cache_vary_key = m_cache_entry_reader->vary_key();- auto data = m_disk_cache->retrieve_associated_data_file(*m_disk_cache_partition, m_url, m_method, *m_request_headers, javascript_bytecode_cache_vary_key, HTTP::CacheEntryAssociatedData::JavaScriptBytecode);- if (!data.is_error() && data.value().has_value()) {- javascript_bytecode_size = data.value()->size;- javascript_bytecode = IPC::File::adopt_fd(data.value()->fd);- }- } else if (m_cache_status == CacheStatus::WrittenToCache && m_cache_entry_writer.has_value()) {- javascript_bytecode_cache_vary_key = m_cache_entry_writer->vary_key();- }-- send_headers_to_client(move(javascript_bytecode), javascript_bytecode_size, javascript_bytecode_cache_vary_key);+ send_headers_to_client();}void Request::did_send_request_body_bytes(u64 bytes_sent)@@ -2343,7 +2327,7 @@ void Request::did_send_request_body_bytes(u64 bytes_sent)m_client->async_request_upload_progress(m_request_id, bytes_sent);}-void Request::send_headers_to_client(Optional<IPC::File> javascript_bytecode, u64 javascript_bytecode_size, Optional<u64> javascript_bytecode_cache_vary_key)+void Request::send_headers_to_client(){// A response means the request body has been sent, including one that a cache or a substitution answered, and// which never went out at all.@@ -2352,7 +2336,7 @@ void Request::send_headers_to_client(Optional<IPC::File> javascript_bytecode, u6auto cache_state = Requests::CacheState::NotCached;if (m_cache_status == CacheStatus::ReadFromCache)cache_state = m_cache_entry_was_revalidated ? Requests::CacheState::Validated : Requests::CacheState::Local;- m_client->async_headers_became_available(m_request_id, m_response_headers->headers(), m_status_code, m_reason_phrase, move(javascript_bytecode), javascript_bytecode_size, javascript_bytecode_cache_vary_key, cache_state, m_http_version);+ m_client->async_headers_became_available(m_request_id, m_response_headers->headers(), m_status_code, m_reason_phrase, cache_state, m_http_version);}ErrorOr<void> Request::write_queued_bytes_without_blocking()diff --git a/Services/RequestServer/Request.h b/Services/RequestServer/Request.hindex da451ed7958..a1b72c14762 100644--- a/Services/RequestServer/Request.h+++ b/Services/RequestServer/Request.h@@ -268,7 +268,7 @@ private:bool defer_until_response_cookies_and_hsts_policy_are_stored(Function<void()> continuation);void request_response_storage(ControlConnectionFromClient&);void handle_fetch_complete(int result_code);- void send_headers_to_client(Optional<IPC::File> javascript_bytecode = {}, u64 javascript_bytecode_size = 0, Optional<u64> javascript_bytecode_cache_vary_key = {});+ void send_headers_to_client();ErrorOr<void> write_queued_bytes_without_blocking();virtual bool is_revalidation_request() const override;diff --git a/Services/RequestServer/RequestClient.ipc b/Services/RequestServer/RequestClient.ipcindex 24becc395da..630753c68e7 100644--- a/Services/RequestServer/RequestClient.ipc+++ b/Services/RequestServer/RequestClient.ipc@@ -14,7 +14,7 @@ endpoint RequestClientrequest_body_file_available(u64 request_id, IPC::File fd, u64 offset, u64 size) =|request_cached_body_file_available(u64 request_id, IPC::File fd, u64 offset, u64 size) =|request_finished(u64 request_id, u64 total_size, Requests::RequestTimingInfo timing_info, Optional<Requests::NetworkError> network_error) =|- headers_became_available(u64 request_id, Vector<HTTP::Header> response_headers, Optional<u32> status_code, Optional<String> reason_phrase, Optional<IPC::File> javascript_bytecode, u64 javascript_bytecode_size, Optional<u64> javascript_bytecode_cache_vary_key, Requests::CacheState cache_state, ByteString http_version) =|+ headers_became_available(u64 request_id, Vector<HTTP::Header> response_headers, Optional<u32> status_code, Optional<String> reason_phrase, Requests::CacheState cache_state, ByteString http_version) =|request_transferred(u64 request_id) =|host_resolved(u64 lookup_id, Vector<ByteString> addresses) =|diff --git a/Services/RequestServer/RequestServer.ipc b/Services/RequestServer/RequestServer.ipcindex c66176ed836..b3568f4987f 100644--- a/Services/RequestServer/RequestServer.ipc+++ b/Services/RequestServer/RequestServer.ipc@@ -1,6 +1,5 @@#include <LibCore/AnonymousBuffer.h>#include <LibHTTP/Cache/CacheMode.h>-#include <LibHTTP/Cache/Utilities.h>#include <LibHTTP/Cookie/IncludeCredentials.h>#include <LibHTTP/Header.h>#include <LibHTTP/NetworkIsolationKey.h>@@ -33,10 +32,6 @@ endpoint RequestServer// browser's DNS settings apply to it too.resolve_host(u64 lookup_id, ByteString host) =|- store_cache_associated_data(Optional<HTTP::NetworkIsolationKey> network_isolation_key, URL::URL url, ByteString method, Vector<HTTP::Header> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData associated_data, Core::AnonymousBuffer data) => (Optional<IPC::File> file, u64 size)- retrieve_cache_associated_data(Optional<HTTP::NetworkIsolationKey> network_isolation_key, URL::URL url, ByteString method, Vector<HTTP::Header> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData associated_data) => (Optional<Core::AnonymousBuffer> data)--// Websocket Connection APIwebsocket_connect(u64 websocket_id, URL::URL url, Optional<HTTP::NetworkIsolationKey> network_isolation_key, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers) =|websocket_send(u64 websocket_id, bool is_text, ByteBuffer data) =|diff --git a/Tests/LibHTTP/TestCacheIndex.cpp b/Tests/LibHTTP/TestCacheIndex.cppindex 151ee5b306a..bc12b27db18 100644--- a/Tests/LibHTTP/TestCacheIndex.cpp+++ b/Tests/LibHTTP/TestCacheIndex.cpp@@ -8,10 +8,13 @@#include <AK/NumericLimits.h>#include <AK/QuickSort.h>#include <LibCore/Directory.h>+#include <LibCore/File.h>#include <LibCore/StandardPaths.h>#include <LibDatabase/Database.h>+#include <LibFileSystem/FileSystem.h>#include <LibHTTP/Cache/CacheIndex.h>#include <LibHTTP/Cache/Utilities.h>+#include <LibTest/TemporaryDirectory.h>#include <LibTest/TestCase.h>struct CacheIndexTestState {@@ -116,32 +119,6 @@ TEST_CASE(remove_entries_exceeding_cache_limit_tolerates_replaced_unloaded_entriEXPECT_EQ(reloaded_index.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total, 80u);}-TEST_CASE(associated_data_counts_toward_cache_size)-{- auto state = create_cache_index();-- auto request_headers = HTTP::HeaderList::create();- auto response_headers = HTTP::HeaderList::create();- auto vary_key = HTTP::create_vary_key(*request_headers, *response_headers).value();- auto now = UnixDateTime::now();-- state.index.set_maximum_disk_cache_size(80);-- for (u64 cache_key = 1; cache_key <= 5; ++cache_key)- TRY_OR_FAIL(state.index.create_entry(cache_key, vary_key, "https://example.com/script.js"_string, request_headers, response_headers, 10, now, now));- TRY_OR_FAIL(state.index.update_associated_data_size(1, vary_key, 50));-- EXPECT_EQ(state.index.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total, 100u);-- Vector<u64> removed_entries;- state.index.remove_entries_exceeding_cache_limit([&](auto removed_cache_key, auto) {- removed_entries.append(removed_cache_key);- });-- EXPECT(removed_entries.size() > 0);- EXPECT(state.index.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total <= 80u);-}-TEST_CASE(newer_cache_index_schema_reports_database_too_new){auto database = TRY_OR_FAIL(Database::Database::create_memory_backed());@@ -169,6 +146,33 @@ TEST_CASE(entries_with_previous_vary_keys_are_dropped_on_migration)EXPECT_EQ(index.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total, 0u);}+TEST_CASE(stored_responses_outlive_the_files_beside_them_on_migration)+{+ Test::TemporaryDirectory const directory { "TestCacheIndex"sv };+ auto database = TRY_OR_FAIL(Database::Database::create(directory.path().string(), "INDEX"sv));++ TRY_OR_FAIL(database->execute_raw("CREATE TABLE SchemaVersions (store TEXT PRIMARY KEY, version INTEGER NOT NULL);"sv));+ TRY_OR_FAIL(database->execute_raw("INSERT INTO SchemaVersions (store, version) VALUES ('CacheIndex', 3);"sv));+ TRY_OR_FAIL(database->execute_raw("CREATE TABLE CacheIndex (cache_key INTEGER, vary_key INTEGER, url TEXT, request_headers BLOB, response_headers BLOB, data_size INTEGER, associated_data_size INTEGER, request_time INTEGER, response_time INTEGER, last_access_time INTEGER, PRIMARY KEY(cache_key, vary_key));"sv));+ TRY_OR_FAIL(database->execute_raw("INSERT INTO CacheIndex VALUES (1, 0, 'https://example.com', x'', x'', 10, 5, 0, 0, 0);"sv));++ auto entry_file = directory.path().append("0000000000000001"sv);+ auto bytecode_file = directory.path().append("0000000000000001.jsbc"sv);+ auto partial_bytecode_file = directory.path().append("0000000000000001.jsbc.tmp"sv);+ for (auto const& path : { entry_file, bytecode_file, partial_bytecode_file })+ (void)TRY_OR_FAIL(Core::File::open(path.string(), Core::File::OpenMode::Write));++ EXPECT_EQ(TRY_OR_FAIL(HTTP::CacheIndex::migrate_schema(*database)), Database::MigrationOutcome::Success);++ EXPECT(FileSystem::exists(entry_file.string()));+ EXPECT(!FileSystem::exists(bytecode_file.string()));+ EXPECT(!FileSystem::exists(partial_bytecode_file.string()));++ auto index = MUST(HTTP::CacheIndex::create(*database, directory.path()));+ EXPECT(index.has_entry(1, 0));+ EXPECT_EQ(index.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total, 10u);+}+TEST_CASE(full_range_cache_keys_round_trip){auto state = create_cache_index();@@ -245,7 +249,6 @@ TEST_CASE(failed_statements_after_creation_do_not_abort)// Writes report that they failed.EXPECT(state.index.create_entry(2, vary_key, "https://example.com/2"_string, request_headers, response_headers, 10, now, now).is_error());EXPECT(state.index.update_response_headers(1, vary_key, response_headers).is_error());- EXPECT(state.index.update_associated_data_size(1, vary_key, 5).is_error());state.index.update_last_access_time(1, vary_key);// Entries that can't be read are missed.@@ -362,8 +365,7 @@ TEST_CASE(persisted_entries_are_found_before_they_are_looked_up)auto reloaded_index = MUST(HTTP::CacheIndex::create(*state.database, cache_directory()));EXPECT(reloaded_index.has_entry(1, 0));- TRY_OR_FAIL(reloaded_index.update_associated_data_size(1, 0, 5));- EXPECT_EQ(reloaded_index.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total, 10u + 5u + 25u);+ EXPECT_EQ(reloaded_index.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total, 10u + 25u);}TEST_CASE(malformed_rows_are_dropped_when_the_index_is_opened)@@ -380,7 +382,7 @@ TEST_CASE(malformed_rows_are_dropped_when_the_index_is_opened)TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET request_headers = NULL WHERE cache_key = 1;"sv));TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET last_access_time = NULL WHERE cache_key = 2;"sv));TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET data_size = 9223372036854775807 WHERE cache_key = 3;"sv));- TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET associated_data_size = 'large' WHERE cache_key = 4;"sv));+ TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET response_time = 'late' WHERE cache_key = 4;"sv));auto reloaded_index = MUST(HTTP::CacheIndex::create(*state.database, cache_directory()));for (u64 cache_key = 1; cache_key <= 4; ++cache_key)diff --git a/Tests/LibHTTP/TestDiskCache.cpp b/Tests/LibHTTP/TestDiskCache.cppindex 13148ad0039..d3ca0ed682e 100644--- a/Tests/LibHTTP/TestDiskCache.cpp+++ b/Tests/LibHTTP/TestDiskCache.cpp@@ -5,8 +5,10 @@*/#include <AK/ByteBuffer.h>+#include <LibCore/File.h>#include <LibCore/ImmutableBytes.h>#include <LibCore/System.h>+#include <LibFileSystem/FileSystem.h>#include <LibHTTP/Cache/CacheRequest.h>#include <LibHTTP/Cache/DiskCache.h>#include <LibHTTP/Cache/Utilities.h>@@ -229,44 +231,25 @@ TEST_CASE(fields_received_after_the_header_section_are_not_stored)EXPECT(!reader->response_headers().contains("X-Trailer"sv));}-TEST_CASE(unreadable_entry_is_removed_with_its_associated_data)+TEST_CASE(unreadable_entry_is_removed){auto disk_cache = MUST(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Testing, test_cache_root())).release_value();TestCacheRequest request;auto url = parse_url("https://example.com/script.js"sv);auto request_headers = create_cacheable_request_headers();+ store_cache_entry(disk_cache, request, url, *request_headers, create_cacheable_response_headers(), "console.log('hello');"sv);- EXPECT(TRY_OR_FAIL(disk_cache.create_synthetic_entry(test_partition(), url, "GET"sv)));-- auto bytecode = TRY_OR_FAIL(ByteBuffer::copy("bytecode"sv.bytes()));- auto stored = TRY_OR_FAIL(disk_cache.store_associated_data(test_partition(), url, "GET"sv, *request_headers, 0, HTTP::CacheEntryAssociatedData::JavaScriptBytecode, bytecode.bytes()));- EXPECT(stored.has_value());- if (stored.has_value())- (void)Core::System::close(stored->fd);-- // A synthetic entry has no body to read.- EXPECT(!open_cache_entry(disk_cache, request, url, *request_headers).has_value());-- EXPECT(TRY_OR_FAIL(disk_cache.create_synthetic_entry(test_partition(), url, "GET"sv)));- auto retrieved_bytecode = TRY_OR_FAIL(disk_cache.retrieve_associated_data(test_partition(), url, "GET"sv, *request_headers, 0, HTTP::CacheEntryAssociatedData::JavaScriptBytecode));- EXPECT(!retrieved_bytecode.has_value());-}--TEST_CASE(synthetic_entry_accounts_for_existing_associated_data)-{- auto disk_cache = MUST(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Testing, test_cache_root())).release_value();-- auto url = parse_url("https://example.com/script.js"sv);auto cache_key = HTTP::create_cache_key(test_partition(), HTTP::serialize_url_for_cache_storage(url), "GET"sv);- auto path = HTTP::path_for_cache_entry_associated_data(disk_cache.cache_directory(), cache_key, 0, HTTP::CacheEntryAssociatedData::JavaScriptBytecode);+ auto path = HTTP::path_for_cache_entry(disk_cache.cache_directory(), cache_key, 0);{- auto file = TRY_OR_FAIL(Core::File::open(path.string(), Core::File::OpenMode::Write));- TRY_OR_FAIL(file->write_until_depleted("leftover bytecode"sv.bytes()));+ auto file = TRY_OR_FAIL(Core::File::open(path.string(), Core::File::OpenMode::Write | Core::File::OpenMode::Truncate));+ TRY_OR_FAIL(file->write_until_depleted("garbage"sv.bytes()));}- EXPECT(TRY_OR_FAIL(disk_cache.create_synthetic_entry(test_partition(), url, "GET"sv)));- EXPECT_EQ(disk_cache.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total, "leftover bytecode"sv.length());+ EXPECT(!open_cache_entry(disk_cache, request, url, *request_headers).has_value());+ EXPECT(!FileSystem::exists(path.string()));+ EXPECT_EQ(disk_cache.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total, 0u);}TEST_CASE(clearing_the_cache_removes_responses_still_being_written)@@ -306,75 +289,6 @@ TEST_CASE(connection_specific_cache_policy_does_not_allow_storage)EXPECT(writer.write_status_and_reason(302, "Found"_string, *request_headers, *response_headers).is_error());}-TEST_CASE(associated_data_round_trips_with_cache_entry)-{- auto disk_cache = MUST(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Testing, test_cache_root())).release_value();- TestCacheRequest request;-- auto url = parse_url("https://example.com/script.js"sv);- auto request_headers = create_cacheable_request_headers();- auto response_headers = create_cacheable_response_headers();-- auto& writer = create_cache_entry(disk_cache, request, url, *request_headers);- TRY_OR_FAIL(writer.write_status_and_reason(200, "OK"_string, *request_headers, *response_headers));- TRY_OR_FAIL(writer.write_data("console.log('hello');"sv.bytes()));- TRY_OR_FAIL(writer.flush(request_headers));-- auto bytecode = TRY_OR_FAIL(ByteBuffer::copy("bytecode"sv.bytes()));- auto stored = TRY_OR_FAIL(disk_cache.store_associated_data(test_partition(), url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode, bytecode.bytes()));- EXPECT(stored.has_value());- if (stored.has_value())- (void)Core::System::close(stored->fd);-- auto retrieved_bytecode = TRY_OR_FAIL(disk_cache.retrieve_associated_data(test_partition(), url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode));- VERIFY(retrieved_bytecode.has_value());- EXPECT_EQ(retrieved_bytecode->bytes(), bytecode.bytes());-- auto retrieved_bytecode_file = TRY_OR_FAIL(disk_cache.retrieve_associated_data_file(test_partition(), url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode));- VERIFY(retrieved_bytecode_file.has_value());- auto mapped_bytecode = TRY_OR_FAIL(Core::ImmutableBytes::map_from_fd_range_and_close(retrieved_bytecode_file->fd, "bytecode"sv, retrieved_bytecode_file->offset, retrieved_bytecode_file->size));- EXPECT_EQ(mapped_bytecode.bytes(), bytecode.bytes());-- disk_cache.remove_entries_accessed_since(UnixDateTime::earliest());-- retrieved_bytecode = TRY_OR_FAIL(disk_cache.retrieve_associated_data(test_partition(), url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode));- EXPECT(!retrieved_bytecode.has_value());-}--TEST_CASE(replacing_cache_entry_removes_associated_data)-{- auto disk_cache = MUST(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Testing, test_cache_root())).release_value();- TestCacheRequest request;-- auto url = parse_url("https://example.com/script.js"sv);- auto request_headers = create_cacheable_request_headers();- auto response_headers = create_cacheable_response_headers();-- auto& writer = create_cache_entry(disk_cache, request, url, *request_headers);- TRY_OR_FAIL(writer.write_status_and_reason(200, "OK"_string, *request_headers, *response_headers));- TRY_OR_FAIL(writer.write_data("console.log('old');"sv.bytes()));- TRY_OR_FAIL(writer.flush(request_headers));-- auto bytecode = TRY_OR_FAIL(ByteBuffer::copy("bytecode"sv.bytes()));- auto stored = TRY_OR_FAIL(disk_cache.store_associated_data(test_partition(), url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode, bytecode.bytes()));- EXPECT(stored.has_value());- if (stored.has_value())- (void)Core::System::close(stored->fd);-- auto retrieved_bytecode = TRY_OR_FAIL(disk_cache.retrieve_associated_data(test_partition(), url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode));- VERIFY(retrieved_bytecode.has_value());-- auto replacement_request_headers = create_cacheable_request_headers();- auto replacement_response_headers = create_cacheable_response_headers();- auto& replacement_writer = create_cache_entry(disk_cache, request, url, *replacement_request_headers);- TRY_OR_FAIL(replacement_writer.write_status_and_reason(200, "OK"_string, *replacement_request_headers, *replacement_response_headers));- TRY_OR_FAIL(replacement_writer.write_data("console.log('new');"sv.bytes()));- TRY_OR_FAIL(replacement_writer.flush(replacement_request_headers));-- retrieved_bytecode = TRY_OR_FAIL(disk_cache.retrieve_associated_data(test_partition(), url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode));- EXPECT(!retrieved_bytecode.has_value());-}-TEST_CASE(flush_returns_mappable_body_file){auto disk_cache = MUST(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Testing, test_cache_root())).release_value();@@ -420,62 +334,6 @@ TEST_CASE(replacing_cache_entry_keeps_existing_body_mapping_stable)EXPECT_EQ(old_body.bytes(), "console.log('old');"sv.bytes());}-TEST_CASE(associated_data_round_trips_with_explicit_vary_key)-{- auto disk_cache = MUST(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Testing, test_cache_root())).release_value();- TestCacheRequest request;-- auto url = parse_url("https://example.com/script.js"sv);- auto request_headers = HTTP::HeaderList::create({- { HTTP::TEST_CACHE_ENABLED_HEADER, "1"sv },- { "Origin"sv, "https://origin.example"sv },- });- auto mismatched_request_headers = create_cacheable_request_headers();- auto response_headers = HTTP::HeaderList::create({- { "Cache-Control"sv, "max-age=60"sv },- { "Vary"sv, "Origin"sv },- });- auto vary_key = HTTP::create_vary_key(*request_headers, *response_headers).value();-- auto& writer = create_cache_entry(disk_cache, request, url, *request_headers);- TRY_OR_FAIL(writer.write_status_and_reason(200, "OK"_string, *request_headers, *response_headers));- TRY_OR_FAIL(writer.write_data("console.log('hello');"sv.bytes()));- TRY_OR_FAIL(writer.flush(request_headers));-- auto bytecode = TRY_OR_FAIL(ByteBuffer::copy("bytecode"sv.bytes()));- EXPECT(!TRY_OR_FAIL(disk_cache.store_associated_data(test_partition(), url, "GET"sv, *mismatched_request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode, bytecode.bytes())).has_value());- auto stored = TRY_OR_FAIL(disk_cache.store_associated_data(test_partition(), url, "GET"sv, *mismatched_request_headers, vary_key, HTTP::CacheEntryAssociatedData::JavaScriptBytecode, bytecode.bytes()));- EXPECT(stored.has_value());- if (stored.has_value())- (void)Core::System::close(stored->fd);-- auto retrieved_bytecode = TRY_OR_FAIL(disk_cache.retrieve_associated_data(test_partition(), url, "GET"sv, *mismatched_request_headers, vary_key, HTTP::CacheEntryAssociatedData::JavaScriptBytecode));- VERIFY(retrieved_bytecode.has_value());- EXPECT_EQ(retrieved_bytecode->bytes(), bytecode.bytes());-}--TEST_CASE(associated_data_participates_in_cache_eviction)-{- auto disk_cache = MUST(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Testing, test_cache_root())).release_value();- TestCacheRequest request;-- auto url = parse_url("https://example.com/script.js"sv);- auto request_headers = create_cacheable_request_headers();- auto response_headers = create_cacheable_response_headers();-- auto& writer = create_cache_entry(disk_cache, request, url, *request_headers);- TRY_OR_FAIL(writer.write_status_and_reason(200, "OK"_string, *request_headers, *response_headers));- TRY_OR_FAIL(writer.write_data("console.log('hello');"sv.bytes()));- TRY_OR_FAIL(writer.flush(request_headers));-- disk_cache.set_maximum_disk_cache_size(80);- auto bytecode = TRY_OR_FAIL(ByteBuffer::create_zeroed(100));- EXPECT(!TRY_OR_FAIL(disk_cache.store_associated_data(test_partition(), url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode, bytecode.bytes())).has_value());-- auto retrieved_bytecode = TRY_OR_FAIL(disk_cache.retrieve_associated_data(test_partition(), url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode));- EXPECT(!retrieved_bytecode.has_value());-}-TEST_CASE(cache_partitions_do_not_share_entries){auto disk_cache = MUST(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Testing, test_cache_root())).release_value();@@ -510,10 +368,7 @@ TEST_CASE(cache_partitions_do_not_share_entries)TRY_OR_FAIL(writer.write_data("console.log('hello');"sv.bytes()));TRY_OR_FAIL(writer.flush(request_headers));- auto bytecode = TRY_OR_FAIL(ByteBuffer::copy("bytecode"sv.bytes()));for (auto const& other_partition : { other_top_level_site, other_frame_site, subframe_document, cross_site_main_frame_navigation }) {- EXPECT(!TRY_OR_FAIL(disk_cache.store_associated_data(other_partition, url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode, bytecode.bytes())).has_value());-disk_cache.open_entry(request, other_partition, url, "GET"sv, *request_headers, HTTP::CacheMode::Default, HTTP::DiskCache::OpenMode::Read).visit([&](Optional<HTTP::CacheEntryReader&> reader) {@@ -522,19 +377,7 @@ TEST_CASE(cache_partitions_do_not_share_entries)[](HTTP::DiskCache::CacheHasOpenEntry) { });}- auto stored = TRY_OR_FAIL(disk_cache.store_associated_data(partition, url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode, bytecode.bytes()));-- EXPECT(stored.has_value());-- if (stored.has_value())-- (void)Core::System::close(stored->fd);- for (auto const& other_partition : { other_top_level_site, other_frame_site, subframe_document, cross_site_main_frame_navigation })- EXPECT(!TRY_OR_FAIL(disk_cache.retrieve_associated_data(other_partition, url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode)).has_value());-- auto retrieved_bytecode = TRY_OR_FAIL(disk_cache.retrieve_associated_data(partition, url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode));- VERIFY(retrieved_bytecode.has_value());- EXPECT_EQ(retrieved_bytecode->bytes(), bytecode.bytes());+ EXPECT(open_cache_entry(disk_cache, request, url, *request_headers).has_value());disk_cache.remove_entries_accessed_since(UnixDateTime::earliest());}diff --git a/Tests/LibWebView/TestFileDownloader.cpp b/Tests/LibWebView/TestFileDownloader.cppindex bbef211f888..d6647960831 100644--- a/Tests/LibWebView/TestFileDownloader.cpp+++ b/Tests/LibWebView/TestFileDownloader.cpp@@ -411,7 +411,7 @@ void expect_request_can_be_released_from_finish_callback(TestHttpServer& server,request->set_body_delivery_paused(true);request->set_unbuffered_request_callbacks(- [](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Optional<Core::ImmutableBytes>, Optional<u64>, Requests::CacheState) {+ [](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Requests::CacheState) {},[&](Requests::ResponseData data) {delivered_size += data.bytes().size();@@ -447,12 +447,12 @@ void expect_request_can_be_exported_from_headers_callback(TestHttpServer& serverbool finished = false;request->set_body_delivery_paused(true);request->set_unbuffered_request_callbacks(- [&](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Optional<Core::ImmutableBytes>, Optional<u64>, Requests::CacheState) {+ [&](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Requests::CacheState) {auto exported = MUST(request_client.export_request(*request));request = request_client.import_request(move(exported));VERIFY(request);request->set_unbuffered_request_callbacks(- [](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Optional<Core::ImmutableBytes>, Optional<u64>, Requests::CacheState) {+ [](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Requests::CacheState) {},[&](Requests::ResponseData data) {delivered_size += data.bytes().size();@@ -497,7 +497,7 @@ void expect_leased_request_is_torn_down_when_transferred_after_finishing(TestHttrequest->set_body_delivery_paused(true);request->set_unbuffered_request_callbacks(- [](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Optional<Core::ImmutableBytes>, Optional<u64>, Requests::CacheState) {+ [](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Requests::CacheState) {},[](Requests::ResponseData) {},@@ -530,7 +530,7 @@ void expect_leased_request_is_torn_down_when_transferred_after_finishing(TestHttbool adopted_request_finished = false;adopted_request->set_unbuffered_request_callbacks(- [](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Optional<Core::ImmutableBytes>, Optional<u64>, Requests::CacheState) {+ [](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Requests::CacheState) {},[&](Requests::ResponseData data) {delivered_size += data.bytes().size();diff --git a/Tests/LibWebView/TestProfile.cpp b/Tests/LibWebView/TestProfile.cppindex 5df347c1321..e980437a580 100644--- a/Tests/LibWebView/TestProfile.cpp+++ b/Tests/LibWebView/TestProfile.cpp@@ -4,7 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/ByteBuffer.h>#include <AK/LexicalPath.h>#include <AK/Time.h>#include <LibCore/Directory.h>@@ -12,6 +11,8 @@#include <LibCore/System.h>#include <LibDatabase/Database.h>#include <LibFileSystem/FileSystem.h>+#include <LibHTTP/Cache/CacheEntry.h>+#include <LibHTTP/Cache/CacheRequest.h>#include <LibHTTP/Cache/DiskCache.h>#include <LibHTTP/Cookie/ParsedCookie.h>#include <LibHTTP/HSTS/ParsedHSTSPolicy.h>@@ -261,6 +262,11 @@ TEST_CASE(profile_databases_are_isolated)remove_test_root();}+struct TestCacheRequest final : public HTTP::CacheRequest {+ virtual bool is_revalidation_request() const override { return false; }+ virtual void notify_request_unblocked(Badge<HTTP::DiskCache>) override { }+};+TEST_CASE(profile_caches_are_isolated){remove_test_root();@@ -268,7 +274,7 @@ TEST_CASE(profile_caches_are_isolated)auto second_profile = MUST(WebView::Profile::create({ .name = "second" }, roots()));auto url = parse_url("https://profile-isolation.example/script.js"sv);auto request_headers = HTTP::HeaderList::create({});- auto bytecode = TRY_OR_FAIL(ByteBuffer::copy("first-profile-bytecode"sv.bytes()));+ auto response_headers = HTTP::HeaderList::create({ { "Cache-Control"sv, "max-age=60"sv } });auto partition = HTTP::NetworkIsolationKey {.top_level_site = "https://profile-isolation.example"_utf16,.frame_site = "https://profile-isolation.example"_utf16,@@ -276,25 +282,31 @@ TEST_CASE(profile_caches_are_isolated).disk_cache_partition().release_value();+ TestCacheRequest request;+ auto has_stored_response = [&](HTTP::DiskCache& cache) {+ return cache.open_entry(request, partition, url, "GET"sv, *request_headers, HTTP::CacheMode::Default, HTTP::DiskCache::OpenMode::Read)+ .visit(+ [](Optional<HTTP::CacheEntryReader&> reader) { return reader.has_value(); },+ [](HTTP::DiskCache::CacheHasOpenEntry) { return false; });+ };+{auto cache = TRY_OR_FAIL(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Normal, LexicalPath { first_profile.paths().cache })).release_value();- EXPECT(TRY_OR_FAIL(cache.create_synthetic_entry(partition, url, "GET"sv)));- auto stored = TRY_OR_FAIL(cache.store_associated_data(partition, url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode, bytecode.bytes()));- EXPECT(stored.has_value());- if (stored.has_value())- (void)Core::System::close(stored->fd);+ auto writer = cache.create_entry(request, partition, url, "GET"sv, *request_headers, UnixDateTime::now()).get<Optional<HTTP::CacheEntryWriter&>>();+ VERIFY(writer.has_value());+ TRY_OR_FAIL(writer->write_status_and_reason(200, "OK"_string, *request_headers, *response_headers));+ TRY_OR_FAIL(writer->write_data("first-profile-script"sv.bytes()));+ TRY_OR_FAIL(writer->flush(request_headers));}{auto cache = TRY_OR_FAIL(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Normal, LexicalPath { second_profile.paths().cache })).release_value();- EXPECT(!TRY_OR_FAIL(cache.retrieve_associated_data(partition, url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode)).has_value());+ EXPECT(!has_stored_response(cache));}{auto cache = TRY_OR_FAIL(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Normal, LexicalPath { first_profile.paths().cache })).release_value();- auto retrieved_bytecode = TRY_OR_FAIL(cache.retrieve_associated_data(partition, url, "GET"sv, *request_headers, {}, HTTP::CacheEntryAssociatedData::JavaScriptBytecode));- VERIFY(retrieved_bytecode.has_value());- EXPECT_EQ(retrieved_bytecode->bytes(), bytecode.bytes());+ EXPECT(has_stored_response(cache));}remove_test_root();diff --git a/Tests/RequestServer/TestCookieResponses.cpp b/Tests/RequestServer/TestCookieResponses.cppindex b155b4d173b..b70b9fdae81 100644--- a/Tests/RequestServer/TestCookieResponses.cpp+++ b/Tests/RequestServer/TestCookieResponses.cpp@@ -174,14 +174,6 @@ public:VERIFY(!response);}- void store_cache_associated_data(HTTP::CacheEntryAssociatedData associated_data)- {- auto url = URL::Parser::basic_parse("http://localhost"sv).release_value();- auto message = make<Messages::RequestServer::StoreCacheAssociatedData>(Optional<HTTP::NetworkIsolationKey> {}, move(url), ByteString { "GET" }, Vector<HTTP::Header> {}, Optional<u64> {}, associated_data, MUST(Core::AnonymousBuffer::create_with_size(1)));- auto response = dispatch(move(message));- VERIFY(response);- }-void websocket_connect(u64 websocket_id, URL::URL url, ByteString origin = "http://localhost"sv, Vector<ByteString> protocols = {}, Vector<HTTP::Header> headers = {}){auto message = make<Messages::RequestServer::WebsocketConnect>(websocket_id, move(url), Optional<HTTP::NetworkIsolationKey> {}, move(origin), move(protocols), Vector<ByteString> {}, move(headers));@@ -453,23 +445,6 @@ TEST_CASE(websockets_to_unsupported_urls_are_refused)EXPECT(connection.is_open());}-TEST_CASE(unknown_cache_associated_data_kind_is_rejected)-{- {- TestServer server;- TestConnection connection { server };-- connection.store_cache_associated_data(HTTP::CacheEntryAssociatedData::JavaScriptBytecode);- EXPECT(connection.is_open());- }-- TestServer server;- TestConnection connection { server };-- connection.store_cache_associated_data(static_cast<HTTP::CacheEntryAssociatedData>(0x7fffffff));- EXPECT(!connection.is_open());-}-TEST_CASE(cookie_responses_cannot_target_connect_requests){TestServer server;diff --git a/Tests/RequestServer/TestSiteBinding.cpp b/Tests/RequestServer/TestSiteBinding.cppindex 12780eb0155..55f6e45f8b9 100644--- a/Tests/RequestServer/TestSiteBinding.cpp+++ b/Tests/RequestServer/TestSiteBinding.cpp@@ -5,7 +5,6 @@*/#include <LibCore/EventLoop.h>-#include <LibCore/System.h>#include <LibCore/Timer.h>#include <LibHTTP/Cache/DiskCache.h>#include <LibHTTP/NetworkIsolationKey.h>@@ -77,22 +76,6 @@ struct TestServer {VERIFY(response);}- // Puts associated data in the cache partition of the key, and returns whether RequestServer reads it back.- bool can_use_cache_partition(HTTP::NetworkIsolationKey const& network_isolation_key)- {- auto url = URL::Parser::basic_parse("https://cdn.example/library.js"sv).release_value();- auto partition = *network_isolation_key.disk_cache_partition();- (void)MUST(disk_cache->create_synthetic_entry(partition, url, "GET"sv));- auto request_headers = HTTP::HeaderList::create();- auto stored = MUST(disk_cache->store_associated_data(partition, url, "GET"sv, *request_headers, 0, HTTP::CacheEntryAssociatedData::JavaScriptBytecode, "data"sv.bytes()));- VERIFY(stored.has_value());- (void)Core::System::close(stored->fd);-- auto& stub = static_cast<RequestServerEndpoint::Stub&>(*connection);- auto response = stub.retrieve_cache_associated_data(network_isolation_key, url, ByteString { "GET" }, {}, 0u, HTTP::CacheEntryAssociatedData::JavaScriptBytecode);- return response.data().has_value();- }-void start_request(u64 request_id, StringView url, HTTP::NetworkIsolationKey const& network_isolation_key){auto message = make<Messages::RequestServer::StartRequest>(@@ -135,22 +118,30 @@ struct TestServer {}-TEST_CASE(bound_client_uses_only_the_cache_partitions_of_its_sites)+TEST_CASE(bound_client_uses_only_the_network_isolation_keys_of_its_sites){TestServer server;+ u64 request_id = 0;++ // NB: Port 2 has no listener, so a request the client may make fails to connect, and one it may not make fails+ // before that.+ auto can_use_key = [&](HTTP::NetworkIsolationKey const& network_isolation_key) {+ server.start_request(++request_id, "http://localhost:2/"sv, network_isolation_key);+ return server.wait_for_request_finished(request_id) == Requests::NetworkError::UnableToConnect;+ };- EXPECT(!server.can_use_cache_partition(key("https://a.example"sv, "https://a.example"sv)));+ EXPECT(!can_use_key(key("https://a.example"sv, "https://a.example"sv)));server.bind_to_site("https://a.example"sv, "https://a.example"sv);- EXPECT(server.can_use_cache_partition(key("https://a.example"sv, "https://a.example"sv)));+ EXPECT(can_use_key(key("https://a.example"sv, "https://a.example"sv)));// Neither another top-level site nor another frame site under the bound one is reachable.- EXPECT(!server.can_use_cache_partition(key("https://b.example"sv, "https://b.example"sv)));- EXPECT(!server.can_use_cache_partition(key("https://b.example"sv, "https://a.example"sv)));- EXPECT(!server.can_use_cache_partition(key("https://a.example"sv, "https://b.example"sv)));+ EXPECT(!can_use_key(key("https://b.example"sv, "https://b.example"sv)));+ EXPECT(!can_use_key(key("https://b.example"sv, "https://a.example"sv)));+ EXPECT(!can_use_key(key("https://a.example"sv, "https://b.example"sv)));server.bind_to_site("https://a.example"sv, "https://b.example"sv);- EXPECT(server.can_use_cache_partition(key("https://a.example"sv, "https://b.example"sv)));+ EXPECT(can_use_key(key("https://a.example"sv, "https://b.example"sv)));}TEST_CASE(bound_client_requests_only_for_its_sites)