Truly independent web browser
RequestServer+LibWeb: Count WebSocket traffic in the performance monitor
Luke Wilde8c093dfd4de0
diff --git a/Libraries/LibRequests/RequestClient.cpp b/Libraries/LibRequests/RequestClient.cppindex adb95c0dbc5..7e9f52ba663 100644--- a/Libraries/LibRequests/RequestClient.cpp+++ b/Libraries/LibRequests/RequestClient.cpp@@ -250,10 +250,10 @@ void RequestClient::request_transferred(u64 request_id)(*request)->did_transfer({});}-RefPtr<WebSocket> RequestClient::websocket_connect(URL::URL const& url, Optional<HTTP::NetworkIsolationKey> const& network_isolation_key, ByteString const& origin, Vector<ByteString> const& protocols, Vector<ByteString> const& extensions, HTTP::HeaderList const& request_headers, HTTP::Cookie::SameSiteContext same_site_context)+RefPtr<WebSocket> RequestClient::websocket_connect(URL::URL const& url, Optional<HTTP::NetworkIsolationKey> const& network_isolation_key, ByteString const& origin, Vector<ByteString> const& protocols, Vector<ByteString> const& extensions, HTTP::HeaderList const& request_headers, u64 originating_page_id, HTTP::Cookie::SameSiteContext same_site_context){auto websocket_id = m_next_websocket_id++;- IPCProxy::async_websocket_connect(websocket_id, url, network_isolation_key, origin, protocols, extensions, request_headers.headers(), same_site_context);+ IPCProxy::async_websocket_connect(websocket_id, url, network_isolation_key, origin, protocols, extensions, request_headers.headers(), originating_page_id, same_site_context);auto connection = WebSocket::create_from_id({}, *this, websocket_id);m_websockets.set(websocket_id, connection);return connection;diff --git a/Libraries/LibRequests/RequestClient.h b/Libraries/LibRequests/RequestClient.hindex 5c401b47b77..3b135ecd19d 100644--- a/Libraries/LibRequests/RequestClient.h+++ b/Libraries/LibRequests/RequestClient.h@@ -68,7 +68,7 @@ public:// No other client this process creates has the same epoch, so a request is known by its id and this epoch.u64 transport_epoch() const { return m_transport_epoch; }- 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, HTTP::Cookie::SameSiteContext);+ 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, u64 originating_page_id, HTTP::Cookie::SameSiteContext);// 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.diff --git a/Libraries/LibWeb/WebSockets/WebSocket.cpp b/Libraries/LibWeb/WebSockets/WebSocket.cppindex 5afac8c45b9..137cffc2f88 100644--- a/Libraries/LibWeb/WebSockets/WebSocket.cpp+++ b/Libraries/LibWeb/WebSockets/WebSocket.cpp@@ -40,6 +40,7 @@#include <LibWeb/Loader/LoaderConfig.h>#include <LibWeb/Loader/ResourceLoader.h>#include <LibWeb/MixedContent/AbstractOperations.h>+#include <LibWeb/Page/Page.h>#include <LibWeb/Platform/EventLoopPlugin.h>#include <LibWeb/UpgradeInsecureRequests/AbstractOperations.h>#include <LibWeb/WebIDL/AbstractOperations.h>@@ -248,7 +249,11 @@ ErrorOr<void> WebSocket::establish_web_socket_connection(URL::URL const& url_recif (!request_client)return Error::from_string_literal("RequestServer is currently unavailable");- m_websocket = request_client->websocket_connect(connection_url, move(network_isolation_key), origin_string, protocol_byte_strings, {}, additional_headers, { .status = request->same_site_status(), .is_safe_method = true });+ // NB: As for its requests, a worker's page has no top-level traversable or browser page ID.+ auto& page = Bindings::principal_host_defined_page(client.realm());+ auto originating_page_id = page.has_top_level_traversable() ? page.client().id().value() : 0;++ m_websocket = request_client->websocket_connect(connection_url, move(network_isolation_key), origin_string, protocol_byte_strings, {}, additional_headers, originating_page_id, { .status = request->same_site_status(), .is_safe_method = true });m_websocket->on_open = GC::weak_callback(*this, [](auto& self) {self.on_open();diff --git a/Services/RequestServer/ConnectionFromClient.cpp b/Services/RequestServer/ConnectionFromClient.cppindex f8aa5d895e6..9f82f368cd7 100644--- a/Services/RequestServer/ConnectionFromClient.cpp+++ b/Services/RequestServer/ConnectionFromClient.cpp@@ -901,7 +901,7 @@ size_t ConnectionFromClient::total_websocket_count() constreturn count;}-void ConnectionFromClient::websocket_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, HTTP::Cookie::SameSiteContext same_site_context)+void ConnectionFromClient::websocket_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, u64 originating_page_id, HTTP::Cookie::SameSiteContext same_site_context){if (m_pending_websockets.contains(websocket_id) || m_websockets.contains(websocket_id)) {did_misbehave("reused live WebSocket ID");@@ -959,11 +959,11 @@ void ConnectionFromClient::websocket_connect(u64 websocket_id, URL::URL url, Optm_websocket_cookie_requests.set(websocket_id, {.cookie_request_id = cookie_request_id,- .continuation = [this, websocket_id, url, origin = move(origin), protocols = move(protocols), extensions = move(extensions), request_headers = move(additional_request_headers)](String cookie) mutable {+ .continuation = [this, websocket_id, originating_page_id, url, origin = move(origin), protocols = move(protocols), extensions = move(extensions), request_headers = move(additional_request_headers)](String cookie) mutable {// Sent as UTF-8, like the Cookie header of a fetch.if (!cookie.is_empty())request_headers.append({ "Cookie"sv, cookie.to_byte_string() });- connect_websocket(websocket_id, move(url), move(origin), move(protocols), move(extensions), move(request_headers));+ connect_websocket(websocket_id, originating_page_id, move(url), move(origin), move(protocols), move(extensions), move(request_headers));},});@@ -987,7 +987,7 @@ bool ConnectionFromClient::websocket_retrieved_http_cookie(Badge<ControlConnectireturn true;}-void ConnectionFromClient::connect_websocket(u64 websocket_id, URL::URL url, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers)+void ConnectionFromClient::connect_websocket(u64 websocket_id, u64 originating_page_id, URL::URL url, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers){auto host = url.serialized_host().to_byte_string();auto weak_self = make_weak_ptr<ConnectionFromClient>();@@ -999,7 +999,7 @@ void ConnectionFromClient::connect_websocket(u64 websocket_id, URL::URL url, Byt}auto proxy = proxy_configuration().proxy_for(url).copy();- resolve_proxy_host(proxy, [weak_self, websocket_id, url = move(url), origin = move(origin), protocols = move(protocols), extensions = move(extensions), additional_request_headers = move(additional_request_headers), proxy](ErrorOr<void> result) mutable {+ resolve_proxy_host(proxy, [weak_self, websocket_id, originating_page_id, url = move(url), origin = move(origin), protocols = move(protocols), extensions = move(extensions), additional_request_headers = move(additional_request_headers), proxy](ErrorOr<void> result) mutable {auto self = weak_self.strong_ref();if (!self)return;@@ -1009,11 +1009,11 @@ void ConnectionFromClient::connect_websocket(u64 websocket_id, URL::URL url, Bytself->fail_websocket(websocket_id, Requests::WebSocket::Error::CouldNotEstablishConnection);return;}- self->look_up_websocket_host(websocket_id, move(url), move(origin), move(protocols), move(extensions), move(additional_request_headers), move(proxy));+ self->look_up_websocket_host(websocket_id, originating_page_id, move(url), move(origin), move(protocols), move(extensions), move(additional_request_headers), move(proxy));});}-void ConnectionFromClient::look_up_websocket_host(u64 websocket_id, URL::URL url, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers, Optional<HTTP::Proxy> proxy)+void ConnectionFromClient::look_up_websocket_host(u64 websocket_id, u64 originating_page_id, URL::URL url, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers, Optional<HTTP::Proxy> proxy){auto host = url.serialized_host().to_byte_string();auto weak_self = make_weak_ptr<ConnectionFromClient>();@@ -1021,7 +1021,7 @@ void ConnectionFromClient::look_up_websocket_host(u64 websocket_id, URL::URL url// Avoid leaking hostnames resolved by the proxy.if (proxy.has_value() && proxy->resolves_hostnames()) {if (m_pending_websockets.remove(websocket_id))- open_websocket(websocket_id, move(url), move(origin), move(protocols), move(extensions), move(additional_request_headers), move(proxy), nullptr);+ open_websocket(websocket_id, originating_page_id, move(url), move(origin), move(protocols), move(extensions), move(additional_request_headers), move(proxy), nullptr);return;}@@ -1035,7 +1035,7 @@ void ConnectionFromClient::look_up_websocket_host(u64 websocket_id, URL::URL urlreturn;self->fail_websocket(websocket_id, Requests::WebSocket::Error::CouldNotEstablishConnection);})- .when_resolved([weak_self, websocket_id, host = move(host), url = move(url), origin = move(origin), protocols = move(protocols), extensions = move(extensions), additional_request_headers = move(additional_request_headers), proxy = move(proxy)](auto const& dns_result) mutable {+ .when_resolved([weak_self, websocket_id, originating_page_id, host = move(host), url = move(url), origin = move(origin), protocols = move(protocols), extensions = move(extensions), additional_request_headers = move(additional_request_headers), proxy = move(proxy)](auto const& dns_result) mutable {auto self = weak_self.strong_ref();if (!self)return;@@ -1051,11 +1051,11 @@ void ConnectionFromClient::look_up_websocket_host(u64 websocket_id, URL::URL urlif (!self->m_pending_websockets.remove(websocket_id))return;- self->open_websocket(websocket_id, move(url), move(origin), move(protocols), move(extensions), move(additional_request_headers), move(proxy), dns_result);+ self->open_websocket(websocket_id, originating_page_id, move(url), move(origin), move(protocols), move(extensions), move(additional_request_headers), move(proxy), dns_result);});}-void ConnectionFromClient::open_websocket(u64 websocket_id, URL::URL url, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers, Optional<HTTP::Proxy> proxy, RefPtr<DNS::LookupResult const> dns_result)+void ConnectionFromClient::open_websocket(u64 websocket_id, u64 originating_page_id, URL::URL url, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers, Optional<HTTP::Proxy> proxy, RefPtr<DNS::LookupResult const> dns_result){auto weak_self = make_weak_ptr<ConnectionFromClient>();@@ -1072,6 +1072,7 @@ void ConnectionFromClient::open_websocket(u64 websocket_id, URL::URL url, ByteStauto impl = WebSocketImplCurl::create(m_websocket_curl.handle);impl->set_proxy(move(proxy));+ impl->set_performance_origin(client_id(), originating_page_id);auto connection = WebSocket::WebSocket::create(move(connection_info), move(impl));connection->on_open = [self = weak_self, websocket_id]() {diff --git a/Services/RequestServer/ConnectionFromClient.h b/Services/RequestServer/ConnectionFromClient.hindex df3e806181c..fc338246fd4 100644--- a/Services/RequestServer/ConnectionFromClient.h+++ b/Services/RequestServer/ConnectionFromClient.h@@ -97,7 +97,7 @@ 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 void websocket_connect(u64 websocket_id, URL::URL, Optional<HTTP::NetworkIsolationKey>, ByteString, Vector<ByteString>, Vector<ByteString>, Vector<HTTP::Header>, HTTP::Cookie::SameSiteContext) override;+ virtual void websocket_connect(u64 websocket_id, URL::URL, Optional<HTTP::NetworkIsolationKey>, ByteString, Vector<ByteString>, Vector<ByteString>, Vector<HTTP::Header>, u64 originating_page_id, HTTP::Cookie::SameSiteContext) override;virtual void websocket_send(u64 websocket_id, bool, ByteBuffer) override;virtual void websocket_send_shared(u64 websocket_id, bool, Core::AnonymousBuffer) override;virtual void websocket_close(u64 websocket_id, u16, ByteString) override;@@ -111,9 +111,9 @@ private:void fail_websocket(u64 websocket_id, Requests::WebSocket::Error);size_t websocket_count() const;size_t total_websocket_count() const;- void connect_websocket(u64 websocket_id, URL::URL, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> request_headers);- void look_up_websocket_host(u64 websocket_id, URL::URL, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers, Optional<HTTP::Proxy>);- void open_websocket(u64 websocket_id, URL::URL, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers, Optional<HTTP::Proxy>, RefPtr<DNS::LookupResult const>);+ void connect_websocket(u64 websocket_id, u64 originating_page_id, URL::URL, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> request_headers);+ void look_up_websocket_host(u64 websocket_id, u64 originating_page_id, URL::URL, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers, Optional<HTTP::Proxy>);+ void open_websocket(u64 websocket_id, u64 originating_page_id, URL::URL, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers, Optional<HTTP::Proxy>, RefPtr<DNS::LookupResult const>);IsPrivate m_is_private { IsPrivate::No };diff --git a/Services/RequestServer/Request.cpp b/Services/RequestServer/Request.cppindex c9509bcc6ff..94c0b5973ca 100644--- a/Services/RequestServer/Request.cpp+++ b/Services/RequestServer/Request.cpp@@ -2549,6 +2549,17 @@ Vector<Requests::NetworkUsage> Request::take_network_usage()return result;}+void Request::add_network_usage(Requests::NetworkUsage const& usage)+{+ if (!s_performance_monitor_enabled || usage.client_id == 0 || (usage.download_bytes == 0 && usage.upload_bytes == 0))+ return;+ auto& total = s_network_usage.ensure(usage.client_id).ensure(usage.page_id, [&] {+ return Requests::NetworkUsage { usage.client_id, usage.page_id, 0, 0 };+ });+ total.download_bytes = saturating_add(total.download_bytes, usage.download_bytes);+ total.upload_bytes = saturating_add(total.upload_bytes, usage.upload_bytes);+}+void Request::set_performance_origin(int client_id, u64 page_id){m_performance_origin = { client_id, page_id, 0, 0 };@@ -2577,11 +2588,7 @@ void Request::sample_network_usage()auto delta = m_performance_origin;delta.download_bytes = download_bytes >= m_sampled_download_bytes ? download_bytes - m_sampled_download_bytes : download_bytes;delta.upload_bytes = upload_bytes >= m_sampled_upload_bytes ? upload_bytes - m_sampled_upload_bytes : upload_bytes;- if (delta.download_bytes || delta.upload_bytes) {- auto& total = s_network_usage.ensure(delta.client_id).ensure(delta.page_id, [&] { return m_performance_origin; });- total.download_bytes = saturating_add(total.download_bytes, delta.download_bytes);- total.upload_bytes = saturating_add(total.upload_bytes, delta.upload_bytes);- }+ add_network_usage(delta);}m_sampled_download_bytes = download_bytes;m_sampled_upload_bytes = upload_bytes;diff --git a/Services/RequestServer/Request.h b/Services/RequestServer/Request.hindex a0f921f307f..00232f92aa6 100644--- a/Services/RequestServer/Request.h+++ b/Services/RequestServer/Request.h@@ -105,6 +105,7 @@ public:static void set_performance_monitor_enabled(bool);static Vector<Requests::NetworkUsage> take_network_usage();+ static void add_network_usage(Requests::NetworkUsage const&);void set_performance_origin(int client_id, u64 page_id);void sample_network_usage();diff --git a/Services/RequestServer/RequestServer.ipc b/Services/RequestServer/RequestServer.ipcindex 8591c6fc723..a2da7a195cf 100644--- a/Services/RequestServer/RequestServer.ipc+++ b/Services/RequestServer/RequestServer.ipc@@ -35,7 +35,7 @@ endpoint RequestServerresolve_host(u64 lookup_id, ByteString host) =|// Websocket Connection API- websocket_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, HTTP::Cookie::SameSiteContext same_site_context) =|+ websocket_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, u64 originating_page_id, HTTP::Cookie::SameSiteContext same_site_context) =|websocket_send(u64 websocket_id, bool is_text, ByteBuffer data) =|websocket_send_shared(u64 websocket_id, bool is_text, Core::AnonymousBuffer data) =|websocket_close(u64 websocket_id, u16 code, ByteString reason) =|diff --git a/Services/RequestServer/WebSocketImplCurl.cpp b/Services/RequestServer/WebSocketImplCurl.cppindex 26687eaec2b..9cc901d28d5 100644--- a/Services/RequestServer/WebSocketImplCurl.cpp+++ b/Services/RequestServer/WebSocketImplCurl.cpp@@ -7,6 +7,7 @@#include <LibCore/Notifier.h>#include <RequestServer/CURL.h>#include <RequestServer/ConnectionFromClient.h>+#include <RequestServer/Request.h>#include <RequestServer/Resolver.h>#include <RequestServer/WebSocketImplCurl.h>@@ -210,6 +211,7 @@ void WebSocketImplCurl::read_from_socket()if (0 == nread)break;+ add_network_usage(nread, 0);if (auto const err = m_read_buffer.write_until_depleted({ buffer, nread }); err.is_error()) {on_connection_error();return;@@ -233,8 +235,10 @@ bool WebSocketImplCurl::flush_pending_write_buffer()}m_pending_write_buffer_offset += sent;- if (sent > 0)+ if (sent > 0) {+ add_network_usage(0, sent);continue;+ }if (result == CURLE_AGAIN) {if (m_write_notifier)@@ -253,6 +257,14 @@ bool WebSocketImplCurl::flush_pending_write_buffer()return true;}+void WebSocketImplCurl::add_network_usage(u64 download_bytes, u64 upload_bytes) const+{+ auto usage = m_performance_origin;+ usage.download_bytes = download_bytes;+ usage.upload_bytes = upload_bytes;+ Request::add_network_usage(usage);+}+bool WebSocketImplCurl::did_connect(){// NB: curl can finish the transfer successfully when the server closes the connection without sending a responsediff --git a/Services/RequestServer/WebSocketImplCurl.h b/Services/RequestServer/WebSocketImplCurl.hindex 9abf240bc1b..4a34941e743 100644--- a/Services/RequestServer/WebSocketImplCurl.h+++ b/Services/RequestServer/WebSocketImplCurl.h@@ -9,6 +9,7 @@#include <AK/MemoryStream.h>#include <LibCore/Forward.h>#include <LibHTTP/Proxy.h>+#include <LibRequests/NetworkUsage.h>#include <LibWebSocket/Impl/WebSocketImpl.h>typedef void CURL;@@ -24,6 +25,7 @@ public:static NonnullRefPtr<WebSocketImplCurl> create(CURLM*);void set_proxy(Optional<HTTP::Proxy> proxy) { m_proxy = move(proxy); }+ void set_performance_origin(int client_id, u64 page_id) { m_performance_origin = { client_id, page_id, 0, 0 }; }virtual void connect(WebSocket::ConnectionInfo const&) override;virtual ErrorOr<ByteBuffer> read(int max_size) override;@@ -38,9 +40,11 @@ private:void read_from_socket();bool flush_pending_write_buffer();+ void add_network_usage(u64 download_bytes, u64 upload_bytes) const;CURLM* m_multi_handle { nullptr };Optional<HTTP::Proxy> m_proxy;+ Requests::NetworkUsage m_performance_origin;CURL* m_easy_handle { nullptr };RefPtr<Core::Notifier> m_read_notifier;RefPtr<Core::Notifier> m_write_notifier;diff --git a/Tests/RequestServer/TestCookieResponses.cpp b/Tests/RequestServer/TestCookieResponses.cppindex 1eea5e78c0c..8455e8061c9 100644--- a/Tests/RequestServer/TestCookieResponses.cpp+++ b/Tests/RequestServer/TestCookieResponses.cpp@@ -195,7 +195,7 @@ public: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), HTTP::Cookie::SameSiteContext {});+ auto message = make<Messages::RequestServer::WebsocketConnect>(websocket_id, move(url), Optional<HTTP::NetworkIsolationKey> {}, move(origin), move(protocols), Vector<ByteString> {}, move(headers), 0, HTTP::Cookie::SameSiteContext {});auto response = dispatch(move(message));VERIFY(!response);}diff --git a/Tests/RequestServer/TestNetworkUsage.cpp b/Tests/RequestServer/TestNetworkUsage.cppindex b86781f2ccd..a94241b4324 100644--- a/Tests/RequestServer/TestNetworkUsage.cpp+++ b/Tests/RequestServer/TestNetworkUsage.cpp@@ -12,6 +12,7 @@#include <LibIPC/Transport.h>#include <LibTest/TestCase.h>#include <LibURL/Parser.h>+#include <LibWebSocket/WebSocket.h>#include <RequestServer/CURL.h>#include <RequestServer/ConnectionFromClient.h>#include <RequestServer/ControlConnectionFromClient.h>@@ -58,30 +59,79 @@ struct TestServer {VERIFY(!MUST(static_cast<RequestServerEndpoint::Stub&>(*connection).handle(move(message))));}- // Runs the event loop until RequestServer has reported at least this much traffic, and returns its reports.- Vector<Requests::NetworkUsage> wait_for_network_usage(u64 download_bytes, u64 upload_bytes)+ void websocket_connect(u64 websocket_id, URL::URL url, u64 originating_page_id)+ {+ auto message = make<Messages::RequestServer::WebsocketConnect>(+ websocket_id, move(url), Optional<HTTP::NetworkIsolationKey> {}, ByteString { "http://127.0.0.1" }, Vector<ByteString> {},+ Vector<ByteString> {}, Vector<HTTP::Header> {}, originating_page_id, HTTP::Cookie::SameSiteContext {});+ VERIFY(!MUST(static_cast<RequestServerEndpoint::Stub&>(*connection).handle(move(message))));+ }++ void websocket_send(u64 websocket_id, StringView text)+ {+ auto message = make<Messages::RequestServer::WebsocketSend>(websocket_id, true, MUST(ByteBuffer::copy(text.bytes())));+ VERIFY(!MUST(static_cast<RequestServerEndpoint::Stub&>(*connection).handle(move(message))));+ }++ // Runs the event loop until RequestServer tells the client that the WebSocket is open.+ void wait_for_websocket_connected(u64 websocket_id){- // The control transport is not part of the event loop here, so keep the loop from sleeping until it has news.+ // The transports are not part of the event loop here, so keep the loop from sleeping until they have news.auto wake_timer = Core::Timer::create_repeating(AK::Duration::from_milliseconds(10), [] { });wake_timer->start();- Vector<Requests::NetworkUsage> usage;- u64 downloaded = 0;- u64 uploaded = 0;+ bool connected = false;event_loop.spin_until([&] {- (void)control_remote_transport->read_as_many_messages_as_possible_without_blocking([&](auto&& raw_message) {- auto message = MUST(RequestServerControlClientEndpoint::decode_message(raw_message.bytes.bytes(), raw_message.attachments));- if (message->message_id() != Messages::RequestServerControlClient::NetworkUsage::static_message_id())+ read_control_messages();+ (void)remote_transport->read_as_many_messages_as_possible_without_blocking([&](auto&& raw_message) {+ auto message = MUST(RequestClientEndpoint::decode_message(raw_message.bytes.bytes(), raw_message.attachments));+ if (message->message_id() != Messages::RequestClient::WebsocketConnected::static_message_id())return;- for (auto const& entry : static_cast<Messages::RequestServerControlClient::NetworkUsage&>(*message).usage()) {- downloaded += entry.download_bytes;- uploaded += entry.upload_bytes;- usage.append(entry);- }+ if (static_cast<Messages::RequestClient::WebsocketConnected&>(*message).websocket_id() == websocket_id)+ connected = true;});+ return connected;+ });+ }++ // Runs the event loop until RequestServer has reported at least this much traffic, and returns its reports.+ Vector<Requests::NetworkUsage> wait_for_network_usage(u64 download_bytes, u64 upload_bytes)+ {+ auto wake_timer = Core::Timer::create_repeating(AK::Duration::from_milliseconds(10), [] { });+ wake_timer->start();++ event_loop.spin_until([&] {+ read_control_messages();+ u64 downloaded = 0;+ u64 uploaded = 0;+ for (auto const& entry : network_usage) {+ downloaded += entry.download_bytes;+ uploaded += entry.upload_bytes;+ }return downloaded >= download_bytes && uploaded >= upload_bytes;});- return usage;+ return move(network_usage);+ }++ // Keeps RequestServer's reports of network usage, and answers its cookie lookups with no cookies.+ void read_control_messages()+ {+ Vector<NonnullOwnPtr<Messages::RequestServerControlClient::RetrieveHttpCookie>> cookie_requests;+ (void)control_remote_transport->read_as_many_messages_as_possible_without_blocking([&](auto&& raw_message) {+ auto message = MUST(RequestServerControlClientEndpoint::decode_message(raw_message.bytes.bytes(), raw_message.attachments));+ if (message->message_id() == Messages::RequestServerControlClient::RetrieveHttpCookie::static_message_id()) {+ cookie_requests.append(message.template release_nonnull<Messages::RequestServerControlClient::RetrieveHttpCookie>());+ return;+ }+ if (message->message_id() == Messages::RequestServerControlClient::NetworkUsage::static_message_id())+ network_usage.extend(static_cast<Messages::RequestServerControlClient::NetworkUsage&>(*message).take_usage());+ });++ for (auto const& cookie_request : cookie_requests) {+ auto message = make<Messages::RequestServerControl::RetrievedHttpCookie>(+ cookie_request->client_id(), cookie_request->request_id(), cookie_request->request_type(), cookie_request->cookie_request_id(), String {});+ VERIFY(!MUST(static_cast<RequestServerControlEndpoint::Stub&>(*control_connection).handle(move(message))));+ }}Core::EventLoop event_loop;@@ -91,6 +141,7 @@ struct TestServer {RefPtr<RequestServer::ControlConnectionFromClient> control_connection;OwnPtr<IPC::Transport> remote_transport;RefPtr<RequestServer::ConnectionFromClient> connection;+ Vector<Requests::NetworkUsage> network_usage;};// A local HTTP server that answers every request with a body of the given size.@@ -127,6 +178,33 @@ private:Vector<NonnullOwnPtr<Core::TCPSocket>> m_sockets;};+// A local WebSocket server that greets every client with a text message.+class WebSocketServer {+public:+ explicit WebSocketServer(StringView greeting)+ {+ m_server = MUST(Core::TCPServer::try_create());+ MUST(m_server->listen(IPv4Address { 127, 0, 0, 1 }, 0));+ m_server->on_ready_to_accept = [this, greeting = ByteString { greeting }] {+ auto websocket = MUST(WebSocket::WebSocket::accept(MUST(m_server->accept()), {}));+ websocket->on_open = [&websocket = *websocket, greeting] {+ websocket.send(WebSocket::Message { greeting });+ };+ websocket->start();+ m_websockets.append(move(websocket));+ };+ }++ URL::URL url() const+ {+ return URL::Parser::basic_parse(ByteString::formatted("ws://127.0.0.1:{}/", *m_server->local_port())).release_value();+ }++private:+ RefPtr<Core::TCPServer> m_server;+ Vector<NonnullRefPtr<WebSocket::WebSocket>> m_websockets;+};+}TEST_CASE(request_traffic_is_reported_under_the_client_that_made_it)@@ -145,3 +223,26 @@ TEST_CASE(request_traffic_is_reported_under_the_client_that_made_it)}EXPECT_EQ(downloaded, 1000u);}++TEST_CASE(websocket_traffic_is_reported_as_it_crosses_the_socket)+{+ TestServer server;+ WebSocketServer websocket_server("hello"sv);++ server.websocket_connect(1, websocket_server.url(), 42);+ server.wait_for_websocket_connected(1);+ server.websocket_send(1, "hi there"sv);++ // The server's frame has a 2-byte header, and ours a 2-byte header and a 4-byte mask.+ auto usage = server.wait_for_network_usage(2 + 5, 6 + 8);+ u64 downloaded = 0;+ u64 uploaded = 0;+ for (auto const& entry : usage) {+ EXPECT_EQ(entry.client_id, server.connection->client_id());+ EXPECT_EQ(entry.page_id, 42u);+ downloaded += entry.download_bytes;+ uploaded += entry.upload_bytes;+ }+ EXPECT_EQ(downloaded, 2u + 5u);+ EXPECT_EQ(uploaded, 6u + 8u);+}