GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — http2: enforce maxSessionMemory for client requests · nodejs/node@929a020

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • doc/api
    • errors.md
  • lib/internal
    • errors.js
    • http2
      • core.js
  • src
    • node_http2.cc
  • test/parallel
    • test-http2-max-session-memory-client-request.js
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎doc/api/errors.md‎

Copy file name to clipboardExpand all lines: doc/api/errors.md
+8Lines changed: 8 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -1764,6 +1764,14 @@ provided.
17641764

17651765
The `Http2Session` closed with a non-zero error code.
17661766

1767+
<a id="ERR_HTTP2_SESSION_MEMORY_EXCEEDED"></a>
1768+
1769+
### `ERR_HTTP2_SESSION_MEMORY_EXCEEDED`
1770+
1771+
A request was rejected before being sent because the `Http2Session` was using
1772+
more memory than its `maxSessionMemory` setting allows. Nothing was sent to the
1773+
peer, so the request can be retried. The session remains usable.
1774+
17671775
<a id="ERR_HTTP2_SETTINGS_CANCEL"></a>
17681776

17691777
### `ERR_HTTP2_SETTINGS_CANCEL`
Collapse file

‎lib/internal/errors.js‎

Copy file name to clipboardExpand all lines: lib/internal/errors.js
+3Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1327,6 +1327,9 @@ E('ERR_HTTP2_SEND_FILE', 'Directories cannot be sent', Error);
13271327
E('ERR_HTTP2_SEND_FILE_NOSEEK',
13281328
'Offset or length can only be specified for regular files', Error);
13291329
E('ERR_HTTP2_SESSION_ERROR', 'Session closed with error code %s', Error);
1330+
E('ERR_HTTP2_SESSION_MEMORY_EXCEEDED',
1331+
'The request was not sent because the session exceeded maxSessionMemory',
1332+
Error);
13301333
E('ERR_HTTP2_SETTINGS_CANCEL', 'HTTP2 session settings canceled', Error);
13311334
E('ERR_HTTP2_SOCKET_BOUND',
13321335
'The socket is already bound to an Http2Session', Error);
Collapse file

‎lib/internal/http2/core.js‎

Copy file name to clipboardExpand all lines: lib/internal/http2/core.js
+8Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ const {
9393
ERR_HTTP2_SEND_FILE,
9494
ERR_HTTP2_SEND_FILE_NOSEEK,
9595
ERR_HTTP2_SESSION_ERROR,
96+
ERR_HTTP2_SESSION_MEMORY_EXCEEDED,
9697
ERR_HTTP2_SETTINGS_CANCEL,
9798
ERR_HTTP2_SOCKET_BOUND,
9899
ERR_HTTP2_SOCKET_UNBOUND,
@@ -894,6 +895,13 @@ function requestOnConnect(headersList, options) {
894895
// For the first two, emit the error on the session,
895896
// For the third, emit the error on the stream, it will bubble up to the
896897
// session if not handled.
898+
if (ret === false) {
899+
// The session is over its `maxSessionMemory` budget. The request was never
900+
// submitted to nghttp2, so nothing reached the peer; only this request is
901+
// rejected and the session itself stays usable.
902+
this.destroy(new ERR_HTTP2_SESSION_MEMORY_EXCEEDED());
903+
return;
904+
}
897905
if (typeof ret === 'number') {
898906
let err;
899907
switch (ret) {
Collapse file

‎src/node_http2.cc‎

Copy file name to clipboardExpand all lines: src/node_http2.cc
+13Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3166,6 +3166,19 @@ void Http2Session::Request(const FunctionCallbackInfo<Value>& args) {
31663166
return;
31673167
}
31683168

3169+
// maxSessionMemory is documented to reject new streams while the limit is
3170+
// exceeded. CanAddStream() enforces that for peer-initiated streams; apply
3171+
// the same memory check to locally initiated requests so that a session
3172+
// whose socket is not draining cannot queue frames without bound. Like the
3173+
// response header check, queued request bodies are not counted, so large
3174+
// uploads do not prevent unrelated requests on the same session.
3175+
if (!session->has_available_session_memory(sizeof(Http2Stream),
3176+
/* exclude_outbound */ true))
3177+
[[unlikely]] {
3178+
Debug(session, "not submitting request: session memory limit exceeded");
3179+
return args.GetReturnValue().Set(false);
3180+
}
3181+
31693182
Debug(session, "request submitted");
31703183

31713184
int32_t ret = 0;
Collapse file

‎test/parallel/test-http2-max-session-memory-client-request.js‎

Copy file name to clipboard
+167Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
if (!common.hasCrypto)
5+
common.skip('missing crypto');
6+
7+
const assert = require('assert');
8+
const http2 = require('http2');
9+
const net = require('net');
10+
const { once } = require('events');
11+
12+
// maxSessionMemory is documented to reject new streams while the limit is
13+
// exceeded. Make sure that also holds for requests initiated by a client
14+
// session, so that a peer that does not read cannot make the client queue
15+
// frames without bound. As for response headers, request bodies that are
16+
// queued waiting for flow control are not counted, so a large upload does not
17+
// prevent unrelated requests on the same session.
18+
19+
async function queuedUploadDoesNotBlockRequests() {
20+
// The server never opens its flow-control window, so the upload stays queued
21+
// in the client session.
22+
const server = http2.createServer({ settings: { initialWindowSize: 0 } });
23+
server.on('stream', common.mustCall((stream) => {
24+
stream.on('error', () => {});
25+
}, 2));
26+
server.listen(0);
27+
await once(server, 'listening');
28+
29+
const client = http2.connect(`http://localhost:${server.address().port}`, {
30+
maxSessionMemory: 1,
31+
});
32+
client.on('error', common.mustNotCall());
33+
await once(client, 'remoteSettings');
34+
35+
const uploadArrived = once(server, 'stream');
36+
const upload = client.request({ ':method': 'POST', ':path': '/upload' });
37+
upload.on('error', () => {});
38+
upload.end(Buffer.alloc(4 * 1024 * 1024));
39+
await uploadArrived;
40+
41+
const other = client.request({ ':path': '/other' });
42+
other.on('error', () => {});
43+
await once(server, 'stream');
44+
45+
other.destroy();
46+
upload.destroy();
47+
client.destroy();
48+
server.close();
49+
}
50+
51+
// A minimal HTTP/2 peer on a plain TCP socket, so that it can genuinely stop
52+
// reading. It acknowledges SETTINGS and answers every request with
53+
// `:status: 200` and END_STREAM, which closes the stream.
54+
function respondingPeer(socket) {
55+
socket.write(Buffer.from([0, 0, 0, 4, 0, 0, 0, 0, 0])); // SETTINGS
56+
let buffered = Buffer.alloc(0);
57+
let prefaceSeen = false;
58+
socket.on('data', (chunk) => {
59+
buffered = Buffer.concat([buffered, chunk]);
60+
if (!prefaceSeen) {
61+
if (buffered.length < 24) return;
62+
buffered = buffered.subarray(24);
63+
prefaceSeen = true;
64+
}
65+
while (buffered.length >= 9) {
66+
const length = buffered.readUIntBE(0, 3);
67+
if (buffered.length < 9 + length) return;
68+
const type = buffered[3];
69+
const flags = buffered[4];
70+
const streamId = buffered.readUInt32BE(5) & 0x7fffffff;
71+
buffered = buffered.subarray(9 + length);
72+
if (type === 4 && !(flags & 1)) {
73+
socket.write(Buffer.from([0, 0, 0, 4, 1, 0, 0, 0, 0])); // SETTINGS ACK
74+
} else if (type === 1) {
75+
// HEADERS, END_STREAM | END_HEADERS, ':status: 200' (static index 8).
76+
const frame = Buffer.from([0, 0, 1, 1, 5, 0, 0, 0, 0, 0x88]);
77+
frame.writeUInt32BE(streamId, 5);
78+
socket.write(frame);
79+
}
80+
}
81+
});
82+
}
83+
84+
async function stalledPeerRejectsRequestsAndSessionRecovers(stall) {
85+
// Requests are submitted in batches that yield to the event loop, so their
86+
// frames are written to the socket. While the peer answers them, streams
87+
// close and nothing is rejected; once it stops reading, no responses arrive,
88+
// so streams stay open and accumulate until maxSessionMemory rejects new
89+
// requests.
90+
let peerSocket;
91+
const server = net.createServer((socket) => {
92+
peerSocket = socket;
93+
respondingPeer(socket);
94+
});
95+
server.listen(0);
96+
await once(server, 'listening');
97+
98+
const client = http2.connect(`http://localhost:${server.address().port}`, {
99+
maxSessionMemory: 1,
100+
});
101+
client.on('error', () => {});
102+
await once(client, 'remoteSettings');
103+
if (stall) peerSocket.pause();
104+
105+
let rejection;
106+
const closed = [];
107+
for (let batch = 0; batch < 200 && rejection === undefined; batch++) {
108+
const batchClosed = [];
109+
for (let i = 0; i < 100; i++) {
110+
const req = client.request({ ':path': '/' });
111+
req.on('error', (err) => {
112+
if (err.code === 'ERR_HTTP2_SESSION_MEMORY_EXCEEDED') rejection ??= err;
113+
});
114+
batchClosed.push(new Promise((resolve) => req.once('close', resolve)));
115+
req.end();
116+
}
117+
closed.push(...batchClosed);
118+
// With a responsive peer, wait for the batch to finish so that the number
119+
// of open streams does not depend on how quickly the peer answers.
120+
await (stall ? new Promise(setImmediate) : Promise.all(batchClosed));
121+
}
122+
123+
if (!stall) {
124+
assert.strictEqual(rejection, undefined);
125+
client.destroy();
126+
peerSocket.destroy();
127+
server.close();
128+
return;
129+
}
130+
131+
assert.ok(rejection, 'expected a request to be rejected');
132+
assert.strictEqual(
133+
rejection.message,
134+
'The request was not sent because the session exceeded maxSessionMemory');
135+
assert.strictEqual(client.destroyed, false);
136+
assert.strictEqual(client.closed, false);
137+
138+
// Once the peer reads again it answers the open streams, which close and
139+
// free session memory, so a request that was rejected can be retried on the
140+
// same session.
141+
peerSocket.resume();
142+
await Promise.all(closed);
143+
let retry;
144+
for (;;) {
145+
retry = client.request({ ':path': '/retry' });
146+
retry.resume();
147+
retry.end();
148+
// An accepted request gets its stream ID synchronously.
149+
if (!retry.pending) break;
150+
const [err] = await once(retry, 'error');
151+
assert.strictEqual(err.code, 'ERR_HTTP2_SESSION_MEMORY_EXCEEDED');
152+
await new Promise(setImmediate);
153+
}
154+
await once(retry, 'close');
155+
assert.strictEqual(retry.rstCode, 0);
156+
assert.strictEqual(client.destroyed, false);
157+
158+
client.destroy();
159+
peerSocket.destroy();
160+
server.close();
161+
}
162+
163+
(async () => {
164+
await queuedUploadDoesNotBlockRequests();
165+
await stalledPeerRejectsRequestsAndSessionRecovers(false);
166+
await stalledPeerRejectsRequestsAndSessionRecovers(true);
167+
})().then(common.mustCall());

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.