Skip to content
Draft
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
b1c82c3
node:http: count response writes as activity for the socket inactivit…
robobun Sep 21, 2026
70db310
test: a request body chunk after a moved deadline gets a full period
robobun Sep 21, 2026
a6c21b4
node:http: time response writes on the monotonic clock, skip discarde…
robobun Sep 22, 2026
f59ae7e
node:http: record a response write after the native call accepts it
robobun Sep 22, 2026
34d193e
node:http: shorten the comments on the response write timer
robobun Sep 22, 2026
2fb29ab
node:http: one-line comments on the response write timer
robobun Sep 22, 2026
e45cb54
node:http: a response write that only backs up is no socket activity
robobun Sep 22, 2026
f276904
ci: retrigger
robobun Sep 22, 2026
670efcd
test: fail the new timeout tests at once when the connection is lost
robobun Sep 22, 2026
a86db78
Merge branch 'main' into robobun/2e43fdec/http-res-write-socket-timeout
robobun Nov 8, 2026
4a922e7
node:http: refresh the socket inactivity timer in the native write path
robobun Nov 8, 2026
941a2fe
node:http: store what a frozen server socket prints now, fix a lint e…
robobun Nov 8, 2026
b41aca6
node:http: look at the progress of a pending write when the socket in…
robobun Nov 9, 2026
f31f4ac
node:http: say in one line what the lock of the pipelined responses i…
robobun Nov 9, 2026
ed93ca2
node:http: count what a write() sent of a pending write when the sock…
robobun Nov 9, 2026
a79f34f
node:http: let the bytes leave at an even pace in the test of a peer …
robobun Nov 9, 2026
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
57 changes: 57 additions & 0 deletions src/js/node/_http_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1355,6 +1355,18 @@ const kKeepAliveTimeoutSet = Symbol("keepAliveTimeoutSet");
// the socket timer on every response; onSocketTimeoutTimerExpired reads it to
// grant the remaining idle budget when the timer actually fires.
const kKeepAliveIdleStart = Symbol("keepAliveIdleStart");
// When a response last wrote to the connection, on performance.now() (monotonic,
// like the timer). Node.js restarts the socket's inactivity timer on every write
// (net.Socket._writeGeneric and onWriteComplete call _unrefTimer()).
// noteResponseWrite records the write instead, for the same reason as
// kKeepAliveIdleStart, and onSocketTimeoutTimerExpired moves the deadline when
// the timer fires.
// https://github.com/nodejs/node/blob/v26.3.0/lib/net.js#L1019
// https://github.com/nodejs/node/blob/v26.3.0/lib/internal/stream_base_commons.js#L101
Comment thread
robobun marked this conversation as resolved.
Resolved
const kLastResponseWrite = Symbol("lastResponseWrite");
// Set once 'timeout' has been emitted: the timer is spent, and like
// timer.refresh() in Node.js the next response write starts it again.
Comment thread
robobun marked this conversation as resolved.
Resolved
const kSocketTimeoutEmitted = Symbol("socketTimeoutEmitted");
// HTTP/1.1 pipelining (responses queued behind an in-flight response):
// - on the socket: array of queued ServerResponses, in arrival order
// - on a queued response: { ops, bytes, needDrain, ended, isAncient } while it
Expand Down Expand Up @@ -1462,6 +1474,22 @@ function onSocketTimeoutTimerExpired(socket) {
return;
}
}
// A response wrote to the connection inside the window: the inactivity
// period starts at that write. Re-arm this timer and move its start back
// to the write (the deadline is _idleStart + _idleTimeout, like Node.js).
// A new, shorter timer in the slot would make the next _unrefTimer()
// refresh that shorter interval.
Comment thread
robobun marked this conversation as resolved.
Resolved
const lastWrite = socket[kLastResponseWrite];
if (lastWrite !== undefined) {
socket[kLastResponseWrite] = undefined;
const sinceWrite = performance.now() - lastWrite;
const timer = socket[kSocketTimeoutTimer];
if (sinceWrite < socket.timeout && timer !== undefined) {
timer.refresh();
if (sinceWrite > 0) timer._idleStart -= sinceWrite;
return;
}
}
// A fired keep-alive idle timer is dead; drop the reference so the next
// response-finish re-arms via setTimeout instead of trusting a fired
// timer whose _idleTimeout still matches (a 'timeout' listener may keep
Expand Down Expand Up @@ -1506,6 +1534,8 @@ function getNodeHTTPServerSocket() {
[kStreamingEnabled] = false;
[kBoundOnAbort] = null;
[kKeepAliveIdleStart] = undefined;
[kLastResponseWrite]: number | undefined = undefined;
[kSocketTimeoutEmitted] = false;
[kBytesWritten] = 0;
[kHandle];
[kUpgradeIncoming]: import("node:http").IncomingMessage | undefined = undefined;
Expand Down Expand Up @@ -1724,6 +1754,7 @@ function getNodeHTTPServerSocket() {
this._unrefTimer();
return;
}
this[kSocketTimeoutEmitted] = true;
this.emit("timeout");
}
_unrefTimer() {
Expand Down Expand Up @@ -2668,6 +2699,7 @@ function advanceResponsePipeline(server, socket) {
// Buffered 1xx bytes: route through the same AsyncSocket buffer the
// response's own writeHead/end use so they precede the final response.
handle.writeInformational(op[1], op[2]);
noteResponseWrite(res);
if (typeof op[3] === "function") process.nextTick(op[3]);
} else if (kind === "write") {
lastWriteResult = res.write(op[1], op[2], op[3]);
Expand Down Expand Up @@ -3000,6 +3032,20 @@ Object.defineProperty(ServerResponse.prototype, "headersSent", {
},
});

// A response write is activity on the connection's inactivity timeout
// (socket.setTimeout / server.timeout), see kLastResponseWrite. Callers run
// it after the native write: a write that throws is no activity, as in Node.js.
Comment thread
robobun marked this conversation as resolved.
Resolved
function noteResponseWrite(res) {
const socket = res[kSocket];
if (socket == null || !socket.timeout) return;
if (socket[kSocketTimeoutEmitted]) {
socket[kSocketTimeoutEmitted] = false;
socket._unrefTimer();
} else {
socket[kLastResponseWrite] = performance.now();
Comment thread
robobun marked this conversation as resolved.
Resolved
}
}

ServerResponse.prototype._writeRaw = function (chunk, encoding, callback) {
if (!this[kHandle]) {
// Standalone path: OutgoingMessage._writeRaw buffers to outputData while
Expand All @@ -3025,6 +3071,7 @@ ServerResponse.prototype._writeRaw = function (chunk, encoding, callback) {
// writeHead/end) so 1xx lines share ordering with the final response bytes;
// socket.write() would land in the socket handle's separate stream buffer.
this[kHandle].writeInformational(chunk, encoding);
noteResponseWrite(this);
if (typeof callback === "function") process.nextTick(callback);
return true;
};
Expand Down Expand Up @@ -3127,6 +3174,7 @@ ServerResponse.prototype.writeContinue = function (cb) {
const native = this.socket?.[kHandle]?.response;
if (native) native.writeContinue();
else this[kHandle]?.writeContinue?.();
noteResponseWrite(this);
this._sent100 = true;
cb?.();
};
Expand Down Expand Up @@ -3270,6 +3318,7 @@ ServerResponse.prototype.end = function (chunk, encoding, callback) {
handle.end(chunk, encoding, undefined, strictContentLength(this));
}
}
noteResponseWrite(this);
this._header = " ";
const req = this.req;
if (!req._consuming && !req?._readableState?.resumeScheduled) {
Expand Down Expand Up @@ -3419,6 +3468,11 @@ ServerResponse.prototype.write = function (chunk, encoding, callback) {
result = handle.write(chunk, encoding, allowWritesToContinue.bind(this), strictContentLength(this));
}

// Node's write_() drops a write to a response without a body (HEAD, 204, 304)
// before it reaches the socket, so it is no activity.
// https://github.com/nodejs/node/blob/v26.3.0/lib/_http_outgoing.js#L983
Comment thread
robobun marked this conversation as resolved.
Resolved
if (this._hasBody) noteResponseWrite(this);

if (result < 0) {
if (callback) {
// The write was buffered due to backpressure.
Expand Down Expand Up @@ -3599,6 +3653,7 @@ ServerResponse.prototype._send = function (data, encoding, callback, _byteLength
} else {
handle.write(data, encoding, callback, strictContentLength(this));
}
noteResponseWrite(this);
};

const kSnapshotStatusCode = Symbol("kSnapshotStatusCode");
Expand Down Expand Up @@ -3726,6 +3781,7 @@ ServerResponse.prototype.flushHeaders = function () {
}
}
handle.flushHeaders();
noteResponseWrite(this);
} else {
// Standalone path: _storeHeader rendered this._header; _send('') pushes
// it to the assigned socket like OutgoingMessage.flushHeaders does.
Expand Down Expand Up @@ -3787,6 +3843,7 @@ function callWriteHeadIfObservable(self, headerState, fromEnd?) {
}

function allowWritesToContinue() {
noteResponseWrite(this);
this._callPendingCallbacks();
this.emit("drain");
}
Expand Down
244 changes: 244 additions & 0 deletions test/js/node/http/node-http-server-timeouts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -423,3 +423,247 @@ describe("node:http server timeout enforcement", () => {
}
});
});

// A write on the response is activity on the connection, like a read: Node's
// net.Socket restarts its inactivity timer in _writeGeneric. Each probe holds
// one request open on a raw TCP socket. The timing checks are one-sided
// ('timeout' must not come sooner than a full period after the activity) or
// compare against a reference timer. Timers fire in deadline order, so a slow
// machine cannot swap the socket's timer and the reference.
describe("node:http response writes restart the socket inactivity timeout", () => {
const TIMEOUT = 400;
// The timer clock counts whole milliseconds. A server that ignores the
// activity fires TIMEOUT / 2 early, far outside this.
const SLACK = 50;

async function send(port: number, request: string, onClose?: (received: string) => void) {
const client = net.connect(port, "127.0.0.1");
let received = "";
client.on("data", chunk => (received += chunk.toString("latin1")));
client.on("error", () => {});
client.on("close", () => onClose?.(received));
await once(client, "connect");
client.write(request);
return client;
}
const GET = "GET / HTTP/1.1\r\nHost: a\r\n\r\n";

test.concurrent.each(["server.timeout", "res.setTimeout()", "req.setTimeout()", "socket.setTimeout()"])(
"%s does not fire while the response keeps writing",
async armedBy => {
const events: string[] = [];
const server = http.createServer((req, res) => {
if (armedBy === "res.setTimeout()") res.setTimeout(TIMEOUT);
if (armedBy === "req.setTimeout()") req.setTimeout(TIMEOUT);
if (armedBy === "socket.setTimeout()") req.socket.setTimeout(TIMEOUT);
Comment thread
robobun marked this conversation as resolved.
Resolved
req.socket.on("timeout", () => events.push("timeout"));
res.writeHead(200, { "Content-Type": "text/plain" });
// Stream for longer than the timeout, one chunk every TIMEOUT / 8.
const startedAt = performance.now();
const interval = setInterval(() => {
if (performance.now() - startedAt < TIMEOUT * 1.5) {
res.write("chunk\n");
return;
}
clearInterval(interval);
events.push("end");
res.end("done\n");
}, TIMEOUT / 8);
res.on("close", () => clearInterval(interval));
});
if (armedBy === "server.timeout") server.timeout = TIMEOUT;
// The idle connection is closed one more period after the response.
server.keepAliveTimeout = TIMEOUT;
server.keepAliveTimeoutBuffer = 0;
const port = await listen(server);
let client: net.Socket | undefined;
try {
const { promise: closed, resolve: onClosed } = Promise.withResolvers<string>();
client = await send(port, GET, onClosed);
const received = await closed;
expect({ events, complete: received.endsWith("done\n\r\n0\r\n\r\n") }).toEqual({
events: ["end", "timeout"],
complete: true,
});
} finally {
client?.destroy();
server.closeAllConnections();
server.close();
}
},
);

const activities: Record<string, (res: http.ServerResponse) => void> = {
"res.write()": res => res.write("chunk\n"),
"res.end()": res => res.end("done\n"),
"res.flushHeaders()": res => res.flushHeaders(),
"res.writeProcessing()": res => res.writeProcessing(),
"res.writeContinue()": res => res.writeContinue(),
};

test.concurrent.each(Object.keys(activities))("the inactivity period restarts at %s", async name => {
let activityAt = 0;
let reference: ReturnType<typeof setTimeout> | undefined;
let referenceFired = false;
const { promise: timedOut, resolve: onTimedOut } = Promise.withResolvers<number>();
const server = http.createServer((req, res) => {
setTimeout(() => {
// After the exact deadline (the activity plus TIMEOUT) and before the deadline of
// a timer that only starts over when it fires (the activity plus 1.5 * TIMEOUT).
reference = setTimeout(() => (referenceFired = true), TIMEOUT * 1.25);
activityAt = performance.now();
activities[name](res);
}, TIMEOUT / 2);
});
server.timeout = TIMEOUT;
// No keep-alive timeout: server.timeout stays armed after res.end().
server.keepAliveTimeout = 0;
server.on("timeout", socket => {
// Only on a machine that stalls past the timeout before the activity runs. The
// activity then starts the timer again, and the next 'timeout' is the one measured.
if (activityAt === 0) return;
onTimedOut(performance.now());
socket.destroy();
});
const port = await listen(server);
let client: net.Socket | undefined;
try {
client = await send(port, GET);
const quietFor = (await timedOut) - activityAt;
expect(quietFor).toBeGreaterThanOrEqual(TIMEOUT - SLACK);
expect(referenceFired).toBe(false);
} finally {
clearTimeout(reference);
client?.destroy();
server.closeAllConnections();
server.close();
}
});

test.concurrent("a write after a 'timeout' that kept the socket open starts the timer again", async () => {
const events: string[] = [];
let writeAt = 0;
const { promise: timedOutAgain, resolve: onTimedOutAgain } = Promise.withResolvers<number>();
let response: http.ServerResponse | undefined;
const server = http.createServer((req, res) => {
response = res;
res.writeHead(200, { "Content-Type": "text/plain" });
});
server.timeout = TIMEOUT;
server.on("timeout", () => {
events.push("timeout");
if (writeAt !== 0) return onTimedOutAgain(performance.now());
// A listener keeps the socket open. Nothing reads or writes until this write.
setTimeout(() => {
events.push("write");
writeAt = performance.now();
response!.write("late\n");
}, TIMEOUT / 4);
});
const port = await listen(server);
let client: net.Socket | undefined;
try {
client = await send(port, GET);
const quietFor = (await timedOutAgain) - writeAt;
expect(events).toEqual(["timeout", "write", "timeout"]);
expect(quietFor).toBeGreaterThanOrEqual(TIMEOUT - SLACK);
} finally {
client?.destroy();
server.closeAllConnections();
server.close();
}
});

// Writes that never reach the socket in Node: write_() drops a write to a response without
// a body, and it validates before it sends anything. A server that ignores every write
// passes these too. They guard against counting such a write as activity, which keeps the
// connection of a handler that writes forever open.
const noActivity: Record<string, { request: string; setup: (res: http.ServerResponse) => void }> = {
"a write that a HEAD response discards": {
request: "HEAD / HTTP/1.1\r\nHost: a\r\n\r\n",
setup: res => res.writeHead(200, { "Content-Type": "text/event-stream" }),
},
"a write that throws": {
request: GET,
// The implicit header is invalid, so every write throws before it sends anything.
setup: res => (res.statusCode = 1000),
},
};

test.concurrent.each(Object.keys(noActivity))("%s does not restart the timer", async name => {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let reference: ReturnType<typeof setTimeout> | undefined;
const { promise: settled, resolve: onSettled } = Promise.withResolvers<string>();
const server = http.createServer((req, res) => {
noActivity[name].setup(res);
const interval = setInterval(() => {
try {
res.write("data: ping\n\n");
} catch {}
}, TIMEOUT / 8);
res.on("close", () => clearInterval(interval));
// Long after the 'timeout' of a connection without activity.
reference = setTimeout(() => onSettled("the reference timer"), TIMEOUT * 2.5);
});
server.timeout = TIMEOUT;
server.on("timeout", socket => {
onSettled("'timeout'");
socket.destroy();
});
const port = await listen(server);
let client: net.Socket | undefined;
try {
client = await send(port, noActivity[name].request);
expect(await settled).toBe("'timeout'");
} finally {
clearTimeout(reference);
client?.destroy();
server.closeAllConnections();
server.close();
}
});

test.concurrent("a request body chunk after a write moved the deadline gets a full period", async () => {
// The write at 0.6 * TIMEOUT moves the deadline from TIMEOUT to 1.6 * TIMEOUT, and the
// body chunk arrives between the two. This guards how the deadline moves, not the bug.
// A server that ignores writes passes too: the 'timeout' at TIMEOUT is swallowed below
// and the chunk restarts the spent timer. It fails when the expiry puts a new, shorter
// timer in the slot, because the chunk then refreshes only 0.6 * TIMEOUT.
let chunkSentAt = 0;
let chunkReceived = false;
const { promise: timedOut, resolve: onTimedOut } = Promise.withResolvers<number>();
const { promise: wrote, resolve: onWrote } = Promise.withResolvers<void>();
const server = http.createServer((req, res) => {
req.on("data", chunk => {
if (chunk.toString("latin1") === "late") chunkReceived = true;
});
setTimeout(() => {
res.write("chunk\n");
onWrote();
}, TIMEOUT * 0.6);
});
server.timeout = TIMEOUT;
server.on("timeout", socket => {
// Before the chunk: a server that ignores writes, or a machine that stalls until the
// moved deadline has passed. The chunk then starts the timer again.
if (!chunkReceived) return;
onTimedOut(performance.now());
socket.destroy();
});
const port = await listen(server);
let client: net.Socket | undefined;
try {
client = await send(port, "POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 100\r\n\r\nearly");
await wrote;
setTimeout(() => {
chunkSentAt = performance.now();
client!.write("late");
}, TIMEOUT * 0.7);
const quietFor = (await timedOut) - chunkSentAt;
expect(quietFor).toBeGreaterThanOrEqual(TIMEOUT - SLACK);
} finally {
client?.destroy();
server.closeAllConnections();
server.close();
}
});
});
Loading