diff --git a/mordant-baseline.toml b/mordant-baseline.toml index b70314448594..fcc39d3004b2 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.rs b/src/http_jsc/websocket_client.rs index 5d3c0ee6d257..208ecc9694f5 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,8 @@ 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>>>, + /// Handshake overflow (bytes the upgrade client read past the 101), until parsed. + initial_data: JsCell>>, pub(crate) deflate: RefCell>>, /// Track if current message is compressed @@ -532,17 +530,8 @@ 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 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() { return; @@ -552,6 +541,30 @@ impl WebSocket { this.handle_data_loop(data_); } + /// 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.replace(None) 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 + } + + /// 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(); + } + 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. @@ -1422,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), - pending_initial_task: Cell::new(None), + initial_data: JsCell::new(None), deflate: RefCell::new( deflate_params.and_then(|params| WebSocketDeflate::init(*params).ok()), ), @@ -1437,7 +1450,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( @@ -1459,20 +1472,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() } @@ -1611,20 +1612,16 @@ 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); } } +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, @@ -1722,6 +1719,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() @@ -1801,6 +1804,12 @@ pub fn bun__websocketclienttls__init( verified_hostname, ) } +// 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, @@ -1825,53 +1834,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 5c0b298f3591..97f6145c2837 100644 --- a/src/http_jsc/websocket_client/CppWebSocket.rs +++ b/src/http_jsc/websocket_client/CppWebSocket.rs @@ -55,6 +55,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, @@ -184,6 +185,23 @@ impl CppWebSocket { WebSocket__didConnectWithTunnel(self, tunnel, buffered_data, deflate_params); event_loop.exit(); } + + /// 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); + } + + /// 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 { @@ -206,8 +224,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 { @@ -218,8 +235,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 3980269212db..67824c161550 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; @@ -821,17 +821,32 @@ 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; + 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()); + + 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; + } } + // 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..]); + } + if is_101 { + CppWebSocket::deliver_initial_data_after_open(overflow_owner); } - 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 a84471cb3164..b7d1a9c93da3 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, const unsigned char* verifiedHostname, size_t verifiedHostnameLen); +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, const unsigned char* verifiedHostname, size_t verifiedHostnameLen); +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 a8177bca2266..bebc43e71c40 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,28 @@ 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) { + 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 @@ -1743,6 +1770,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 e6f152ad9119..79166a282556 100644 --- a/src/jsc/bindings/webcore/WebSocket.h +++ b/src/jsc/bindings/webcore/WebSocket.h @@ -211,6 +211,8 @@ 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, std::span verifiedHostname); void didConnectWithTunnel(void* tunnel, void* bufferedData, const PerMessageDeflateParams* deflate_params); + // 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); void didReceiveMessage(String&& message); @@ -227,7 +229,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); @@ -334,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/src/jsc/lib.rs b/src/jsc/lib.rs index 64bbac5457e5..893ac7c3b39e 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/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 { 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..cbdb6e474810 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, isLinux, isWindows, 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,420 @@ 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(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: options.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"; + 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(); + // The first immediate runs before the poll in which the client reads `first`, the second one after it. + setImmediate(() => setImmediate(respond, first.length)); + }, + }, + }); + return { + url: `${options.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({ + secure: protocol === "wss", + glued: 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({ glued: 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({ glued: 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(); + } + }); + + // 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(); + } + }); + + // "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(); + }); + + try { + await opened.promise; + expect(order).toEqual(["open", "microtask from open", "message greeting", "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", () => { + 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, { 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(); + }); + 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).each(["ws", "wss"])("%s: a Close frame, then FIN", async protocol => { + const glued = Buffer.concat([textFrame("last words"), closeFrame(1000)]); + expect(await eventsOf(protocol, 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("ws", 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. + using server = rawServer({ + glued: Buffer.concat([textFrame("last words"), closeFrame(1000)]), + afterHandshake: 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