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
39 changes: 19 additions & 20 deletions src/js/internal/cluster/primary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,21 @@
send(worker, { ack: message.seq });
}

// RoundRobinHandle: the primary accepts and hands each connection to a worker. SharedHandle: every
// worker accepts on its own copy of one socket. UDP has no connections to hand out, and a TLS
// server accepts natively, so both always share.
//
// On Windows a TCP listener is served by the primary even under SCHED_NONE. When two workers poll
// copies of one listening socket, the worker that loses the race for a connection blocks inside
// accept() (the copy is non-blocking, Winsock waits anyway) and its event loop stops, and libuv's
// exclusive AFD polls on the same socket from two processes cancel each other in a loop. Node shares
// listeners there through AcceptEx, which Bun's listen sockets do not use.
Comment thread
robobun marked this conversation as resolved.
Resolved
function usesRoundRobinHandle(message) {
if (message.sharedOnly === true || message.addressType === "udp4" || message.addressType === "udp6") return false;
if (schedulingPolicy === SCHED_RR) return true;
return process.platform === "win32" && (message.addressType === 4 || message.addressType === 6);
}

function queryServer(worker, message) {
// Stop processing if worker already disconnecting
if (worker.exitedAfterDisconnect) return;
Expand All @@ -237,15 +252,7 @@
send(worker, { errno: UV_EINVAL, key, ack: message.seq, data: handle.data, bunHint: kSharedOnlyHint }, null);
return;
}
if (
schedulingPolicy === SCHED_RR &&
handle !== undefined &&
message.sharedOnly !== true &&
handle instanceof SharedHandle &&
handle.sharedOnly &&
message.addressType !== "udp4" &&
message.addressType !== "udp6"
) {
if (handle instanceof SharedHandle && handle.sharedOnly && usesRoundRobinHandle(message)) {

Check warning on line 255 in src/js/internal/cluster/primary.ts

View check run for this annotation

Claude / Claude Code Review

kSharedOnlyHint says 'under SCHED_RR' but now fires under SCHED_NONE on Windows

`kSharedOnlyHint` reads "…cannot share the same address:port **under SCHED_RR**…", but this guard now uses `usesRoundRobinHandle(message)`, which on Windows returns true for TCP even when `schedulingPolicy === SCHED_NONE` — so a Windows user who set `NODE_CLUSTER_SCHED_POLICY=none` gets a hint naming the opposite policy (the new SCHED_NONE test in this PR exercises exactly that path). Consider dropping "under SCHED_RR" or rewording to e.g. "when the primary distributes connections".
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
send(worker, { errno: UV_EINVAL, key, ack: message.seq, data: handle.data, bunHint: kSharedOnlyHint }, null);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return;
}
Expand All @@ -260,25 +267,17 @@
if (message.address.length < address.length) address = message.address;
}

// UDP is exempt from round-robin connection balancing for what should
// be obvious reasons: it's connectionless. There is nothing to send to
// the workers except raw datagrams and that's pointless.
if (process.platform === "win32" && (message.addressType === "udp4" || message.addressType === "udp6")) {
const error = new Error(`write ENOTSUP - cannot share a dgram socket with a worker on Windows`);
error.code = "ENOTSUP";
error.syscall = "write";
worker.emit("error", error);
return;
}
if (
schedulingPolicy !== SCHED_RR ||
message.sharedOnly === true ||
message.addressType === "udp4" ||
message.addressType === "udp6"
) {
handle = new SharedHandle(key, address, message);
} else {
if (usesRoundRobinHandle(message)) {
handle = new RoundRobinHandle(key, address, message);
} else {
handle = new SharedHandle(key, address, message);
}

if (!cachedHandle) handles.set(key, handle);
Expand Down
136 changes: 127 additions & 9 deletions test/js/node/cluster.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,102 @@ if (cluster.isPrimary) {
expect(stdout).toContain("listening workers: 2 distinct ports: 1");
});

// Two workers accepting on copies of one Windows listening socket race each other for every
// connection, and the loser blocks inside accept(): its event loop never runs again, so it stops
// answering IPC and never exits. Each connection below is one such race; the primary pings both
// workers after every one. TCP listens under SCHED_NONE are served by the primary on Windows instead.
test.skipIf(!isWindows)(
"SCHED_NONE: two workers sharing one port keep answering IPC while connections arrive, then exit",
async () => {
using dir = tempDir("cluster-shared-accept-race", {
"main.ts": `
const cluster = require("node:cluster");
const net = require("node:net");
cluster.schedulingPolicy = cluster.SCHED_NONE;

if (cluster.isPrimary) {
const CONNECTIONS = 100;
const workers = [cluster.fork(), cluster.fork()];
const ports = new Set();
const exits = [];
let listening = 0;

function fail(message) {
console.log(message);
for (const worker of workers) worker.process.kill();
process.exit(1);
}

cluster.on("listening", (worker, address) => {
ports.add(address.port);
if (++listening !== workers.length) return;
run(address.port).catch(err => fail("error: " + err.message));
});

cluster.on("exit", (worker, code, signal) => {
exits.push(code ?? signal);
if (exits.length === workers.length) console.log("exits:", exits.join(","));
});

function connectOnce(port) {
return new Promise((resolve, reject) => {
const c = net.connect(port, "127.0.0.1");
let data = "";
c.setEncoding("utf8");
c.on("data", chunk => (data += chunk));
c.on("error", reject);
c.on("close", () => (data === "hi" ? resolve() : reject(new Error("got " + JSON.stringify(data)))));
});
}

function pingWorkers(connection) {
return Promise.all(
workers.map(worker => {
return new Promise(resolve => {
const stuck = setTimeout(() => fail("worker " + worker.id + " stopped answering after connection " + connection), 10_000);
worker.once("message", () => {
clearTimeout(stuck);
resolve();
});
worker.send("ping");
});
}),
);
}

async function run(port) {
for (let connection = 1; connection <= CONNECTIONS; connection++) {
await connectOnce(port);
await pingWorkers(connection);
}
console.log("served:", CONNECTIONS, "ports:", ports.size);
for (const worker of workers) worker.disconnect();
}
} else {
net.createServer(socket => socket.end("hi")).listen(0, "127.0.0.1");
process.on("message", message => {
if (message === "ping") process.send("pong");
});
}
`,
});
await using proc = Bun.spawn({
cmd: [bunExe(), "main.ts"],
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({ stdout, stderr, exitCode }).toEqual({
stdout: "served: 100 ports: 1\nexits: 0,0\n",
stderr: expect.any(String),
exitCode: 0,
});
},
30_000,
);

test("SCHED_NONE: close() releases the shared handle so the worker can re-listen on the same port", async () => {
using dir = tempDir("cluster-shared-relisten", {
"main.ts": `
Expand Down Expand Up @@ -807,11 +903,10 @@ if (cluster.isPrimary) {
expect(stdout).toContain("reply: echo:hi");
}, 30_000);

test("plain worker listening on a key already owned by a TLS shared-only handle fails with EINVAL", async () => {
const dir = tempDirWithFiles("bun-test", {
"cert.pem": tlsCerts.cert,
"key.pem": tlsCerts.key,
"main.ts": `
const netWorkerAfterTlsWorkerFixture = {
"cert.pem": tlsCerts.cert,
"key.pem": tlsCerts.key,
"main.ts": `
const cluster = require("node:cluster");
const net = require("node:net");
const tls = require("node:tls");
Expand All @@ -824,11 +919,18 @@ if (cluster.isPrimary) {
const tlsWorker = cluster.fork({ ROLE: "tls" });
cluster.once("listening", () => {
const netWorker = cluster.fork({ ROLE: "net" });
netWorker.on("message", msg => {
console.log("net listen error code:", msg.code, msg.msg);
const done = code => {
tlsWorker.kill();
netWorker.kill();
process.exit(0);
process.exit(code);
};
netWorker.on("message", msg => {
console.log("net listen error code:", msg.code, msg.msg);
done(0);
});
netWorker.on("listening", () => {
console.log("net worker is listening on the TLS worker's socket");
done(1);
});
});
} else if (process.env.ROLE === "tls") {
Expand All @@ -839,12 +941,28 @@ if (cluster.isPrimary) {
server.listen(0);
}
`,
});
};

test("plain worker listening on a key already owned by a TLS shared-only handle fails with EINVAL", async () => {
const dir = tempDirWithFiles("bun-test", netWorkerAfterTlsWorkerFixture);
const { stdout } = await bunRun(joinP(dir, "main.ts"), bunEnv);
expect(stdout).toContain("net listen error code: EINVAL");
expect(stdout).toContain("TLS and non-TLS cluster workers cannot share");
}, 30_000);

// On Windows the primary serves TCP listens under SCHED_NONE too (two workers accepting on copies of
// one socket is what hangs a worker there), so the plain worker is refused under either policy.
test.skipIf(!isWindows)(
"SCHED_NONE on Windows: plain worker listening on a key owned by a TLS shared-only handle fails with EINVAL",
async () => {
const dir = tempDirWithFiles("bun-test", netWorkerAfterTlsWorkerFixture);
const { stdout } = await bunRun(joinP(dir, "main.ts"), { NODE_CLUSTER_SCHED_POLICY: "none" });
expect(stdout).toContain("net listen error code: EINVAL");
expect(stdout).toContain("TLS and non-TLS cluster workers cannot share");
},
30_000,
);

test.skipIf(isWindows)(
"SCHED_NONE listen({fd:2}) fails EINVAL like node and does not close the primary's stderr",
async () => {
Expand Down