Skip to content
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion mordant-baseline.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
126 changes: 42 additions & 84 deletions src/http_jsc/websocket_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -103,10 +103,8 @@ pub struct WebSocket<const SSL: bool> {
pub(crate) payload_length_frame_bytes: Cell<[u8; 8]>,
pub(crate) payload_length_frame_len: Cell<u8>,

/// 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<Option<BackRef<InitialDataTask<SSL>, Root>>>,
/// Handshake overflow (bytes the upgrade client read past the 101), until parsed.
initial_data: Cell<Option<Vec<u8>>>,
pub(crate) deflate: RefCell<Option<Box<WebSocketDeflate>>>,

/// Track if current message is compressed
Expand Down Expand Up @@ -532,17 +530,8 @@ impl<const SSL: bool> WebSocket<SSL> {
// 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;
Comment thread
robobun marked this conversation as resolved.
Resolved
Expand All @@ -552,6 +541,25 @@ impl<const SSL: bool> WebSocket<SSL> {
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.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
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/// 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<Self>) {
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.
Expand Down Expand Up @@ -1422,7 +1430,7 @@ impl<const SSL: bool> WebSocket<SSL> {
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()),
),
Expand All @@ -1437,7 +1445,7 @@ impl<const SSL: bool> WebSocket<SSL> {
}

/// 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(
Expand All @@ -1459,20 +1467,8 @@ impl<const SSL: bool> WebSocket<SSL> {
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()
}
Expand Down Expand Up @@ -1611,16 +1607,6 @@ impl<const SSL: bool> Drop for WebSocket<SSL> {
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);
}
}
Expand Down Expand Up @@ -1722,6 +1708,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<crate::websocket_client::WebSocketClient>,
) {
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()
Expand Down Expand Up @@ -1801,6 +1793,12 @@ pub fn bun__websocketclienttls__init(
verified_hostname,
)
}
// HOST_EXPORT(Bun__WebSocketClientTLS__deliverInitialData, c)
pub fn bun__websocketclienttls__deliver_initial_data(
this: ThisPtr<crate::websocket_client::WebSocketClientTLS>,
) {
WebSocketClientTLS::deliver_initial_data(this)
}
// HOST_EXPORT(Bun__WebSocketClientTLS__memoryCost, c)
pub fn bun__websocketclienttls__memory_cost(
this: &crate::websocket_client::WebSocketClientTLS,
Expand All @@ -1825,53 +1823,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<u8>);

/// Handshake-overflow bytes plus the pending-activity ref that keeps the C++
/// `WebSocket` alive until they are delivered.
struct InitialDataHandler {
slice: Vec<u8>,
_pending_activity: CppWebSocketRef,
}

impl InitialDataHandler {
/// Feed the buffered bytes to `ws` as if they had just arrived.
fn deliver<const SSL: bool>(self, ws: ThisPtr<WebSocket<SSL>>) {
// 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::<SSL>::handle_data(ws, &self.slice);
}
}
}

/// Microtask that delivers [`InitialDataHandler`] ahead of fresh socket data.
pub(crate) struct InitialDataTask<const SSL: bool> {
/// Detached by `WebSocket`'s `Drop` (or by `handle_data` draining `data`
/// first) so a task that outlives its client does nothing.
ws: Cell<Option<BackRef<WebSocket<SSL>, Root>>>,
data: JsCell<Option<InitialDataHandler>>,
}

impl<const SSL: bool> jsc::MicrotaskCallback for InitialDataTask<SSL> {
fn run(self: Box<Self>) {
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
// ──────────────────────────────────────────────────────────────────────────
Expand Down
31 changes: 28 additions & 3 deletions src/http_jsc/websocket_client/CppWebSocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ unsafe extern "C" {
buffered_data: Option<Box<InitialData>>,
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,
Expand Down Expand Up @@ -189,6 +190,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<CppWebSocketRef>) {
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 {
Expand All @@ -211,8 +229,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<CppWebSocket>);

impl CppWebSocketRef {
Expand All @@ -223,8 +240,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();
}
}
35 changes: 25 additions & 10 deletions src/http_jsc/websocket_client/WebSocketUpgradeClient.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -815,17 +815,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());
Comment thread
robobun marked this conversation as resolved.
Resolved

if let Some(ws) = this.cpp_websocket() {
Self::dispatch_handshake(
ws,
&response,
if is_101 { &[] } else { &full[head_len..] },
);
Comment thread
robobun marked this conversation as resolved.
Resolved
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<Self>` because `terminate`/`handle_data` may free `this`.
Expand Down
45 changes: 0 additions & 45 deletions src/jsc/JSGlobalObject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<C>(
&self,
ctx_val: *mut C,
function: unsafe extern "C" fn(*mut c_void),
) {
crate::mark_binding();
JSC__JSGlobalObject__queueMicrotaskCallback(self, ctx_val.cast::<c_void>(), 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<T: MicrotaskCallback>(
&self,
task: Box<T>,
) -> bun_ptr::BackRef<T, bun_ptr::Root> {
unsafe extern "C" fn run<T: MicrotaskCallback>(ctx: *mut c_void) {
// SAFETY: `ctx` is the `Box<T>` leaked below; the microtask queue
// invokes each callback exactly once.
T::run(unsafe { bun_core::heap::take(ctx.cast::<T>()) });
}
let task = bun_core::heap::into_raw(task);
self.queue_microtask_callback(task, run::<T>);
// 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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<Self>);
}
Loading
Loading