Skip to content

Commit 082c0cb

Browse files
committed
http2: wait for session socket writable end on close/destroy
This slightly alters the behaviour of session close by first using .end() on a session socket to finish writing the data and only then calls .destroy() to make sure the Readable side is closed. This allows the socket to finish transmitting data, receive proper FIN packet and avoid ECONNRESET errors upon graceful close. onStreamClose now directly calls stream.destroy() instead of kMaybeDestroy because the latter will first check that the stream has writableFinished set. And that may not be true as we have just (synchronously) called .end() on the stream if it was not closed and that doesn't give it enough time to finish. Furthermore there is no point in waiting for 'finish' as the other party have already closed the stream and we won't be able to write anyway. This also changes a few tests to correctly handle graceful session close. This includes: * not reading request data (on client side) * not reading push stream data (on client side) * relying on socket.destroy() (on client) to finish server session due to the destroy of the socket without closing the server session. As the goaway itself is *not* a session close. Added few 'close' event mustCall checks.
1 parent 0995c29 commit 082c0cb

10 files changed

+101
-45
lines changed

lib/internal/http2/core.js

+71-36
Original file line numberDiff line numberDiff line change
@@ -486,7 +486,10 @@ function onStreamClose(code) {
486486
if (!stream || stream.destroyed)
487487
return false;
488488

489-
debugStreamObj(stream, 'closed with code %d', code);
489+
debugStreamObj(
490+
stream, 'closed with code %d, closed %s, readable %s',
491+
code, stream.closed, stream.readable
492+
);
490493

491494
if (!stream.closed)
492495
closeStream(stream, code, kNoRstStream);
@@ -495,7 +498,7 @@ function onStreamClose(code) {
495498
// Defer destroy we actually emit end.
496499
if (!stream.readable || code !== NGHTTP2_NO_ERROR) {
497500
// If errored or ended, we can destroy immediately.
498-
stream[kMaybeDestroy](code);
501+
stream.destroy();
499502
} else {
500503
// Wait for end to destroy.
501504
stream.on('end', stream[kMaybeDestroy]);
@@ -983,22 +986,76 @@ function emitClose(self, error) {
983986
self.emit('close');
984987
}
985988

986-
function finishSessionDestroy(session, error) {
987-
debugSessionObj(session, 'finishSessionDestroy');
988-
989+
function cleanupSession(session) {
989990
const socket = session[kSocket];
990-
if (!socket.destroyed)
991-
socket.destroy(error);
992-
991+
const handle = session[kHandle];
993992
session[kProxySocket] = undefined;
994993
session[kSocket] = undefined;
995994
session[kHandle] = undefined;
996995
session[kNativeFields] = new Uint8Array(kSessionUint8FieldCount);
997-
socket[kSession] = undefined;
998-
socket[kServer] = undefined;
996+
if (handle)
997+
handle.ondone = null;
998+
if (socket) {
999+
socket[kSession] = undefined;
1000+
socket[kServer] = undefined;
1001+
}
1002+
}
1003+
1004+
function finishSessionClose(session, error) {
1005+
debugSessionObj(session, 'finishSessionClose');
1006+
1007+
const socket = session[kSocket];
1008+
cleanupSession(session);
1009+
1010+
if (socket && !socket.destroyed) {
1011+
// Always wait for writable side to finish.
1012+
socket.end((err) => {
1013+
debugSessionObj(session, 'finishSessionClose socket end', err);
1014+
// Due to the way the underlying stream is handled in Http2Session we
1015+
// won't get graceful Readable end from the other side even if it was sent
1016+
// as the stream is already considered closed and will neither be read
1017+
// from nor keep the event loop alive.
1018+
// Therefore destroy the socket immediately.
1019+
// Fixing this would require some heavy juggling of ReadStart/ReadStop
1020+
// mostly on Windows as on Unix it will be fine with just ReadStart
1021+
// after this 'ondone' callback.
1022+
socket.destroy(error);
1023+
emitClose(session, error);
1024+
});
1025+
} else {
1026+
process.nextTick(emitClose, session, error);
1027+
}
1028+
}
1029+
1030+
function closeSession(session, code, error) {
1031+
debugSessionObj(session, 'start closing/destroying');
1032+
1033+
const state = session[kState];
1034+
state.flags |= SESSION_FLAGS_DESTROYED;
1035+
state.destroyCode = code;
1036+
1037+
// Clear timeout and remove timeout listeners.
1038+
session.setTimeout(0);
1039+
session.removeAllListeners('timeout');
1040+
1041+
// Destroy any pending and open streams
1042+
if (state.pendingStreams.size > 0 || state.streams.size > 0) {
1043+
const cancel = new ERR_HTTP2_STREAM_CANCEL(error);
1044+
state.pendingStreams.forEach((stream) => stream.destroy(cancel));
1045+
state.streams.forEach((stream) => stream.destroy(error));
1046+
}
9991047

1000-
// Finally, emit the close and error events (if necessary) on next tick.
1001-
process.nextTick(emitClose, session, error);
1048+
// Disassociate from the socket and server.
1049+
const socket = session[kSocket];
1050+
const handle = session[kHandle];
1051+
1052+
// Destroy the handle if it exists at this point.
1053+
if (handle !== undefined) {
1054+
handle.ondone = finishSessionClose.bind(null, session, error);
1055+
handle.destroy(code, socket.destroyed);
1056+
} else {
1057+
finishSessionClose(session, error);
1058+
}
10021059
}
10031060

10041061
// Upon creation, the Http2Session takes ownership of the socket. The session
@@ -1325,6 +1382,7 @@ class Http2Session extends EventEmitter {
13251382
destroy(error = NGHTTP2_NO_ERROR, code) {
13261383
if (this.destroyed)
13271384
return;
1385+
13281386
debugSessionObj(this, 'destroying');
13291387

13301388
if (typeof error === 'number') {
@@ -1336,30 +1394,7 @@ class Http2Session extends EventEmitter {
13361394
if (code === undefined && error != null)
13371395
code = NGHTTP2_INTERNAL_ERROR;
13381396

1339-
const state = this[kState];
1340-
state.flags |= SESSION_FLAGS_DESTROYED;
1341-
state.destroyCode = code;
1342-
1343-
// Clear timeout and remove timeout listeners
1344-
this.setTimeout(0);
1345-
this.removeAllListeners('timeout');
1346-
1347-
// Destroy any pending and open streams
1348-
const cancel = new ERR_HTTP2_STREAM_CANCEL(error);
1349-
state.pendingStreams.forEach((stream) => stream.destroy(cancel));
1350-
state.streams.forEach((stream) => stream.destroy(error));
1351-
1352-
// Disassociate from the socket and server
1353-
const socket = this[kSocket];
1354-
const handle = this[kHandle];
1355-
1356-
// Destroy the handle if it exists at this point
1357-
if (handle !== undefined) {
1358-
handle.ondone = finishSessionDestroy.bind(null, this, error);
1359-
handle.destroy(code, socket.destroyed);
1360-
} else {
1361-
finishSessionDestroy(this, error);
1362-
}
1397+
closeSession(this, code, error);
13631398
}
13641399

13651400
// Closing the session will:

src/node_http2.cc

+1-1
Original file line numberDiff line numberDiff line change
@@ -1862,7 +1862,7 @@ void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) {
18621862
Context::Scope context_scope(env()->context());
18631863
Http2Scope h2scope(this);
18641864
CHECK_NOT_NULL(stream_);
1865-
Debug(this, "receiving %d bytes", nread);
1865+
Debug(this, "receiving %d bytes, offset %d", nread, stream_buf_offset_);
18661866
AllocatedBuffer buf(env(), buf_);
18671867

18681868
// Only pass data on if nread > 0

test/parallel/test-http2-capture-rejection.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,6 @@ events.captureRejections = true;
7272
}));
7373
}
7474

75-
7675
{
7776
// Test error thrown in 'request' event
7877

@@ -136,6 +135,7 @@ events.captureRejections = true;
136135
const session = connect(`http://localhost:${port}`);
137136

138137
const req = session.request();
138+
req.resume();
139139

140140
session.on('stream', common.mustCall(async (stream) => {
141141
session.close();

test/parallel/test-http2-client-destroy.js

+1
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ const Countdown = require('../common/countdown');
145145
server.on('stream', common.mustNotCall());
146146
server.listen(0, common.mustCall(() => {
147147
const client = h2.connect(`http://localhost:${server.address().port}`);
148+
client.on('close', common.mustCall());
148149
const socket = client[kSocket];
149150
socket.on('close', common.mustCall(() => {
150151
assert(socket.destroyed);

test/parallel/test-http2-client-stream-destroy-before-connect.js

+7-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ if (!common.hasCrypto)
66
const assert = require('assert');
77
const h2 = require('http2');
88
const NGHTTP2_INTERNAL_ERROR = h2.constants.NGHTTP2_INTERNAL_ERROR;
9+
const Countdown = require('../common/countdown');
910

1011
const server = h2.createServer();
1112

@@ -27,6 +28,11 @@ server.on('stream', (stream) => {
2728

2829
server.listen(0, common.mustCall(() => {
2930
const client = h2.connect(`http://localhost:${server.address().port}`);
31+
const countdown = new Countdown(2, () => {
32+
server.close();
33+
client.close();
34+
});
35+
client.on('connect', () => countdown.dec());
3036

3137
const req = client.request();
3238
req.destroy(new Error('test'));
@@ -39,8 +45,7 @@ server.listen(0, common.mustCall(() => {
3945
req.on('close', common.mustCall(() => {
4046
assert.strictEqual(req.rstCode, NGHTTP2_INTERNAL_ERROR);
4147
assert.strictEqual(req.rstCode, NGHTTP2_INTERNAL_ERROR);
42-
server.close();
43-
client.close();
48+
countdown.dec();
4449
}));
4550

4651
req.on('response', common.mustNotCall());

test/parallel/test-http2-compat-client-upload-reject.js

+2
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,11 @@ fs.readFile(loc, common.mustCall((err, data) => {
2323
res.end();
2424
});
2525
}));
26+
server.on('close', common.mustCall());
2627

2728
server.listen(0, common.mustCall(() => {
2829
const client = http2.connect(`http://localhost:${server.address().port}`);
30+
client.on('close', common.mustCall());
2931

3032
const req = client.request({ ':method': 'POST' });
3133
req.on('response', common.mustCall((headers) => {

test/parallel/test-http2-create-client-connect.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,13 @@ const URL = url.URL;
3838
const client =
3939
h2.connect.apply(null, i)
4040
.on('connect', common.mustCall(() => maybeClose(client)));
41+
client.on('close', common.mustCall());
4142
});
4243

4344
// Will fail because protocol does not match the server.
44-
h2.connect({ port: port, protocol: 'https:' })
45+
const client = h2.connect({ port: port, protocol: 'https:' })
4546
.on('error', common.mustCall(() => serverClose.dec()));
47+
client.on('close', common.mustCall());
4648
}));
4749
}
4850

test/parallel/test-http2-goaway-opaquedata.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,24 @@ const http2 = require('http2');
88

99
const server = http2.createServer();
1010
const data = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
11+
let session;
1112

1213
server.on('stream', common.mustCall((stream) => {
13-
stream.session.goaway(0, 0, data);
14+
session = stream.session;
15+
session.on('close', common.mustCall());
16+
session.goaway(0, 0, data);
1417
stream.respond();
1518
stream.end();
1619
}));
20+
server.on('close', common.mustCall());
1721

1822
server.listen(0, () => {
19-
2023
const client = http2.connect(`http://localhost:${server.address().port}`);
2124
client.once('goaway', common.mustCall((code, lastStreamID, buf) => {
2225
assert.deepStrictEqual(code, 0);
2326
assert.deepStrictEqual(lastStreamID, 1);
2427
assert.deepStrictEqual(data, buf);
28+
session.close();
2529
server.close();
2630
}));
2731
const req = client.request();

test/parallel/test-http2-ping-settings-heapdump.js

+7-2
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,12 @@ for (const variant of ['ping', 'settings']) {
3030
}));
3131

3232
server.listen(0, common.mustCall(() => {
33-
http2.connect(`http://localhost:${server.address().port}`,
34-
common.mustCall());
33+
const client = http2.connect(`http://localhost:${server.address().port}`,
34+
common.mustCall());
35+
client.on('error', (err) => {
36+
// We destroy the session so it's possible to get ECONNRESET here.
37+
if (err.code !== 'ECONNRESET')
38+
throw err;
39+
});
3540
}));
3641
}

test/parallel/test-http2-server-push-stream.js

+2
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ server.listen(0, common.mustCall(() => {
5555
assert.strictEqual(headers['x-push-data'], 'pushed by server');
5656
}));
5757
stream.on('aborted', common.mustNotCall());
58+
// We have to read the data of the push stream to end gracefully.
59+
stream.resume();
5860
}));
5961

6062
let data = '';

0 commit comments

Comments
 (0)