From 93b6b8c6da061cd3f95722f4e3de4e89f61fc56e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 21 Sep 2026 15:30:55 +0000 Subject: [PATCH 1/8] WebSocket client: dispatch the frames that arrive with the 101 after the microtasks of open The connected client keeps the bytes the upgrade client read past the 101 response. The upgrade client has it parse them after the microtask checkpoint that follows the open event, in the same socket callback. They were parsed by a microtask queued ahead of the ones the open listeners queue, so a message listener ran before code that awaited open. Removes InitialDataTask, and JSGlobalObject::queue_microtask_boxed, queue_microtask_callback and MicrotaskCallback, which had no other user. --- src/http_jsc/websocket_client.rs | 131 ++++------ src/http_jsc/websocket_client/CppWebSocket.rs | 21 +- .../WebSocketUpgradeClient.rs | 37 ++- src/jsc/JSGlobalObject.rs | 45 ---- src/jsc/bindings/headers.h | 2 + src/jsc/bindings/webcore/WebSocket.cpp | 19 ++ src/jsc/bindings/webcore/WebSocket.h | 5 +- src/jsc/lib.rs | 2 +- .../websocket-client-short-read.test.ts | 232 +++++++++++++++++- test/js/web/websocket/websocket-proxy.test.ts | 59 +++++ 10 files changed, 407 insertions(+), 146 deletions(-) diff --git a/src/http_jsc/websocket_client.rs b/src/http_jsc/websocket_client.rs index e13498b81e4a..92985ac198ae 100644 --- a/src/http_jsc/websocket_client.rs +++ b/src/http_jsc/websocket_client.rs @@ -19,11 +19,11 @@ use bun_core::{EncodedSlice, strings}; use bun_http::websocket::{Opcode, WebsocketHeader}; use bun_io::KeepAlive; use bun_jsc::{self as jsc, GlobalRef, JSGlobalObject}; -use bun_ptr::{BackRef, JsCell, RefPtr, Root, ThisPtr}; +use bun_ptr::{BackRef, JsCell, RefPtr, ThisPtr}; use bun_uws::{self as uws, NewSocketHandler, us_bun_verify_error_t}; use bun_uws_sys::us_socket_t; -use self::cpp_websocket::{CppWebSocket, CppWebSocketRef}; +use self::cpp_websocket::CppWebSocket; use self::websocket_deflate::WebSocketDeflate; use self::websocket_proxy_tunnel::WebSocketProxyTunnel; @@ -103,10 +103,9 @@ pub struct WebSocket { pub(crate) payload_length_frame_bytes: Cell<[u8; 8]>, pub(crate) payload_length_frame_len: Cell, - /// The queued `InitialDataTask` (handshake-overflow bytes) until it runs or - /// `handle_data` drains it first; detached in `Drop` so a task that - /// outlives us does nothing. - pending_initial_task: Cell, Root>>>, + /// Bytes the upgrade client read past the 101 (handshake overflow), until + /// `deliver_initial_data` parses them or `handle_data` gets there first. + initial_data: Cell>>, pub(crate) deflate: RefCell>>, /// Track if current message is compressed @@ -528,17 +527,9 @@ impl WebSocket { // Bumps the intrusive refcount and derefs on Drop. let _guard = RefPtr::from_this(this); - // Due to scheduling, it is possible for the websocket onData - // handler to run with additional data before the microtask queue is - // drained. - if let Some(task) = this.pending_initial_task.take() { - // Deliver the buffered bytes now (this calls `handle_data`); the - // queued `InitialDataTask` is detached and will do nothing. - task.ws.set(None); - if let Some(initial_data) = task.data.replace(None) { - initial_data.deliver(this); - } - + // An `open` listener that spins the event loop lets a read in before + // `deliver_initial_data`; the handshake overflow still comes first. + if this.parse_initial_data() { // If we disconnected for any reason in the re-entrant case, we should just ignore the data if this.cpp_websocket().is_none() || !this.has_tcp() { return; @@ -548,6 +539,28 @@ impl WebSocket { this.handle_data_loop(data_); } + /// Parse the handshake overflow if it is still pending. Returns whether it + /// was. The caller holds a ref guard. + fn parse_initial_data(&self) -> bool { + let Some(initial_data) = self.initial_data.take() else { + return false; + }; + // For tunnel mode, tcp is detached but connection is still active through the tunnel + let is_connected = !self.tcp.get().is_closed() || self.tunnel().is_some(); + if self.cpp_websocket().is_some() && is_connected && !self.close_received.get() { + self.handle_data_loop(&initial_data); + } + true + } + + /// The upgrade client calls this (through C++) after the microtask + /// checkpoint that follows the `open` event, so a frame that arrived in + /// the same read as the 101 is dispatched like one from a later read. + pub(crate) fn deliver_initial_data(this: ThisPtr) { + let _guard = RefPtr::from_this(this); + this.parse_initial_data(); + } + fn handle_data_loop(&self, data: &[u8]) { // In the WebSocket specification, control frames may not be fragmented. // However, the frame parser should handle fragmented control frames nonetheless. @@ -1417,7 +1430,7 @@ impl WebSocket { header_fragment: Cell::new(None), payload_length_frame_bytes: Cell::new([0u8; 8]), payload_length_frame_len: Cell::new(0), - pending_initial_task: Cell::new(None), + initial_data: Cell::new(None), deflate: RefCell::new( deflate_params.and_then(|params| WebSocketDeflate::init(*params).ok()), ), @@ -1431,7 +1444,7 @@ impl WebSocket { } /// Shared tail of `init`/`init_with_tunnel`: record the I/O-layer ref, - /// reserve the I/O buffers, take the keep-alive ref, queue any + /// reserve the I/O buffers, take the keep-alive ref, keep any /// handshake-buffered bytes, and take the C++-side ref. Returns the /// pointer handed back to C++. fn finish_init( @@ -1453,20 +1466,8 @@ impl WebSocket { ws.poll_ref.set(poll_ref); } - if let Some(buffered_data) = buffered_data.filter(|b| !b.0.is_empty()) { - // Use a higher-priority callback for the initial onData handler. - let task = Box::new(InitialDataTask { - ws: Cell::new(Some(BackRef::from(ws))), - data: JsCell::new(Some(InitialDataHandler { - slice: buffered_data.0, - // We need to ref the outgoing websocket so that it doesn't get - // finalized before the initial data handler is called. - _pending_activity: CppWebSocketRef::new(outgoing), - })), - }); - ws.pending_initial_task - .set(Some(global_this.queue_microtask_boxed(task))); - } + ws.initial_data + .set(buffered_data.map(|b| b.0).filter(|b| !b.is_empty())); ws.as_ptr() } @@ -1603,16 +1604,6 @@ impl Drop for WebSocket { self.clear_data(); // deflate already dropped in clear_data; this is defensive self.deflate.replace(None); - if let Some(task) = self.pending_initial_task.take() { - // Still queued (or abandoned with the VM's microtask queue); it - // must not follow its back-reference to us. - task.ws.set(None); - if self.global_this.bun_vm().is_shutting_down() { - // The queue will never run it; release the C++ pending-activity - // ref it holds now. - task.data.set(None); - } - } bun_core::scoped_log!(alloc, "destroy({}) = {:p}", Self::ALLOC_TYPE_NAME, self); } } @@ -1712,6 +1703,12 @@ pub fn bun__websocketclient__init_with_tunnel( ) -> *mut crate::websocket_client::WebSocketClient { WebSocketClient::init_with_tunnel(outgoing, tunnel, global_this, buffered_data, deflate_params) } +// HOST_EXPORT(Bun__WebSocketClient__deliverInitialData, c) +pub fn bun__websocketclient__deliver_initial_data( + this: ThisPtr, +) { + WebSocketClient::deliver_initial_data(this) +} // HOST_EXPORT(Bun__WebSocketClient__memoryCost, c) pub fn bun__websocketclient__memory_cost(this: &crate::websocket_client::WebSocketClient) -> usize { this.memory_cost() @@ -1789,6 +1786,12 @@ pub fn bun__websocketclienttls__init( secure, ) } +// HOST_EXPORT(Bun__WebSocketClientTLS__deliverInitialData, c) +pub fn bun__websocketclienttls__deliver_initial_data( + this: ThisPtr, +) { + WebSocketClientTLS::deliver_initial_data(this) +} // HOST_EXPORT(Bun__WebSocketClientTLS__memoryCost, c) pub fn bun__websocketclienttls__memory_cost( this: &crate::websocket_client::WebSocketClientTLS, @@ -1813,53 +1816,13 @@ pub fn bun__websocketclienttls__write_string( } // ────────────────────────────────────────────────────────────────────────── -// InitialDataHandler +// InitialData // ────────────────────────────────────────────────────────────────────────── /// Bytes the upgrade client read past the end of the handshake response; boxed /// so they cross C++ (`WebSocket::didConnect*`) as one opaque pointer. pub struct InitialData(pub Vec); -/// Handshake-overflow bytes plus the pending-activity ref that keeps the C++ -/// `WebSocket` alive until they are delivered. -struct InitialDataHandler { - slice: Vec, - _pending_activity: CppWebSocketRef, -} - -impl InitialDataHandler { - /// Feed the buffered bytes to `ws` as if they had just arrived. - fn deliver(self, ws: ThisPtr>) { - // For tunnel mode, tcp is detached but connection is still active through the tunnel - let is_connected = !ws.tcp.get().is_closed() || ws.tunnel().is_some(); - if ws.cpp_websocket().is_some() && is_connected { - WebSocket::::handle_data(ws, &self.slice); - } - } -} - -/// Microtask that delivers [`InitialDataHandler`] ahead of fresh socket data. -pub(crate) struct InitialDataTask { - /// Detached by `WebSocket`'s `Drop` (or by `handle_data` draining `data` - /// first) so a task that outlives its client does nothing. - ws: Cell, Root>>>, - data: JsCell>, -} - -impl jsc::MicrotaskCallback for InitialDataTask { - fn run(self: Box) { - let Some(ws) = self.ws.take() else { - return; - }; - let ws = ws.this_ptr(); - ws.pending_initial_task.set(None); - if let Some(initial_data) = self.data.replace(None) { - let _guard = RefPtr::from_this(ws); - initial_data.deliver(ws); - } - } -} - // ────────────────────────────────────────────────────────────────────────── // ErrorCode // ────────────────────────────────────────────────────────────────────────── diff --git a/src/http_jsc/websocket_client/CppWebSocket.rs b/src/http_jsc/websocket_client/CppWebSocket.rs index 77ba804b9af2..ad54c0f95a3c 100644 --- a/src/http_jsc/websocket_client/CppWebSocket.rs +++ b/src/http_jsc/websocket_client/CppWebSocket.rs @@ -54,6 +54,7 @@ unsafe extern "C" { buffered_data: Option>, deflate_params: Option<&websocket_deflate::Params>, ); + safe fn WebSocket__deliverInitialData(websocket_context: &CppWebSocket); safe fn WebSocket__didAbruptClose(websocket_context: &CppWebSocket, reason: ErrorCode); safe fn WebSocket__didReceiveHandshakeResponse( websocket_context: &CppWebSocket, @@ -180,6 +181,13 @@ impl CppWebSocket { WebSocket__didConnectWithTunnel(self, tunnel, buffered_data, deflate_params); event_loop.exit(); } + + /// Have the connected client, if there still is one, parse the + /// `buffered_data` it got from `did_connect*`. No scope of its own: each + /// message it dispatches gets a microtask checkpoint, as on a socket read. + pub(crate) fn deliver_initial_data(&self) { + WebSocket__deliverInitialData(self); + } } impl CppWebSocket { @@ -202,8 +210,7 @@ impl CppWebSocket { /// RAII owner of one pending-activity ref on a C++ `WebCore::WebSocket`. /// /// Construction calls [`CppWebSocket::r#ref`]; `Drop` calls -/// [`CppWebSocket::unref`]. For when the ref must outlive the constructing -/// scope (e.g. stored on a queued task). +/// [`CppWebSocket::unref`]. C++ has room for one such ref at a time. pub struct CppWebSocketRef(core::ptr::NonNull); impl CppWebSocketRef { @@ -214,8 +221,16 @@ impl CppWebSocketRef { } } +impl core::ops::Deref for CppWebSocketRef { + type Target = CppWebSocket; + + fn deref(&self) -> &CppWebSocket { + CppWebSocket::opaque_ref(self.0.as_ptr()) + } +} + impl Drop for CppWebSocketRef { fn drop(&mut self) { - CppWebSocket::opaque_ref(self.0.as_ptr()).unref(); + self.unref(); } } diff --git a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs index be8366048f3a..ce3f82d782cf 100644 --- a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs +++ b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs @@ -39,7 +39,7 @@ use bun_ptr::{BackRef, JsCell, RefPtr, ThisPtr}; use super::websocket_proxy_tunnel::IntoUpgradeClientRef; use bun_uws::{self as uws, SocketHandler, SocketKind}; -use super::cpp_websocket::CppWebSocket; +use super::cpp_websocket::{CppWebSocket, CppWebSocketRef}; use super::websocket_deflate as WebSocketDeflate; use super::websocket_proxy::WebSocketProxy; use super::websocket_proxy_tunnel::WebSocketProxyTunnel; @@ -815,17 +815,34 @@ where let head_len = response.bytes_read; let is_101 = response.status_code == 101; - // 101: one scope across 'upgrade'+'open' so microtasks drain after open. - let _scope = is_101 - .then(|| bun_jsc::virtual_machine::VirtualMachine::get().enter_event_loop_scope()); - - if let Some(ws) = this.cpp_websocket() { - Self::dispatch_handshake(ws, &response, if is_101 { &[] } else { &full[head_len..] }); - if this.cpp_websocket().is_none() { - return; + // With bytes behind the 101: a ref that keeps the C++ WebSocket alive + // whatever the `open` listeners and their microtasks do to it. + let overflow_owner = this + .cpp_websocket() + .filter(|_| is_101 && full.len() > head_len) + .map(|ws| CppWebSocketRef::new(&ws)); + { + // 101: one scope across 'upgrade'+'open' so microtasks drain after open. + let _scope = is_101 + .then(|| bun_jsc::virtual_machine::VirtualMachine::get().enter_event_loop_scope()); + + if let Some(ws) = this.cpp_websocket() { + Self::dispatch_handshake( + ws, + &response, + if is_101 { &[] } else { &full[head_len..] }, + ); + if this.cpp_websocket().is_none() { + return; + } } + Self::process_response(this, response, &full[head_len..]); + } + // The scope above has drained the microtasks of `open`: the connected + // client now parses those frames, as it parses the frames of a later read. + if let Some(ws) = overflow_owner { + ws.deliver_initial_data(); } - Self::process_response(this, response, &full[head_len..]); } /// Takes `ThisPtr` because `terminate`/`handle_data` may free `this`. diff --git a/src/jsc/JSGlobalObject.rs b/src/jsc/JSGlobalObject.rs index 11115339f3f0..9e98d9b1d011 100644 --- a/src/jsc/JSGlobalObject.rs +++ b/src/jsc/JSGlobalObject.rs @@ -829,37 +829,6 @@ impl JSGlobalObject { self.throw_value(instance) } - /// Queue a native callback as a microtask. Callers supply the C-ABI - /// trampoline directly; the wrapper only erases the context pointer type. - pub fn queue_microtask_callback( - &self, - ctx_val: *mut C, - function: unsafe extern "C" fn(*mut c_void), - ) { - crate::mark_binding(); - JSC__JSGlobalObject__queueMicrotaskCallback(self, ctx_val.cast::(), function); - } - - /// Queue `task` to run as a microtask; the queue owns the box until then - /// and the returned back-reference is valid until [`MicrotaskCallback::run`] - /// is entered. If the VM is torn down before the microtask queue drains, - /// the box is leaked along with the rest of the queue. - pub fn queue_microtask_boxed( - &self, - task: Box, - ) -> bun_ptr::BackRef { - unsafe extern "C" fn run(ctx: *mut c_void) { - // SAFETY: `ctx` is the `Box` leaked below; the microtask queue - // invokes each callback exactly once. - T::run(unsafe { bun_core::heap::take(ctx.cast::()) }); - } - let task = bun_core::heap::into_raw(task); - self.queue_microtask_callback(task, run::); - // SAFETY: `task` is the live leaked box; see the doc comment for the - // holder's obligation. - unsafe { bun_ptr::BackRef::from_root(task) } - } - pub fn queue_microtask(&self, function: JSValue, args: &[JSValue]) { self.queue_microtask_job( function, @@ -1508,15 +1477,6 @@ unsafe extern "C" { target: BunPluginTarget, ) -> JSValue; - // safe: `JSGlobalObject` is an opaque `UnsafeCell`-backed ZST handle (`&` is - // ABI-identical to non-null `*const`); `ctx` is an opaque round-trip pointer - // C++ only stores and forwards to `function` (never dereferenced as Rust data). - safe fn JSC__JSGlobalObject__queueMicrotaskCallback( - this: &JSGlobalObject, - ctx: *mut c_void, - function: unsafe extern "C" fn(*mut c_void), - ); - safe fn Bun__Process__emitWarning( global_object: &JSGlobalObject, warning: JSValue, @@ -1612,8 +1572,3 @@ unsafe extern "C" { // safe: by-value `u32` in, raw nullable pointer out (caller checks before deref). safe fn ScriptExecutionContextIdentifier__getGlobalObject(id: u32) -> *mut JSGlobalObject; } - -/// A native microtask queued with [`JSGlobalObject::queue_microtask_boxed`]. -pub trait MicrotaskCallback: Sized + 'static { - fn run(self: Box); -} diff --git a/src/jsc/bindings/headers.h b/src/jsc/bindings/headers.h index 3d3a4286f09e..921b9441a8e5 100644 --- a/src/jsc/bindings/headers.h +++ b/src/jsc/bindings/headers.h @@ -591,6 +591,7 @@ ZIG_DECL void Bun__WebSocketClient__close(WebSocketClient* arg0, uint16_t arg1, ZIG_DECL void Bun__WebSocketClient__finalize(WebSocketClient* arg0); ZIG_DECL void Bun__WebSocketClient__dropConnectionWithoutCallback(WebSocketClient* arg0); ZIG_DECL WebSocketClient* Bun__WebSocketClient__init(CppWebSocket* arg0, void* arg1, JSC::JSGlobalObject* arg2, void* bufferedData, const PerMessageDeflateParams* arg5, void* customSSLCtx); +ZIG_DECL void Bun__WebSocketClient__deliverInitialData(WebSocketClient* arg0); ZIG_DECL void Bun__WebSocketClient__writeBinaryData(WebSocketClient* arg0, const unsigned char* arg1, size_t arg2, unsigned char arg3); ZIG_DECL void Bun__WebSocketClient__writeString(WebSocketClient* arg0, const EncodedSlice* arg1, unsigned char arg2); ZIG_DECL size_t Bun__WebSocketClient__memoryCost(WebSocketClient* arg0); @@ -607,6 +608,7 @@ ZIG_DECL void Bun__WebSocketClientTLS__close(WebSocketClientTLS* arg0, uint16_t ZIG_DECL void Bun__WebSocketClientTLS__finalize(WebSocketClientTLS* arg0); ZIG_DECL void Bun__WebSocketClientTLS__dropConnectionWithoutCallback(WebSocketClientTLS* arg0); ZIG_DECL WebSocketClientTLS* Bun__WebSocketClientTLS__init(CppWebSocket* arg0, void* arg1, JSC::JSGlobalObject* arg2, void* bufferedData, const PerMessageDeflateParams* arg5, void* customSSLCtx); +ZIG_DECL void Bun__WebSocketClientTLS__deliverInitialData(WebSocketClientTLS* arg0); ZIG_DECL void Bun__WebSocketClientTLS__writeBinaryData(WebSocketClientTLS* arg0, const unsigned char* arg1, size_t arg2, unsigned char arg3); ZIG_DECL void Bun__WebSocketClientTLS__writeString(WebSocketClientTLS* arg0, const EncodedSlice* arg1, unsigned char arg2); ZIG_DECL size_t Bun__WebSocketClientTLS__memoryCost(WebSocketClientTLS* arg0); diff --git a/src/jsc/bindings/webcore/WebSocket.cpp b/src/jsc/bindings/webcore/WebSocket.cpp index b72642deaa80..5af030f6f18d 100644 --- a/src/jsc/bindings/webcore/WebSocket.cpp +++ b/src/jsc/bindings/webcore/WebSocket.cpp @@ -1728,6 +1728,20 @@ void WebSocket::didConnectWithTunnel(void* tunnel, void* bufferedData, const Per WebSocketProxyTunnel__setConnectedWebSocket(tunnel, m_connectedWebSocketKind == ConnectedWebSocketKind::Client ? this->m_connectedWebSocket.client : nullptr); } +void WebSocket::deliverInitialData() +{ + switch (m_connectedWebSocketKind) { + case ConnectedWebSocketKind::Client: + Bun__WebSocketClient__deliverInitialData(m_connectedWebSocket.client); + break; + case ConnectedWebSocketKind::ClientSSL: + Bun__WebSocketClientTLS__deliverInitialData(m_connectedWebSocket.clientSSL); + break; + case ConnectedWebSocketKind::None: + break; + } +} + } // namespace WebCore // `bufferedData` is an opaque Rust box (handshake overflow bytes) forwarded @@ -1742,6 +1756,11 @@ extern "C" void WebSocket__didConnectWithTunnel(WebCore::WebSocket* webSocket, v webSocket->didConnectWithTunnel(tunnel, bufferedData, deflate_params); } +extern "C" void WebSocket__deliverInitialData(WebCore::WebSocket* webSocket) +{ + webSocket->deliverInitialData(); +} + struct FfiRawHeaderSlice { const WebCore::WebSocket::HandshakeRawHeader* ptr; size_t len; diff --git a/src/jsc/bindings/webcore/WebSocket.h b/src/jsc/bindings/webcore/WebSocket.h index 6af322b184a3..04b2671ebc01 100644 --- a/src/jsc/bindings/webcore/WebSocket.h +++ b/src/jsc/bindings/webcore/WebSocket.h @@ -211,6 +211,9 @@ class WebSocket final : public RefCounted, public EventTargetWithInli void didClose(unsigned unhandledBufferedAmount, unsigned short code, const String& reason); void didConnect(us_socket_t* socket, void* bufferedData, const PerMessageDeflateParams* deflate_params, void* customSSLCtx); void didConnectWithTunnel(void* tunnel, void* bufferedData, const PerMessageDeflateParams* deflate_params); + // The connected client parses the `bufferedData` didConnect*() gave it. The upgrade client + // calls this after the microtask checkpoint that follows the open event. + void deliverInitialData(); void didFailWithErrorCode(Bun::WebSocketErrorCode code); void didReceiveMessage(String&& message); @@ -227,7 +230,7 @@ class WebSocket final : public RefCounted, public EventTargetWithInli }; void didReceiveHandshakeResponse(uint16_t statusCode, std::span statusMessage, std::span headers, std::span body); - // A single claim the native client holds while it has queued work that will call back in. + // A single claim the native side holds while it has work left that will call back in. void holdPendingActivityForClient() { ASSERT(!m_pendingActivityForClient); diff --git a/src/jsc/lib.rs b/src/jsc/lib.rs index 72100756b9d9..8d336b2ea4a4 100644 --- a/src/jsc/lib.rs +++ b/src/jsc/lib.rs @@ -778,7 +778,7 @@ pub use script_execution_context::{ // re-exported here so `crate::VM` and `crate::vm::VM` name the same nominal // type (and likewise for `JSGlobalObject`). Both structs carry `UnsafeCell` // so `&T → *mut T` for FFI is sound under Stacked Borrows. -pub use self::js_global_object::{GlobalRef, JSGlobalObject, MicrotaskCallback}; +pub use self::js_global_object::{GlobalRef, JSGlobalObject}; pub use self::vm::VM; /// Options for `JSGlobalObject::validate_integer_range` / `validate_bigint_range`. diff --git a/test/js/web/websocket/websocket-client-short-read.test.ts b/test/js/web/websocket/websocket-client-short-read.test.ts index 3a0650c34b6b..d51cc1a7ff0a 100644 --- a/test/js/web/websocket/websocket-client-short-read.test.ts +++ b/test/js/web/websocket/websocket-client-short-read.test.ts @@ -1,6 +1,7 @@ -import { TCPSocketListener } from "bun"; +import { type Socket, TCPSocketListener } from "bun"; import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe, normalizeBunSnapshot } from "harness"; +import { bunEnv, bunExe, normalizeBunSnapshot, tls } from "harness"; +import { once } from "node:events"; import { WebSocket } from "ws"; const hostname = process.env.HOST || "127.0.0.1"; @@ -346,3 +347,230 @@ describe("WebSocket buffered handshake data", () => { expect(exitCode).toBe(0); }); }); + +describe("WebSocket frames in the same read as the 101", () => { + function frame(opcode: number, payload: Uint8Array): Uint8Array { + return Uint8Array.from([0x80 | opcode, payload.length, ...payload]); + } + const textFrame = (text: string) => frame(0x1, new TextEncoder().encode(text)); + const binaryFrame = (text: string) => frame(0x2, new TextEncoder().encode(text)); + const closeFrame = (code: number) => frame(0x8, Uint8Array.from([code >> 8, code & 0xff])); + + // A raw peer that answers the upgrade with the 101 response and `glued` in one + // write, so the client gets both from one read. `peer()` is the accepted socket. + function rawServer( + secure: boolean, + glued: Uint8Array, + afterHandshake?: (socket: Socket<{ request: string }>) => void, + ) { + let accepted: Socket<{ request: string }> | undefined; + const server = Bun.listen<{ request: string }>({ + hostname: "127.0.0.1", + port: 0, + tls: secure ? tls : undefined, + socket: { + open(socket) { + socket.data = { request: "" }; + }, + data(socket, chunk) { + if (accepted) return; + socket.data.request += chunk.toString("latin1"); + if (!socket.data.request.includes("\r\n\r\n")) return; + accepted = socket; + const key = /sec-websocket-key: (.*)\r\n/i.exec(socket.data.request)![1]; + const hasher = new Bun.CryptoHasher("sha1"); + hasher.update(key); + hasher.update("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); + const head = + "HTTP/1.1 101 Switching Protocols\r\n" + + "Upgrade: websocket\r\n" + + "Connection: Upgrade\r\n" + + `Sec-WebSocket-Accept: ${hasher.digest("base64")}\r\n` + + "\r\n"; + socket.write(Buffer.concat([Buffer.from(head), glued])); + socket.flush(); + afterHandshake?.(socket); + }, + }, + }); + return { + url: `${secure ? "wss" : "ws"}://127.0.0.1:${server.port}`, + peer: () => accepted!, + [Symbol.dispose]: () => server.stop(true), + }; + } + + // Rejects every promise in `pending` when the connection fails or closes early. + function rejectOnFailure(ws: globalThis.WebSocket, ...pending: { reject: (reason: Error) => void }[]) { + ws.addEventListener("error", event => { + for (const { reject } of pending) reject(new Error(`error: ${(event as ErrorEvent).message}`)); + }); + ws.addEventListener("close", event => { + for (const { reject } of pending) reject(new Error(`closed: ${event.code} ${event.reason}`)); + }); + } + + describe.each(["ws", "wss"])("%s", protocol => { + // "split" sends the same frames once the client has dispatched `open`, so a later read brings them. + test.each(["glued", "split"])("%s: open, its microtasks, then each message", async segmentation => { + const frames = Buffer.concat([textFrame("a"), binaryFrame("b")]); + using server = rawServer(protocol === "wss", segmentation === "glued" ? frames : new Uint8Array()); + + const order: string[] = []; + const opened = Promise.withResolvers(); + const done = Promise.withResolvers(); + let ready = false; + const ws = new globalThis.WebSocket(server.url, { tls: { rejectUnauthorized: false } }); + rejectOnFailure(ws, opened, done); + ws.addEventListener("open", () => { + order.push("open"); + queueMicrotask(() => order.push("microtask from open")); + if (segmentation === "split") { + server.peer().write(frames); + server.peer().flush(); + } + }); + ws.addEventListener("open", () => opened.resolve()); + ws.addEventListener("message", event => { + order.push(`message ${event.data} ready=${ready}`); + queueMicrotask(() => { + order.push(`microtask from message ${event.data}`); + if (String(event.data) === "b") done.resolve(); + }); + }); + + try { + await opened.promise; + // Still inside the microtask checkpoint that follows `open`. + for (let i = 0; i < 4; i++) await null; + order.push("microtasks from open done"); + ready = true; + await done.promise; + expect(order).toEqual([ + "open", + "microtask from open", + "microtasks from open done", + "message a ready=true", + "microtask from message a", + "message b ready=true", + "microtask from message b", + ]); + } finally { + ws.close(); + } + }); + }); + + test("the ws package: code that awaits 'open' gets the message that came with the 101", async () => { + using server = rawServer(false, textFrame("greeting")); + + const order: string[] = []; + const received = Promise.withResolvers(); + let ready = false; + const ws = new WebSocket(server.url); + ws.on("message", data => { + order.push(`message ${data} ready=${ready}`); + received.resolve(); + }); + ws.on("error", received.reject); + ws.on("close", code => received.reject(new Error(`closed: ${code}`))); + + try { + // Rejects on "error". + await once(ws, "open"); + order.push("open awaited"); + ready = true; + await received.promise; + expect(order).toEqual(["open awaited", "message greeting ready=true"]); + } finally { + ws.close(); + } + }); + + test("a Bun.serve peer that sends from its open handler", async () => { + using server = Bun.serve({ + port: 0, + fetch(req, server) { + return server.upgrade(req) ? undefined : new Response("not a websocket", { status: 400 }); + }, + websocket: { + open(ws) { + ws.send("greeting"); + }, + message() {}, + }, + }); + + const order: string[] = []; + const opened = Promise.withResolvers(); + const received = Promise.withResolvers(); + let ready = false; + const ws = new globalThis.WebSocket(`ws://127.0.0.1:${server.port}`); + rejectOnFailure(ws, opened, received); + ws.addEventListener("open", () => opened.resolve()); + ws.addEventListener("message", event => { + order.push(`message ${event.data} ready=${ready}`); + received.resolve(); + }); + + try { + await opened.promise; + order.push("open awaited"); + ready = true; + await received.promise; + expect(order).toEqual(["open awaited", "message greeting ready=true"]); + } finally { + ws.close(); + } + }); + + test("an open listener that spins the event loop gets them ahead of the frames it read meanwhile", async () => { + using server = rawServer(false, textFrame("with the 101")); + + const order: string[] = []; + const opened = Promise.withResolvers(); + const laterFrameRead = Promise.withResolvers(); + const ws = new globalThis.WebSocket(server.url); + rejectOnFailure(ws, opened, laterFrameRead); + ws.addEventListener("open", () => { + order.push("open"); + server.peer().write(textFrame("after the 101")); + server.peer().flush(); + // Ticks the event loop until the client has read that frame. + expect(laterFrameRead.promise).resolves.toBeUndefined(); + order.push("open returns"); + opened.resolve(); + }); + ws.addEventListener("message", event => { + order.push(`message ${event.data}`); + if (event.data === "after the 101") laterFrameRead.resolve(); + }); + + try { + await opened.promise; + expect(order).toEqual(["open", "message with the 101", "message after the 101", "open returns"]); + } finally { + ws.close(); + } + }); + + test("a peer that ends the connection right behind them still gets them delivered", async () => { + // The 101, a message, a Close frame, then FIN: the client can see the end of the stream in + // the same poll as the data. + using server = rawServer(false, Buffer.concat([textFrame("last words"), closeFrame(1000)]), socket => socket.end()); + + const events: string[] = []; + const closed = Promise.withResolvers(); + const ws = new globalThis.WebSocket(server.url); + ws.addEventListener("open", () => events.push("open")); + ws.addEventListener("message", event => events.push(`message ${event.data}`)); + ws.addEventListener("error", () => events.push("error")); + ws.addEventListener("close", event => { + events.push(`close ${event.code} clean=${event.wasClean}`); + closed.resolve(); + }); + + await closed.promise; + expect(events).toEqual(["open", "message last words", "close 1000 clean=true"]); + }); +}); diff --git a/test/js/web/websocket/websocket-proxy.test.ts b/test/js/web/websocket/websocket-proxy.test.ts index 415272b4c64b..728e7d414ce4 100644 --- a/test/js/web/websocket/websocket-proxy.test.ts +++ b/test/js/web/websocket/websocket-proxy.test.ts @@ -689,6 +689,65 @@ describe("WebSocket wss:// through HTTP proxy (TLS tunnel)", () => { }); }); +// A Bun.serve origin that sends from its open handler puts the 101 and the frame in one write (one +// TLS record for wss://), so the client gets the frame in the same read as the 101. wss:// goes +// through the TLS tunnel; ws:// hands the proxy socket to the client directly. +describe("a message that arrives with the 101 through a proxy", () => { + test.each([ + ["ws", "http"], + ["ws", "https"], + ["wss", "http"], + ["wss", "https"], + ])("%s:// through an %s proxy: code that awaits open gets the message", async (protocol, scheme) => { + using origin = Bun.serve({ + port: 0, + tls: protocol === "wss" ? { key: tlsCerts.key, cert: tlsCerts.cert } : undefined, + fetch(req, server) { + if (server.upgrade(req)) return; + return new Response("Expected WebSocket", { status: 400 }); + }, + websocket: { + open(ws) { + ws.send("greeting"); + }, + message() {}, + }, + }); + using recorded = await startRecordingProxy({ tls: scheme === "https" }); + + const order: string[] = []; + const opened = Promise.withResolvers(); + const received = Promise.withResolvers(); + let ready = false; + const ws = new WebSocket(`${protocol}://127.0.0.1:${origin.port}`, { + proxy: `${scheme}://127.0.0.1:${recorded.port}`, + tls: { rejectUnauthorized: false }, + }); + ws.addEventListener("open", () => opened.resolve()); + ws.addEventListener("message", event => { + order.push(`message ${event.data} ready=${ready}`); + received.resolve(); + }); + for (const pending of [opened, received]) { + ws.addEventListener("error", event => pending.reject(new Error(`error: ${(event as ErrorEvent).message}`))); + ws.addEventListener("close", event => pending.reject(new Error(`closed: ${event.code} ${event.reason}`))); + } + + try { + await opened.promise; + order.push("open awaited"); + ready = true; + await received.promise; + expect({ order, requests: recorded.requests }).toEqual({ + order: ["open awaited", "message greeting ready=true"], + requests: [connectRequest(origin.port)], + }); + } finally { + ws.close(); + } + }); +}); + describe("WebSocket through HTTPS proxy (TLS proxy)", () => { // These tests verify WebSocket connections through HTTPS (TLS) proxy servers From d93830349337957d844be20c15b36c1f39586ef1 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 21 Sep 2026 16:32:29 +0000 Subject: [PATCH 2/8] WebSocket client: drain before the bytes behind the 101 under a nested event-loop spin Under a nested event-loop spin the scope around open is not the outermost one and drains nothing, so the upgrade client drains the microtasks itself before the connected client parses the bytes behind the 101. The upgrade client takes the pending-activity claim after the 'upgrade' event. A listener that spins the event loop can re-enter process_websocket_upgrade_response for the same WebSocket, and C++ has one slot for that claim. --- .../WebSocketUpgradeClient.rs | 29 +++-- .../websocket-client-short-read.test.ts | 120 ++++++++++++++++-- 2 files changed, 126 insertions(+), 23 deletions(-) diff --git a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs index ce3f82d782cf..10cfebee8380 100644 --- a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs +++ b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs @@ -815,16 +815,11 @@ where let head_len = response.bytes_read; let is_101 = response.status_code == 101; - // With bytes behind the 101: a ref that keeps the C++ WebSocket alive - // whatever the `open` listeners and their microtasks do to it. - let overflow_owner = this - .cpp_websocket() - .filter(|_| is_101 && full.len() > head_len) - .map(|ws| CppWebSocketRef::new(&ws)); + let vm = bun_jsc::virtual_machine::VirtualMachine::get(); + let overflow_owner; { // 101: one scope across 'upgrade'+'open' so microtasks drain after open. - let _scope = is_101 - .then(|| bun_jsc::virtual_machine::VirtualMachine::get().enter_event_loop_scope()); + let _scope = is_101.then(|| vm.enter_event_loop_scope()); if let Some(ws) = this.cpp_websocket() { Self::dispatch_handshake( @@ -836,11 +831,25 @@ where return; } } + // With bytes behind the 101, keep the C++ WebSocket alive whatever the + // `open` listeners and their microtasks do to it. Taken after 'upgrade': + // C++ has one slot, and a listener that spins the event loop re-enters + // this function. + overflow_owner = this + .cpp_websocket() + .filter(|_| is_101 && full.len() > head_len) + .map(|ws| CppWebSocketRef::new(&ws)); Self::process_response(this, response, &full[head_len..]); } - // The scope above has drained the microtasks of `open`: the connected - // client now parses those frames, as it parses the frames of a later read. + // The connected client parses those bytes after the microtasks of `open`, + // like a later read. Under a nested event-loop spin (`expect().resolves`, + // a `Bun.build` plugin) the scope above was not the outermost and did not + // drain them. if let Some(ws) = overflow_owner { + let event_loop = vm.event_loop_mut(); + if event_loop.entered_event_loop_count > 0 { + let _ = event_loop.drain_microtasks(); + } ws.deliver_initial_data(); } } diff --git a/test/js/web/websocket/websocket-client-short-read.test.ts b/test/js/web/websocket/websocket-client-short-read.test.ts index d51cc1a7ff0a..7e8ef5af33dd 100644 --- a/test/js/web/websocket/websocket-client-short-read.test.ts +++ b/test/js/web/websocket/websocket-client-short-read.test.ts @@ -358,16 +358,18 @@ describe("WebSocket frames in the same read as the 101", () => { // A raw peer that answers the upgrade with the 101 response and `glued` in one // write, so the client gets both from one read. `peer()` is the accepted socket. - function rawServer( - secure: boolean, - glued: Uint8Array, - afterHandshake?: (socket: Socket<{ request: string }>) => void, - ) { + function rawServer(options: { + glued: Uint8Array; + secure?: boolean; + // Sends the start of the status line in a write of its own first, so the client buffers it. + splitHead?: boolean; + afterHandshake?: (socket: Socket<{ request: string }>) => void; + }) { let accepted: Socket<{ request: string }> | undefined; const server = Bun.listen<{ request: string }>({ hostname: "127.0.0.1", port: 0, - tls: secure ? tls : undefined, + tls: options.secure ? tls : undefined, socket: { open(socket) { socket.data = { request: "" }; @@ -387,14 +389,22 @@ describe("WebSocket frames in the same read as the 101", () => { "Connection: Upgrade\r\n" + `Sec-WebSocket-Accept: ${hasher.digest("base64")}\r\n` + "\r\n"; - socket.write(Buffer.concat([Buffer.from(head), glued])); + const respond = (from: number) => { + socket.write(Buffer.concat([Buffer.from(head.slice(from)), options.glued])); + socket.flush(); + options.afterHandshake?.(socket); + }; + if (!options.splitHead) return respond(0); + const first = "HTTP/1.1 101 "; + socket.write(first); socket.flush(); - afterHandshake?.(socket); + // The client shows no sign of having read `first`. 50 ms puts the rest in a later read. + setTimeout(respond, 50, first.length); }, }, }); return { - url: `${secure ? "wss" : "ws"}://127.0.0.1:${server.port}`, + url: `${options.secure ? "wss" : "ws"}://127.0.0.1:${server.port}`, peer: () => accepted!, [Symbol.dispose]: () => server.stop(true), }; @@ -414,7 +424,10 @@ describe("WebSocket frames in the same read as the 101", () => { // "split" sends the same frames once the client has dispatched `open`, so a later read brings them. test.each(["glued", "split"])("%s: open, its microtasks, then each message", async segmentation => { const frames = Buffer.concat([textFrame("a"), binaryFrame("b")]); - using server = rawServer(protocol === "wss", segmentation === "glued" ? frames : new Uint8Array()); + using server = rawServer({ + secure: protocol === "wss", + glued: segmentation === "glued" ? frames : new Uint8Array(), + }); const order: string[] = []; const opened = Promise.withResolvers(); @@ -462,7 +475,7 @@ describe("WebSocket frames in the same read as the 101", () => { }); test("the ws package: code that awaits 'open' gets the message that came with the 101", async () => { - using server = rawServer(false, textFrame("greeting")); + using server = rawServer({ glued: textFrame("greeting") }); const order: string[] = []; const received = Promise.withResolvers(); @@ -525,7 +538,7 @@ describe("WebSocket frames in the same read as the 101", () => { }); test("an open listener that spins the event loop gets them ahead of the frames it read meanwhile", async () => { - using server = rawServer(false, textFrame("with the 101")); + using server = rawServer({ glued: textFrame("with the 101") }); const order: string[] = []; const opened = Promise.withResolvers(); @@ -554,10 +567,91 @@ describe("WebSocket frames in the same read as the 101", () => { } }); + // A callback that waits synchronously ticks the event loop below its own event-loop scope. A + // socket callback in there is not the outermost scope, so its exit drains no microtasks. + test.each(["glued", "split"])( + "%s, while a callback waits synchronously: open, its microtasks, then the message", + async segmentation => { + using server = rawServer({ glued: segmentation === "glued" ? textFrame("a") : new Uint8Array() }); + + const order: string[] = []; + const received = Promise.withResolvers(); + const waited = Promise.withResolvers(); + setImmediate(() => { + const ws = new globalThis.WebSocket(server.url); + rejectOnFailure(ws, received); + ws.addEventListener("open", () => { + order.push("open"); + queueMicrotask(() => order.push("microtask from open")); + if (segmentation === "split") { + server.peer().write(textFrame("a")); + server.peer().flush(); + } + }); + ws.addEventListener("message", event => { + order.push(`message ${event.data}`); + received.resolve(); + }); + try { + // The connection opens while this ticks the event loop. + expect(received.promise).resolves.toBeUndefined(); + waited.resolve(); + } catch (error) { + waited.reject(error); + } finally { + ws.close(); + } + }); + + await waited.promise; + expect(order).toEqual(["open", "microtask from open", "message a"]); + }, + ); + + test("an 'upgrade' listener of the ws package that spins the event loop while a later frame arrives", async () => { + // With the head split over two reads, the read that the listener lets in parses the same 101 + // again and completes the connection below the listener. + using server = rawServer({ glued: textFrame("with the 101"), splitHead: true }); + + const order: string[] = []; + const laterFrameRead = Promise.withResolvers(); + const upgradeReturned = Promise.withResolvers(); + const ws = new WebSocket(server.url); + ws.on("upgrade", () => { + order.push("upgrade"); + server.peer().write(textFrame("after the 101")); + server.peer().flush(); + try { + expect(laterFrameRead.promise).resolves.toBeUndefined(); + order.push("upgrade returns"); + upgradeReturned.resolve(); + } catch (error) { + upgradeReturned.reject(error); + } + }); + ws.on("open", () => order.push("open")); + ws.on("message", data => { + order.push(`message ${data}`); + if (String(data) === "after the 101") laterFrameRead.resolve(); + }); + ws.on("error", laterFrameRead.reject); + ws.on("close", code => laterFrameRead.reject(new Error(`closed: ${code}`))); + + try { + await upgradeReturned.promise; + expect(order).toEqual(["upgrade", "open", "message with the 101", "message after the 101", "upgrade returns"]); + } finally { + ws.close(); + } + }); + test("a peer that ends the connection right behind them still gets them delivered", async () => { // The 101, a message, a Close frame, then FIN: the client can see the end of the stream in // the same poll as the data. - using server = rawServer(false, Buffer.concat([textFrame("last words"), closeFrame(1000)]), socket => socket.end()); + using server = rawServer({ + glued: Buffer.concat([textFrame("last words"), closeFrame(1000)]), + afterHandshake: socket => socket.end(), + }); const events: string[] = []; const closed = Promise.withResolvers(); From 281a43dd5c6307a33e81db1e15505cea09453082 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 21 Sep 2026 16:35:28 +0000 Subject: [PATCH 3/8] WebSocket client: shorten the comments on the handshake overflow path --- src/http_jsc/websocket_client.rs | 13 ++++--------- src/http_jsc/websocket_client/CppWebSocket.rs | 4 +--- .../websocket_client/WebSocketUpgradeClient.rs | 10 ++-------- src/jsc/bindings/webcore/WebSocket.h | 3 +-- 4 files changed, 8 insertions(+), 22 deletions(-) diff --git a/src/http_jsc/websocket_client.rs b/src/http_jsc/websocket_client.rs index 92985ac198ae..74f0d8678967 100644 --- a/src/http_jsc/websocket_client.rs +++ b/src/http_jsc/websocket_client.rs @@ -103,8 +103,7 @@ pub struct WebSocket { pub(crate) payload_length_frame_bytes: Cell<[u8; 8]>, pub(crate) payload_length_frame_len: Cell, - /// Bytes the upgrade client read past the 101 (handshake overflow), until - /// `deliver_initial_data` parses them or `handle_data` gets there first. + /// Handshake overflow (bytes the upgrade client read past the 101), until parsed. initial_data: Cell>>, pub(crate) deflate: RefCell>>, @@ -527,8 +526,7 @@ impl WebSocket { // Bumps the intrusive refcount and derefs on Drop. let _guard = RefPtr::from_this(this); - // An `open` listener that spins the event loop lets a read in before - // `deliver_initial_data`; the handshake overflow still comes first. + // An `open` listener that spins the event loop lets a read in ahead of `deliver_initial_data`. if this.parse_initial_data() { // If we disconnected for any reason in the re-entrant case, we should just ignore the data if this.cpp_websocket().is_none() || !this.has_tcp() { @@ -539,8 +537,7 @@ impl WebSocket { this.handle_data_loop(data_); } - /// Parse the handshake overflow if it is still pending. Returns whether it - /// was. The caller holds a ref guard. + /// Returns whether the handshake overflow was still pending. The caller holds a ref guard. fn parse_initial_data(&self) -> bool { let Some(initial_data) = self.initial_data.take() else { return false; @@ -553,9 +550,7 @@ impl WebSocket { true } - /// The upgrade client calls this (through C++) after the microtask - /// checkpoint that follows the `open` event, so a frame that arrived in - /// the same read as the 101 is dispatched like one from a later read. + /// Called by the upgrade client (through C++) after the microtask checkpoint that follows `open`. pub(crate) fn deliver_initial_data(this: ThisPtr) { let _guard = RefPtr::from_this(this); this.parse_initial_data(); diff --git a/src/http_jsc/websocket_client/CppWebSocket.rs b/src/http_jsc/websocket_client/CppWebSocket.rs index ad54c0f95a3c..579078835a64 100644 --- a/src/http_jsc/websocket_client/CppWebSocket.rs +++ b/src/http_jsc/websocket_client/CppWebSocket.rs @@ -182,9 +182,7 @@ impl CppWebSocket { event_loop.exit(); } - /// Have the connected client, if there still is one, parse the - /// `buffered_data` it got from `did_connect*`. No scope of its own: each - /// message it dispatches gets a microtask checkpoint, as on a socket read. + /// No event-loop scope here: each message gets its own microtask checkpoint, as on a socket read. pub(crate) fn deliver_initial_data(&self) { WebSocket__deliverInitialData(self); } diff --git a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs index 10cfebee8380..73f65b89f1fe 100644 --- a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs +++ b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs @@ -831,22 +831,16 @@ where return; } } - // With bytes behind the 101, keep the C++ WebSocket alive whatever the - // `open` listeners and their microtasks do to it. Taken after 'upgrade': - // C++ has one slot, and a listener that spins the event loop re-enters - // this function. + // After 'upgrade': a listener that spins the event loop re-enters here, and C++ has one slot. overflow_owner = this .cpp_websocket() .filter(|_| is_101 && full.len() > head_len) .map(|ws| CppWebSocketRef::new(&ws)); Self::process_response(this, response, &full[head_len..]); } - // The connected client parses those bytes after the microtasks of `open`, - // like a later read. Under a nested event-loop spin (`expect().resolves`, - // a `Bun.build` plugin) the scope above was not the outermost and did not - // drain them. if let Some(ws) = overflow_owner { let event_loop = vm.event_loop_mut(); + // Under a nested event-loop spin (`expect().resolves`) the scope above drained nothing. if event_loop.entered_event_loop_count > 0 { let _ = event_loop.drain_microtasks(); } diff --git a/src/jsc/bindings/webcore/WebSocket.h b/src/jsc/bindings/webcore/WebSocket.h index 04b2671ebc01..b619ecd79800 100644 --- a/src/jsc/bindings/webcore/WebSocket.h +++ b/src/jsc/bindings/webcore/WebSocket.h @@ -211,8 +211,7 @@ class WebSocket final : public RefCounted, public EventTargetWithInli void didClose(unsigned unhandledBufferedAmount, unsigned short code, const String& reason); void didConnect(us_socket_t* socket, void* bufferedData, const PerMessageDeflateParams* deflate_params, void* customSSLCtx); void didConnectWithTunnel(void* tunnel, void* bufferedData, const PerMessageDeflateParams* deflate_params); - // The connected client parses the `bufferedData` didConnect*() gave it. The upgrade client - // calls this after the microtask checkpoint that follows the open event. + // The connected client parses didConnect*()'s bufferedData; called after the microtasks of open. void deliverInitialData(); void didFailWithErrorCode(Bun::WebSocketErrorCode code); From b3f055c9b48f879e36eddee1df31f73a16285d8d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 21 Sep 2026 17:31:29 +0000 Subject: [PATCH 4/8] WebSocket client: parse the bytes behind the 101 before a FIN or a reset that gets in first An open listener that spins the event loop lets the end of the stream in before the upgrade client delivers the bytes behind the 101. handle_end and handle_close now parse them first, as handle_data does, so they are not lost. clear_data drops them, so a terminate() from script does not parse them on its way out. Under a nested event-loop spin the upgrade client now drains the microtasks of open for every 101, not only when bytes follow it. On Windows the read loop probes the socket once more after the data callback, and a frame that was already there ran its message listener before those microtasks. --- src/http_jsc/websocket_client.rs | 12 +++-- .../WebSocketUpgradeClient.rs | 10 ++-- .../websocket-client-short-read.test.ts | 46 ++++++++++++++++++- 3 files changed, 59 insertions(+), 9 deletions(-) diff --git a/src/http_jsc/websocket_client.rs b/src/http_jsc/websocket_client.rs index 74f0d8678967..3eb1f9affd7c 100644 --- a/src/http_jsc/websocket_client.rs +++ b/src/http_jsc/websocket_client.rs @@ -173,6 +173,7 @@ impl WebSocket { pub(crate) fn clear_data(&self) { log!("clearData"); self.unref_keep_alive(); + drop(self.initial_data.take()); self.clear_receive_buffers(true); self.clear_send_buffers(true); self.control_frame_started.set(false); @@ -285,6 +286,8 @@ impl WebSocket { pub fn handle_close(&self, _socket: Socket, _code: c_int, _reason: *mut c_void) { log!("onClose"); jsc::mark_binding!(); + // A reset can get in ahead of `deliver_initial_data`, like the read in `handle_data`. + self.parse_initial_data(); if let Some((code, reason)) = self.close_dispatch_pending.take() { // The socket closed while our close frame was mid-flush; the peer // either got it or didn't, but JS should still see the @@ -542,9 +545,7 @@ impl WebSocket { let Some(initial_data) = self.initial_data.take() else { return false; }; - // For tunnel mode, tcp is detached but connection is still active through the tunnel - let is_connected = !self.tcp.get().is_closed() || self.tunnel().is_some(); - if self.cpp_websocket().is_some() && is_connected && !self.close_received.get() { + if self.cpp_websocket().is_some() && !self.close_received.get() { self.handle_data_loop(&initial_data); } true @@ -1211,6 +1212,11 @@ impl WebSocket { pub fn handle_end(&self, socket: Socket) { debug_assert!(self.is_same_socket(&socket)); + // A FIN can get in ahead of `deliver_initial_data`, like the read in `handle_data`. + if self.parse_initial_data() && self.cpp_websocket().is_none() { + // A Close frame in those bytes ended the connection; uSockets closes the socket after on_end. + return; + } if self.has_pending_close_dispatch() { // Peer FIN'd while we're still draining our close frame; finish the // drain on the next writable event instead of RST'ing via diff --git a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs index 73f65b89f1fe..1c412505506f 100644 --- a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs +++ b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs @@ -838,12 +838,12 @@ where .map(|ws| CppWebSocketRef::new(&ws)); Self::process_response(this, response, &full[head_len..]); } + // Under a nested event-loop spin (`expect().resolves`) the scope above drained nothing. + let event_loop = vm.event_loop_mut(); + if is_101 && event_loop.entered_event_loop_count > 0 { + let _ = event_loop.drain_microtasks(); + } if let Some(ws) = overflow_owner { - let event_loop = vm.event_loop_mut(); - // Under a nested event-loop spin (`expect().resolves`) the scope above drained nothing. - if event_loop.entered_event_loop_count > 0 { - let _ = event_loop.drain_microtasks(); - } ws.deliver_initial_data(); } } diff --git a/test/js/web/websocket/websocket-client-short-read.test.ts b/test/js/web/websocket/websocket-client-short-read.test.ts index 7e8ef5af33dd..f1562d5c7844 100644 --- a/test/js/web/websocket/websocket-client-short-read.test.ts +++ b/test/js/web/websocket/websocket-client-short-read.test.ts @@ -1,6 +1,6 @@ import { type Socket, TCPSocketListener } from "bun"; import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe, normalizeBunSnapshot, tls } from "harness"; +import { bunEnv, bunExe, isLinux, isWindows, normalizeBunSnapshot, tls } from "harness"; import { once } from "node:events"; import { WebSocket } from "ws"; @@ -645,6 +645,50 @@ describe("WebSocket frames in the same read as the 101", () => { } }); + // The nested event loop can see the end of the stream before the open listener returns. + describe("an open listener that spins the event loop with the end of the stream behind them", () => { + async function eventsOf(glued: Uint8Array, afterHandshake: (socket: Socket<{ request: string }>) => void) { + using server = rawServer({ glued, afterHandshake }); + + const events: string[] = []; + const closed = Promise.withResolvers(); + const ws = new globalThis.WebSocket(server.url); + ws.addEventListener("open", () => { + events.push("open"); + // Two turns of the event loop, each with a poll of the socket. + expect(new Promise(resolve => setImmediate(() => setImmediate(resolve)))).resolves.toBeUndefined(); + }); + ws.addEventListener("message", event => events.push(`message ${event.data}`)); + ws.addEventListener("error", () => events.push("error")); + ws.addEventListener("close", event => { + events.push(`close ${event.code} clean=${event.wasClean}`); + closed.resolve(); + }); + await closed.promise; + return events; + } + + // Windows: a socket that closes while its own data callback spins the event loop is freed under + // the outer dispatch (libuv.c does not count tick_depth). A debug build segfaults, with or without this fix. + test.skipIf(isWindows)("a Close frame, then FIN", async () => { + const glued = Buffer.concat([textFrame("last words"), closeFrame(1000)]); + expect(await eventsOf(glued, socket => socket.end())).toEqual([ + "open", + "message last words", + "close 1000 clean=true", + ]); + }); + + // Only Linux is known to keep received bytes readable once the reset is in. + test.skipIf(!isLinux)("a reset", async () => { + expect(await eventsOf(textFrame("last words"), socket => socket.terminate())).toEqual([ + "open", + "message last words", + "close 1006 clean=false", + ]); + }); + }); + test("a peer that ends the connection right behind them still gets them delivered", async () => { // The 101, a message, a Close frame, then FIN: the client can see the end of the stream in // the same poll as the data. From c57f38f4396404fd118ee4743cf134d64704a8c9 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 21 Sep 2026 19:24:42 +0000 Subject: [PATCH 5/8] WebSocket client: deliver the bytes behind the 101 from a task when open spins the event loop An open listener that waits synchronously (expect().resolves, a Bun.build plugin) ticks the event loop before the upgrade client can deliver the bytes behind the 101. C++ now queues a task before it dispatches open. The first tick of that wait runs it, so the frames arrive inside the wait, as they did when a microtask carried them. In the normal case the upgrade client has already delivered them and the task finds nothing. This replaces the parse in handle_end and handle_close: the task runs before the nested loop polls the socket, so a FIN or a reset behind the frames finds them delivered, on a TLS socket too. --- src/http_jsc/websocket_client.rs | 14 ++--- src/jsc/bindings/webcore/WebSocket.cpp | 13 +++++ src/jsc/bindings/webcore/WebSocket.h | 3 +- .../websocket-client-short-read.test.ts | 56 ++++++++++++++++--- 4 files changed, 68 insertions(+), 18 deletions(-) diff --git a/src/http_jsc/websocket_client.rs b/src/http_jsc/websocket_client.rs index 3eb1f9affd7c..0257e5031dda 100644 --- a/src/http_jsc/websocket_client.rs +++ b/src/http_jsc/websocket_client.rs @@ -173,7 +173,6 @@ impl WebSocket { pub(crate) fn clear_data(&self) { log!("clearData"); self.unref_keep_alive(); - drop(self.initial_data.take()); self.clear_receive_buffers(true); self.clear_send_buffers(true); self.control_frame_started.set(false); @@ -286,8 +285,6 @@ impl WebSocket { pub fn handle_close(&self, _socket: Socket, _code: c_int, _reason: *mut c_void) { log!("onClose"); jsc::mark_binding!(); - // A reset can get in ahead of `deliver_initial_data`, like the read in `handle_data`. - self.parse_initial_data(); if let Some((code, reason)) = self.close_dispatch_pending.take() { // The socket closed while our close frame was mid-flush; the peer // either got it or didn't, but JS should still see the @@ -545,13 +542,15 @@ impl WebSocket { let Some(initial_data) = self.initial_data.take() else { return false; }; - if self.cpp_websocket().is_some() && !self.close_received.get() { + // For tunnel mode, tcp is detached but connection is still active through the tunnel + let is_connected = !self.tcp.get().is_closed() || self.tunnel().is_some(); + if self.cpp_websocket().is_some() && is_connected && !self.close_received.get() { self.handle_data_loop(&initial_data); } true } - /// Called by the upgrade client (through C++) after the microtask checkpoint that follows `open`. + /// Called through C++: after the microtask checkpoint that follows `open`, or from a task if `open` spins the event loop. pub(crate) fn deliver_initial_data(this: ThisPtr) { let _guard = RefPtr::from_this(this); this.parse_initial_data(); @@ -1212,11 +1211,6 @@ impl WebSocket { pub fn handle_end(&self, socket: Socket) { debug_assert!(self.is_same_socket(&socket)); - // A FIN can get in ahead of `deliver_initial_data`, like the read in `handle_data`. - if self.parse_initial_data() && self.cpp_websocket().is_none() { - // A Close frame in those bytes ended the connection; uSockets closes the socket after on_end. - return; - } if self.has_pending_close_dispatch() { // Peer FIN'd while we're still draining our close frame; finish the // drain on the next writable event instead of RST'ing via diff --git a/src/jsc/bindings/webcore/WebSocket.cpp b/src/jsc/bindings/webcore/WebSocket.cpp index 5af030f6f18d..38ee2818eaaf 100644 --- a/src/jsc/bindings/webcore/WebSocket.cpp +++ b/src/jsc/bindings/webcore/WebSocket.cpp @@ -1528,6 +1528,8 @@ void WebSocket::didConnect(us_socket_t* socket, void* bufferedData, const PerMes if (m_paused) applyPauseToConnectedClient(); + if (bufferedData) + queueInitialDataDelivery(); this->didConnect(); } @@ -1717,6 +1719,9 @@ void WebSocket::didConnectWithTunnel(void* tunnel, void* bufferedData, const Per if (m_paused) applyPauseToConnectedClient(); + if (bufferedData) + queueInitialDataDelivery(); + // IMPORTANT: Call didConnect() BEFORE setting the connected websocket on the tunnel. // didConnect() sets m_state = OPEN, and messages are dropped if state != OPEN. // By calling didConnect() first, we ensure the state is OPEN before the tunnel @@ -1728,6 +1733,14 @@ void WebSocket::didConnectWithTunnel(void* tunnel, void* bufferedData, const Per WebSocketProxyTunnel__setConnectedWebSocket(tunnel, m_connectedWebSocketKind == ConnectedWebSocketKind::Client ? this->m_connectedWebSocket.client : nullptr); } +// An open listener that spins the event loop gets the bytes behind the 101 from this task. +void WebSocket::queueInitialDataDelivery() +{ + queueTaskKeepingObjectAlive(*this, TaskSource::WebSocket, [](WebSocket& ws) { + ws.deliverInitialData(); + }); +} + void WebSocket::deliverInitialData() { switch (m_connectedWebSocketKind) { diff --git a/src/jsc/bindings/webcore/WebSocket.h b/src/jsc/bindings/webcore/WebSocket.h index b619ecd79800..1b75af8bcc0d 100644 --- a/src/jsc/bindings/webcore/WebSocket.h +++ b/src/jsc/bindings/webcore/WebSocket.h @@ -211,7 +211,7 @@ class WebSocket final : public RefCounted, public EventTargetWithInli void didClose(unsigned unhandledBufferedAmount, unsigned short code, const String& reason); void didConnect(us_socket_t* socket, void* bufferedData, const PerMessageDeflateParams* deflate_params, void* customSSLCtx); void didConnectWithTunnel(void* tunnel, void* bufferedData, const PerMessageDeflateParams* deflate_params); - // The connected client parses didConnect*()'s bufferedData; called after the microtasks of open. + // The connected client parses didConnect*()'s bufferedData: after the microtasks of open, or from a task if open spins the event loop. void deliverInitialData(); void didFailWithErrorCode(Bun::WebSocketErrorCode code); @@ -336,6 +336,7 @@ class WebSocket final : public RefCounted, public EventTargetWithInli // Drop the in-flight upgrade / the connected client without a closing handshake. Neither // dispatches anything itself; the native side may call back synchronously. void cancelUpgradeClient(); + void queueInitialDataDelivery(); bool applyPauseToConnectedClient(); void cancelConnectedClient(); bool m_rejectUnauthorized { false }; diff --git a/test/js/web/websocket/websocket-client-short-read.test.ts b/test/js/web/websocket/websocket-client-short-read.test.ts index f1562d5c7844..8041eb821d3b 100644 --- a/test/js/web/websocket/websocket-client-short-read.test.ts +++ b/test/js/web/websocket/websocket-client-short-read.test.ts @@ -645,16 +645,58 @@ describe("WebSocket frames in the same read as the 101", () => { } }); + test("an open listener that waits synchronously for them", async () => { + using server = rawServer({ glued: textFrame("with the 101") }); + + const order: string[] = []; + const opened = Promise.withResolvers(); + const received = Promise.withResolvers(); + const ws = new globalThis.WebSocket(server.url); + rejectOnFailure(ws, opened, received); + ws.addEventListener("open", () => { + order.push("open"); + // Nothing else arrives on the socket. Without the cap, a client that holds the message back hangs here. + const { promise: cap, resolve: giveUp } = Promise.withResolvers(); + const timer = setTimeout(giveUp, 2000); + try { + // Ticks the event loop until the message is dispatched. + expect(Promise.race([received.promise, cap])).resolves.toBeUndefined(); + order.push("open returns"); + opened.resolve(); + } catch (error) { + opened.reject(error); + } finally { + clearTimeout(timer); + } + }); + ws.addEventListener("message", event => { + order.push(`message ${event.data}`); + received.resolve(); + }); + + try { + await opened.promise; + expect(order).toEqual(["open", "message with the 101", "open returns"]); + } finally { + ws.close(); + } + }); + // The nested event loop can see the end of the stream before the open listener returns. - describe("an open listener that spins the event loop with the end of the stream behind them", () => { - async function eventsOf(glued: Uint8Array, afterHandshake: (socket: Socket<{ request: string }>) => void) { - using server = rawServer({ glued, afterHandshake }); + describe("an open listener that ends the peer and spins the event loop", () => { + async function eventsOf( + protocol: string, + glued: Uint8Array, + endPeer: (socket: Socket<{ request: string }>) => void, + ) { + using server = rawServer({ secure: protocol === "wss", glued }); const events: string[] = []; const closed = Promise.withResolvers(); - const ws = new globalThis.WebSocket(server.url); + const ws = new globalThis.WebSocket(server.url, { tls: { rejectUnauthorized: false } }); ws.addEventListener("open", () => { events.push("open"); + endPeer(server.peer()); // Two turns of the event loop, each with a poll of the socket. expect(new Promise(resolve => setImmediate(() => setImmediate(resolve)))).resolves.toBeUndefined(); }); @@ -670,9 +712,9 @@ describe("WebSocket frames in the same read as the 101", () => { // Windows: a socket that closes while its own data callback spins the event loop is freed under // the outer dispatch (libuv.c does not count tick_depth). A debug build segfaults, with or without this fix. - test.skipIf(isWindows)("a Close frame, then FIN", async () => { + test.skipIf(isWindows).each(["ws", "wss"])("%s: a Close frame, then FIN", async protocol => { const glued = Buffer.concat([textFrame("last words"), closeFrame(1000)]); - expect(await eventsOf(glued, socket => socket.end())).toEqual([ + expect(await eventsOf(protocol, glued, socket => socket.end())).toEqual([ "open", "message last words", "close 1000 clean=true", @@ -681,7 +723,7 @@ describe("WebSocket frames in the same read as the 101", () => { // Only Linux is known to keep received bytes readable once the reset is in. test.skipIf(!isLinux)("a reset", async () => { - expect(await eventsOf(textFrame("last words"), socket => socket.terminate())).toEqual([ + expect(await eventsOf("ws", textFrame("last words"), socket => socket.terminate())).toEqual([ "open", "message last words", "close 1006 clean=false", From b68378212a1eea50f8c6936dfc62d536cea7d7c2 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 21 Sep 2026 20:10:14 +0000 Subject: [PATCH 6/8] WebSocket client: address the mordant findings of the handshake overflow change Delete BackRef::from_root: queue_microtask_boxed was its only caller. Move the SSL-independent tail of process_websocket_upgrade_response (the nested-spin drain and the delivery) into CppWebSocket, so it is compiled once. Record WebSocket::new_raw in mordant-baseline.toml. Its field initializers do not depend on SSL. The handle of the old task was the one that did, and it split them into two parts that were each under the lint's threshold. --- mordant-baseline.toml | 2 +- src/http_jsc/websocket_client/CppWebSocket.rs | 12 ++++++++++++ .../websocket_client/WebSocketUpgradeClient.rs | 13 ++++--------- src/ptr/lib.rs | 15 --------------- 4 files changed, 17 insertions(+), 25 deletions(-) diff --git a/mordant-baseline.toml b/mordant-baseline.toml index 74a53d6d7126..ab6b46c2227a 100644 --- a/mordant-baseline.toml +++ b/mordant-baseline.toml @@ -35,7 +35,7 @@ "generic_body_not_generic:src/http/lib.rs" = 2 [bun_http_jsc] -"generic_body_not_generic:src/http_jsc/websocket_client.rs" = 2 +"generic_body_not_generic:src/http_jsc/websocket_client.rs" = 5 "generic_body_not_generic:src/http_jsc/websocket_client/WebSocketUpgradeClient.rs" = 1 [bun_install] diff --git a/src/http_jsc/websocket_client/CppWebSocket.rs b/src/http_jsc/websocket_client/CppWebSocket.rs index 579078835a64..525ae35370d3 100644 --- a/src/http_jsc/websocket_client/CppWebSocket.rs +++ b/src/http_jsc/websocket_client/CppWebSocket.rs @@ -186,6 +186,18 @@ impl CppWebSocket { pub(crate) fn deliver_initial_data(&self) { WebSocket__deliverInitialData(self); } + + /// Call when the scope around `open` has ended. `overflow_owner` is the WebSocket with bytes behind its 101. + pub(crate) fn deliver_initial_data_after_open(overflow_owner: Option) { + let event_loop = VirtualMachine::get().event_loop_mut(); + // Under a nested event-loop spin (`expect().resolves`) that scope drained nothing. + if event_loop.entered_event_loop_count > 0 { + let _ = event_loop.drain_microtasks(); + } + if let Some(ws) = overflow_owner { + ws.deliver_initial_data(); + } + } } impl CppWebSocket { diff --git a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs index 1c412505506f..67395a78e081 100644 --- a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs +++ b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs @@ -815,11 +815,11 @@ where let head_len = response.bytes_read; let is_101 = response.status_code == 101; - let vm = bun_jsc::virtual_machine::VirtualMachine::get(); let overflow_owner; { // 101: one scope across 'upgrade'+'open' so microtasks drain after open. - let _scope = is_101.then(|| vm.enter_event_loop_scope()); + let _scope = is_101 + .then(|| bun_jsc::virtual_machine::VirtualMachine::get().enter_event_loop_scope()); if let Some(ws) = this.cpp_websocket() { Self::dispatch_handshake( @@ -838,13 +838,8 @@ where .map(|ws| CppWebSocketRef::new(&ws)); Self::process_response(this, response, &full[head_len..]); } - // Under a nested event-loop spin (`expect().resolves`) the scope above drained nothing. - let event_loop = vm.event_loop_mut(); - if is_101 && event_loop.entered_event_loop_count > 0 { - let _ = event_loop.drain_microtasks(); - } - if let Some(ws) = overflow_owner { - ws.deliver_initial_data(); + if is_101 { + CppWebSocket::deliver_initial_data_after_open(overflow_owner); } } diff --git a/src/ptr/lib.rs b/src/ptr/lib.rs index bfc818cbd971..86417e9dd238 100644 --- a/src/ptr/lib.rs +++ b/src/ptr/lib.rs @@ -208,21 +208,6 @@ impl BackRef { // SAFETY: see above. unsafe { ThisPtr::new(self.0.as_ptr()) } } - - /// Wrap the root pointer of a live heap allocation. - /// - /// # Safety - /// [`BackRef::from_raw`]'s contract, and `p` is what `Box::into_raw` / - /// `heap::into_raw` returned for an allocation that stays live while the - /// result is held. - #[inline] - pub const unsafe fn from_root(p: *mut T) -> Self { - // SAFETY: caller contract — `p` is non-null. - BackRef( - unsafe { core::ptr::NonNull::new_unchecked(p) }, - core::marker::PhantomData, - ) - } } impl From> for BackRef { From b1b915324abb44d2c09d7a364bd813601264643e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 21 Sep 2026 21:01:11 +0000 Subject: [PATCH 7/8] WebSocket client: run the microtasks of open before the task delivers the bytes behind the 101 When an open listener spins the event loop, the queued task delivers the bytes at the first tick of that wait. The microtasks that the listener queued before it started to wait were still pending, so glued bytes gave open, message, microtask and split bytes gave open, microtask, message. deliver_initial_data now runs a microtask checkpoint before it parses, when bytes are still pending. initial_data is a JsCell so that it can be checked without taking the bytes: a read that gets in during the checkpoint must still find them. --- src/http_jsc/websocket_client.rs | 17 ++++- .../websocket-client-short-read.test.ts | 74 +++++++++++-------- 2 files changed, 56 insertions(+), 35 deletions(-) diff --git a/src/http_jsc/websocket_client.rs b/src/http_jsc/websocket_client.rs index 8cc1846354f8..208ecc9694f5 100644 --- a/src/http_jsc/websocket_client.rs +++ b/src/http_jsc/websocket_client.rs @@ -104,7 +104,7 @@ pub struct WebSocket { pub(crate) payload_length_frame_len: Cell, /// Handshake overflow (bytes the upgrade client read past the 101), until parsed. - initial_data: Cell>>, + initial_data: JsCell>>, pub(crate) deflate: RefCell>>, /// Track if current message is compressed @@ -543,7 +543,7 @@ impl WebSocket { /// Returns whether the handshake overflow was still pending. The caller holds a ref guard. fn parse_initial_data(&self) -> bool { - let Some(initial_data) = self.initial_data.take() else { + let Some(initial_data) = self.initial_data.replace(None) else { return false; }; // For tunnel mode, tcp is detached but connection is still active through the tunnel @@ -556,7 +556,12 @@ impl WebSocket { /// Called through C++: after the microtask checkpoint that follows `open`, or from a task if `open` spins the event loop. pub(crate) fn deliver_initial_data(this: ThisPtr) { + if this.initial_data.get().is_none() { + return; + } let _guard = RefPtr::from_this(this); + // From the task, `open` is still on the stack with its microtasks queued: they come first. + microtask_checkpoint(); this.parse_initial_data(); } @@ -1430,7 +1435,7 @@ impl WebSocket { header_fragment: Cell::new(None), payload_length_frame_bytes: Cell::new([0u8; 8]), payload_length_frame_len: Cell::new(0), - initial_data: Cell::new(None), + initial_data: JsCell::new(None), deflate: RefCell::new( deflate_params.and_then(|params| WebSocketDeflate::init(*params).ok()), ), @@ -1611,6 +1616,12 @@ impl Drop for WebSocket { } } +fn microtask_checkpoint() { + let _ = jsc::virtual_machine::VirtualMachine::get() + .event_loop_mut() + .drain_microtasks(); +} + /// Transcode a close reason to UTF-8 into `buf`; `None` when it exceeds `MAX_CLOSE_REASON`. fn encode_close_reason( reason: &EncodedSlice, diff --git a/test/js/web/websocket/websocket-client-short-read.test.ts b/test/js/web/websocket/websocket-client-short-read.test.ts index 8041eb821d3b..962835101261 100644 --- a/test/js/web/websocket/websocket-client-short-read.test.ts +++ b/test/js/web/websocket/websocket-client-short-read.test.ts @@ -645,42 +645,52 @@ describe("WebSocket frames in the same read as the 101", () => { } }); - test("an open listener that waits synchronously for them", async () => { - using server = rawServer({ glued: textFrame("with the 101") }); + // "split" sends the frame from inside the listener, so a read during the wait brings it. + test.each(["glued", "split"])( + "%s: an open listener that queues a microtask and then waits synchronously for the message", + async segmentation => { + const frames = textFrame("greeting"); + using server = rawServer({ glued: segmentation === "glued" ? frames : new Uint8Array() }); + + const order: string[] = []; + const opened = Promise.withResolvers(); + const received = Promise.withResolvers(); + const ws = new globalThis.WebSocket(server.url); + rejectOnFailure(ws, opened, received); + ws.addEventListener("open", () => { + order.push("open"); + queueMicrotask(() => order.push("microtask from open")); + if (segmentation === "split") { + server.peer().write(frames); + server.peer().flush(); + } + // Without the cap, a client that holds the message back hangs here. + const { promise: cap, resolve: giveUp } = Promise.withResolvers(); + const timer = setTimeout(giveUp, 2000); + try { + // Ticks the event loop until the message is dispatched. + expect(Promise.race([received.promise, cap])).resolves.toBeUndefined(); + order.push("open returns"); + opened.resolve(); + } catch (error) { + opened.reject(error); + } finally { + clearTimeout(timer); + } + }); + ws.addEventListener("message", event => { + order.push(`message ${event.data}`); + received.resolve(); + }); - const order: string[] = []; - const opened = Promise.withResolvers(); - const received = Promise.withResolvers(); - const ws = new globalThis.WebSocket(server.url); - rejectOnFailure(ws, opened, received); - ws.addEventListener("open", () => { - order.push("open"); - // Nothing else arrives on the socket. Without the cap, a client that holds the message back hangs here. - const { promise: cap, resolve: giveUp } = Promise.withResolvers(); - const timer = setTimeout(giveUp, 2000); try { - // Ticks the event loop until the message is dispatched. - expect(Promise.race([received.promise, cap])).resolves.toBeUndefined(); - order.push("open returns"); - opened.resolve(); - } catch (error) { - opened.reject(error); + await opened.promise; + expect(order).toEqual(["open", "microtask from open", "message greeting", "open returns"]); } finally { - clearTimeout(timer); + ws.close(); } - }); - ws.addEventListener("message", event => { - order.push(`message ${event.data}`); - received.resolve(); - }); - - try { - await opened.promise; - expect(order).toEqual(["open", "message with the 101", "open returns"]); - } finally { - ws.close(); - } - }); + }, + ); // The nested event loop can see the end of the stream before the open listener returns. describe("an open listener that ends the peer and spins the event loop", () => { From 49d4a0d261f93bf9a30295a8d6ae492894e9b65e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 21 Sep 2026 21:20:38 +0000 Subject: [PATCH 8/8] test(websocket): split the 101 head over two reads by event-loop turns, not by a 50 ms timer --- test/js/web/websocket/websocket-client-short-read.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/js/web/websocket/websocket-client-short-read.test.ts b/test/js/web/websocket/websocket-client-short-read.test.ts index 962835101261..cbdb6e474810 100644 --- a/test/js/web/websocket/websocket-client-short-read.test.ts +++ b/test/js/web/websocket/websocket-client-short-read.test.ts @@ -398,8 +398,8 @@ describe("WebSocket frames in the same read as the 101", () => { const first = "HTTP/1.1 101 "; socket.write(first); socket.flush(); - // The client shows no sign of having read `first`. 50 ms puts the rest in a later read. - setTimeout(respond, 50, first.length); + // The first immediate runs before the poll in which the client reads `first`, the second one after it. + setImmediate(() => setImmediate(respond, first.length)); }, }, });