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
13 changes: 13 additions & 0 deletions src/js/node/net.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2149,6 +2149,9 @@ Socket.prototype.connect = function connect(...args) {
}

this.connecting = true;
// A live reconnect replaces the native socket, so the undelivered bytes of the old
// connection go away with it, as they do in node.
Comment thread
robobun marked this conversation as resolved.
Resolved
dropOnreadTail(this);
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

const { path } = options;
const pipe = !!path;
Expand Down Expand Up @@ -2186,6 +2189,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 @@ -2325,6 +2329,15 @@ function hasUnflushedWrites(connection) {
return connection.writableLength > 0 || connection[kwriteCallback] != null;
}

// Node keeps the bytes a paused onread socket has not taken in the kernel, so they go away
// with the fd. Bun holds them in kOnreadTail, which must not outlive the connection.
Comment thread
robobun marked this conversation as resolved.
Resolved
function dropOnreadTail(self) {
if (self[kOnreadBuffer] === undefined) return;
self[kOnreadTail] = undefined;
self[kOnreadPendingEnd] = false;
self[kOnreadReadRequested] = false;
Comment thread
robobun marked this conversation as resolved.
Resolved
}

function drainOnreadTail(self, fromRead?) {
if (self[kOnreadTail] === undefined) return false;
if (fromRead) self[kOnreadReadRequested] = true;
Expand Down
52 changes: 52 additions & 0 deletions test/js/node/net/node-net.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2649,6 +2649,58 @@ 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");
});
const calls: [number, string][] = [];
let connection = 1;
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) {
calls.push([connection, buf.toString("latin1", 0, n)]);
if (connection === 1) {
first.resolve();
return false; // leaves "BBBBCCCC" undelivered
}
},
},
});
client.on("error", first.reject);
await first.promise;
client.destroy();
await once(client, "close");

connection = 2;
client.connect({ port, host: "127.0.0.1" });
client.resume();
await once(client, "close");
expect(calls).toEqual([
[1, "AAAA"],
[2, "xxxx"],
[2, "yyyy"],
]);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} 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
63 changes: 63 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,69 @@ 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 calls = [];
let connection = 1;
const first = Promise.withResolvers();
const s = connect({
port,
host: "127.0.0.1",
onread: {
buffer: Buffer.alloc(4),
callback(n, buf) {
calls.push([connection, buf.toString("latin1", 0, n)]);
if (connection === 1) {
first.resolve();
return false;
}
},
},
});
s.on("error", () => {});
await first.promise;
connection = 2;
s.connect({ port, host: "127.0.0.1" });
await once(s, "connect");
s.resume();
await once(s, "close");
srv.close();
console.log(JSON.stringify(calls));
});
`,
],
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([
[1, "AAAA"],
[2, "xxxx"],
[2, "yyyy"],
]),
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