Skip to content
Open
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
18 changes: 16 additions & 2 deletions doc/api/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -1757,25 +1757,38 @@
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/REPLACEME

Check warning on line 1766 in doc/api/http.md

View workflow job for this annotation

GitHub Actions / lint-pr-url

pr-url doesn't match the URL of the current PR.
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.

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

Expand Down Expand Up @@ -5029,7 +5042,8 @@
[`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 @@

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/REPLACEME

Check warning on line 151 in doc/api/https.md

View workflow job for this annotation

GitHub Actions / lint-pr-url

pr-url doesn't match the URL of the current PR.
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 @@
[`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 @@
[`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
63 changes: 59 additions & 4 deletions lib/internal/http/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

const {
ArrayIsArray,
Error,

Check failure on line 26 in lib/internal/http/server.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Do not use prototype primordials in this file

Check failure on line 26 in lib/internal/http/server.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Do not use prototype primordials in this file
MathMin,
NumberIsFinite,
ObjectKeys,
Expand Down Expand Up @@ -105,7 +105,13 @@
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 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,13 @@
// 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;
}
Comment on lines +633 to +636

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This clears kCloseTimeout but leaves clearCloseTimeout attached on 'close'. If close({ timeout }) gets called again before 'close' fires (like after calling listen() again, or if upgraded sockets keep the server open), it'll attach a duplicate listener

Same thing in onCloseTimeout

Suggested change
if (this[kCloseTimeout] != null) {
clearTimeout(this[kCloseTimeout]);
this[kCloseTimeout] = null;
}
if (this[kCloseTimeout] != null) {
clearTimeout(this[kCloseTimeout]);
this[kCloseTimeout] = null;
this.removeListener('close', clearCloseTimeout);
}


if (this[kConnectionsCheckingInterval]) {
clearInterval(this[kConnectionsCheckingInterval]);
}
Expand All @@ -635,6 +649,47 @@
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);
Expand Down Expand Up @@ -679,9 +734,8 @@
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 +1606,7 @@
storeHTTPOptions,
_connectionListener: connectionListener,
kServerResponse,
httpServerClose,
httpServerPreClose,
kConnectionsCheckingInterval,
};
97 changes: 97 additions & 0 deletions test/parallel/test-http-server-close-timeout.js
Original file line number Diff line number Diff line change
@@ -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());
34 changes: 34 additions & 0 deletions test/parallel/test-https-server-close-timeout.js
Original file line number Diff line number Diff line change
@@ -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');
}));
}));
Loading