Skip to content

Commit edbaebf

Browse files
committed
http: close busy connections after server.close()
`server.close()` only closes connections that are idle at that moment. A busy one stays keep-alive after its response, serving requests until `keepAliveTimeout` reaps it. This is a breaking change: such a connection now closes once it has answered every request it accepted. Its last response says `Connection: close`, unless its headers were written before close(). A request that arrives behind a pending response after close() is not processed. Connections accepted after close(), e.g. once the server listens again, are not affected. Four existing tests called close() while their connection was still in use. They now expect `Connection: close`, or call close() only once they are done with the connection. Signed-off-by: WhatCats <whatcater@gmail.com> Assisted-by: a closed-source coding agent
1 parent d2da05f commit edbaebf

7 files changed

Lines changed: 514 additions & 12 deletions

‎doc/api/http.md‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1759,6 +1759,11 @@ unless the user specified another socket type.
17591759
<!-- YAML
17601760
added: v0.1.90
17611761
changes:
1762+
- version: REPLACEME
1763+
pr-url: https://github.com/nodejs/node/pull/66000
1764+
description: Connections that are still active when the method is called
1765+
now close once they go idle, instead of staying open until
1766+
`server.keepAliveTimeout` elapses.
17621767
- version:
17631768
- v19.0.0
17641769
pr-url: https://github.com/nodejs/node/pull/43522
@@ -1770,7 +1775,12 @@ changes:
17701775

17711776
Stops the server from accepting new connections and closes all connections
17721777
connected to this server which are not sending a request or waiting for
1773-
a response.
1778+
a response. A connection that is still sending a request or waiting for a
1779+
response is left alone until that request/response finishes, and is then
1780+
closed as well. Its last response is sent with `Connection: close`, unless
1781+
that response's headers were already written before this method was called.
1782+
Requests on it whose handlers have already run are still answered; any
1783+
request pipelined behind them is not processed and gets no response.
17741784
See [`net.Server.close()`][].
17751785

17761786
```js

‎lib/internal/http/server.js‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ const kUpgradeStream = Symbol('UpgradeStream');
121121

122122
const kOptimizeEmptyRequests = Symbol('OptimizeEmptyRequestsOption');
123123
const kConnectionState = Symbol('ConnectionState');
124+
const kCloseCount = Symbol('CloseCount');
124125
const kParserExecuting = Symbol('kParserExecuting');
125126
const kParserDeferred = Symbol('kParserDeferred');
126127
const kResponseOptions = Symbol('ResponseOptions');
@@ -519,12 +520,21 @@ function writeHead(statusCode, reason, obj) {
519520
this.shouldKeepAlive = false;
520521
}
521522

523+
// The last response of a connection whose server is closing must not
524+
// advertise keep-alive: the connection closes once it is done.
525+
const state = this[kConnectionState];
526+
if (state !== undefined && isClosing(state) && isLastResponse(this, state)) {
527+
this.shouldKeepAlive = false;
528+
}
529+
522530
this._storeHeader(statusLine, headers);
523531

524532
return this;
525533
}
526534

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

@@ -647,7 +657,24 @@ function setupConnectionsTracking() {
647657
setInterval(checkConnections.bind(this), this.connectionsCheckingInterval).unref();
648658
}
649659

660+
// A connection is closing if `close()` was called since it was accepted.
661+
// A count rather than a flag, so a later `listen()` doesn't undo it.
662+
function isClosing(state) {
663+
return state.closeCount !== state.server[kCloseCount];
664+
}
665+
666+
// Whether `res` is the last response queued on its connection. While closing,
667+
// only that one ends the connection, so accepted pipelined requests are still
668+
// answered. A queued response has no socket yet, so look at the state instead.
669+
function isLastResponse(res, state) {
670+
const { outgoing } = state;
671+
return outgoing.length > 0 ?
672+
outgoing[outgoing.length - 1] === res :
673+
state.socket._httpMessage === res;
674+
}
675+
650676
function httpServerPreClose(server) {
677+
server[kCloseCount]++;
651678
server.closeIdleConnections();
652679
clearInterval(server[kConnectionsCheckingInterval]);
653680
}
@@ -849,6 +876,7 @@ function connectionListenerInternal(server, socket) {
849876
onPendingData: null,
850877
server,
851878
socket,
879+
closeCount: server[kCloseCount],
852880
};
853881
state.onPendingData = updateOutgoingData.bind(undefined, socket, state);
854882
state.onData = socketOnData.bind(undefined,
@@ -1274,7 +1302,8 @@ function resOnFinish(req, res, socket, state, server) {
12741302
clearIncoming(req);
12751303
process.nextTick(emitCloseNT, res);
12761304

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

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

‎test/parallel/test-http-pipeline-assertionerror-finish.js‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,16 @@ const net = require('net');
1111

1212
const COUNT = 10;
1313

14+
let handled = 0;
1415
const server = http
1516
.createServer(
1617
common.mustCall((req, res) => {
17-
// Close the server, we have only one TCP connection anyway
18-
server.close();
18+
// Close the server once every request has been dispatched, we have only
19+
// one TCP connection anyway. A request that arrives behind a response in
20+
// flight after `server.close()` is not processed.
21+
if (++handled === COUNT) {
22+
server.close();
23+
}
1924
res.writeHead(200);
2025
res.write('data');
2126

‎test/parallel/test-http-pipeline-socket-parser-typeerror.js‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ require('../common');
88
const http = require('http');
99
const net = require('net');
1010

11-
let once = false;
1211
let first = null;
1312
let second = null;
1413

@@ -21,9 +20,6 @@ let done;
2120

2221
const server = http
2322
.createServer((req, res) => {
24-
if (!once) server.close();
25-
once = true;
26-
2723
if (first === null) {
2824
first = res;
2925
return;
@@ -42,6 +38,9 @@ const server = http
4238
done();
4339
})
4440
.on('upgrade', (req, socket) => {
41+
// Every request has been dispatched by now. A request that arrives behind
42+
// a response in flight after `server.close()` is not processed.
43+
server.close();
4544
second.end(chunk, () => {
4645
socket.end();
4746
});

‎test/parallel/test-http-raw-headers.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,15 +93,15 @@ http.createServer(common.mustCall(function(req, res) {
9393
'Date',
9494
null,
9595
'Connection',
96-
'keep-alive',
96+
'close',
9797
'Transfer-Encoding',
9898
'chunked',
9999
];
100100
const expectHeaders = { '__proto__': null,
101101
'keep-alive': 'timeout=1',
102102
'trailer': 'x-foo',
103103
'date': null,
104-
'connection': 'keep-alive',
104+
'connection': 'close',
105105
'transfer-encoding': 'chunked' };
106106
res.rawHeaders[5] = null;
107107
res.headers.date = null;

0 commit comments

Comments
 (0)