From 29ccebc90a6b2cc1cd3f777c21188164ee6177fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Guilherme=20Ara=C3=BAjo?= Date: Sat, 28 Nov 2026 13:21:16 -0300 Subject: [PATCH 1/2] http: add timeout option to server.close() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit server.close() waits indefinitely for connections that are sending a request or waiting for a response, so a single slow or stuck request keeps the server from closing. Add an optional `options` argument with a `timeout` in milliseconds to `http.Server` and `https.Server`. Connections that are still open when it elapses are destroyed with `closeAllConnections()`. Assisted-by: Claude Signed-off-by: Guilherme Araújo --- doc/api/http.md | 18 +++- doc/api/https.md | 14 ++- lib/https.js | 8 +- lib/internal/http/server.js | 63 +++++++++++- .../test-http-server-close-timeout.js | 97 +++++++++++++++++++ .../test-https-server-close-timeout.js | 34 +++++++ 6 files changed, 220 insertions(+), 14 deletions(-) create mode 100644 test/parallel/test-http-server-close-timeout.js create mode 100644 test/parallel/test-https-server-close-timeout.js diff --git a/doc/api/http.md b/doc/api/http.md index 42a7a59d69db..b0c83ab7ab22 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -1757,11 +1757,14 @@ stream. If required, you can access the raw connection underlying the request via [`request.socket`][], which is guaranteed to be an instance of {net.Socket} unless the user specified another socket type. -### `server.close([callback])` +### `server.close([options][, callback])` +* `options` {Object} + * `timeout` {integer} The number of milliseconds to wait for the remaining + connections to end before destroying them. Must be greater than `0`. + **Default:** no timeout. * `callback` {Function} Stops the server from accepting new connections and closes all connections @@ -1776,6 +1783,12 @@ connected to this server which are not sending a request or waiting for a response. See [`net.Server.close()`][]. +By default, the server waits indefinitely for the remaining connections to +end. If `options.timeout` is set, connections that are still open when it +elapses are destroyed with [`server.closeAllConnections()`][], which interrupts +any request in progress. Sockets upgraded to a different protocol, such as +WebSocket or HTTP/2, are not destroyed. + ```js const http = require('node:http'); @@ -5029,7 +5042,8 @@ const agent2 = new http.Agent({ proxyEnv: process.env }); [`response.writeEarlyHints()`]: #responsewriteearlyhintshints-callback [`response.writeHead()`]: #responsewriteheadstatuscode-statusmessage-headers [`response.writeProcessing()`]: #responsewriteprocessingcallback -[`server.close()`]: #serverclosecallback +[`server.close()`]: #servercloseoptions-callback +[`server.closeAllConnections()`]: #servercloseallconnections [`server.headersTimeout`]: #serverheaderstimeout [`server.keepAliveTimeoutBuffer`]: #serverkeepalivetimeoutbuffer [`server.keepAliveTimeout`]: #serverkeepalivetimeout diff --git a/doc/api/https.md b/doc/api/https.md index 2d3426778eb8..5fc8a933e1f1 100644 --- a/doc/api/https.md +++ b/doc/api/https.md @@ -142,12 +142,20 @@ added: v0.3.4 See [`http.Server`][] for more information. -### `server.close([callback])` +### `server.close([options][, callback])` +* `options` {Object} + * `timeout` {integer} The number of milliseconds to wait for the remaining + connections to end before destroying them. Must be greater than `0`. + **Default:** no timeout. * `callback` {Function} * Returns: {https.Server} @@ -765,7 +773,7 @@ statusCode: 200 [`import()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import [`net.Server`]: net.md#class-netserver [`new URL()`]: url.md#new-urlinput-base -[`server.close()`]: http.md#serverclosecallback +[`server.close()`]: http.md#servercloseoptions-callback [`server.closeAllConnections()`]: http.md#servercloseallconnections [`server.closeIdleConnections()`]: http.md#servercloseidleconnections [`server.headersTimeout`]: http.md#serverheaderstimeout @@ -778,5 +786,5 @@ statusCode: 200 [`tls.connect()`]: tls.md#tlsconnectoptions-callback [`tls.createSecureContext()`]: tls.md#tlscreatesecurecontextoptions [`tls.createServer()`]: tls.md#tlscreateserveroptions-secureconnectionlistener -[httpsServerClose]: #serverclosecallback +[httpsServerClose]: #servercloseoptions-callback [sni wiki]: https://en.wikipedia.org/wiki/Server_Name_Indication diff --git a/lib/https.js b/lib/https.js index 7481439bf1b5..cd4632222c5d 100644 --- a/lib/https.js +++ b/lib/https.js @@ -33,7 +33,6 @@ const { NumberParseInt, ObjectAssign, ObjectSetPrototypeOf, - ReflectApply, ReflectConstruct, SafeWeakMap, String, @@ -66,7 +65,7 @@ const { } = require('internal/http'); const { Agent: HttpAgent } = require('internal/http/agent'); const { - httpServerPreClose, + httpServerClose, Server: HttpServer, setupConnectionsTracking, storeHTTPOptions, @@ -135,9 +134,8 @@ Server.prototype.closeIdleConnections = HttpServer.prototype.closeIdleConnection Server.prototype.setTimeout = HttpServer.prototype.setTimeout; -Server.prototype.close = function close() { - httpServerPreClose(this); - ReflectApply(tls.Server.prototype.close, this, arguments); +Server.prototype.close = function close(options, callback) { + httpServerClose(this, tls.Server.prototype.close, options, callback); return this; }; diff --git a/lib/internal/http/server.js b/lib/internal/http/server.js index fe870c471440..95b78959b63c 100644 --- a/lib/internal/http/server.js +++ b/lib/internal/http/server.js @@ -105,7 +105,13 @@ const { validateFunction, } = require('internal/validators'); const Buffer = require('buffer').Buffer; -const { setInterval, clearInterval } = require('timers'); +const { + clearInterval, + clearTimeout, + setInterval, + setTimeout, +} = require('timers'); +const { TIMEOUT_MAX } = require('internal/timers'); let debug = require('internal/util/debuglog').debuglog('http', (fn) => { debug = fn; }); @@ -204,6 +210,7 @@ const kOnTimeout = HTTPParser.kOnTimeout | 0; const kConnections = Symbol('http.server.connections'); const kConnectionsCheckingInterval = Symbol('http.server.connectionsCheckingInterval'); +const kCloseTimeout = Symbol('http.server.closeTimeout'); const HTTP_SERVER_TRACE_EVENT_NAME = 'http.server.request'; @@ -621,6 +628,13 @@ function setupConnectionsTracking() { // Start connection handling this[kConnections] ||= new ConnectionsList(); + // A deadline set by a previous close() must not affect the connections of + // a server that is listening again. + if (this[kCloseTimeout] != null) { + clearTimeout(this[kCloseTimeout]); + this[kCloseTimeout] = null; + } + if (this[kConnectionsCheckingInterval]) { clearInterval(this[kConnectionsCheckingInterval]); } @@ -635,6 +649,47 @@ function httpServerPreClose(server) { clearInterval(server[kConnectionsCheckingInterval]); } +function onCloseTimeout(server) { + server[kCloseTimeout] = null; + server.closeAllConnections(); +} + +function clearCloseTimeout() { + clearTimeout(this[kCloseTimeout]); + this[kCloseTimeout] = null; +} + +// Shared implementation of `close([options][, callback])` for HTTP and HTTPS +// servers. `superClose` is the `close()` method of the underlying server. +function httpServerClose(server, superClose, options, callback) { + let timeout; + if (typeof options === 'function') { + callback = options; + } else if (options !== null && typeof options === 'object') { + // Other values are ignored, as they always have been, so that + // `emitter.once('event', server.close.bind(server))` keeps working. + timeout = options.timeout; + if (timeout !== undefined) { + validateInteger(timeout, 'options.timeout', 1, TIMEOUT_MAX); + } + } + + httpServerPreClose(server); + superClose.call(server, callback); + + if (timeout !== undefined) { + if (server[kCloseTimeout] == null) { + server.once('close', clearCloseTimeout); + } else { + clearTimeout(server[kCloseTimeout]); + } + // Connections that are still open when the timer fires keep the event + // loop alive on their own. + server[kCloseTimeout] = + setTimeout(onCloseTimeout, timeout, server).unref(); + } +} + function Server(options, requestListener) { if (!(this instanceof Server)) { return deprecateInstantiation(Server, 'DEP0195', options, requestListener); @@ -679,9 +734,8 @@ function Server(options, requestListener) { ObjectSetPrototypeOf(Server.prototype, net.Server.prototype); ObjectSetPrototypeOf(Server, net.Server); -Server.prototype.close = function close() { - httpServerPreClose(this); - ReflectApply(net.Server.prototype.close, this, arguments); +Server.prototype.close = function close(options, callback) { + httpServerClose(this, net.Server.prototype.close, options, callback); return this; }; @@ -1552,6 +1606,7 @@ module.exports = { storeHTTPOptions, _connectionListener: connectionListener, kServerResponse, + httpServerClose, httpServerPreClose, kConnectionsCheckingInterval, }; diff --git a/test/parallel/test-http-server-close-timeout.js b/test/parallel/test-http-server-close-timeout.js new file mode 100644 index 000000000000..aa79d7206b0a --- /dev/null +++ b/test/parallel/test-http-server-close-timeout.js @@ -0,0 +1,97 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const { createServer, get } = require('http'); + +function listen(server) { + return new Promise((resolve) => server.listen(0, resolve)); +} + +// Connections that are still active when the timeout expires are closed. +async function closesActiveConnections() { + const server = createServer(common.mustCall((req, res) => { + // Never send a response. + res.on('close', common.mustCall()); + const ret = server.close({ timeout: common.platformTimeout(100) }, + common.mustSucceed()); + assert.strictEqual(ret, server); + })); + + await listen(server); + + const { promise, resolve } = Promise.withResolvers(); + server.on('close', resolve); + + get({ port: server.address().port }, common.mustNotCall()) + .on('error', common.mustCall((err) => { + assert.strictEqual(err.code, 'ECONNRESET'); + })); + + await promise; +} + +// A request that completes before the timeout expires is not interrupted, +// and the pending timer does not keep the process alive. +async function doesNotInterruptRequests() { + const server = createServer(common.mustCall((req, res) => { + server.close({ timeout: common.platformTimeout(60_000) }, + common.mustSucceed()); + setTimeout(() => res.end('ok'), common.platformTimeout(50)); + })); + + await listen(server); + + const { promise, resolve } = Promise.withResolvers(); + server.on('close', resolve); + + get({ + port: server.address().port, + headers: { connection: 'close' }, + }, common.mustCall((res) => { + let body = ''; + res.setEncoding('utf8'); + res.on('data', (chunk) => { body += chunk; }); + res.on('end', common.mustCall(() => { + assert.strictEqual(body, 'ok'); + })); + })); + + await promise; +} + +// The options are validated before the server stops listening. +async function validatesOptions() { + const server = createServer(common.mustNotCall()); + + await listen(server); + + for (const timeout of [0, -1, 1.5, 2 ** 31, NaN, Infinity]) { + assert.throws(() => server.close({ timeout }), { + code: 'ERR_OUT_OF_RANGE', + name: 'RangeError', + }); + } + + for (const timeout of ['1', null, true, {}, 1n]) { + assert.throws(() => server.close({ timeout }), { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + }); + } + + assert.strictEqual(server.listening, true); + + // A first argument that is neither an object nor a function is ignored. + const { promise, resolve } = Promise.withResolvers(); + server.on('close', resolve); + server.close('SIGTERM'); + + await promise; +} + +(async () => { + await closesActiveConnections(); + await doesNotInterruptRequests(); + await validatesOptions(); +})().then(common.mustCall()); diff --git a/test/parallel/test-https-server-close-timeout.js b/test/parallel/test-https-server-close-timeout.js new file mode 100644 index 000000000000..d23bf33d77be --- /dev/null +++ b/test/parallel/test-https-server-close-timeout.js @@ -0,0 +1,34 @@ +'use strict'; + +const common = require('../common'); + +if (!common.hasCrypto) { + common.skip('missing crypto'); +} + +const assert = require('assert'); +const { createServer, get } = require('https'); +const fixtures = require('../common/fixtures'); + +const options = { + key: fixtures.readKey('agent1-key.pem'), + cert: fixtures.readKey('agent1-cert.pem'), +}; + +// Connections that are still active when the timeout expires are closed. +const server = createServer(options, common.mustCall((req, res) => { + // Never send a response. + res.on('close', common.mustCall()); + const ret = server.close({ timeout: common.platformTimeout(100) }, + common.mustSucceed()); + assert.strictEqual(ret, server); +})); + +server.listen(0, common.mustCall(() => { + get({ + port: server.address().port, + rejectUnauthorized: false, + }, common.mustNotCall()).on('error', common.mustCall((err) => { + assert.strictEqual(err.code, 'ECONNRESET'); + })); +})); From 8b74e83f375d150e1cc62fc339309e6e78995e62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Guilherme=20Ara=C3=BAjo?= Date: Sat, 28 Nov 2026 13:24:40 -0300 Subject: [PATCH 2/2] fixup! http: add timeout option to server.close() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Guilherme Araújo --- doc/api/http.md | 2 +- doc/api/https.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/api/http.md b/doc/api/http.md index b0c83ab7ab22..c801a76393c0 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -1763,7 +1763,7 @@ unless the user specified another socket type. added: v0.1.90 changes: - version: REPLACEME - pr-url: https://github.com/nodejs/node/pull/REPLACEME + pr-url: https://github.com/nodejs/node/pull/67851 description: Added the `options` argument with the `timeout` option. - version: - v19.0.0 diff --git a/doc/api/https.md b/doc/api/https.md index 5fc8a933e1f1..4e39a47b1e4a 100644 --- a/doc/api/https.md +++ b/doc/api/https.md @@ -148,7 +148,7 @@ See [`http.Server`][] for more information. added: v0.1.90 changes: - version: REPLACEME - pr-url: https://github.com/nodejs/node/pull/REPLACEME + pr-url: https://github.com/nodejs/node/pull/67851 description: Added the `options` argument with the `timeout` option. -->