Skip to content
Open
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
19 changes: 17 additions & 2 deletions doc/api/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -1757,25 +1757,39 @@ 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])`

<!-- YAML
added: v0.1.90
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/67851
description: Added the `options` argument with the `timeout` option.
- version:
- v19.0.0
pr-url: https://github.com/nodejs/node/pull/43522
description: The method closes idle connections before returning.

-->

* `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
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. Calling [`server.listen()`][] again
before the timeout elapses cancels it.

```js
const http = require('node:http');

Expand Down Expand Up @@ -5029,7 +5043,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
Expand Down
14 changes: 11 additions & 3 deletions doc/api/https.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,12 +142,20 @@ added: v0.3.4

See [`http.Server`][] for more information.

### `server.close([callback])`
### `server.close([options][, callback])`

<!-- YAML
added: v0.1.90
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/67851
description: Added the `options` argument with the `timeout` option.
-->

* `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}

Expand Down Expand Up @@ -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
Expand All @@ -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
8 changes: 3 additions & 5 deletions lib/https.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ const {
NumberParseInt,
ObjectAssign,
ObjectSetPrototypeOf,
ReflectApply,
ReflectConstruct,
SafeWeakMap,
String,
Expand Down Expand Up @@ -66,7 +65,7 @@ const {
} = require('internal/http');
const { Agent: HttpAgent } = require('internal/http/agent');
const {
httpServerPreClose,
httpServerClose,
Server: HttpServer,
setupConnectionsTracking,
storeHTTPOptions,
Expand Down Expand Up @@ -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;
};

Expand Down
60 changes: 56 additions & 4 deletions lib/internal/http/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
});
Expand Down Expand Up @@ -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';

Expand Down Expand Up @@ -621,6 +628,11 @@ function setupConnectionsTracking() {
// Start connection handling
this[kConnections] ||= new ConnectionsList();

// Listening again cancels the timeout of a previous close().
if (this[kCloseTimeout] != null) {
clearCloseTimeout.call(this);
}
Comment thread
araujogui marked this conversation as resolved.
Resolved

if (this[kConnectionsCheckingInterval]) {
clearInterval(this[kConnectionsCheckingInterval]);
}
Expand All @@ -635,6 +647,46 @@ function httpServerPreClose(server) {
clearInterval(server[kConnectionsCheckingInterval]);
}

function onCloseTimeout(server) {
clearCloseTimeout.call(server);
server.closeAllConnections();
}

// Attached as a 'close' listener only while kCloseTimeout is set.
function clearCloseTimeout() {
clearTimeout(this[kCloseTimeout]);
this[kCloseTimeout] = null;
this.removeListener('close', clearCloseTimeout);
}

// Shared by http.Server and https.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 for backward compatibility.
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]);
}
// Open connections 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);
Expand Down Expand Up @@ -679,9 +731,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;
};

Expand Down Expand Up @@ -1552,6 +1603,7 @@ module.exports = {
storeHTTPOptions,
_connectionListener: connectionListener,
kServerResponse,
httpServerClose,
httpServerPreClose,
kConnectionsCheckingInterval,
};
174 changes: 174 additions & 0 deletions test/parallel/test-http-server-close-timeout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
'use strict';

const common = require('../common');
const assert = require('assert');
const { createServer, get } = require('http');
const net = require('net');

function listen(server) {
return new Promise((resolve) => server.listen(0, resolve));
}

// Active connections are closed when the timeout expires.
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;
}

// Requests that end before the timeout are not interrupted.
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;
}

// An upgraded socket keeps the server open past the timeout. Calling close()
// again does not leak 'close' listeners.
async function closeAgainAfterTimeout() {
const server = createServer(common.mustNotCall());

server.on('upgrade', common.mustCall((req, socket) => {
const baseline = server.listenerCount('close');
server.close({ timeout: common.platformTimeout(10) });
assert.strictEqual(server.listenerCount('close'), baseline + 1);

setTimeout(common.mustCall(() => {
assert.strictEqual(server.listening, false);
assert.strictEqual(server.listenerCount('close'), baseline);

server.close({ timeout: common.platformTimeout(60_000) });
assert.strictEqual(server.listenerCount('close'), baseline + 1);

server.once('close', common.mustCall(() => {
assert.strictEqual(server.listenerCount('close'), baseline);
}));
socket.destroy();
}), common.platformTimeout(50));
}));

await listen(server);

const { promise, resolve } = Promise.withResolvers();
server.on('close', resolve);

const client = net.connect(server.address().port, common.mustCall(() => {
client.write('GET / HTTP/1.1\r\n' +
'Host: localhost\r\n' +
'Connection: Upgrade\r\n' +
'Upgrade: test\r\n\r\n');
}));
client.resume();
client.on('close', common.mustCall());

await promise;
}

// Listening again cancels the timeout.
async function listenAgainCancelsTimeout() {
const server = createServer(common.mustCall((req, res) => {
const baseline = server.listenerCount('close');
server.close({ timeout: common.platformTimeout(10) });
assert.strictEqual(server.listenerCount('close'), baseline + 1);

server.listen(0, common.mustCall(() => {
assert.strictEqual(server.listenerCount('close'), baseline);

// Close first, or closeIdleConnections() destroys the socket.
setTimeout(common.mustCall(() => {
server.close();
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) => {
res.resume();
res.on('end', common.mustCall());
}));

await promise;
}

// 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);

// Other first arguments are ignored.
const { promise, resolve } = Promise.withResolvers();
server.on('close', resolve);
server.close('SIGTERM');

await promise;
}

(async () => {
await closesActiveConnections();
await doesNotInterruptRequests();
await closeAgainAfterTimeout();
await listenAgainCancelsTimeout();
await validatesOptions();
})().then(common.mustCall());
Loading
Loading