Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
20 changes: 10 additions & 10 deletions src/js/node/net.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ const kOnreadPendingEnd = Symbol("kOnreadPendingEnd");
const kOnreadReadRequested = Symbol("kOnreadReadRequested");
const kOnreadEmptyTail = Buffer.alloc(0);
const kwriteCallback = Symbol("writeCallback");
const kLastWriteQueueSize = Symbol("lastWriteQueueSize");
const kSocketClass = Symbol("kSocketClass");

// A completed write whose status is a negative errno: Node hands it to the write
Expand Down Expand Up @@ -1603,6 +1604,7 @@ function Socket(options?) {
// node initializes the timer slot to null so it is observable before setTimeout() is called.
// https://github.com/nodejs/node/blob/v26.3.0/lib/net.js#L401
this[kTimeout] = null;
this[kLastWriteQueueSize] = 0;
this[kwriteCallback] = undefined;
this._pendingData = undefined;
this._pendingEncoding = undefined; // for compatibility
Expand Down Expand Up @@ -1801,17 +1803,14 @@ Socket.prototype.address = function address() {
};

Socket.prototype._onTimeout = function () {
// if there is pending data, write is in progress
// so we suppress the timeout
if (this._pendingData) {
return;
}

const handle = this._handle;
// if there is a handle, and it has pending data,
// we suppress the timeout because a write is in progress
if (handle && getBufferedAmount(handle) > 0) {
return;
if (this[kwriteCallback] && handle) {
const writeQueueSize = getBufferedAmount(handle);
if (this[kLastWriteQueueSize] !== writeQueueSize) {
this[kLastWriteQueueSize] = writeQueueSize;
this._unrefTimer();
return;
}
}
this.emit("timeout");
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -2824,6 +2823,7 @@ Socket.prototype._write = function _write(chunk, encoding, callback) {
callback(new Error("overlapping _write()"));
} else {
this[kwriteCallback] = callback;
this[kLastWriteQueueSize] = getBufferedAmount(socket);
Comment thread
robobun marked this conversation as resolved.
Resolved
// A pending write holds the loop even on a handle whose FIN/pause dropped
// its hold (libuv: the uv_write_t is active); unrefAfterDrain lets go again.
if ((this[kended] || this[kPausedUnref]) && !this[kUserUnrefed]) socket.ref?.();
Expand Down
129 changes: 128 additions & 1 deletion test/js/node/http/client-timeout-error.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { describe, expect, it } from "bun:test";
import { isWindows } from "harness";
import { once } from "node:events";
import { createServer, request } from "node:http";
import { createServer, get, request } from "node:http";
import net from "node:net";

describe("node:http client timeout", () => {
it("should emit timeout event when timeout is reached", async () => {
Expand Down Expand Up @@ -90,4 +92,129 @@ describe("node:http client timeout", () => {
server.close();
}
});

// The socket stays in the `connecting` state while the lookup callback is
// withheld, which is observationally equivalent to a SYN that is never
// acknowledged. Node.js arms the idle timer at socket creation, so the
// 'timeout' event fires mid-connect; it must not be swallowed just because
// the request headers are queued in _pendingData waiting for the handle.
describe("fires while the socket is still connecting", () => {
type Finish = (err: NodeJS.ErrnoException | null, address: string, family: number) => void;

function stallingLookup(deferred: { finish?: Finish }) {
return function lookup(_hostname: string, opts: unknown, cb?: Finish) {
deferred.finish = typeof opts === "function" ? (opts as Finish) : cb!;
};
}

it("options.timeout emits req 'timeout' before connect", async () => {
const deferred: { finish?: Finish } = {};
const req = get({
host: "stalled.invalid",
port: 1,
path: "/",
timeout: 100,
agent: false,
autoSelectFamily: false,
lookup: stallingLookup(deferred),
});
req.on("error", () => {});
try {
await once(req, "timeout");
expect(req.socket?.connecting).toBe(true);
} finally {
req.destroy();
deferred.finish?.(new Error("aborted"), "", 0);
}
});

it("socket.setTimeout() emits socket 'timeout' before connect", async () => {
const deferred: { finish?: Finish } = {};
const req = get({
host: "stalled.invalid",
port: 1,
path: "/",
agent: false,
autoSelectFamily: false,
lookup: stallingLookup(deferred),
});
req.on("error", () => {});
const [socket] = await once(req, "socket");
socket.setTimeout(100);
try {
await once(socket, "timeout");
expect(socket.connecting).toBe(true);
} finally {
req.destroy();
deferred.finish?.(new Error("aborted"), "", 0);
}
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

it("net.Socket 'timeout' fires with a write buffered pre-connect", async () => {
const deferred: { finish?: Finish } = {};
const socket = net.connect({
host: "stalled.invalid",
port: 1,
autoSelectFamily: false,
lookup: stallingLookup(deferred),
});
socket.on("error", () => {});
socket.write("GET / HTTP/1.1\r\n\r\n");
socket.setTimeout(100);
try {
await once(socket, "timeout");
expect(socket.connecting).toBe(true);
} finally {
socket.destroy();
deferred.finish?.(new Error("aborted"), "", 0);
}
});
});

// A connected peer that has stopped reading: the kernel send and receive
// buffers fill, the rest of the write sits in the handle's native queue, and
// getBufferedAmount() stays nonzero. Node's _onTimeout heuristic suppresses
// 'timeout' only while that queue is still *draining* (writeQueueSize moved
// since the last check), re-arming each time; once it stalls it emits. The
// old `if (getBufferedAmount(handle) > 0) return` dropped the one-shot timer
// with no re-arm, so 'timeout' was lost for good.
//
// One 64 MiB chunk is far above any POSIX loopback socket-buffer capacity
// (Linux defaults cap at 4 MiB send + 6 MiB receive), so the native queue
// can never drain. A smaller write can fit in the kernel outright, and then
// the old guard never triggers. Windows is skipped: winsock takes the whole
// non-blocking send() into the kernel (all 64 MiB on loopback in CI), so the
// write never goes async and the queue under test is never populated.
it.skipIf(isWindows)(
"net.Socket 'timeout' fires when a connected write is stalled by a non-reading peer",
async () => {
const accepted: net.Socket[] = [];
const server = net.createServer(s => {
accepted.push(s);
s.on("error", () => {});
s.pause();
});
server.listen(0, "127.0.0.1");
await once(server, "listening");
const { port } = server.address() as net.AddressInfo;

const socket = net.connect({ host: "127.0.0.1", port });
socket.on("error", () => {});
try {
await once(socket, "connect");
let writeComplete = false;
expect(socket.write(Buffer.alloc(64 << 20), () => (writeComplete = true))).toBe(false);
expect(socket.writableLength).toBeGreaterThan(0);

socket.setTimeout(200);
await once(socket, "timeout");
Comment thread
robobun marked this conversation as resolved.
Resolved
expect(writeComplete).toBe(false);
expect(socket.connecting).toBe(false);
} finally {
socket.destroy();
for (const s of accepted) s.destroy();
server.close();
}
},
);
});