Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 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
9 changes: 9 additions & 0 deletions src/js/node/net.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2094,6 +2094,7 @@ Socket.prototype[kCloseRawConnection] = function () {

Socket.prototype.connect = function connect(...args) {
$debug("Socket.prototype.connect");
dropOnreadTail(this);
{
const [options, connectListener] =
$isArray(args[0]) && args[0][normalizedArgsSymbol] ? args[0] : normalizeArgs(args);
Expand Down Expand Up @@ -2369,6 +2370,7 @@ Socket.prototype._destroy = function _destroy(err, callback) {
$debug("Socket.prototype._destroy");

this.connecting = false;
dropOnreadTail(this);
// Tear down a wrapped generic duplex with this socket: the native handle's
// close only flushes close_notify and lets the wrapper drain; without an
// explicit destroy here a late RST on the underlying transport can surface
Expand Down Expand Up @@ -2510,6 +2512,13 @@ function hasUnflushedWrites(connection) {
return connection.writableLength > 0 || connection[kwriteCallback] != null;
}

// The undelivered bytes of a read belong to the connection, as kernel-buffered bytes do in node.
function dropOnreadTail(self) {
if (self[kOnreadBuffer] === undefined) return;
self[kOnreadTail] = undefined;
self[kOnreadPendingEnd] = false;
}

function drainOnreadTail(self, fromRead?) {
if (self[kOnreadTail] === undefined) return false;
if (fromRead) self[kOnreadReadRequested] = true;
Expand Down
122 changes: 122 additions & 0 deletions test/js/node/net/node-net.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2680,6 +2680,128 @@ it("onread: read() redelivers the declined tail without resume()", async () => {
}
});

it("onread: a destroyed socket that connects again does not replay the declined tail", async () => {
// Node keeps the bytes a false return left behind in the kernel, so they go
// away with the fd. The second connection must only see its own bytes.
let connections = 0;
const server = createServer(c => {
c.on("error", () => {});
c.end(++connections === 1 ? "AAAABBBBCCCC" : "xxxxyyyy");
});
// Bytes per connection. The first callback returns false, so connection 1
// gets exactly one slice and the rest of its read stays undelivered.
const received = ["", ""];
let connection = 0;
const first = Promise.withResolvers<void>();
let client: Socket | undefined;
try {
const listening = Promise.withResolvers<void>();
server.once("error", listening.reject);
server.listen(0, "127.0.0.1", () => listening.resolve());
await listening.promise;
const port = (server.address() as import("node:net").AddressInfo).port;
client = createConnection({
port,
host: "127.0.0.1",
onread: {
buffer: Buffer.alloc(4),
callback(n: number, buf: Buffer) {
received[connection] += buf.toString("latin1", 0, n);
if (connection === 0) {
first.resolve();
return false;
}
},
},
});
client.on("error", first.reject);
await first.promise;
client.destroy();
await once(client, "close");

connection = 1;
client.connect({ port, host: "127.0.0.1" });
client.resume();
await once(client, "close");
expect(received[0].length).toBeLessThanOrEqual(4);
expect("AAAABBBBCCCC".startsWith(received[0])).toBe(true);
expect(received[1]).toBe("xxxxyyyy");
} finally {
client?.destroy();
server.close();
}
});

it("onread: a peer reset that lands on the declined tail does not end the next connection early", async () => {
// A native close with a tail still undelivered defers the 'end' until the
// tail drains. That deferred end belongs to the closed connection: after
// destroy() and connect(), the next tail drain must not emit it.
let connections = 0;
const serverSockets: Socket[] = [];
const server = createServer(c => {
serverSockets.push(c);
c.on("error", () => {});
if (++connections === 1) {
c.write("AAAABBBBCCCC");
} else {
c.write("xxxxyyyy");
c.on("data", () => c.end());
}
});
const events: string[] = [];
let delivered = Promise.withResolvers<void>();
let client: Socket | undefined;
try {
const listening = Promise.withResolvers<void>();
server.once("error", listening.reject);
server.listen(0, "127.0.0.1", () => listening.resolve());
await listening.promise;
const port = (server.address() as import("node:net").AddressInfo).port;
client = createConnection({
port,
host: "127.0.0.1",
onread: {
buffer: Buffer.alloc(4),
callback(n: number, buf: Buffer) {
const slice = buf.toString("latin1", 0, n);
events.push(slice);
if (slice === "AAAA" || slice === "xxxx") {
delivered.resolve();
return false;
}
if (slice === "yyyy") delivered.resolve();
},
},
});
client.on("end", () => events.push("end"));
client.on("close", () => events.push("close"));
await delivered.promise;
// No 'error' listener: the reset reaches the client as a plain close while
// "BBBBCCCC" is still undelivered, which parks the end behind the tail.
serverSockets[0].resetAndDestroy();
await once(serverSockets[0], "close");
for (let i = 0; i < 10; i++) await new Promise(resolve => setImmediate(resolve));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
events.push("destroy");
client.destroy();
await once(client, "close");

delivered = Promise.withResolvers<void>();
client.connect({ port, host: "127.0.0.1" });
await delivered.promise; // "xxxx" taken, "yyyy" left as the tail
delivered = Promise.withResolvers<void>();
client.resume();
await delivered.promise; // the tail drained
for (let i = 0; i < 10; i++) await new Promise(resolve => setImmediate(resolve));
events.push("write");
client.write("go");
await once(client, "close");
expect(events).toEqual(["AAAA", "destroy", "close", "xxxx", "yyyy", "write", "end", "close"]);
} finally {
client?.destroy();
server.close();
}
});

it("onread: a buffer factory that never yields a Uint8Array hands the callback `true`", async () => {
// Node leaves kBuffer as the literal `true` and passes it through:
// https://github.com/nodejs/node/blob/v26.3.0/lib/net.js#L332-L342
Expand Down
59 changes: 59 additions & 0 deletions test/js/node/net/socket-reconnect-live.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,65 @@ describe.concurrent("socket.connect() on an already-connected socket", () => {
});
});

it("does not replay the declined onread tail of the previous connection", async () => {
// The first connection's callback takes one 4-byte slice and returns false. The
// rest of that read belongs to the connection that connect() replaces, so the
// second connection must only see its own bytes.
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`
const { createServer, connect } = require("node:net");
const { once } = require("node:events");
let connections = 0;
const srv = createServer(c => {
c.on("error", () => {});
c.end(++connections === 1 ? "AAAABBBBCCCC" : "xxxxyyyy");
});
srv.listen(0, "127.0.0.1", async () => {
const port = srv.address().port;
const received = ["", ""];
let connection = 0;
const first = Promise.withResolvers();
const s = connect({
port,
host: "127.0.0.1",
onread: {
buffer: Buffer.alloc(4),
callback(n, buf) {
received[connection] += buf.toString("latin1", 0, n);
if (connection === 0) {
first.resolve();
return false;
}
},
},
});
s.on("error", () => {});
await first.promise;
connection = 1;
s.connect({ port, host: "127.0.0.1" });
await once(s, "connect");
s.resume();
await once(s, "close");
srv.close();
console.log(JSON.stringify({ firstIsPrefix: "AAAABBBBCCCC".startsWith(received[0]) && received[0].length <= 4, second: received[1] }));
});
`,
],
env: bunEnv,
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({ firstIsPrefix: true, second: "xxxxyyyy" }),
stderr,
exitCode: 0,
});
});

it("does not crash when reconnecting while the first connect is still in flight", async () => {
await using proc = Bun.spawn({
cmd: [
Expand Down
Loading