Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
13 changes: 11 additions & 2 deletions src/runtime/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1182,13 +1182,22 @@ impl SendQueue {
log!("SendQueue#_onAfterIPCClosed");
if !sq.close_event_sent.replace(true) {
let global = sq.get_global_this();
let mut behind_handle = false;
if let Some(item) = sq.waiting_for_ack.with_mut(|w| w.take()) {
behind_handle = true;
item.complete(&global);
}
// on_write_complete already dequeued everything fully written; the rest was never delivered.
// node calls back each write it submitted, with null even if the close cancels it: https://github.com/nodejs/node/blob/v26.3.0/lib/internal/child_process.js#L868-L874
// Sends parked behind an unacknowledged handle were never submitted, so their callbacks never run: https://github.com/nodejs/node/blob/v26.3.0/lib/internal/child_process.js#L818-L853
Comment thread
robobun marked this conversation as resolved.
Resolved
for item in sq.queue.with_mut(std::mem::take) {
item.abort_unsent(&global);
if behind_handle {
item.abort_unsent(&global);
Comment thread
robobun marked this conversation as resolved.
Resolved
} else {
behind_handle = item.handle.is_some();
item.complete(&global);
}
}
// The callbacks are queued first on purpose: ChildProcess queues 'disconnect' and 'close' from this call, and they must not run after 'close'.
if let Some(owner) = sq.owner.get() {
owner.handle_ipc_close();
Comment thread
robobun marked this conversation as resolved.
Resolved
}
Expand Down
57 changes: 57 additions & 0 deletions test/js/node/child_process/child_process_ipc_handle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,63 @@ server.listen(0, '127.0.0.1', () => {
},
);

test.concurrent(
"channel close: callbacks fire null up to the first unsent handle; sends queued behind it never fire",
async () => {
// node v26.3.0 prints the same object: it submits `before` and `handle` to the channel, and parks the rest.
using dir = tempDir("ipc-handle-close-mixed-queue", {
"parent.js": `
const { fork } = require('node:child_process');
const net = require('node:net');
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const child = fork('child.js');
const server = net.createServer();
server.listen(0, '127.0.0.1', () => {
net.connect(server.address().port, '127.0.0.1', function () {
const out = { before: 'never called', handle: 'never called', behind: 'never called', behindLarge: 'never called' };
const order = [];
const record = name => err => { out[name] = err; order.push(name); };
// Larger than the IPC socket buffer, so it is still being written when the handle is queued.
const pad = Buffer.alloc(1 << 21, 'd').toString();
child.send({ pad }, record('before'));
child.send('handle', this, record('handle'));
child.send('behind', record('behind'));
child.send({ pad }, record('behindLarge'));
child.kill('SIGKILL');
child.on('close', () => {
order.push('close');
setImmediate(() => {
console.log(JSON.stringify({ ...out, order }));
server.close();
process.exit(0);
});
});
}).on('error', () => {});
});
`,
"child.js": `const end = Date.now() + 30_000; while (Date.now() < end) {}`,
});
await using proc = Bun.spawn({
cmd: [bunExe(), "parent.js"],
env: bunEnv,
cwd: String(dir),
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect({ out: JSON.parse(stdout.trim()), stderr }).toEqual({
out: {
before: null,
handle: null,
behind: "never called",
behindLarge: "never called",
order: ["before", "handle", "close"],
},
stderr: expect.any(String),
});
expect(exitCode).toBe(0);
},
);

test.concurrent(
"sending a tls.TLSSocket throws ERR_INVALID_HANDLE_TYPE instead of silently dropping the handle",
async () => {
Expand Down
60 changes: 58 additions & 2 deletions test/js/node/child_process/child_process_send_cb.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { expect, test } from "bun:test";
import { bunExe } from "harness";
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, tempDir } from "harness";
import { fork } from "node:child_process";
import { once } from "node:events";
import path from "node:path";
import { text } from "node:stream/consumers";

const ok_repeated = "ok".repeat(16384);

Expand Down Expand Up @@ -50,3 +54,55 @@ test("child_process_send_cb", () => {
EXIT CODE: 0"
`);
});

// Three messages of 1 MiB do not fit in any IPC socket buffer, so they are still queued when the
// channel goes down in the same tick. node v26.3.0 runs every callback, with null, in all of these.
describe.each(["json", "advanced"])("send() callbacks for messages still queued at close (%s)", serialization => {
test.concurrent.each(["disconnect", "kill"])("run before 'close' after subprocess.%s()", async how => {
using dir = tempDir("send-cb-at-close", {
"child.js": `
process.on("message", () => {});
process.on("disconnect", () => process.exit(0));
`,
});
const child = fork(path.join(String(dir), "child.js"), { env: bunEnv, serialization });
try {
const events = [];
child.on("close", () => events.push("close"));
const closed = once(child, "close");
const pad = Buffer.alloc(1 << 20, "d").toString();
for (let i = 0; i < 3; i++) child.send({ i, pad }, err => events.push(`callback ${i}: ${err}`));
if (how === "kill") child.kill("SIGKILL");
else child.disconnect();

await closed;
expect(events).toEqual(["callback 0: null", "callback 1: null", "callback 2: null", "close"]);
} finally {
child.kill("SIGKILL");
}
});

test.concurrent("run before 'exit' after process.disconnect() in the child", async () => {
using dir = tempDir("send-cb-at-close-child", {
"child.js": `
const { writeSync } = require("node:fs");
const pad = Buffer.alloc(1 << 20, "d").toString();
const errors = [];
for (let i = 0; i < 3; i++) process.send({ i, pad }, err => errors.push(err));
process.disconnect();
process.on("exit", () => writeSync(1, JSON.stringify(errors)));
`,
});
const child = fork(path.join(String(dir), "child.js"), {
env: bunEnv,
serialization,
stdio: ["ignore", "pipe", "inherit", "ipc"],
});
try {
const [stdout, [exitCode, signalCode]] = await Promise.all([text(child.stdout), once(child, "close")]);
expect({ stdout, exitCode, signalCode }).toEqual({ stdout: "[null,null,null]", exitCode: 0, signalCode: null });
} finally {
child.kill("SIGKILL");
}
});
});
Loading