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
20 changes: 18 additions & 2 deletions doc/api/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -1757,25 +1757,40 @@ 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. If `server.close()` is called more than
once, the timeout that elapses first applies.

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

Expand Down Expand Up @@ -5029,7 +5044,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
67 changes: 63 additions & 4 deletions lib/internal/http/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const {
prepareError,
} = require('internal/http/common');
const { ConnectionsList } = internalBinding('http_parser');
const timersBinding = internalBinding('timers');
const {
kUniqueHeaders,
parseUniqueHeadersOption,
Expand Down Expand Up @@ -105,7 +106,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 +211,8 @@ const kOnTimeout = HTTPParser.kOnTimeout | 0;

const kConnections = Symbol('http.server.connections');
const kConnectionsCheckingInterval = Symbol('http.server.connectionsCheckingInterval');
const kCloseTimeout = Symbol('http.server.closeTimeout');
const kCloseDeadline = Symbol('http.server.closeDeadline');

const HTTP_SERVER_TRACE_EVENT_NAME = 'http.server.request';

Expand Down Expand Up @@ -621,6 +630,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 +649,51 @@ 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) {
// When close() is called more than once, the earliest deadline wins.
const deadline = timersBinding.getLibuvNow() + timeout;
if (server[kCloseTimeout] == null) {
server.once('close', clearCloseTimeout);
} else if (deadline >= server[kCloseDeadline]) {
return;
} else {
clearTimeout(server[kCloseTimeout]);
}
server[kCloseDeadline] = deadline;
// 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 +738,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 +1610,7 @@ module.exports = {
storeHTTPOptions,
_connectionListener: connectionListener,
kServerResponse,
httpServerClose,
httpServerPreClose,
kConnectionsCheckingInterval,
};
Loading
Loading