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
5 changes: 0 additions & 5 deletions src/js/internal/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@
setRequestTimeout,
headersTuple,
webRequestOrResponseHasBodyValue,
setServerCustomOptions,
getCompleteWebRequestOrResponseBodyValueAsArrayBuffer,
drainMicrotasks,
setServerIdleTimeout,
} = $cpp("NodeHTTP.cpp", "createNodeHTTPInternalBinding") as {

Check warning on line 14 in src/js/internal/http.ts

View check run for this annotation

Claude / Claude Code Review

Orphaned native binding setServerIdleTimeout not removed

Removing the JS import/export of `setServerIdleTimeout` orphans its native binding: `jsHTTPSetServerIdleTimeout` is still defined at `src/jsc/bindings/NodeHTTP.cpp:996` and registered via `putDirect` at :1188-1189, with no remaining JS consumer. Per the repo's "delete dead code in the same PR that makes it dead" rule, the C++ function and its `putDirect` entry should be removed here as well.
Comment thread
robobun marked this conversation as resolved.
Resolved
getHeader: (headers: Headers, name: string) => string | undefined;
setHeader: (headers: Headers, name: string, value: string) => void;
Headers: (typeof globalThis)["Headers"];
Expand All @@ -29,7 +28,6 @@
) => void;
getCompleteWebRequestOrResponseBodyValueAsArrayBuffer: (arg: any) => ArrayBuffer | undefined;
drainMicrotasks: () => void;
setServerIdleTimeout: (server: any, timeout: number) => void;
};

const getRawKeys = $newCppFunction("JSFetchHeaders.cpp", "jsFetchHeaders_getRawKeys", 0);
Expand Down Expand Up @@ -88,7 +86,6 @@
const kPendingCallbacks = Symbol("pendingCallbacks");
const kRequest = Symbol("request");
const kCloseCallback = Symbol("closeCallback");
const kDeferredTimeouts = Symbol("deferredTimeouts");

const kEmptyObject = Object.freeze(Object.create(null));

Expand Down Expand Up @@ -543,7 +540,6 @@
kBodyChunks,
kClearTimeout,
kCloseCallback,
kDeferredTimeouts,
kDeprecatedReplySymbol,
kEmitState,
kEmptyObject,
Expand Down Expand Up @@ -586,7 +582,6 @@
setMaxHTTPHeaderSize,
setRequestTimeout,
Comment thread
robobun marked this conversation as resolved.
Resolved
setServerCustomOptions,
setServerIdleTimeout,
statusCodeSymbol,
statusMessageSymbol,
timeoutTimerSymbol,
Expand Down
2 changes: 2 additions & 0 deletions src/js/node/_http_incoming.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,8 @@ function onDataIncomingMessage(
return;
}

this.socket?._unrefTimer?.();

if (chunk && !this._dumped) this.push(chunk);

if (isLast) {
Expand Down
51 changes: 33 additions & 18 deletions src/js/node/_http_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
kRealListen,
tlsSymbol,
optionsSymbol,
kDeferredTimeouts,
kDeprecatedReplySymbol,
headerStateSymbol,
NodeHTTPHeaderState,
Expand All @@ -51,7 +50,6 @@
eofInProgress,
runSymbol,
drainMicrotasks,
setServerIdleTimeout,
setServerCustomOptions,
getMaxHTTPHeaderSize,
fakeSocketSymbol,
Expand Down Expand Up @@ -254,6 +252,7 @@

this.listening = false;
this._unref = false;
this.timeout = 0;
this.maxRequestsPerSocket = 0;
this.maxHeadersCount = null;
this[kInternalSocketData] = undefined;
Expand Down Expand Up @@ -711,6 +710,8 @@
server.emit("connection", socket);
}

const serverTimeoutMs = server.timeout;
if (serverTimeoutMs || socket.timeout) socket.setTimeout(serverTimeoutMs || 0);

Check warning on line 714 in src/js/node/_http_server.ts

View check run for this annotation

Claude / Claude Code Review

Per-request setTimeout(0) clears user-set socket timeout on keep-alive

When `server.timeout === 0` (the default) but a prior request handler set a per-socket timeout via `res.setTimeout(N)` / `req.socket.setTimeout(N)`, the guard `serverTimeoutMs || socket.timeout` is truthy on the next keep-alive request and calls `socket.setTimeout(0)`, silently clearing the user's timer. Node only arms `socket.setTimeout(server.timeout)` once at connection time and merely refreshes via `_unrefTimer()` on activity — consider gating this on `isSocketNew`, or `if (serverTimeoutMs)
Comment thread
robobun marked this conversation as resolved.
Resolved
socket[kRequest] = http_req;
// Node.js (llhttp) only flags a request as an upgrade when it carries
// both an Upgrade header and a Connection header with the "upgrade"
Expand Down Expand Up @@ -920,25 +921,16 @@
this.once("listening", onListen);
}

if (this[kDeferredTimeouts]) {
for (const { msecs, callback } of this[kDeferredTimeouts]) {
this.setTimeout(msecs, callback);
}
delete this[kDeferredTimeouts];
}

setTimeout(emitListeningNextTick, 1, this, this[serverSymbol]?.hostname, this[serverSymbol]?.port);
}
};

// Like Node.js: the server records the value and applies it to each new
// connection via socket.setTimeout(); the socket emits 'timeout' and a
// listener on any of req/res/server vetoes the default destroy.
Server.prototype.setTimeout = function (msecs, callback) {
const server = this[serverSymbol];
if (server) {
setServerIdleTimeout(server, Math.ceil(msecs / 1000));
if (typeof callback === "function") this.once("timeout", callback);
} else {
(this[kDeferredTimeouts] ??= []).push({ msecs, callback });
}
this.timeout = msecs;
if (typeof callback === "function") this.on("timeout", callback);
Comment thread
robobun marked this conversation as resolved.
Resolved
return this;
};

Expand Down Expand Up @@ -1042,6 +1034,8 @@
_httpMessage;
_secureEstablished = false;
#pendingCallback = null;
#timeoutTimer = null;
#boundOnTimeout = null;
constructor(server: Server, handle, encrypted) {
super();
this.server = server;
Expand Down Expand Up @@ -1086,6 +1080,7 @@
}
}
#onDrain() {
Comment thread
robobun marked this conversation as resolved.
Resolved
this._unrefTimer();
const handle = this[kHandle];
this[kBytesWritten] = handle ? (handle.response?.getBytesWritten?.() ?? handle.bytesWritten ?? 0) : 0;
const callback = this.#pendingCallback;
Expand All @@ -1096,6 +1091,7 @@
this.emit("drain");
}
#onData(chunk, last) {
this._unrefTimer();
if (chunk) {
this.push(chunk);
}
Expand All @@ -1122,6 +1118,11 @@
}
#onClose() {
this[kHandle] = null;
const timer = this.#timeoutTimer;
if (timer) {
clearTimeout(timer);
this.#timeoutTimer = null;
}
this.server?.[kTrackedConnections]?.delete(this);

// Node.js's `socketOnClose` → `abortIncoming()` only destroys requests
Expand Down Expand Up @@ -1180,15 +1181,16 @@
_onTimeout() {
const handle = this[kHandle];
const response = handle?.response;
// If there is a response, and it has pending data,
// we suppress the timeout because a write is in progress.
if (response && response.writableLength > 0) {
this._unrefTimer();
return;
}
this.emit("timeout");
}
_unrefTimer() {
// for compatibility
this.#timeoutTimer?.refresh();

Check failure on line 1193 in src/js/node/_http_server.ts

View check run for this annotation

Claude / Claude Code Review

Response body writes never refresh the socket idle timer; streaming responses time out mid-write

Response body writes never refresh the new JS idle timer, so `server.setTimeout(N)` (with no listener) now destroys an actively-streaming response after N ms. The intended guard here is dead: `handle.response` is a native `NodeHTTPResponse`, which exposes `bufferedAmount` but not `writableLength`, so `response.writableLength > 0` is always `undefined > 0` → false. Fix by calling `this.socket?._unrefTimer()` in `ServerResponse.prototype.write` / `_send` / `end` (Node refreshes the socket timer on
Comment thread
robobun marked this conversation as resolved.
Resolved
}

address() {
Expand Down Expand Up @@ -1324,7 +1326,18 @@
return this;
}

setTimeout(_timeout, _callback) {
setTimeout(msecs, callback) {
this.timeout = msecs;
const existing = this.#timeoutTimer;
if (existing) clearTimeout(existing);
if (msecs === 0) {
this.#timeoutTimer = null;
if (callback) this.removeListener("timeout", callback);
} else {
const bound = (this.#boundOnTimeout ??= this._onTimeout.bind(this));
Comment thread
robobun marked this conversation as resolved.
Resolved
this.#timeoutTimer = setTimeout(bound, msecs).unref();
if (callback) this.once("timeout", callback);
}
return this;
Comment thread
robobun marked this conversation as resolved.
Resolved
}

Expand Down Expand Up @@ -1687,6 +1700,8 @@
function endSocketOnFinishIfNeeded(socket, res) {
if (res[kMustCloseConnection]) {
socket?.end();
} else {
socket?._unrefTimer();
}
}

Expand Down
159 changes: 159 additions & 0 deletions test/js/node/http/node-http-server-setTimeout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import { test, expect, describe } from "bun:test";
import http from "node:http";
import net from "node:net";
import { once } from "node:events";

// https://nodejs.org/api/http.html#serversettimeoutmsecs-callback
// Once a 'timeout' listener is installed on the server (or on req/res), the
// runtime must NOT destroy the socket on timeout; the listener decides.

async function connectAndWrite(port: number, wire: string) {
const s = net.connect(port, "127.0.0.1");
s.setNoDelay(true);
s.on("error", () => {});
s.resume();
await once(s, "connect");
s.write(wire);
return s;
}

async function listen(handler: http.RequestListener) {
const srv = http.createServer(handler);
srv.listen(0, "127.0.0.1");
await once(srv, "listening");
return srv;
}

function cleanup(srv: http.Server, client: net.Socket) {
try {
client.destroy();
} catch {}
try {
srv.close();
srv.closeAllConnections?.();
} catch {}
}

describe("http.Server.prototype.setTimeout", () => {
test("sets server.timeout and returns this", () => {
const srv = http.createServer();
expect(srv.timeout).toBe(0);
const ret = srv.setTimeout(1234);
expect(ret).toBe(srv);
expect(srv.timeout).toBe(1234);
});

test("callback is registered as a 'timeout' listener", () => {
const srv = http.createServer();
const cb = () => {};
srv.setTimeout(1234, cb);
expect(srv.listeners("timeout")).toContain(cb);
});

test.concurrent("a server 'timeout' listener vetoes the default destroy (stalled body)", async () => {
const srv = await listen((req, _res) => void req.resume());
srv.setTimeout(200);

const { promise, resolve } = Promise.withResolvers<{ event: string; socket?: any }>();
srv.on("timeout", socket => resolve({ event: "timeout", socket }));

const client = await connectAndWrite(
(srv.address() as net.AddressInfo).port,
"POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 900\r\n\r\nab",
);
client.on("close", () => resolve({ event: "close" }));

try {
const { event, socket } = await promise;
// The 'timeout' event must fire before the connection is torn down.
expect(event).toBe("timeout");
expect(socket.destroyed).toBe(false);
// And the connection must still be open afterwards: the listener did
// not destroy, so the runtime must not either. Race a fresh 'timeout'
// (listener returning without destroying leaves the socket alive; the
// timer is one-shot until refreshed, but the old native path closed
// within a few ms of the event) against 'close'.
const winner = await Promise.race([
once(client, "close").then(() => "close"),
Bun.sleep(250).then(() => "alive"),
]);
expect(winner).toBe("alive");
expect(socket.destroyed).toBe(false);
} finally {
cleanup(srv, client);
}
});

test.concurrent("a server 'timeout' listener vetoes the default destroy (idle keep-alive)", async () => {
const srv = await listen((req, res) => {
req.resume();
req.on("end", () => res.end("ok"));
});
srv.setTimeout(200);

const { promise, resolve } = Promise.withResolvers<{ event: string; socket?: any }>();
srv.on("timeout", socket => resolve({ event: "timeout", socket }));

const client = await connectAndWrite((srv.address() as net.AddressInfo).port, "GET / HTTP/1.1\r\nHost: a\r\n\r\n");
client.on("close", () => resolve({ event: "close" }));

try {
const { event, socket } = await promise;
// An idle keep-alive connection reaped by the server timeout must
// emit 'timeout' (not close silently).
expect(event).toBe("timeout");
expect(socket.destroyed).toBe(false);
const winner = await Promise.race([
once(client, "close").then(() => "close"),
Bun.sleep(250).then(() => "alive"),
]);
expect(winner).toBe("alive");
expect(socket.destroyed).toBe(false);
} finally {
cleanup(srv, client);
}
});

test.concurrent("with no listener, the socket is destroyed on timeout", async () => {
const srv = await listen((req, _res) => void req.resume());
srv.setTimeout(200);

const client = await connectAndWrite(
(srv.address() as net.AddressInfo).port,
"POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 900\r\n\r\nab",
);
try {
await once(client, "close");
} finally {
cleanup(srv, client);
}
});

test.concurrent("a request 'timeout' listener also vetoes the default destroy", async () => {
const { promise, resolve } = Promise.withResolvers<{ event: string; socket?: any }>();
const srv = await listen((req, _res) => {
req.resume();
req.on("timeout", () => resolve({ event: "timeout", socket: req.socket }));
});
srv.setTimeout(200);

const client = await connectAndWrite(
(srv.address() as net.AddressInfo).port,
"POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 900\r\n\r\nab",
);
client.on("close", () => resolve({ event: "close" }));

try {
const { event, socket } = await promise;
expect(event).toBe("timeout");
expect(socket.destroyed).toBe(false);
const winner = await Promise.race([
once(client, "close").then(() => "close"),
Bun.sleep(250).then(() => "alive"),
]);
expect(winner).toBe("alive");
} finally {
cleanup(srv, client);
}
});
});
Loading