Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 6 additions & 0 deletions packages/bun-usockets/src/libusockets.h
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,12 @@ void us_socket_local_address(us_socket_r s, char *nonnull_arg buf, int *nonnull_

struct us_socket_t *us_socket_detach(us_socket_r s) nonnull_fn_decl;
int us_socket_ipc_write_fd(us_socket_r s, const char *data, int length, int fd) nonnull_fn_decl;
/* Synchronously read and dispatch whatever the kernel still holds for `s`, then
* dispatch on_end and close it as if the peer's EOF had been read. For owners
* that learn out of band that the peer is gone (IPC child exit) and would
* otherwise close on top of undelivered data. Stops at EOF or would-block, so a
* peer end still held open elsewhere does not stall it. POSIX only. */
void us_socket_drain_readable_then_end(us_socket_r s) nonnull_fn_decl;
void us_socket_sendfile_needs_more(us_socket_r s) nonnull_fn_decl;
void *us_listen_socket_ext(struct us_listen_socket_t *ls) nonnull_fn_decl;
LIBUS_SOCKET_DESCRIPTOR us_listen_socket_get_fd(struct us_listen_socket_t *ls) nonnull_fn_decl;
Expand Down
16 changes: 16 additions & 0 deletions packages/bun-usockets/src/socket.c
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,22 @@ int us_socket_ipc_write_fd(struct us_socket_t *s, const char *data, int length,

return sent;
}

/* The owner learned out of band that the peer is gone (the child process on the
* other end of an IPC socketpair was reaped) and is about to close this socket.
* What the peer wrote before exiting is still queued in the kernel, and its
* readable event may not have been dispatched yet (the exit can arrive through
* a task queue that runs before the next poll). Run the readable dispatch now
* with the EOF hint set: it reads and dispatches on_data until recv() reports
* EOF or would block, then dispatches on_end and closes the socket, exactly as
* the peer's FIN would have. Would-block still ends the socket, so a peer end
* that something else (a grandchild) still holds open cannot keep it alive. */
void us_socket_drain_readable_then_end(struct us_socket_t *s) {
if (us_socket_is_closed(s)) {
return;
}
us_internal_dispatch_ready_poll(&s->p, 0, 1, LIBUS_SOCKET_READABLE);
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
}
#endif

__attribute__((always_inline)) void *us_socket_ext(struct us_socket_t *s) {
Expand Down
17 changes: 8 additions & 9 deletions src/runtime/api/bun/subprocess.rs
Original file line number Diff line number Diff line change
Expand Up @@ -838,11 +838,6 @@ impl Subprocess<'_> {
crate::ipc_host::do_send(this.ipc(), global, call_frame, context, this.pid() as u32)
}

pub(crate) fn disconnect_ipc(&self, next_tick: bool) {
let Some(ipc_data) = self.ipc() else { return };
ipc_data.close_socket_next_tick(next_tick);
}

#[bun_jsc::host_fn(method)]
pub(crate) fn disconnect(
this: &Self,
Expand Down Expand Up @@ -949,9 +944,7 @@ impl Subprocess<'_> {
let is_sync = self.flags.get().contains(Flags::IS_SYNC);
self.clear_abort_signal();

// `deref()` and `disconnect_ipc(true)` run at the tail of this body.
// R-2: now that both take `&self`, scopeguard would no longer alias —
// kept explicit at the tail for now (no early returns in this body).
// `deref()` runs at the tail of this body (no early returns in this body).

if self.event_loop_timer.get().state == EventLoopTimerState::ACTIVE {
Self::timer_all().remove(self.event_loop_timer.as_ptr());
Expand Down Expand Up @@ -1103,6 +1096,13 @@ impl Subprocess<'_> {
}
}

// Like stdout/stderr above, deliver what the child sent over IPC before
// it exited (the `ipc` callback runs here, ahead of `exited`/`onExit`,
// the order node produces), then close the channel.
Comment thread
robobun marked this conversation as resolved.
Resolved
if let Some(ipc_data) = self.ipc() {
ipc_data.close_after_peer_exit();
}

let mut did_update_has_pending_activity = false;

// Kept as raw `*mut` so the enter guard and the body can both call
Expand Down Expand Up @@ -1188,7 +1188,6 @@ impl Subprocess<'_> {
if !did_update_has_pending_activity {
self.update_has_pending_activity();
}
self.disconnect_ipc(true);
self.deref();
}

Expand Down
19 changes: 19 additions & 0 deletions src/runtime/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1279,6 +1279,25 @@ impl SendQueue {
self.schedule_deferred();
}

/// The peer process has exited. Its exit can reach us ahead of the socket's
/// readable event (the waiter thread posts it as a task, which runs before
/// the next poll), so messages it sent right before exiting may still be
/// unread in the socket; closing now would drop them, whereas node reads the
/// channel to EOF. Drain it first: the drain ends in `on_end`, which closes
/// the socket and queues the disconnect notification as a peer EOF would.
/// A close the user already requested is left alone, as is the Windows
/// pipe, which has no synchronous read; those still close next tick.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn close_after_peer_exit(&self) {
log!("SendQueue#closeAfterPeerExit");
#[cfg(not(windows))]
if !self.pending_close.get() {
if let Some(socket) = self.get_socket() {
socket.drain_readable_then_end();
}
}
self.close_socket_next_tick(true);
}

/// User disconnect(): reports disconnected now but, like node, closes only once a handle awaiting its ack and the queue behind it have gone out.
pub fn disconnect(&self) {
if self.socket_is_open()
Expand Down
11 changes: 11 additions & 0 deletions src/uws_sys/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,17 @@ impl<const IS_SSL: bool> NewSocketHandler<IS_SSL> {
}
}

/// Synchronously reads and dispatches what the peer sent before it went
/// away, then ends and closes the socket (see `us_socket_t::drain_readable_then_end`).
/// The socket's handlers, including `on_end` and `on_close`, run before
/// this returns. POSIX-only, like the IPC socketpair it exists for.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[cfg(not(windows))]
pub fn drain_readable_then_end(&self) {
if let InternalSocket::Connected(s) = self.socket {
sock(s).drain_readable_then_end();
}
}

/// Vectored raw write: one writev on real sockets; sequential raw writes on
/// transports without an fd (duplex/pipe). Plain-TCP callers only — raw
/// writes bypass TLS framing.
Expand Down
15 changes: 15 additions & 0 deletions src/uws_sys/us_socket_t.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,19 @@ impl us_socket_t {
unreachable!("us_socket_t::write_fd is not implemented on Windows")
}

/// Reads and dispatches everything the kernel still holds for this socket,
/// then dispatches `on_end` and closes it, as if the peer's EOF had been
/// read. For owners that learn out of band that the peer is gone (IPC
/// child exit). Re-enters the socket's handlers synchronously.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[cfg(not(windows))]
pub(crate) fn drain_readable_then_end(&mut self) {
bun_core::scoped_log!(uws, "us_socket_drain_readable_then_end({:p})", self);
// SAFETY: self is a live us_socket_t. Declared over `*mut` (like
// `us_socket_close`) because the dispatch re-enters this socket's
// handlers, which reach it again through their own pointers.
unsafe { c::us_socket_drain_readable_then_end(self) };
}

pub fn write2(&mut self, first: &[u8], second: &[u8]) -> i32 {
let rc = unsafe {
// SAFETY: both slices valid for their respective lengths
Expand Down Expand Up @@ -524,6 +537,8 @@ mod c {
length: i32,
fd: i32,
) -> i32;
#[cfg(not(windows))]
pub(super) fn us_socket_drain_readable_then_end(s: *mut us_socket_t);
pub(super) fn us_socket_write2(
s: *mut us_socket_t,
header: *const u8,
Expand Down
97 changes: 96 additions & 1 deletion test/js/bun/spawn/spawn.ipc.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { spawn } from "bun";
import { describe, expect, it } from "bun:test";
import { bunEnv, bunExe, gcTick, isWindows } from "harness";
import { bunEnv, bunExe, gcTick, isLinux, isWindows, shellExe } from "harness";
import path from "path";

describe.each(["advanced", "json"])("ipc mode %s", mode => {
Expand Down Expand Up @@ -85,8 +85,103 @@ describe.each(["advanced", "json"])("ipc mode %s", mode => {
.sort((a, b) => a - b),
).toEqual(Array.from({ length: 32 }, (_, i) => i));
});

// On the waiter-thread exit path (no usable pidfd, forced here with the feature flag) the
// child's exit reaches the parent as a task, which runs before the event loop polls the IPC
// socket. The parent used to close the channel on exit without reading it, dropping whatever
// the child sent right before exiting; node reads the channel to EOF. The parent below stays
// off its event loop until the child is dead, so the exit is always processed first.
it.concurrent.skipIf(!isLinux)("delivers messages sent right before exit when the exit is seen first", async () => {
const parent = `
const { readFileSync } = require("node:fs");
const received = [];
const disconnected = Promise.withResolvers();
const child = Bun.spawn({
cmd: [
process.execPath, "-e",
'process.send("one"); process.send({ two: 2 }); Promise.resolve().then(() => process.exit(7));',
],
stdio: ["ignore", "inherit", "inherit"],
serialization: ${JSON.stringify(mode)},
ipc(message) { received.push(message); },
onDisconnect() { disconnected.resolve(); },
});
function childIsDead() {
let stat;
try {
stat = readFileSync("/proc/" + child.pid + "/stat", "latin1");
} catch {
return true; // already reaped
}
// "<pid> (<comm>) <state> ..."
return stat[stat.lastIndexOf(")") + 2] === "Z";
}
const deadline = Date.now() + 30_000;
while (!childIsDead()) {
if (Date.now() > deadline) throw new Error("child did not exit");
Bun.sleepSync(1);
}
// The waiter thread posts the exit task moments after the child dies; give it a generous
// head start before this process returns to its event loop.
Bun.sleepSync(50);
const exitCode = await child.exited;
const receivedBeforeExited = [...received];
await disconnected.promise;
console.log(JSON.stringify({ receivedBeforeExited, received, exitCode }));
`;
await using proc = spawn({
cmd: [bunExe(), "-e", parent],
// BUN_FEATURE_FLAG_FORCE_WAITER_THREAD is only honored when BUN_GARBAGE_COLLECTOR_LEVEL is
// also set; bunEnv sets the latter.
env: { ...bunEnv, BUN_FEATURE_FLAG_FORCE_WAITER_THREAD: "1" },
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect({ stdout: stdout.trim(), stderr, exitCode }).toEqual({
stdout: JSON.stringify({
receivedBeforeExited: ["one", { two: 2 }],
received: ["one", { two: 2 }],
exitCode: 7,
}),
stderr: "",
exitCode: 0,
});
});
});

// After the child exits the channel is closed even if its end is still held open by a grandchild
// (the channel is never awaited to EOF), but not before what was already written has been read.
it.concurrent.skipIf(isWindows)(
"a grandchild holding the channel open delays neither the last message nor the disconnect",
async () => {
const received: unknown[] = [];
const disconnected = Promise.withResolvers<void>();
await using child = spawn({
// fd 3 is the child's end of the channel. `sleep` inherits it and outlives the shell.
cmd: [shellExe(), "-c", 'echo \'{"from":"shell"}\' >&3; sleep 30 >/dev/null 2>&1 & echo $!'],
env: bunEnv,
stdio: ["ignore", "pipe", "inherit"],
serialization: "json",
ipc(message) {
received.push(message);
},
onDisconnect() {
disconnected.resolve();
},
});
const grandchildPid = Number((await child.stdout.text()).trim());
try {
expect(grandchildPid).toBeGreaterThan(0);
expect(await child.exited).toBe(0);
await disconnected.promise;
expect(received).toEqual([{ from: "shell" }]);
} finally {
if (grandchildPid > 0) process.kill(grandchildPid);
}
},
);

describe("ipc mode advanced", () => {
it("unwraps the Buffer envelope before cmd dispatch", async () => {
// A cmd-bearing message whose payload holds a Buffer travels as the
Expand Down
74 changes: 73 additions & 1 deletion test/js/node/child_process/child_process.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
import { semver, write } from "bun";
import { afterAll, beforeEach, describe, expect, it } from "bun:test";
import fs from "fs";
import { bunEnv, bunExe, isLinux, isPosix, isWindows, nodeExe, runBunInstall, shellExe, tmpdirSync } from "harness";
import {
bunEnv,
bunExe,
isLinux,
isPosix,
isWindows,
nodeExe,
runBunInstall,
shellExe,
tempDir,
tmpdirSync,
} from "harness";
import { ChildProcess, exec, execFile, execFileSync, execSync, fork, spawn, spawnSync } from "node:child_process";
import { getEventListeners, once, setMaxListeners } from "node:events";
import { promisify } from "node:util";
Expand Down Expand Up @@ -194,6 +205,67 @@ describe("fork() IPC", () => {
});
expect(exitCode).toBe(0);
});

// Same scenario as "delivers messages sent right before exit" in test/js/bun/spawn/spawn.ipc.test.ts,
// through fork(): on the waiter-thread exit path the child's exit is processed before the IPC
// socket is read, and the messages it sent just before exiting used to be dropped. node emits
// them before 'exit'. The parent stays off its event loop until the child is dead so the exit is
// always processed first.
it.concurrent.skipIf(!isLinux)("delivers messages the child sent right before exiting", async () => {
using dir = tempDir("fork-message-before-exit", {
"child.js": `process.send("hello"); Promise.resolve().then(() => process.exit(3));`,
"parent.js": `
const { fork } = require("node:child_process");
const { readFileSync } = require("node:fs");
const events = [];
const child = fork(require("node:path").join(__dirname, "child.js"));
child.on("message", message => events.push(["message", message]));
child.on("exit", code => events.push(["exit", code]));
child.on("disconnect", () => events.push(["disconnect"]));
child.on("close", code => {
events.push(["close", code]);
console.log(JSON.stringify(events));
});
function childIsDead() {
let stat;
try {
stat = readFileSync("/proc/" + child.pid + "/stat", "latin1");
} catch {
return true; // already reaped
}
// "<pid> (<comm>) <state> ..."
return stat[stat.lastIndexOf(")") + 2] === "Z";
}
const deadline = Date.now() + 30_000;
while (!childIsDead()) {
if (Date.now() > deadline) throw new Error("child did not exit");
Bun.sleepSync(1);
}
// The waiter thread posts the exit task moments after the child dies; give it a generous
// head start before this process returns to its event loop.
Bun.sleepSync(50);
`,
});
await using proc = Bun.spawn({
cmd: [bunExe(), "parent.js"],
cwd: String(dir),
// BUN_FEATURE_FLAG_FORCE_WAITER_THREAD is only honored when BUN_GARBAGE_COLLECTOR_LEVEL is
// also set; bunEnv sets the latter.
env: { ...bunEnv, BUN_FEATURE_FLAG_FORCE_WAITER_THREAD: "1" },
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
const events: unknown[][] = JSON.parse(stdout);
// 'message' comes first, as in node. 'exit' and 'disconnect' are independent notifications
// and may come in either order; 'close' follows both.
const [first, ...rest] = events;
expect(first).toEqual(["message", "hello"]);
expect(rest.sort()).toEqual([["close", 3], ["disconnect"], ["exit", 3]]);
expect(events.at(-1)).toEqual(["close", 3]);
expect(exitCode).toBe(0);
});
});

describe("spawn()", () => {
Expand Down