Truly independent web browser
LibRequests+LibWeb+RequestServer: Report upload progress while sending
sideshowbarker82e64304ca85
diff --git a/Libraries/LibRequests/Request.cpp b/Libraries/LibRequests/Request.cppindex 19a766d701a..1be7744fa6d 100644--- a/Libraries/LibRequests/Request.cpp+++ b/Libraries/LibRequests/Request.cpp@@ -363,6 +363,7 @@ void Request::defer_teardown()Core::deferred_invoke([self = NonnullRefPtr(*this)] {self->on_headers_received = nullptr;self->on_finish = nullptr;+ self->on_upload_progress = nullptr;self->m_internal_buffered_data = nullptr;self->m_internal_stream_data = nullptr;});diff --git a/Libraries/LibRequests/Request.h b/Libraries/LibRequests/Request.hindex fb50da3b57b..89920fded2b 100644--- a/Libraries/LibRequests/Request.h+++ b/Libraries/LibRequests/Request.h@@ -125,6 +125,7 @@ public:void set_stop_callback(RequestStopped);Function<void()> on_requires_network;+ Function<void(u64 bytes_sent)> on_upload_progress;enum class TeardownReason : u8 {Stopped,diff --git a/Libraries/LibRequests/RequestClient.cpp b/Libraries/LibRequests/RequestClient.cppindex ec94ef226b4..931459d99a0 100644--- a/Libraries/LibRequests/RequestClient.cpp+++ b/Libraries/LibRequests/RequestClient.cpp@@ -207,6 +207,14 @@ void RequestClient::request_requires_network(u64 request_id)}}+void RequestClient::request_upload_progress(u64 request_id, u64 bytes_sent)+{+ if (auto request = m_requests.get(request_id); request.has_value()) {+ if ((*request)->on_upload_progress)+ (*request)->on_upload_progress(bytes_sent);+ }+}+void RequestClient::request_started(u64 request_id, IPC::File response_file){auto request = m_requests.get(request_id);diff --git a/Libraries/LibRequests/RequestClient.h b/Libraries/LibRequests/RequestClient.hindex 3f383254ae1..b6deea21a3c 100644--- a/Libraries/LibRequests/RequestClient.h+++ b/Libraries/LibRequests/RequestClient.h@@ -79,6 +79,7 @@ private:virtual void die() override;virtual void request_requires_network(u64 request_id) override;+ virtual void request_upload_progress(u64 request_id, u64 bytes_sent) override;virtual void request_started(u64 request_id, IPC::File) override;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;diff --git a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cpp b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cppindex 0024f1bd420..695848f4b72 100644--- a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cpp+++ b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cpp@@ -48,6 +48,11 @@ void NetworkTransportHandle::set_on_requires_network(Function<void()> on_requirem_request->on_requires_network = move(on_requires_network);}+void NetworkTransportHandle::set_on_upload_progress(Function<void(u64 bytes_sent)> on_upload_progress)+{+ m_request->on_upload_progress = move(on_upload_progress);+}+void NetworkTransportHandle::set_on_teardown(Function<void(Requests::Request::TeardownReason)> on_teardown){m_request->on_teardown = move(on_teardown);diff --git a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.hindex 0e765e5f35e..a63749c6dc7 100644--- a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h+++ b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h@@ -32,6 +32,7 @@ public:void release_transfer_lease();void set_on_requires_network(Function<void()>);+ void set_on_upload_progress(Function<void(u64 bytes_sent)>);void set_on_teardown(Function<void(Requests::Request::TeardownReason)>);private:diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex 55636f868d0..a3f6b27c6ec 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -3041,10 +3041,27 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(// 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, processBodyError, and// fetchParams’s task destination.- // AD-HOC: A request holds its body's source and length but not its stream. A body with a source is read as its- // stream would give it, as one chunk of the whole source, and a body without one through the reader- // fetch() acquired for its stream.- if (auto const& source = body->source(); source.has_value()) {+ // AD-HOC: A request holds its body's source and length but not its stream. A body with a source is read in the+ // chunks RequestServer reports sending it in, when it goes over the network, and otherwise as one+ // chunk of the whole source. A body without a source is read through the reader fetch() acquired for+ // its stream.+ auto const& source = body->source();+ if (source.has_value() && source->size() > 0 && network_transport) {+ network_transport->set_on_upload_progress([fetch_params = NonnullRefPtr { fetch_params }, process_body_chunk, process_end_of_body = GC::Root { process_end_of_body }, length = source->size(), bytes_read = u64 { 0 }](u64 bytes_sent) mutable {+ bytes_sent = min(bytes_sent, length);+ if (bytes_sent <= bytes_read)+ return;+ auto chunk_length = bytes_sent - bytes_read;+ bytes_read = bytes_sent;++ auto controller = fetch_params->controller();+ Infrastructure::queue_fetch_task(controller, controller->task_destination(), GC::create_function(GC::Heap::the(), [process_body_chunk, chunk_length] {+ process_body_chunk(chunk_length);+ }));+ if (bytes_read == length)+ Infrastructure::queue_fetch_task(controller, controller->task_destination(), GC::Ref { *process_end_of_body });+ });+ } else if (source.has_value()) {if (auto length = source->size(); length > 0) {Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.controller()->task_destination(), GC::create_function(GC::Heap::the(), [process_body_chunk, length] {process_body_chunk(length);diff --git a/Services/RequestServer/Request.cpp b/Services/RequestServer/Request.cppindex 915bbcc8acb..06471100cca 100644--- a/Services/RequestServer/Request.cpp+++ b/Services/RequestServer/Request.cpp@@ -344,8 +344,11 @@ static void record_chunk(Request const* request, size_t bytes)stats.max_chunk_bytes = bytes;}-[[maybe_unused]] static int on_xferinfo(void* user_data, curl_off_t /*dltotal*/, curl_off_t dlnow, curl_off_t /*ultotal*/, curl_off_t /*ulnow*/)+static int on_xferinfo(void* user_data, curl_off_t /*dltotal*/, curl_off_t dlnow, curl_off_t /*ultotal*/, curl_off_t ulnow){+ if (ulnow > 0)+ static_cast<Request*>(user_data)->did_send_request_body_bytes(static_cast<u64>(ulnow));+if constexpr (!REQUESTSERVER_WIRE_DEBUG)return 0;auto* request = static_cast<Request const*>(user_data);@@ -1625,7 +1628,8 @@ void Request::handle_fetch_state()set_option(CURLOPT_WRITEFUNCTION, &on_data_received);set_option(CURLOPT_WRITEDATA, this);- if constexpr (REQUESTSERVER_WIRE_DEBUG) {+ // Progress callbacks report how much of a request body curl has sent.+ if (REQUESTSERVER_WIRE_DEBUG || (m_type == RequestType::Fetch && !m_request_body.is_empty())) {set_option(CURLOPT_NOPROGRESS, 0L);set_option(CURLOPT_XFERINFOFUNCTION, &on_xferinfo);set_option(CURLOPT_XFERINFODATA, this);@@ -2318,8 +2322,33 @@ void Request::transfer_headers_to_client_if_needed()send_headers_to_client(move(javascript_bytecode), javascript_bytecode_size, javascript_bytecode_cache_vary_key);}+void Request::did_send_request_body_bytes(u64 bytes_sent)+{+ if (m_type != RequestType::Fetch)+ return;++ bytes_sent = min(bytes_sent, m_request_body.size());+ if (bytes_sent <= m_reported_request_body_bytes)+ return;++ // Curl calls back far more often than a client could use, so report at most every 50ms, which is how often XHR+ // fires its upload progress events, and always report the whole body once it's sent.+ auto now = MonotonicTime::now();+ if (bytes_sent < m_request_body.size() && m_last_request_body_report_time.has_value()+ && now - *m_last_request_body_report_time < AK::Duration::from_milliseconds(50))+ return;++ m_last_request_body_report_time = now;+ m_reported_request_body_bytes = 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){+ // 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.+ did_send_request_body_bytes(m_request_body.size());+auto cache_state = Requests::CacheState::NotCached;if (m_cache_status == CacheStatus::ReadFromCache)cache_state = m_cache_entry_was_revalidated ? Requests::CacheState::Validated : Requests::CacheState::Local;diff --git a/Services/RequestServer/Request.h b/Services/RequestServer/Request.hindex b6bedba0d36..da451ed7958 100644--- a/Services/RequestServer/Request.h+++ b/Services/RequestServer/Request.h@@ -127,6 +127,9 @@ public:bool notify_retrieved_http_cookie(Badge<ControlConnectionFromClient>, u64 cookie_request_id, StringView cookie);bool notify_stored_response_cookies_and_hsts_policy(Badge<ControlConnectionFromClient>, u64 store_request_id);void notify_fetch_complete(Badge<ConnectionFromClient>, int result_code);++ // Tells the client how much of the request body has been sent.+ void did_send_request_body_bytes(u64 bytes_sent);void retry_after_aia(Badge<ConnectionFromClient>);AIACollector* aia_collector() const { return m_aia_collector.ptr(); }@@ -343,6 +346,8 @@ private:MonotonicTime m_last_activity_time { MonotonicTime::now() };NonnullRefPtr<HTTP::HeaderList> m_request_headers;ByteBuffer m_request_body;+ u64 m_reported_request_body_bytes { 0 };+ Optional<MonotonicTime> m_last_request_body_report_time;HTTP::Cookie::IncludeCredentials m_include_credentials { HTTP::Cookie::IncludeCredentials::Yes };diff --git a/Services/RequestServer/RequestClient.ipc b/Services/RequestServer/RequestClient.ipcindex 0b89380d0ef..24becc395da 100644--- a/Services/RequestServer/RequestClient.ipc+++ b/Services/RequestServer/RequestClient.ipc@@ -9,6 +9,7 @@endpoint RequestClient{request_requires_network(u64 request_id) =|+ request_upload_progress(u64 request_id, u64 bytes_sent) =|request_started(u64 request_id, IPC::File fd) =|request_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) =|diff --git a/Tests/LibWeb/Fixtures/http-test-server.py b/Tests/LibWeb/Fixtures/http-test-server.pyindex 865780982f4..568e8c34dfe 100755--- a/Tests/LibWeb/Fixtures/http-test-server.py+++ b/Tests/LibWeb/Fixtures/http-test-server.py@@ -34,6 +34,8 @@ Description:Endpoints:- POST /echo <json body>, Creates an echo response for later use. See "Echo" class below for body properties.- Echo responses accept chunks=<byte-counts> and chunk_unblock_tokens=<tokens> query parameters.+ - Echo responses accept request_body_read_size=<bytes> and request_body_read_delay_ms=<ms> query parameters,+ which read the request's body that many bytes at a time, waiting that long before each read.Each named token holds the response after the corresponding chunk until GET /unblock/<token>.- GET <any path> with an "Upgrade: websocket" header: Performs a WebSocket handshake and then echoesevery text/binary frame back to the client verbatim. With a "send-binary=<size>" query parameter, the@@ -610,7 +612,17 @@ class TestHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):# The request's body is read before responding, so closing the connection does not reset it.content_length = int(self.headers.get("Content-Length", 0))if content_length:- self.rfile.read(content_length)+ read_size = int(query.get("request_body_read_size", [content_length])[0])+ read_delay_ms = int(query.get("request_body_read_delay_ms", [0])[0])+ remaining = content_length+ while remaining > 0:+ if read_delay_ms:+ time.sleep(read_delay_ms / 1000)+ read = len(self.rfile.read(min(read_size, remaining)))+ # The client closed the connection before sending the whole body.+ if read == 0:+ break+ remaining -= readis_revalidation_request = "If-Modified-Since" in self.headerssend_not_modified = is_revalidation_request and "X-Ladybird-Respond-With-Not-Modified" in self.headersdiff --git a/Tests/LibWeb/Text/expected/XHR/upload-progress-follows-transmission.txt b/Tests/LibWeb/Text/expected/XHR/upload-progress-follows-transmission.txtnew file mode 100644index 00000000000..77dcc591b3a--- /dev/null+++ b/Tests/LibWeb/Text/expected/XHR/upload-progress-follows-transmission.txt@@ -0,0 +1,12 @@+File: more than one loaded value: true+File: loaded never decreases: true+File: first progress before the end: true+File: load true+File: loadend true+File: status 200+FormData: more than one loaded value: true+FormData: loaded never decreases: true+FormData: first progress before the end: true+FormData: load true+FormData: loadend true+FormData: status 200diff --git a/Tests/LibWeb/Text/input/XHR/upload-progress-follows-transmission.html b/Tests/LibWeb/Text/input/XHR/upload-progress-follows-transmission.htmlnew file mode 100644index 00000000000..0a7bae9504b--- /dev/null+++ b/Tests/LibWeb/Text/input/XHR/upload-progress-follows-transmission.html@@ -0,0 +1,49 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // The server reads each request body slowly, so upload progress events fire as the body goes out, not all at once.+ asyncTest(async done => {+ const httpServer = httpTestServer();+ const url = await httpServer.createEcho("POST", "/xhr-upload-progress-follows-transmission", {+ status: 200,+ headers: { "Access-Control-Allow-Origin": "*" },+ body: "ok",+ });+ const bytes = new Uint8Array(16 * 1024 * 1024);++ function upload(name, body) {+ return new Promise(resolve => {+ const xhr = new XMLHttpRequest();+ const progress = [];+ let total = 0;+ xhr.upload.onprogress = event => {+ progress.push(event.loaded);+ total = event.total;+ };+ xhr.upload.onload = event => {+ // The progress event that completing the upload fires can repeat the last one's loaded value.+ const neverDecreases = progress.every((loaded, index) => index === 0 || loaded >= progress[index - 1]);+ println(`${name}: more than one loaded value: ${new Set(progress).size > 1}`);+ println(`${name}: loaded never decreases: ${neverDecreases}`);+ println(`${name}: first progress before the end: ${progress[0] < total}`);+ println(`${name}: load ${event.loaded === event.total && event.total === total}`);+ };+ xhr.upload.onloadend = event => {+ println(`${name}: loadend ${event.loaded === event.total && event.total === total}`);+ };+ xhr.onloadend = () => {+ println(`${name}: status ${xhr.status}`);+ resolve();+ };+ xhr.open("POST", `${url}?request_body_read_size=524288&request_body_read_delay_ms=25`);+ xhr.send(body);+ });+ }++ await upload("File", new File([bytes], "file.bin"));+ const formData = new FormData();+ formData.append("file", new File([bytes], "file.bin"));+ await upload("FormData", formData);+ done();+ });+</script>