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
12 changes: 11 additions & 1 deletion doc/api/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -1759,6 +1759,11 @@ unless the user specified another socket type.
<!-- YAML
added: v0.1.90
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/66000
description: Connections that are still active when the method is called
now close once they go idle, instead of staying open until
`server.keepAliveTimeout` elapses.
- version:
- v19.0.0
pr-url: https://github.com/nodejs/node/pull/43522
Expand All @@ -1770,7 +1775,12 @@ changes:

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.
a response. A connection that is still sending a request or waiting for a
response is left alone until that request/response finishes, and is then
closed as well. Its last response is sent with `Connection: close`, unless
that response's headers were already written before this method was called.
Requests on it whose handlers have already run are still answered; any
request pipelined behind them is not processed and gets no response.
See [`net.Server.close()`][].

```js
Expand Down
43 changes: 42 additions & 1 deletion lib/internal/http/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ const kUpgradeStream = Symbol('UpgradeStream');

const kOptimizeEmptyRequests = Symbol('OptimizeEmptyRequestsOption');
const kConnectionState = Symbol('ConnectionState');
const kCloseCount = Symbol('CloseCount');
const kParserExecuting = Symbol('kParserExecuting');
const kParserDeferred = Symbol('kParserDeferred');
const kResponseOptions = Symbol('ResponseOptions');
Expand Down Expand Up @@ -519,12 +520,21 @@ function writeHead(statusCode, reason, obj) {
this.shouldKeepAlive = false;
}

// The last response of a connection whose server is closing must not
// advertise keep-alive: the connection closes once it is done.
const state = this[kConnectionState];
if (state !== undefined && isClosing(state) && isLastResponse(this, state)) {
this.shouldKeepAlive = false;
}

this._storeHeader(statusLine, headers);

return this;
}

function storeHTTPOptions(options) {
// How many times `close()` was called, see isClosing().
this[kCloseCount] = 0;
this[kIncomingMessage] = options.IncomingMessage || IncomingMessage;
this[kServerResponse] = options.ServerResponse || ServerResponse;

Expand Down Expand Up @@ -647,7 +657,24 @@ function setupConnectionsTracking() {
setInterval(checkConnections.bind(this), this.connectionsCheckingInterval).unref();
}

// A connection is closing if `close()` was called since it was accepted.
// A count rather than a flag, so a later `listen()` doesn't undo it.
function isClosing(state) {
return state.closeCount !== state.server[kCloseCount];
}

// Whether `res` is the last response queued on its connection. While closing,
// only that one ends the connection, so accepted pipelined requests are still
// answered. A queued response has no socket yet, so look at the state instead.
function isLastResponse(res, state) {
const { outgoing } = state;
return outgoing.length > 0 ?
outgoing[outgoing.length - 1] === res :
state.socket._httpMessage === res;
}

function httpServerPreClose(server) {
server[kCloseCount]++;
server.closeIdleConnections();
clearInterval(server[kConnectionsCheckingInterval]);
}
Expand Down Expand Up @@ -849,6 +876,7 @@ function connectionListenerInternal(server, socket) {
onPendingData: null,
server,
socket,
closeCount: server[kCloseCount],
};
state.onPendingData = updateOutgoingData.bind(undefined, socket, state);
state.onData = socketOnData.bind(undefined,
Expand Down Expand Up @@ -1274,7 +1302,8 @@ function resOnFinish(req, res, socket, state, server) {
clearIncoming(req);
process.nextTick(emitCloseNT, res);

if (res._last) {
// While closing, the last response ends it, even if it advertised keep-alive.
if (res._last || (isClosing(state) && state.outgoing.length === 0)) {
if (typeof socket.destroySoon === 'function') {
socket.destroySoon();
} else {
Expand Down Expand Up @@ -1373,6 +1402,18 @@ function onResponseFinish() {
function parserOnIncoming(server, socket, state, req, keepAlive) {
resetSocketTimeout(server, socket, state);

// Once the server is closing, a response that is in flight (or one that just
// finished, with the socket ending) is the last one this connection sends,
// so a request pipelined behind it is not processed (RFC 9112 Section 9.6).
if (isClosing(state) && (socket._httpMessage || socket.writableEnded)) {
debug('dropping a request pipelined behind the last response before close');
// That includes Upgrade and CONNECT requests. The parser does not parse
// what follows one, clearing the flag keeps it from being emitted too.
req.upgrade = false;
req._dump();
return 0;
}

if (req.upgrade) {
req.upgrade = req.method === 'CONNECT' ||
!!server.shouldUpgradeCallback(req);
Expand Down
9 changes: 7 additions & 2 deletions test/parallel/test-http-pipeline-assertionerror-finish.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,16 @@ const net = require('net');

const COUNT = 10;

let handled = 0;
const server = http
.createServer(
common.mustCall((req, res) => {
// Close the server, we have only one TCP connection anyway
server.close();
// Close the server once every request has been dispatched, we have only
// one TCP connection anyway. A request that arrives behind a response in
// flight after `server.close()` is not processed.
if (++handled === COUNT) {
server.close();
}
res.writeHead(200);
res.write('data');

Expand Down
7 changes: 3 additions & 4 deletions test/parallel/test-http-pipeline-socket-parser-typeerror.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ require('../common');
const http = require('http');
const net = require('net');

let once = false;
let first = null;
let second = null;

Expand All @@ -21,9 +20,6 @@ let done;

const server = http
.createServer((req, res) => {
if (!once) server.close();
once = true;

if (first === null) {
first = res;
return;
Expand All @@ -42,6 +38,9 @@ const server = http
done();
})
.on('upgrade', (req, socket) => {
// Every request has been dispatched by now. A request that arrives behind
// a response in flight after `server.close()` is not processed.
server.close();
second.end(chunk, () => {
socket.end();
});
Expand Down
4 changes: 2 additions & 2 deletions test/parallel/test-http-raw-headers.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,15 +93,15 @@ http.createServer(common.mustCall(function(req, res) {
'Date',
null,
'Connection',
'keep-alive',
'close',
'Transfer-Encoding',
'chunked',
];
const expectHeaders = { '__proto__': null,
'keep-alive': 'timeout=1',
'trailer': 'x-foo',
'date': null,
'connection': 'keep-alive',
'connection': 'close',
'transfer-encoding': 'chunked' };
res.rawHeaders[5] = null;
res.headers.date = null;
Expand Down
Loading
Loading