Skip to content
10 changes: 9 additions & 1 deletion src/runtime/api/BunObject.classes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,14 @@ export default [
cache: true,
},
},
values: ["exitedPromise", "onExitCallback", "onDisconnectCallback", "ipcCallback"],
values: [
"exitedPromise",
"onExitCallback",
"onDisconnectCallback",
"ipcCallback",
"ipcWorker",
"ipcInternalCallback",
"ipcAckCallbacks",
],
}),
];
9 changes: 8 additions & 1 deletion src/runtime/api/bun/subprocess.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,10 @@ pub(crate) mod js {
exitedPromise,
onExitCallback,
onDisconnectCallback,
ipcCallback
ipcCallback,
ipcWorker,
ipcInternalCallback,
ipcAckCallbacks
);
}

Expand Down Expand Up @@ -1473,6 +1476,10 @@ impl Subprocess<'_> {

if !this_jsvalue.is_empty() {
// The ipc callback is kept: a server/dgram handle still adopting at EOF is delivered afterwards, as in node.
js::ipc_worker_set_cached(this_jsvalue, global_this, JSValue::ZERO);
js::ipc_internal_callback_set_cached(this_jsvalue, global_this, JSValue::ZERO);
js::ipc_ack_callbacks_set_cached(this_jsvalue, global_this, JSValue::ZERO);

// Call the onDisconnectCallback if it exists and prevent it from being kept alive longer than necessary
if let Some(callback) =
js::on_disconnect_callback_take_cached(this_jsvalue, global_this)
Expand Down
137 changes: 101 additions & 36 deletions src/runtime/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,34 +41,91 @@ use bun_sys::windows::libuv::{UvHandle as _, UvStream as _};
pub(crate) struct InternalMsgHolder {
pub seq: i32,

// TODO: move this to an Array or a JS Object or something which doesn't
// individually create a Strong for every single IPC message...
pub callbacks: bun_collections::ArrayHashMap<i32, bun_jsc::StrongOptional>,
// Child side only. The primary keeps this state in the Subprocess wrapper's cached slots.
pub worker: bun_jsc::StrongOptional,
pub cb: bun_jsc::StrongOptional,
pub(crate) messages: Vec<bun_jsc::StrongOptional>,
/// A JS Array of the messages that arrived before the listener was installed.
pub(crate) messages: bun_jsc::StrongOptional,
}

impl Default for InternalMsgHolder {
fn default() -> Self {
Self {
seq: 0,
callbacks: bun_collections::ArrayHashMap::default(),
worker: bun_jsc::StrongOptional::empty(),
cb: bun_jsc::StrongOptional::empty(),
messages: Vec::new(),
messages: bun_jsc::StrongOptional::empty(),
}
}
}

impl InternalMsgHolder {
/// The ack-callback `Map` in the Subprocess wrapper's `ipcAckCallbacks` slot.
fn ack_callbacks(subprocess: JSValue) -> Option<&'static mut bun_jsc::JSMap> {
if subprocess.is_empty() {
return None;
}
let map = crate::api::bun::subprocess::js::ipc_ack_callbacks_get_cached(subprocess)?;
Some(bun_jsc::JSMap::opaque_mut(
bun_jsc::JSMap::from_js(map)?.as_ptr(),
))
}

/// Store `callback` under `seq` in the wrapper's ack-callback `Map`, created on first use.
/// A `Map` in a cached slot is one GC edge for all in-flight acks, not a root per ack.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn put_callback(
subprocess: JSValue,
global: &JSGlobalObject,
seq: i32,
callback: JSValue,
) -> JsResult<()> {
let map = match Self::ack_callbacks(subprocess) {
Some(map) => map,
None => {
let created = bun_jsc::JSMap::create(global);
crate::api::bun::subprocess::js::ipc_ack_callbacks_set_cached(
subprocess, global, created,
);
Self::ack_callbacks(subprocess).ok_or(JsError::OutOfMemory)?
}
};
map.set(global, JSValue::js_number(seq as f64), callback)
}

/// Remove and return the callback stored under `seq`, or `None` when absent.
pub(crate) fn take_callback(
subprocess: JSValue,
global: &JSGlobalObject,
seq: i32,
) -> JsResult<Option<JSValue>> {
let Some(map) = Self::ack_callbacks(subprocess) else {
return Ok(None);
};
let key = JSValue::js_number(seq as f64);
let cb = map.get(global, key)?;
if cb.is_undefined() {
return Ok(None);
}
map.remove(global, key)?;
Ok(Some(cb))
}

pub(crate) fn is_ready(&self) -> bool {
self.worker.has() && self.cb.has()
}

pub(crate) fn enqueue(&mut self, message: JSValue, global: &JSGlobalObject) {
self.messages
.push(bun_jsc::StrongOptional::create(message, global));
pub(crate) fn enqueue(&mut self, message: JSValue, global: &JSGlobalObject) -> JsResult<()> {
let arr = match self.messages.get() {
Some(a) => a,
None => {
let a = JSValue::create_empty_array(global, 0)?;
self.messages.set(global, a);
a
}
};
// Own-slot writes and reads: an indexed accessor on `Array.prototype` must not see the queue.
let len = arr.get_length(global)? as u32;
arr.put_index(global, len, message)
}

pub(crate) fn dispatch(
Expand All @@ -80,8 +137,7 @@ impl InternalMsgHolder {
if !self.is_ready() {
// Queued messages drop their handle; the cluster listener is
// installed before any handle-bearing reply can arrive.
self.enqueue(message, global);
return Ok(());
return self.enqueue(message, global);
}
self.dispatch_unsafe(message, handle, global)
}
Expand Down Expand Up @@ -109,28 +165,25 @@ impl InternalMsgHolder {

pub(crate) fn flush(&mut self, global: &JSGlobalObject) -> JsResult<()> {
debug_assert!(self.is_ready());
// PORT_NOTES_PLAN R-2: `&mut self` carries LLVM `noalias`, but
// `dispatch_unsafe` → `event_loop.run_callback` runs the JS IPC
// listener which can re-enter via a fresh `&mut Self` from the
// owner's `m_ctx` and write `self.cb` / `self.worker` /
// `self.callbacks`. With the loop body inlined, LLVM was hoisting the
// `self.cb`/`self.worker` reads (at the top of `dispatch_unsafe`) out
// of the loop — ASM-verified PROVEN_CACHED. Launder so each iteration
// re-reads through an opaque pointer.
let Some(messages) = self.messages.try_swap() else {
return Ok(());
};
let _keep = bun_jsc::EnsureStillAlive(messages);
// The JS listener can re-enter through `child_singleton()` and replace `cb` / `worker`,
// so each iteration must re-read them through a pointer LLVM cannot treat as `noalias`.
Comment thread
robobun marked this conversation as resolved.
Resolved
let this: *mut Self = core::hint::black_box(core::ptr::from_mut(self));
// SAFETY: `this` aliases the live `&mut self`; single JS thread.
let messages = core::mem::take(unsafe { &mut (*this).messages });
for strong in messages {
if let Some(message) = strong.get() {
// SAFETY: `this` is still live across re-entry — the IPC
// dispatcher is owned by the Subprocess/Worker which outlives
// this `flush` frame; `&mut *this` is the unique mutable view
// for this call.
unsafe { &mut *this }.dispatch_unsafe(message, JSValue::NULL, global)?;
let len = messages.get_length(global)? as u32;
for i in 0..len {
let message = messages.get_direct_index(global, i)?;
if message.is_empty_or_undefined_or_null() {
continue;
}
// strong drops here (== `strong.deinit()`)
// SAFETY: `this` is still live across re-entry — the IPC
// dispatcher is owned by the Subprocess/Worker which outlives
// this `flush` frame; `&mut *this` is the unique mutable view
// for this call.
unsafe { &mut *this }.dispatch_unsafe(message, JSValue::NULL, global)?;
}
// messages Vec drops here (== `messages.deinit(bun.default_allocator)`)
Ok(())
}

Expand Down Expand Up @@ -1007,6 +1060,14 @@ impl SendQueue {
self.owner.get()
}

/// The owning Subprocess's JS wrapper, or `ZERO` for the VM-side owner.
#[inline]
pub(crate) fn owner_this_jsvalue(&self) -> JSValue {
self.owner_ref()
.map(SendQueueOwner::this_jsvalue)
.unwrap_or_default()
}

pub(crate) fn set_owner(&self, owner: SendQueueOwner) {
self.owner.set(Some(owner));
}
Expand Down Expand Up @@ -1391,13 +1452,17 @@ impl SendQueue {
.waiting_for_ack
.with_mut(|w| w.as_ref().and_then(|i| i.handle.as_ref()?.cluster_seq));
if let Some(seq) = cluster_seq {
let cb = self.internal_msg_queue.with_mut(|q| {
let entry = q.callbacks.get(&seq).map(|s| s.get());
if entry.is_some() {
q.callbacks.swap_remove(&seq);
let cb = match InternalMsgHolder::take_callback(
self.owner_this_jsvalue(),
global,
seq,
) {
Ok(cb) => cb,
Err(err) => {
crate::dispatch::fold(Err(err));
None
}
entry.flatten()
});
};
if let Some(cb) = cb {
let reply = JSValue::create_empty_object(global, 1);
reply.put(global, b"accepted", JSValue::FALSE);
Expand Down
64 changes: 24 additions & 40 deletions src/runtime/node/node_cluster_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
// - We should not be creating JSFunction's in process.nextTick.

use crate::ipc::{IsInternal, SerializeAndSendResult};
use bun_jsc::{CallFrame, JSGlobalObject, JSValue, JsResult, StrongOptional};
use bun_jsc::{CallFrame, JSGlobalObject, JSValue, JsResult};

use crate::api::bun::subprocess::Subprocess;
use crate::api::bun::subprocess::{Subprocess, js as subprocess_js};

// Struct lives in `crate::ipc` —
// `SendQueue` stores one inline so it must live at that tier. Re-exported here so
Expand Down Expand Up @@ -47,9 +47,8 @@ pub(crate) fn on_internal_message_child(
bun_output::scoped_log!(IPC, "onInternalMessageChild");
let arguments = frame.arguments_as_array::<2>();
let singleton = child_singleton();
// TODO: we should not create two jsc.Strong.Optional here. If absolutely necessary, a single Array. should be all we use.
singleton.worker = StrongOptional::create(arguments[0], global);
singleton.cb = StrongOptional::create(arguments[1], global);
singleton.worker.set(global, arguments[0]);
singleton.cb.set(global, arguments[1]);
singleton.flush(global)?;
Ok(JSValue::UNDEFINED)
}
Expand Down Expand Up @@ -140,15 +139,11 @@ pub(crate) fn send_helper_primary(global: &JSGlobalObject, frame: &CallFrame) ->
}
let this_seq = ipc_data.internal_msg_queue.with_mut(|q| {
let seq = q.seq;
if callback.is_function() {
let _ = q
.callbacks
.put(seq, StrongOptional::create(callback, global));
}
q.seq = seq.wrapping_add(1);
seq
});
if callback.is_function() {
InternalMsgHolder::put_callback(arguments[0], global, this_seq, callback)?;
if let Some(h) = &mut native_handle {
h.cluster_seq = Some(this_seq);
}
Expand Down Expand Up @@ -194,14 +189,12 @@ pub(crate) fn on_internal_message_primary(
let Some(subprocess) = arguments[0].as_class_ref::<Subprocess<'_>>() else {
return Ok(JSValue::UNDEFINED);
};
let Some(ipc_data) = subprocess.ipc() else {
if subprocess.ipc().is_none() {
return Ok(JSValue::UNDEFINED);
};
// TODO: remove these strongs.
ipc_data.internal_msg_queue.with_mut(|q| {
q.worker = StrongOptional::create(arguments[1], global);
q.cb = StrongOptional::create(arguments[2], global);
});
}
// Cached slots, not `Strong` handles: a `Strong` here roots the worker's whole object graph.
subprocess_js::ipc_worker_set_cached(arguments[0], global, arguments[1]);
subprocess_js::ipc_internal_callback_set_cached(arguments[0], global, arguments[2]);
Ok(JSValue::UNDEFINED)
}

Expand All @@ -213,52 +206,43 @@ pub(crate) fn handle_internal_message_primary(
let Some(ipc_data) = subprocess.ipc() else {
return Ok(());
};

if !ipc_data.internal_msg_queue.get().is_ready() {
let this_jsvalue = ipc_data.owner_this_jsvalue();
let _keep = bun_jsc::EnsureStillAlive(this_jsvalue);
if this_jsvalue.is_empty() {
return Ok(());
}

let (Some(worker), Some(cb)) = (
subprocess_js::ipc_worker_get_cached(this_jsvalue),
subprocess_js::ipc_internal_callback_get_cached(this_jsvalue),
) else {
return Ok(());
};

let event_loop = global.bun_vm().event_loop_mut();

// TODO: investigate if "ack" and "seq" are observable and if they're not, remove them entirely.
if let Some(p) = message.get(global, "ack")? {
if !p.is_undefined() {
let ack = p.to_int32();
let entry = ipc_data.internal_msg_queue.with_mut(|q| {
let cb = q.callbacks.get(&ack).and_then(|s| s.get());
if q.callbacks.contains_key(&ack) {
q.callbacks.swap_remove(&ack);
}
cb.zip(q.worker.get())
});
if let Some((cb, worker)) = entry {
if let Some(callback) = InternalMsgHolder::take_callback(this_jsvalue, global, ack)? {
event_loop.run_callback(
subprocess.context,
cb,
callback,
global,
worker,
&[
message,
JSValue::NULL, // handle
],
&[message, JSValue::NULL],
);
return Ok(());
}
}
}
let (cb, worker) = {
let q = ipc_data.internal_msg_queue.get();
(q.cb.get().unwrap(), q.worker.get().unwrap())
};
event_loop.run_callback(
subprocess.context,
cb,
global,
worker,
&[
message,
JSValue::NULL, // handle
],
&[message, JSValue::NULL],
);
Ok(())
}
Expand Down
Loading
Loading