Skip to content

Truly independent web browser

LibWeb+LibWebSocket+RequestServer: Keep unsent data in bufferedAmount

Luke Wilde27dcf09691d2
diff --git a/Libraries/LibRequests/RequestClient.cpp b/Libraries/LibRequests/RequestClient.cpp
index 7e9f52ba663..bfe5dd39c6c 100644
--- a/Libraries/LibRequests/RequestClient.cpp
+++ b/Libraries/LibRequests/RequestClient.cpp
@@ -271,6 +271,12 @@ void RequestClient::websocket_received(u64 websocket_id, bool is_text, ByteBuffe
(*connection)->did_receive({}, move(data), is_text);
}
+void RequestClient::websocket_transmitted(u64 websocket_id, u64 message_byte_count)
+{
+ if (auto connection = m_websockets.get(websocket_id); connection.has_value())
+ (*connection)->did_transmit({}, message_byte_count);
+}
+
void RequestClient::websocket_received_shared(u64 websocket_id, bool is_text, Core::AnonymousBuffer data)
{
auto connection = m_websockets.get(websocket_id);
diff --git a/Libraries/LibRequests/RequestClient.h b/Libraries/LibRequests/RequestClient.h
index 3b135ecd19d..bb79e3aea71 100644
--- a/Libraries/LibRequests/RequestClient.h
+++ b/Libraries/LibRequests/RequestClient.h
@@ -90,6 +90,7 @@ private:
virtual void websocket_connected(u64 websocket_id) override;
virtual void websocket_received(u64 websocket_id, bool, ByteBuffer) override;
virtual void websocket_received_shared(u64 websocket_id, bool, Core::AnonymousBuffer) override;
+ virtual void websocket_transmitted(u64 websocket_id, u64 message_byte_count) override;
virtual void websocket_errored(u64 websocket_id, i32) override;
virtual void websocket_closed(u64 websocket_id, u16, ByteString, bool) override;
virtual void websocket_ready_state_changed(u64 websocket_id, u32 ready_state) override;
diff --git a/Libraries/LibRequests/WebSocket.cpp b/Libraries/LibRequests/WebSocket.cpp
index e81629d8894..80270985c55 100644
--- a/Libraries/LibRequests/WebSocket.cpp
+++ b/Libraries/LibRequests/WebSocket.cpp
@@ -81,6 +81,12 @@ void WebSocket::did_receive(Badge<RequestClient>, ByteBuffer data, bool is_text)
on_message(WebSocket::Message { move(data), is_text });
}
+void WebSocket::did_transmit(Badge<RequestClient>, u64 message_byte_count)
+{
+ if (on_message_bytes_transmitted)
+ on_message_bytes_transmitted(message_byte_count);
+}
+
void WebSocket::did_error(Badge<RequestClient>, i32 error_code)
{
if (on_error)
diff --git a/Libraries/LibRequests/WebSocket.h b/Libraries/LibRequests/WebSocket.h
index f5afc438bd1..bf1ea8201f0 100644
--- a/Libraries/LibRequests/WebSocket.h
+++ b/Libraries/LibRequests/WebSocket.h
@@ -60,12 +60,14 @@ public:
Function<void()> on_open;
Function<void(Message)> on_message;
+ Function<void(u64 message_byte_count)> on_message_bytes_transmitted;
Function<void(Error)> on_error;
Function<void(u16 code, ByteString reason, bool was_clean)> on_close;
Function<void()> on_ready_state_change;
void did_open(Badge<RequestClient>);
void did_receive(Badge<RequestClient>, ByteBuffer, bool);
+ void did_transmit(Badge<RequestClient>, u64 message_byte_count);
void did_error(Badge<RequestClient>, i32);
void did_close(Badge<RequestClient>, u16, ByteString, bool);
void detach_from_client(Badge<RequestClient>);
diff --git a/Libraries/LibWeb/WebSockets/WebSocket.cpp b/Libraries/LibWeb/WebSockets/WebSocket.cpp
index 137cffc2f88..abde06a2993 100644
--- a/Libraries/LibWeb/WebSockets/WebSocket.cpp
+++ b/Libraries/LibWeb/WebSockets/WebSocket.cpp
@@ -261,6 +261,9 @@ ErrorOr<void> WebSocket::establish_web_socket_connection(URL::URL const& url_rec
m_websocket->on_message = GC::weak_callback(*this, [](auto& self, auto message) {
self.on_message(move(message.data), message.is_text);
});
+ m_websocket->on_message_bytes_transmitted = GC::weak_callback(*this, [](auto& self, u64 byte_count) {
+ self.on_message_bytes_transmitted(byte_count);
+ });
m_websocket->on_close = GC::weak_callback(*this, [](auto& self, auto code, auto reason, bool was_clean) {
self.on_close(code, Utf16String::from_utf8(StringView { reason.bytes() }), was_clean);
});
@@ -380,10 +383,21 @@ u64 WebSocket::buffered_amount() const
{
// The bufferedAmount getter steps are to return the number of bytes of application data (UTF-8 text and binary
// data) that have been queued using send() but that, as of the last time the event loop reached step 1, had not
- // yet been transmitted to the network.
+ // yet been transmitted to the network. (This thus includes any text sent during the execution of the current task,
+ // regardless of whether the user agent is able to transmit text in the background in parallel with script
+ // execution.) This does not include framing overhead incurred by the protocol, or buffering done by the operating
+ // system or network hardware.
return m_buffered_amount;
}
+void WebSocket::on_message_bytes_transmitted(u64 byte_count)
+{
+ // Applied in a task of its own, so that bufferedAmount never changes while a task runs.
+ HTML::queue_a_task(HTML::Task::Source::WebSocket, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *this }, byte_count), [](auto& self, auto& byte_count) {
+ self->m_buffered_amount -= min(byte_count, self->m_buffered_amount);
+ }));
+}
+
// https://websockets.spec.whatwg.org/#dom-websocket-send
WebIDL::ExceptionOr<void> WebSocket::send(WebSocketSendData const& data)
{
@@ -431,14 +445,6 @@ WebIDL::ExceptionOr<void> WebSocket::send(WebSocketSendData const& data)
m_buffered_amount += message_size;
- // NB: A sent message is handed to the network process right away, so it counts as transmitted to the network once
- // the event loop has moved on from the current task.
- if (is_open && message_size > 0) {
- HTML::queue_a_task(HTML::Task::Source::WebSocket, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *this }, message_size), [](auto& self, auto& message_size) {
- self->m_buffered_amount -= message_size;
- }));
- }
-
return {};
}
diff --git a/Libraries/LibWeb/WebSockets/WebSocket.h b/Libraries/LibWeb/WebSockets/WebSocket.h
index 606a4dfd4b5..15d32994407 100644
--- a/Libraries/LibWeb/WebSockets/WebSocket.h
+++ b/Libraries/LibWeb/WebSockets/WebSocket.h
@@ -66,6 +66,7 @@ public:
private:
void on_open();
void on_message(ByteBuffer message, bool is_text);
+ void on_message_bytes_transmitted(u64 byte_count);
void on_closing_handshake_started();
void on_error();
void on_close(u16 code, Utf16String reason, bool was_clean);
diff --git a/Libraries/LibWebSocket/Impl/AcceptedSocket.cpp b/Libraries/LibWebSocket/Impl/AcceptedSocket.cpp
index cd492bc56e0..a5ef08da7b5 100644
--- a/Libraries/LibWebSocket/Impl/AcceptedSocket.cpp
+++ b/Libraries/LibWebSocket/Impl/AcceptedSocket.cpp
@@ -46,7 +46,11 @@ ErrorOr<ByteBuffer> AcceptedSocket::read(int max_size)
bool AcceptedSocket::send(ReadonlyBytes bytes)
{
- return !m_socket->write_until_depleted(bytes).is_error();
+ if (m_socket->write_until_depleted(bytes).is_error())
+ return false;
+ if (on_bytes_written)
+ on_bytes_written(bytes.size());
+ return true;
}
bool AcceptedSocket::eof()
diff --git a/Libraries/LibWebSocket/Impl/WebSocketImpl.h b/Libraries/LibWebSocket/Impl/WebSocketImpl.h
index ff6c339d9f5..104af90d2ab 100644
--- a/Libraries/LibWebSocket/Impl/WebSocketImpl.h
+++ b/Libraries/LibWebSocket/Impl/WebSocketImpl.h
@@ -29,6 +29,9 @@ public:
Function<void()> on_connection_error;
Function<void()> on_ready_to_read;
+ // Called with how many of the bytes passed to send() have been written to the connection, in order.
+ Function<void(size_t)> on_bytes_written;
+
protected:
WebSocketImpl();
};
diff --git a/Libraries/LibWebSocket/WebSocket.cpp b/Libraries/LibWebSocket/WebSocket.cpp
index 65057c11a8e..91076e7435b 100644
--- a/Libraries/LibWebSocket/WebSocket.cpp
+++ b/Libraries/LibWebSocket/WebSocket.cpp
@@ -59,6 +59,7 @@ WebSocket::~WebSocket()
m_impl->on_connection_error = nullptr;
m_impl->on_connected = nullptr;
m_impl->on_ready_to_read = nullptr;
+ m_impl->on_bytes_written = nullptr;
m_impl->discard_connection();
}
}
@@ -105,6 +106,9 @@ void WebSocket::start()
auto protector = NonnullRefPtr { *this };
drain_read();
};
+ m_impl->on_bytes_written = [this](size_t byte_count) {
+ did_write_bytes(byte_count);
+ };
set_state(WebSocket::InternalState::EstablishingProtocolConnection);
m_impl->connect(m_connection);
}
@@ -304,7 +308,7 @@ static bool contains_header_token(ByteString const& value, StringView token)
void WebSocket::reject_client_handshake(StringView status)
{
auto response = ByteString::formatted("HTTP/1.1 {}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", status);
- m_impl->send(response.bytes());
+ send_bytes(response.bytes());
fail_connection(to_underlying(CloseStatusCode::AbnormalClosure), Error::ConnectionUpgradeFailed, {});
}
@@ -366,7 +370,7 @@ void WebSocket::read_client_handshake()
return;
}
if (!version.has_value() || *version != "13"sv) {
- m_impl->send("HTTP/1.1 426 Upgrade Required\r\nSec-WebSocket-Version: 13\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"sv.bytes());
+ send_bytes("HTTP/1.1 426 Upgrade Required\r\nSec-WebSocket-Version: 13\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"sv.bytes());
fail_connection(to_underlying(CloseStatusCode::AbnormalClosure), Error::ConnectionUpgradeFailed, {});
return;
}
@@ -382,7 +386,7 @@ void WebSocket::read_client_handshake()
auto digest = Crypto::Hash::digest(Crypto::Hash::HashKind::SHA1, accept_input.bytes());
auto accept = MUST(encode_base64(digest.bytes()));
auto response = ByteString::formatted("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {}\r\n\r\n", accept);
- if (!m_impl->send(response.bytes())) {
+ if (!send_bytes(response.bytes())) {
fail_connection(to_underlying(CloseStatusCode::AbnormalClosure), Error::ConnectionUpgradeFailed, {});
return;
}
@@ -712,10 +716,42 @@ void WebSocket::send_frame(WebSocket::OpCode op_code, ReadonlyBytes payload, boo
buf.overwrite(offset, payload.data(), payload.size());
offset += payload.size();
}
- if (!m_impl->send(buf.span().slice(0, offset)) && m_role == Role::Server)
+ auto is_message_frame = op_code == OpCode::Text || op_code == OpCode::Binary || op_code == OpCode::Continuation;
+ if (!send_bytes(buf.span().slice(0, offset), is_message_frame ? payload.size() : 0) && m_role == Role::Server)
fail_connection(to_underlying(CloseStatusCode::AbnormalClosure), Error::ServerClosedSocket, "Unable to send a frame");
}
+bool WebSocket::send_bytes(ReadonlyBytes bytes, u64 message_byte_count)
+{
+ // A frame's message bytes come last. Record them first, as the connection may write them before send() returns.
+ auto end = m_bytes_passed_to_connection + bytes.size();
+ if (message_byte_count > 0)
+ m_unwritten_message_bytes.enqueue({ end - message_byte_count, end });
+ m_bytes_passed_to_connection = end;
+ return m_impl->send(bytes);
+}
+
+void WebSocket::did_write_bytes(size_t byte_count)
+{
+ auto written_before = m_bytes_written;
+ m_bytes_written += byte_count;
+
+ u64 message_byte_count = 0;
+ while (!m_unwritten_message_bytes.is_empty()) {
+ auto const& message_bytes = m_unwritten_message_bytes.head();
+ auto start = max(message_bytes.start, written_before);
+ auto end = min(message_bytes.end, m_bytes_written);
+ if (end > start)
+ message_byte_count += end - start;
+ if (message_bytes.end > m_bytes_written)
+ break;
+ (void)m_unwritten_message_bytes.dequeue();
+ }
+
+ if (message_byte_count > 0 && on_message_bytes_transmitted)
+ on_message_bytes_transmitted(message_byte_count);
+}
+
void WebSocket::discard_connection()
{
if (m_discard_connection_requested)
@@ -730,6 +766,7 @@ void WebSocket::discard_connection()
m_impl->on_connection_error = nullptr;
m_impl->on_connected = nullptr;
m_impl->on_ready_to_read = nullptr;
+ m_impl->on_bytes_written = nullptr;
m_impl = nullptr;
});
}
diff --git a/Libraries/LibWebSocket/WebSocket.h b/Libraries/LibWebSocket/WebSocket.h
index af60df9b7fb..5cc85826ffa 100644
--- a/Libraries/LibWebSocket/WebSocket.h
+++ b/Libraries/LibWebSocket/WebSocket.h
@@ -7,6 +7,7 @@
#pragma once
+#include <AK/Queue.h>
#include <AK/Span.h>
#include <AK/Time.h>
#include <LibCore/EventReceiver.h>
@@ -83,6 +84,9 @@ public:
Function<void(ReadyState)> on_ready_state_change;
Function<void(ByteString)> on_subprotocol;
+ // Called with how many bytes of sent messages have been written to the connection, frame headers aside.
+ Function<void(u64)> on_message_bytes_transmitted;
+
enum class Error {
CouldNotEstablishConnection,
ConnectionUpgradeFailed,
@@ -113,6 +117,8 @@ private:
ErrorOr<void> read_frame();
void send_frame(OpCode, ReadonlyBytes, bool is_final);
+ bool send_bytes(ReadonlyBytes, u64 message_byte_count = 0);
+ void did_write_bytes(size_t);
void notify_open();
void notify_close(u16 code, ByteString reason, bool was_clean);
@@ -151,6 +157,15 @@ private:
RefPtr<Core::Timer> m_closing_handshake_timer;
RefPtr<Core::Timer> m_opening_handshake_timer;
+ // Where the bytes of each sent message lie among all the bytes passed to the connection, until they are written.
+ struct MessageBytes {
+ u64 start { 0 };
+ u64 end { 0 };
+ };
+ Queue<MessageBytes> m_unwritten_message_bytes;
+ u64 m_bytes_passed_to_connection { 0 };
+ u64 m_bytes_written { 0 };
+
Vector<u8> m_buffered_data;
size_t m_buffered_data_offset { 0 };
ByteBuffer m_fragmented_data_buffer;
diff --git a/Services/RequestServer/ConnectionFromClient.cpp b/Services/RequestServer/ConnectionFromClient.cpp
index 9f82f368cd7..893eacc7af3 100644
--- a/Services/RequestServer/ConnectionFromClient.cpp
+++ b/Services/RequestServer/ConnectionFromClient.cpp
@@ -1104,6 +1104,10 @@ void ConnectionFromClient::open_websocket(u64 websocket_id, u64 originating_page
}
strong_self->async_websocket_received(websocket_id, message.is_text(), data);
};
+ connection->on_message_bytes_transmitted = [self = weak_self, websocket_id](u64 byte_count) {
+ if (auto strong_self = self.strong_ref())
+ strong_self->async_websocket_transmitted(websocket_id, byte_count);
+ };
connection->on_error = [self = weak_self, websocket_id](auto message) {
if (auto strong_self = self.strong_ref())
strong_self->async_websocket_errored(websocket_id, (i32)message);
diff --git a/Services/RequestServer/RequestClient.ipc b/Services/RequestServer/RequestClient.ipc
index 21126319892..79d92e75bd4 100644
--- a/Services/RequestServer/RequestClient.ipc
+++ b/Services/RequestServer/RequestClient.ipc
@@ -23,6 +23,7 @@ endpoint RequestClient
websocket_connected(u64 websocket_id) =|
websocket_received(u64 websocket_id, bool is_text, ByteBuffer data) =|
websocket_received_shared(u64 websocket_id, bool is_text, Core::AnonymousBuffer data) =|
+ websocket_transmitted(u64 websocket_id, u64 message_byte_count) =|
websocket_errored(u64 websocket_id, i32 message) =|
websocket_closed(u64 websocket_id, u16 code, ByteString reason, bool clean) =|
websocket_ready_state_changed(u64 websocket_id, u32 ready_state) =|
diff --git a/Services/RequestServer/WebSocketImplCurl.cpp b/Services/RequestServer/WebSocketImplCurl.cpp
index 9cc901d28d5..5fddc6e41a3 100644
--- a/Services/RequestServer/WebSocketImplCurl.cpp
+++ b/Services/RequestServer/WebSocketImplCurl.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/ScopeGuard.h>
#include <LibCore/Notifier.h>
#include <RequestServer/CURL.h>
#include <RequestServer/ConnectionFromClient.h>
@@ -224,6 +225,16 @@ void WebSocketImplCurl::read_from_socket()
bool WebSocketImplCurl::flush_pending_write_buffer()
{
+ // Reported once per flush, as each report becomes a message to the client.
+ size_t written = 0;
+ ScopeGuard report_written_bytes = [&] {
+ if (written == 0)
+ return;
+ add_network_usage(0, written);
+ if (on_bytes_written)
+ on_bytes_written(written);
+ };
+
while (m_pending_write_buffer_offset < m_pending_write_buffer.size()) {
auto pending_bytes = m_pending_write_buffer.bytes().slice(m_pending_write_buffer_offset);
@@ -235,10 +246,9 @@ bool WebSocketImplCurl::flush_pending_write_buffer()
}
m_pending_write_buffer_offset += sent;
- if (sent > 0) {
- add_network_usage(0, sent);
+ written += sent;
+ if (sent > 0)
continue;
- }
if (result == CURLE_AGAIN) {
if (m_write_notifier)
diff --git a/Tests/LibWeb/Fixtures/http-test-server.py b/Tests/LibWeb/Fixtures/http-test-server.py
index 7bff6391fe3..eea2207eee1 100755
--- a/Tests/LibWeb/Fixtures/http-test-server.py
+++ b/Tests/LibWeb/Fixtures/http-test-server.py
@@ -42,7 +42,8 @@ Endpoints:
"ignore_range": true. Then it sends the entire body, as a server that doesn't support ranges does.
- GET <any path> with an "Upgrade: websocket" header: Performs a WebSocket handshake and then echoes
every text/binary frame back to the client verbatim. With a "send-binary=<size>" query parameter, the
- server first sends a binary frame of that many bytes: a 1, zeros, and then a 2.
+ server first sends a binary frame of that many bytes: a 1, zeros, and then a 2. With a
+ "read_unblock_token=<token>" query parameter, the server reads nothing until GET /unblock/<token>.
- GET /reflect-websocket-cookie with an "Upgrade: websocket" header: As above, but first sends the
handshake's Cookie header (or an empty string) as a text frame.
- GET /websocket-close-without-response with an "Upgrade: websocket" header: Closes the connection without
@@ -814,6 +815,9 @@ class TestHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
payload[-1] = 2
self._send_websocket_frame(bytes(payload), opcode=0x2)
+ if "read_unblock_token" in query:
+ unblock_events.setdefault(query["read_unblock_token"][0], threading.Event()).wait()
+
while True:
frame = self._read_websocket_frame()
if frame is None:
@@ -866,7 +870,9 @@ class TestHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
if payload is None:
return None
if is_masked:
- payload = bytes(payload[i] ^ mask[i % 4] for i in range(length))
+ # One XOR over the whole payload as an integer keeps large messages quick to unmask.
+ repeated_mask = (mask * (length // 4 + 1))[:length]
+ payload = (int.from_bytes(payload, "big") ^ int.from_bytes(repeated_mask, "big")).to_bytes(length, "big")
return opcode, payload
def _build_ws_frame(self, data, opcode=0x1):
diff --git a/Tests/LibWeb/Text/expected/WebSocket/buffered-amount-counts-what-is-not-yet-transmitted.txt b/Tests/LibWeb/Text/expected/WebSocket/buffered-amount-counts-what-is-not-yet-transmitted.txt
new file mode 100644
index 00000000000..1150b7166ee
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebSocket/buffered-amount-counts-what-is-not-yet-transmitted.txt
@@ -0,0 +1,3 @@
+Buffered after send(): true
+Buffered while the server reads nothing: true
+Echoed 67108864 bytes, bufferedAmount: 0
diff --git a/Tests/LibWeb/Text/input/WebSocket/buffered-amount-counts-what-is-not-yet-transmitted.html b/Tests/LibWeb/Text/input/WebSocket/buffered-amount-counts-what-is-not-yet-transmitted.html
new file mode 100644
index 00000000000..b916061a110
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebSocket/buffered-amount-counts-what-is-not-yet-transmitted.html
@@ -0,0 +1,32 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ const port = internals.getEchoServerPort();
+ const token = `buffered-amount-${Math.random()}`;
+ const ws = new WebSocket(`ws://localhost:${port}/?read_unblock_token=${token}`);
+ ws.binaryType = "arraybuffer";
+ await new Promise(resolve => (ws.onopen = resolve));
+
+ // Far more than the operating system buffers while the server reads nothing. Windows takes in the whole of a
+ // message while its buffer has room, however large, so there the second message is what stays behind.
+ const size = 32 * 1024 * 1024;
+ ws.send(new Uint8Array(size));
+ ws.send(new Uint8Array(size));
+ println(`Buffered after send(): ${ws.bufferedAmount === 2 * size}`);
+
+ // A round trip to the server runs many tasks.
+ await fetch(`http://localhost:${port}/recorded-request-count/nothing`);
+ println(`Buffered while the server reads nothing: ${ws.bufferedAmount > 0}`);
+
+ // The first echo can arrive while the second message is still being sent.
+ let echoed = 0;
+ ws.onmessage = event => {
+ echoed += event.data.byteLength;
+ if (echoed < 2 * size) return;
+ println(`Echoed ${echoed} bytes, bufferedAmount: ${ws.bufferedAmount}`);
+ done();
+ };
+ await fetch(`http://localhost:${port}/unblock/${token}`);
+ });
+</script>
diff --git a/Tests/LibWebSocket/TestWebSocket.cpp b/Tests/LibWebSocket/TestWebSocket.cpp
index 4a50ec69fd6..c2c6db09372 100644
--- a/Tests/LibWebSocket/TestWebSocket.cpp
+++ b/Tests/LibWebSocket/TestWebSocket.cpp
@@ -45,6 +45,8 @@ public:
on_ready_to_read();
}
+ void write(size_t byte_count) { on_bytes_written(byte_count); }
+
Vector<ByteBuffer> const& sent_frames() const { return m_sent_frames; }
bool fail_writes { false };
@@ -448,6 +450,37 @@ TEST_CASE(ping_is_answered_only_while_open)
EXPECT_EQ(implementation->sent_frames().size(), 2u);
}
+TEST_CASE(only_message_bytes_count_as_transmitted)
+{
+ Core::EventLoop event_loop;
+
+ auto implementation = adopt_ref(*new TestWebSocketImpl);
+ auto url = URL::Parser::basic_parse("ws://localhost/"sv).release_value();
+ auto websocket = WebSocket::WebSocket::create(WebSocket::ConnectionInfo(move(url)), implementation);
+ u64 transmitted = 0;
+ websocket->on_message_bytes_transmitted = [&](u64 byte_count) { transmitted += byte_count; };
+ websocket->start();
+ EXPECT(websocket->ready_state() == WebSocket::ReadyState::Open);
+
+ // A 5-byte message after a 2-byte header and a 4-byte mask, a 7-byte pong, and a 200-byte message after a 4-byte
+ // header and the mask.
+ websocket->send(WebSocket::Message { ByteString { "hello"sv } });
+ u8 const ping[] { 0x89, 1, 'P' };
+ implementation->receive(MUST(ByteBuffer::copy(ping)));
+ websocket->send(WebSocket::Message { ByteString::repeated('x', 200) });
+
+ implementation->write(6);
+ EXPECT_EQ(transmitted, 0u);
+ implementation->write(3);
+ EXPECT_EQ(transmitted, 3u);
+ implementation->write(2 + 7 + 8);
+ EXPECT_EQ(transmitted, 5u);
+ implementation->write(150);
+ EXPECT_EQ(transmitted, 155u);
+ implementation->write(50);
+ EXPECT_EQ(transmitted, 205u);
+}
+
TEST_CASE(oversized_ping_fails_connection)
{
Core::EventLoop event_loop;