Truly independent web browser
RequestServer: Fill the disk cache as response data arrives
Andreas Kling794ece92846a
diff --git a/Services/RequestServer/Request.cpp b/Services/RequestServer/Request.cppindex 314e60eb7e8..c25fefa2362 100644--- a/Services/RequestServer/Request.cpp+++ b/Services/RequestServer/Request.cpp@@ -658,12 +658,8 @@ Request::~Request()if (m_disk_cache.has_value())m_disk_cache->close_entries_read_by(*this);- if (m_cache_entry_writer.has_value()) {- if (m_state == State::Complete && m_curl_result_code == CURLE_OK)- (void)m_cache_entry_writer->flush(m_request_headers);- else- m_cache_entry_writer->remove_incomplete_entry();- }+ // A finished response has closed its entry by now.+ close_disk_cache_entry(DiskCacheEntryOutcome::Incomplete);if constexpr (REQUESTSERVER_WIRE_DEBUG)wire_stats().remove(this);@@ -905,8 +901,14 @@ void Request::handle_fetch_complete(int result_code)m_curl_result_code = result_code;- if (m_response_buffer.is_eof())+ if (m_response_buffer.is_eof()) {transition_to_state(State::Complete);+ return;+ }++ // The client hasn't taken the whole response yet, and it may never do so. Requests waiting on the cache entry+ // shouldn't have to wait for it.+ close_disk_cache_entry(result_code == CURLE_OK ? DiskCacheEntryOutcome::Complete : DiskCacheEntryOutcome::Incomplete);}void Request::reset_for_retry()@@ -1714,41 +1716,25 @@ void Request::handle_complete_state()// 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)) {- auto body_file = m_cache_entry_writer->flush_and_take_body_file(m_request_headers);- if (!body_file.is_error())- cached_body_file = body_file.release_value();- } else {- (void)m_cache_entry_writer->flush(m_request_headers);- }- m_cache_entry_writer.clear();- }+ close_disk_cache_entry(DiskCacheEntryOutcome::Complete);if (m_export.has_value()) {write_export_result();} else {- if (cached_body_file.has_value())- m_client->async_request_cached_body_file_available(m_request_id, IPC::File::adopt_fd(cached_body_file->fd), cached_body_file->offset, cached_body_file->size);-m_client->async_request_finished(m_request_id, m_bytes_transferred_to_client, timing_info, m_network_error);}}- if (m_cache_entry_writer.has_value()) {- if (m_curl_result_code == CURLE_OK)- (void)m_cache_entry_writer->flush(m_request_headers);- else- m_cache_entry_writer->remove_incomplete_entry();- m_cache_entry_writer.clear();- }+ close_disk_cache_entry(m_curl_result_code == CURLE_OK ? DiskCacheEntryOutcome::Complete : DiskCacheEntryOutcome::Incomplete);m_client->request_complete({}, *this);}void Request::handle_error_state(){+ // A transfer lease can keep this request alive long after it has failed.+ close_disk_cache_entry(DiskCacheEntryOutcome::Incomplete);+if (m_export.has_value()) {write_export_result();} else if (delivers_response_to_client()) {@@ -1958,7 +1944,9 @@ void Request::read_imported_body()}mark_activity();- if (auto write_result = m_response_buffer.write_some({ buffer, static_cast<size_t>(result.value()) }); write_result.is_error()) {+ ReadonlyBytes bytes { buffer, static_cast<size_t>(result.value()) };+ write_to_disk_cache(bytes);+ if (auto write_result = m_response_buffer.write_some(bytes); write_result.is_error()) {m_network_error = Requests::NetworkError::Unknown;transition_to_state(State::Error);return;@@ -2011,6 +1999,7 @@ void Request::complete_import_if_finished()return;m_curl_result_code = CURLE_OK;+ close_disk_cache_entry(m_import->network_error.has_value() ? DiskCacheEntryOutcome::Incomplete : DiskCacheEntryOutcome::Complete);if (auto result = write_queued_bytes_without_blocking(); result.is_error()) {m_network_error = Requests::NetworkError::Unknown;transition_to_state(State::Error);@@ -2106,6 +2095,11 @@ size_t Request::on_data_received(void* buffer, size_t size, size_t nmemb, void*auto total_size = size * nmemb;ReadonlyBytes bytes { static_cast<u8 const*>(buffer), total_size };+ request.write_to_disk_cache(bytes);++ if (request.m_type == RequestType::BackgroundRevalidation)+ return total_size;+auto result = [&] -> ErrorOr<void> {TRY(request.m_response_buffer.write_some(bytes));return request.write_queued_bytes_without_blocking();@@ -2339,35 +2333,35 @@ void Request::send_headers_to_client()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()+void Request::write_to_disk_cache(ReadonlyBytes bytes){- auto write_bytes_to_disk_cache = [&](ReadonlyBytes bytes) {- if (!m_cache_entry_writer.has_value())- return;-- if (m_cache_entry_writer->write_data(bytes).is_error()) {- m_cache_entry_writer.clear();- return;- }-- // The entry is still filling, even once curl has nothing left to deliver: A client that reads its response- // slowly keeps these writes coming long after the transfer is over — so they count as progress too.- mark_activity();- };+ if (!m_cache_entry_writer.has_value())+ return;- if (m_type == RequestType::BackgroundRevalidation) {- while (!m_response_buffer.is_eof()) {- auto bytes = m_response_buffer.peek_some_contiguous();- write_bytes_to_disk_cache(bytes);- MUST(m_response_buffer.discard(bytes.size()));- }+ if (m_cache_entry_writer->write_data(bytes).is_error())+ m_cache_entry_writer.clear();+}- if (m_curl_result_code.has_value())- transition_to_state(State::Complete);+void Request::close_disk_cache_entry(DiskCacheEntryOutcome outcome)+{+ if (!m_cache_entry_writer.has_value())+ return;- return {};+ if (outcome == DiskCacheEntryOutcome::Incomplete) {+ m_cache_entry_writer->remove_incomplete_entry();+ } else if (delivers_response_to_client() && !m_export.has_value() && m_cache_entry_writer->body_size() >= static_cast<u64>(PAGE_SIZE)) {+ // The client may still be reading the response through its pipe, which this file doesn't replace.+ if (auto body_file = m_cache_entry_writer->flush_and_take_body_file(m_request_headers); !body_file.is_error())+ m_client->async_request_cached_body_file_available(m_request_id, IPC::File::adopt_fd(body_file.value().fd), body_file.value().offset, body_file.value().size);+ } else {+ (void)m_cache_entry_writer->flush(m_request_headers);}+ m_cache_entry_writer.clear();+}++ErrorOr<void> Request::write_queued_bytes_without_blocking()+{if (!m_client_writer_notifier) {m_client_writer_notifier = Core::Notifier::construct(m_client_request_pipe->writer_fd(), Core::NotificationType::Write);m_client_writer_notifier->set_enabled(false);@@ -2418,7 +2412,6 @@ ErrorOr<void> Request::write_queued_bytes_without_blocking()}auto written = result.value();- write_bytes_to_disk_cache(bytes.slice(0, written));MUST(m_response_buffer.discard(written));m_bytes_transferred_to_client += written;diff --git a/Services/RequestServer/Request.h b/Services/RequestServer/Request.hindex a1b72c14762..43116378933 100644--- a/Services/RequestServer/Request.h+++ b/Services/RequestServer/Request.h@@ -249,8 +249,8 @@ private:static size_t on_header_received(void* buffer, size_t size, size_t nmemb, void* user_data);static size_t on_data_received(void* buffer, size_t size, size_t nmemb, void* user_data);- // A state change, response bytes from curl, or bytes written to the cache entry count as progress — and a- // request waiting on the cache entry this request holds open judges by it whether this request has stalled.+ // A state change or response bytes from the network count as progress, and a request waiting on the cache entry+ // this request holds open judges by it whether this request has stalled.void mark_activity() { m_last_activity_time = MonotonicTime::now(); }ErrorOr<void> detach_curl_handle_from_multi();@@ -270,6 +270,13 @@ private:void handle_fetch_complete(int result_code);void send_headers_to_client();ErrorOr<void> write_queued_bytes_without_blocking();+ void write_to_disk_cache(ReadonlyBytes);++ enum class DiskCacheEntryOutcome : u8 {+ Complete,+ Incomplete,+ };+ void close_disk_cache_entry(DiskCacheEntryOutcome);virtual bool is_revalidation_request() const override;ErrorOr<void> revalidation_failed();diff --git a/Tests/RequestServer/TestDiskCacheWaiters.cpp b/Tests/RequestServer/TestDiskCacheWaiters.cppindex 6a93c458cc8..ab0f027f3a1 100644--- a/Tests/RequestServer/TestDiskCacheWaiters.cpp+++ b/Tests/RequestServer/TestDiskCacheWaiters.cpp@@ -5,6 +5,7 @@*/#include <AK/ByteString.h>+#include <AK/HashTable.h>#include <AK/Time.h>#include <LibCore/EventLoop.h>#include <LibCore/Socket.h>@@ -262,26 +263,13 @@ public:// Pumps the event loop until the request finishes or the budget runs out — reading every response as it comes.Optional<FinishedRequest> wait_for_request_to_finish(u64 request_id, AK::Duration budget)- {- return wait_for_request_to_finish_reading_slowly(request_id, budget, 64 * KiB, AK::Duration {});- }-- // Pumps the event loop until the request finishes or the budget runs out — reading a bounded amount of every- // response, no more often than every interval: A client that's slow to consume what it asked for, but never stops.- // Reading less than RequestServer has ready leaves it holding the rest.- Optional<FinishedRequest> wait_for_request_to_finish_reading_slowly(u64 request_id, AK::Duration budget, size_t bytes_per_read, AK::Duration interval){auto deadline = MonotonicTime::now() + budget;- auto next_read = MonotonicTime::now();while (MonotonicTime::now() < deadline) {m_server.event_loop.pump(Core::EventLoop::WaitMode::PollForEvents);drain_client_messages();-- if (MonotonicTime::now() >= next_read) {- read_from_response_sockets(bytes_per_read);- next_read = MonotonicTime::now() + interval;- }+ read_from_response_sockets();if (auto finished = m_finished_requests.get(request_id); finished.has_value())return *finished;@@ -290,14 +278,18 @@ public:return {};}+ void never_read_response_of(u64 request_id) { m_unread_requests.set(request_id); }+private:- void read_from_response_sockets(size_t max_bytes_per_socket)+ void read_from_response_sockets(){- if (m_response_read_buffer.size() < max_bytes_per_socket)- m_response_read_buffer = MUST(ByteBuffer::create_uninitialized(max_bytes_per_socket));+ u8 buffer[64 * KiB];- for (auto& response_socket : m_response_sockets)- (void)response_socket.value->read_some(m_response_read_buffer.span().slice(0, max_bytes_per_socket));+ for (auto& response_socket : m_response_sockets) {+ if (m_unread_requests.contains(response_socket.key))+ continue;+ (void)response_socket.value->read_some({ buffer, sizeof(buffer) });+ }}void drain_client_messages()@@ -336,7 +328,7 @@ private:RefPtr<RequestServer::ConnectionFromClient> m_connection;HashMap<u64, ByteString> m_cache_statuses;HashMap<u64, NonnullOwnPtr<Core::LocalSocket>> m_response_sockets;- ByteBuffer m_response_read_buffer;+ HashTable<u64> m_unread_requests;HashMap<u64, FinishedRequest> m_finished_requests;};@@ -477,12 +469,13 @@ TEST_CASE(request_waiting_on_a_cache_entry_writer_that_stopped_receiving_data_byEXPECT_EQ(http_server.connection_count_when_finished(0).value_or(0), 1u);}-// A request whose cache entry is held open by a transfer that's over on the wire, but whose bytes are still going out-// to a slow client, keeps waiting: The entry is still filling — however slowly — so fetching a second copy would waste-// a request on a response that's already on its way to disk.-TEST_CASE(request_waiting_on_a_cache_entry_a_slow_client_is_still_filling_keeps_waiting)+// A request waiting on a cache entry depends only on the transfer filling it. Once that's over on the wire the entry is+// complete, however far behind the client of that transfer is. A client may never read its response at all: Fetching a+// resource and dropping the unread response is a common way to warm a cache.+TEST_CASE(request_waiting_on_a_cache_entry_is_not_held_up_by_a_client_that_never_reads_its_response){- RequestServer::Request::set_wait_for_cache_timeout(AK::Duration::from_seconds(1));+ // NB: Long enough that waiting it out can't be what finishes the second request.+ RequestServer::Request::set_wait_for_cache_timeout(AK::Duration::from_seconds(60));RequestServer::Request::set_revalidation_stall_timeout(AK::Duration::from_seconds(60));TestServer server;@@ -497,25 +490,44 @@ TEST_CASE(request_waiting_on_a_cache_entry_a_slow_client_is_still_filling_keeps_} };auto url = http_server.url_for_path("/resource"sv);- auto started_at = MonotonicTime::now();+ connection.never_read_response_of(1);connection.start_request(1, url);connection.start_request(2, url);- // The client takes 64 KiB every 25ms: three wait limits or so for the whole body, with the entry filling the whole- // way through — and the request waiting on it has to sit through all of it. And that pace isn't arbitrary:- // RequestServer writes to the entry only as the pipe takes bytes, and Linux reports a stream socket writable again- // only once three quarters of its send buffer have drained. So, the client has to take a few hundred KiB well within- // one limit — or the entry goes quiet for a whole one, and the waiting request rightly gives up on it.- auto finished = connection.wait_for_request_to_finish_reading_slowly(1, AK::Duration::from_seconds(30), 64 * KiB, AK::Duration::from_milliseconds(25));- expect_finished_without_error(finished, "written-to-cache"sv);-- // NB: A pipe that could hold the whole body would end the transfer at once — and leave the wait untested.- EXPECT(MonotonicTime::now() - started_at >= AK::Duration::from_seconds(2));-expect_finished_without_error(connection.wait_for_request_to_finish(2, AK::Duration::from_seconds(10)), "read-from-cache"sv);EXPECT_EQ(http_server.connection_count(), 1u);}+TEST_CASE(request_waiting_on_a_cache_entry_is_not_held_up_by_a_failed_transfer_nobody_read)+{+ // NB: Long enough that waiting it out can't be what finishes the second request.+ RequestServer::Request::set_wait_for_cache_timeout(AK::Duration::from_seconds(60));+ RequestServer::Request::set_revalidation_stall_timeout(AK::Duration::from_seconds(60));++ TestServer server;+ auto disk_cache = create_test_disk_cache();+ TestConnection connection { server, disk_cache };++ // The first connection closes halfway through a body too large for the client pipe to hold.+ auto partial_body = ByteString::repeated('x', 8 * MiB);+ StallingServer http_server { [&](size_t connection_index) -> Optional<ServerResponse> {+ if (connection_index == 0) {+ auto response = chunked_http_response("max-age=60"sv, partial_body, 32 * KiB, AK::Duration::from_milliseconds(2));+ response.pieces[0] = http_response_head("max-age=60"sv, 16 * MiB);+ return response;+ }+ return ServerResponse::at_once(http_response("max-age=60"sv, "hello"sv));+ } };++ auto url = http_server.url_for_path("/resource"sv);+ connection.never_read_response_of(1);+ connection.start_request(1, url);+ connection.start_request(2, url);++ expect_finished_without_error(connection.wait_for_request_to_finish(2, AK::Duration::from_seconds(10)), "written-to-cache"sv);+ EXPECT_EQ(http_server.connection_count(), 2u);+}+TEST_CASE(not_modified_response_that_changes_vary_fails_revalidation){RequestServer::Request::set_wait_for_cache_timeout(AK::Duration::from_seconds(10));diff --git a/Tests/RequestServer/TestExportImport.cpp b/Tests/RequestServer/TestExportImport.cppindex a30e645b001..fbc03bf01b1 100644--- a/Tests/RequestServer/TestExportImport.cpp+++ b/Tests/RequestServer/TestExportImport.cpp@@ -277,6 +277,8 @@ public:return URL::Parser::basic_parse(ByteString::formatted("http://127.0.0.1:{}/document", *m_server->local_port())).release_value();}+ void end_first_transfer_early_at(size_t offset) { m_first_transfer_end = offset; }+size_t request_count() const { return m_request_count; }bool peer_closed(size_t index) const { return m_connections[index]->peer_closed; }bool finished(size_t index) const { return m_connections[index]->offset == m_body.size(); }@@ -311,7 +313,8 @@ private:}MUST(connection.socket->set_blocking(false));connection.offset += piece.size();- if (connection.offset == m_body.size()) {+ auto ends_early = m_first_transfer_end.has_value() && &connection == m_connections.first().ptr() && connection.offset >= *m_first_transfer_end;+ if (connection.offset == m_body.size() || ends_early) {connection.piece_timer->stop();connection.socket->close();}@@ -323,6 +326,7 @@ private:size_t m_piece_size { 0 };AK::Duration m_interval;size_t m_request_count { 0 };+ Optional<size_t> m_first_transfer_end;};ByteBuffer patterned_body(size_t size)@@ -384,6 +388,65 @@ TEST_CASE(exported_response_is_delivered_and_cached_by_the_importing_request_serEXPECT_EQ(http_server.request_count(), 1u);}+TEST_CASE(imported_response_whose_transfer_failed_is_not_cached)+{+ Core::EventLoop event_loop;+ TestServer source_server { "failed-export-source"sv };+ TestServer target_server { "failed-export-target"sv };+ DrippingServer http_server { patterned_body(300 * KiB), 16 * KiB, AK::Duration::from_milliseconds(2) };+ http_server.end_first_transfer_early_at(128 * KiB);+ auto url = http_server.url();+ auto key = navigation_key_for(url);++ TestConnection navigator { source_server, ReadsBodies::No };+ TestConnection source_ui { source_server, ReadsBodies::No };+ navigator.start_request(1, url, key, true);+ (void)navigator.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 1);+ source_ui.adopt_request(navigator.client_id(), 1, 10, true);+ (void)source_ui.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 10);++ auto exported = source_ui.export_request(10);+ EXPECT(exported.has_value());++ TestConnection target_ui { target_server, ReadsBodies::No };+ TestConnection target { target_server };+ target_ui.import_request(20, exported.release_value(), true);+ target.adopt_request(target_ui.client_id(), 20, 30, false);++ auto finished = target.wait_for<Messages::RequestClient::RequestFinished>(event_loop, 30);+ EXPECT(finished->network_error().has_value());++ target.start_request(31, url, key, false);+ auto headers = target.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 31);+ auto cache_status = headers->response_headers().first_matching([](auto const& header) { return header.name == HTTP::TEST_CACHE_STATUS_HEADER; });+ EXPECT(cache_status.has_value());+ EXPECT_NE(cache_status->value, "read-from-cache"sv);+ (void)target.wait_for<Messages::RequestClient::RequestFinished>(event_loop, 31);+ EXPECT_EQ(http_server.request_count(), 2u);+}++TEST_CASE(failed_request_with_a_transfer_lease_releases_its_cache_entry)+{+ Core::EventLoop event_loop;+ TestServer server { "failed-lease"sv };+ DrippingServer http_server { patterned_body(300 * KiB), 16 * KiB, AK::Duration::from_milliseconds(2) };+ http_server.end_first_transfer_early_at(128 * KiB);+ auto url = http_server.url();+ auto key = navigation_key_for(url);++ TestConnection connection { server };+ connection.start_request(1, url, key, true);+ auto finished = connection.wait_for<Messages::RequestClient::RequestFinished>(event_loop, 1);+ EXPECT(finished->network_error().has_value());++ connection.start_request(2, url, key, false);+ auto headers = connection.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 2);+ auto cache_status = headers->response_headers().first_matching([](auto const& header) { return header.name == HTTP::TEST_CACHE_STATUS_HEADER; });+ EXPECT(cache_status.has_value());+ EXPECT_EQ(cache_status->value, "written-to-cache"sv);+ (void)connection.wait_for<Messages::RequestClient::RequestFinished>(event_loop, 2);+}+TEST_CASE(stopping_an_imported_request_aborts_the_transfer){Core::EventLoop event_loop;