h2lean 0.11.3 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -69,15 +69,28 @@
69
69
  // _wireDone already tracks these streams for the graceful close; the reset path does not
70
70
  // consult it. Pinned as the excluded shape in test/client/client-rst.test.js.
71
71
  //
72
- // KNOWN DIVERGENCE: settings() submits the seven standard settings only. node also takes
73
- // a `customSettings` object of raw id/value pairs (validateSettings caps it at
74
- // MAX_ADDITIONAL_SETTINGS = 10, updateSettingsBuffer puts the entries on the wire and
75
- // getSettings reflects them back, including an enableConnectProtocol it stores as id 8).
76
- // Here those entries are neither validated nor submitted, so a caller using them gets a
77
- // SETTINGS frame without them rather than node's. The standard-object path -- argument
78
- // checks, id-ordered payload, the (null, localSettings, duration) callback, the
79
- // 'localSettings' event, the 'connect' deferral and the ten-pending-ACK limit -- is
80
- // node's, measured on a live node 26 client against a raw frame-decoding peer.
72
+ // settings() and the initial submission take customSettings, node-shaped and measured on
73
+ // a live node 26 client against a raw frame-decoding peer (test/custom-settings.test.js):
74
+ // entries below the flags slot fold into the named setting at node's enum index (custom
75
+ // id 4 is enum MAX_CONCURRENT_STREAMS, wire id 3), the rest rides the custom section, the
76
+ // packer checks -- id/value ranges, the ten-entry cap, a non-number value skipped -- run
77
+ // where node's run, and the section accumulates into the view localSettings.customSettings
78
+ // reports at submit, before the ACK moves the named values. Two things still differ.
79
+ // nghttp2 refuses to SUBMIT a frame whose folded values it considers invalid -- custom id
80
+ // 1 with a value other than 0/1 (ENABLE_PUSH), id 2 above 2**31-1 (INITIAL_WINDOW_SIZE),
81
+ // id 6 other than 0/1 (ENABLE_CONNECT_PROTOCOL) -- and node dies with a native abort;
82
+ // h2lean has no C layer to abort and sends the frame instead. And localSettings is
83
+ // readable before the socket connects: node answers {} while connecting, h2lean the
84
+ // option bag's values, and the custom view appears at the setup call here, where node's
85
+ // appears at its setup call too.
86
+ //
87
+ // The standard-object path -- argument checks, id-ordered payload, the (null,
88
+ // localSettings, duration) callback, the 'localSettings' event, the 'connect' deferral
89
+ // and the ten-pending-ACK limit -- is node's, measured on a live node 26 client against a
90
+ // raw frame-decoding peer. The server half submits only the entries the current call
91
+ // names too (lib/session.js settings(): node's shape, measured on a live node server --
92
+ // two calls produced 5=32768 then 3=5), pinned as parity in
93
+ // test/settings-validation.test.js.
81
94
  //
82
95
  // destroy() terminates the connection the way node's closeSession does: the derived code
83
96
  // goes out as GOAWAY(last=0, code) before the socket goes, preceded by a RST_STREAM for
@@ -114,7 +127,7 @@
114
127
  const { EventEmitter } = require('node:events');
115
128
  const tls = require('node:tls');
116
129
  const f = require('./frames');
117
- const { Decoder, Encoder, HPackError, latin1 } = require('./hpack');
130
+ const { Decoder, Encoder, HPackError } = require('./hpack');
118
131
  const FlatList = require('./flat-list');
119
132
  const fastTick = require('./fast-tick');
120
133
  // The process-wide inbound decode scratch, same shape and size as the server
@@ -134,7 +147,9 @@ const {
134
147
  OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID, ID_BY_SETTING, BODY_MIN, MAX_OUT_BATCH,
135
148
  STAGE_MIN, MAX_SHAPES, MAX_SEND_BLOCK, PRIORITY_SPECLEN,
136
149
  strictSingleValueFields, hashBlock, hashPieces, kBoundSession,
137
- proxySocketHandler, urlOrigin, parseAltSvc, parseOrigins, received, extError
150
+ proxySocketHandler, urlOrigin, parseAltSvc, parseOrigins, received, extError, checkPing,
151
+ pingCancelled, checkSettings, buildSubmission, submissionValues, accumulateCustom,
152
+ customView, checkRemoteCustomEntries
138
153
  } = require('./session');
139
154
 
140
155
  const {
@@ -176,64 +191,9 @@ function payloadMeaningless(method) {
176
191
  || method === 'OPTIONS' || method === 'TRACE';
177
192
  }
178
193
 
179
- // The ranges validateSettings applies (internal/http2/core.js), whose limits are
180
- // kMaxInt = 2**32-1, kMaxInitialWindowSize = 2**31-1, kMaxFrameSize = 2**24-1 and
181
- // kMaxStreams = 2**32-1. maxFrameSize is the only one with a non-zero floor: RFC 9113
182
- // 6.5.2 defines SETTINGS_MAX_FRAME_SIZE as 16384..16777215.
183
- const SETTINGS_RANGE = {
184
- headerTableSize: [0, 0xffffffff],
185
- initialWindowSize: [0, 0x7fffffff],
186
- maxFrameSize: [16384, 0xffffff],
187
- maxConcurrentStreams: [0, 0xffffffff],
188
- maxHeaderListSize: [0, 0xffffffff],
189
- maxHeaderSize: [0, 0xffffffff]
190
- };
191
-
192
- // ERR_HTTP2_INVALID_SETTING_VALUE is a TypeError, not ERR_OUT_OF_RANGE, and its message
193
- // names the setting and the value only; .actual is always set and .min/.max only for a
194
- // range check (internal/errors.js: the factory takes min/max defaulting to undefined).
195
- // Measured on a live node 26 client: {maxFrameSize: 100} and {headerTableSize: -1} both
196
- // report `Invalid value for setting "<name>": <value>`, and so does {enablePush: 1},
197
- // which is a type check rather than a range one and carries no .min.
198
- function invalidSetting(name, value, min, max) {
199
- const err = new TypeError(`Invalid value for setting "${name}": ${value}`);
200
- err.code = 'ERR_HTTP2_INVALID_SETTING_VALUE';
201
- err.actual = value;
202
- if (min !== undefined) {
203
- err.min = min;
204
- err.max = max;
205
- }
206
- return err;
207
- }
208
-
209
- // assertIsObject + validateSettings, in node's order. undefined is legal -- it submits an
210
- // empty SETTINGS frame -- while null, a string and an array are ERR_INVALID_ARG_TYPE;
211
- // a Buffer is an object whose setting properties are all undefined, so it passes and
212
- // submits nothing (both measured). An unknown key is ignored, not refused.
213
- function checkSettings(settings) {
214
- if (settings === undefined) {
215
- return;
216
- }
217
- if (settings === null || typeof settings !== 'object' || Array.isArray(settings)) {
218
- throw extError('ERR_INVALID_ARG_TYPE',
219
- `The "settings" argument must be of type object. Received ${received(settings)}`);
220
- }
221
- for (const name of Object.keys(SETTINGS_RANGE)) {
222
- const value = settings[name];
223
- if (value === undefined) {
224
- continue;
225
- }
226
- const [min, max] = SETTINGS_RANGE[name];
227
- if (typeof value !== 'number' || value < min || value > max) {
228
- throw invalidSetting(name, value, min, max);
229
- }
230
- }
231
- for (const name of ['enablePush', 'enableConnectProtocol']) {
232
- if (settings[name] !== undefined && typeof settings[name] !== 'boolean') {
233
- throw invalidSetting(name, settings[name]);
234
- }
235
- }
236
- }
194
+ // assertIsObject + validateSettings live in lib/session.js as checkSettings, beside checkPing:
195
+ // settings() and ping() are methods of node's Http2Session, so both halves of this library take
196
+ // both validators from the same place.
237
197
 
238
198
  // The request method request() fills ':method' from when the application did not
239
199
  // supply one. Hoisted for reuse, not for speed: V8 interns string literals, so the
@@ -259,6 +219,10 @@ class ClientHttp2Session extends EventEmitter {
259
219
  }
260
220
  socket[kBoundSession] = this;
261
221
  this._socket = socket;
222
+ // Read by _setup at the setup call -- the socket's connect event for a connecting
223
+ // socket, the constructor tail for an already-connected one -- where node's
224
+ // setupHandle re-runs settings() (core.js binds setupHandle to the whole options).
225
+ this._opts = opts;
262
226
  // Every deferred callback this session schedules runs through ONE route:
263
227
  // node's own tick queue (default) or the shared batched pump of
264
228
  // lib/fast-tick.js (`batchNextTick: true`) -- see session.js. Streams and
@@ -305,11 +269,21 @@ class ClientHttp2Session extends EventEmitter {
305
269
  enableConnectProtocol: false,
306
270
  ...opts.settings
307
271
  };
272
+ // maxHeaderSize is the deprecated alias of maxHeaderListSize and wins whenever the
273
+ // two differ (updateSettingsBuffer); node warns at the pack, which for this half is
274
+ // the setup call -- _setup below -- so the movement here stays silent. The client
275
+ // enforces no inbound header-list bound, so nothing guard-coupled rides on it.
308
276
  if (typeof opts.settings?.maxHeaderSize === 'number'
309
- && opts.settings.maxHeaderListSize === undefined) {
277
+ && opts.settings.maxHeaderSize !== this.localSettings.maxHeaderListSize) {
310
278
  this.localSettings.maxHeaderListSize = opts.settings.maxHeaderSize;
311
279
  }
312
280
  this.localSettings.maxHeaderSize = this.localSettings.maxHeaderListSize;
281
+ // The custom entries this side has SUBMITTED (accumulated for the view) and the
282
+ // declared/received pair the peer's customs surface through (see _applySettings).
283
+ // Filled by _setup, where node's setupHandle runs.
284
+ this._customEntries = new Map();
285
+ this._remoteCustomIds = new Set(opts.remoteCustomSettings || []);
286
+ this._remoteCustomValues = new Map();
313
287
  // SETTINGS submits awaiting an ACK, and the callbacks they owe, oldest first. The
314
288
  // public pendingSettingsAck stays the boolean it has always been; node's own getter
315
289
  // is `pendingAck > 0` (core.js), so the counter is what makes it accurate when more
@@ -477,8 +451,12 @@ class ClientHttp2Session extends EventEmitter {
477
451
  // rstCode from `goawayCode || destroyCode` (core.js:2503), so the number has to be
478
452
  // kept separately from the error object the session reports.
479
453
  this._destroyCode = NO_ERROR;
480
- this._pings = new Map(); // 8-octet payload -> callback
481
- this._pingSeq = 0;
454
+ // One entry per ping awaiting its pong, oldest first: node answers pings out of a queue
455
+ // rather than by matching octets (measured with a raw peer that acknowledges only the
456
+ // second of two outstanding pings -- the FIRST callback fires, with the second ping's
457
+ // octets as its pong). Matching by payload would hand those octets to the wrong callback
458
+ // and, for two identical payloads, lose one of them outright.
459
+ this._pingQ = [];
482
460
  // Response header shapes seen before: the cached object for a block whose bytes
483
461
  // we have already decoded under this dynamic-table state (the server's cache).
484
462
  this._shapes = opts.shapeCache === false ? null : new Map();
@@ -507,15 +485,63 @@ class ClientHttp2Session extends EventEmitter {
507
485
  // under TLS that is 'secureConnect' -- the handshake has to complete and pick
508
486
  // ALPN before the first octet is written (core.js defers setupHandle the same
509
487
  // way: "socket.connecting || socket.secureConnecting"). A createConnection
510
- // socket can already be established, so start immediately then.
488
+ // socket can already be established, so start immediately then -- and node's
489
+ // setupHandle runs synchronously in the constructor there, so the setup (the
490
+ // option validations and the initial submission build) runs unguarded and a
491
+ // refused value throws out of connect().
511
492
  if (socket.connecting || socket.secureConnecting) {
512
493
  const ev = socket instanceof tls.TLSSocket ? 'secureConnect' : 'connect';
513
- socket.once(ev, () => this._start());
494
+ socket.once(ev, () => {
495
+ // node wraps the deferred setupFn in try/catch and destroys the socket with
496
+ // the error (core.js setupHandle's caller): the session reports it through
497
+ // 'error' and no 'connect' fires -- measured on a live node client with
498
+ // remoteCustomSettings: ['x'] (ERR_HTTP2_INVALID_SETTING_VALUE, no uncaught).
499
+ try {
500
+ this._setup();
501
+ } catch (err) {
502
+ this._socket.destroy(err);
503
+ return;
504
+ }
505
+ this._start();
506
+ });
514
507
  } else {
508
+ this._setup();
515
509
  this._start();
516
510
  }
517
511
  }
518
512
 
513
+ // node's setupHandle, in its order: the declared remote custom ids are imported
514
+ // (remoteCustomSettingsToBuffer), then options.settings re-runs through settings() --
515
+ // validateSettings and the packer, whose throw for a refused value (a custom id of 0,
516
+ // say) lands where node's lands: escaping connect() for an already-connected socket,
517
+ // reaching 'error' through socket.destroy(error) for a connecting one. The build
518
+ // parks the initial frame for _sendSettings and accumulates the section into the
519
+ // custom view; the fold-converted named values ride the initial ACK slot, because
520
+ // named values take effect at ACK on this half (see _settingsAcks).
521
+ _setup() {
522
+ const opts = this._opts;
523
+ checkRemoteCustomEntries(opts.remoteCustomSettings);
524
+ checkSettings(opts.settings);
525
+ const built = buildSubmission(submissionValues(opts.settings, this._advertised),
526
+ opts.settings?.customSettings);
527
+ this._initialSettings = built.body;
528
+ this._initialAckValues = built.ackValues;
529
+ this._addCustomEntries(built.rest);
530
+ }
531
+
532
+ // Joins one submission's custom section into the session's accumulated view: node
533
+ // accumulates at submit (node_http2.cc UpdateLocalCustomSettings) and getSettings
534
+ // reads the list back, so localSettings.customSettings appears as soon as a custom
535
+ // entry was submitted and keeps every entry ever submitted (see accumulateCustom).
536
+ _addCustomEntries(rest) {
537
+ accumulateCustom(rest, this._customEntries);
538
+ if (this._customEntries.size === 0) {
539
+ delete this.localSettings.customSettings;
540
+ } else {
541
+ this.localSettings.customSettings = customView(this._customEntries);
542
+ }
543
+ }
544
+
519
545
  // ---- start / connect --------------------------------------------------------
520
546
  _start() {
521
547
  if (this._started) {
@@ -545,7 +571,7 @@ class ClientHttp2Session extends EventEmitter {
545
571
  const preQueued = this._outQ;
546
572
  this._outQ = [];
547
573
  this._need(PREFACE_LEN);
548
- PREFACE.copy(this._stage, this._stageLen);
574
+ f.copyInto(this._stage, this._stageLen, PREFACE, 0, PREFACE_LEN);
549
575
  this._stageLen += PREFACE_LEN;
550
576
  this._outLen += PREFACE_LEN;
551
577
  this._sendSettings();
@@ -616,7 +642,7 @@ class ClientHttp2Session extends EventEmitter {
616
642
  const off = this._stageLen;
617
643
  writeHeader(this._stage, off, len, type, flags, sid);
618
644
  if (len) {
619
- payload.copy(this._stage, off + HEADER_LEN);
645
+ f.copyInto(this._stage, off + HEADER_LEN, payload, 0, len);
620
646
  }
621
647
  this._stageLen = off + HEADER_LEN + len;
622
648
  }
@@ -740,26 +766,20 @@ class ClientHttp2Session extends EventEmitter {
740
766
  }
741
767
 
742
768
  _sendSettings() {
743
- const s = this.localSettings;
744
- const names = [...this._advertised].filter((k) => ID_BY_SETTING[k] !== undefined
745
- && s[k] !== undefined);
746
- const body = Buffer.allocUnsafe(names.length * 6);
747
- for (let i = 0; i < names.length; i++) {
748
- const name = names[i];
749
- const value = typeof s[name] === 'boolean' ? (s[name] ? 1 : 0) : s[name];
750
- const at = i * 6;
751
- body.writeUInt16BE(ID_BY_SETTING[name], at);
752
- body.writeUInt32BE(value >>> 0, at + 2);
753
- }
754
- this._frame(SETTINGS, 0, 0, body, true);
769
+ // Built in _setup, where node's setupHandle runs settings() (see the comment
770
+ // there). The initial frame carries the advertised named values, the option bag's
771
+ // folded customs and the custom section.
772
+ this._frame(SETTINGS, 0, 0, this._initialSettings, true);
755
773
  this.pendingSettingsAck = true;
756
774
  this._settingsPending++;
757
775
  // The connection's own first SETTINGS occupies a slot in the ACK queue with no
758
776
  // callback, exactly as it occupies one in nghttp2's pending count: its ACK emits
759
777
  // 'localSettings' and answers nothing else. Without the slot the first ACK would
760
778
  // answer the application's first settings() call instead, and the callback would
761
- // fire one ACK early (measured against a live node 26 client: event, callback, event).
762
- this._settingsAcks.push({ cb: undefined, values: [] });
779
+ // fire one ACK early (measured against a live node 26 client: event, callback,
780
+ // event). The slot carries the fold-converted named values: named values take
781
+ // effect at ACK on this half.
782
+ this._settingsAcks.push({ cb: undefined, values: this._initialAckValues });
763
783
  }
764
784
 
765
785
  // request(): the node-shaped surface. Accepts an object, an array of pairs, or
@@ -871,7 +891,12 @@ class ClientHttp2Session extends EventEmitter {
871
891
  }
872
892
  stream._origin = `${originScheme === undefined ? this._scheme : originScheme}`
873
893
  + `://${originAuthority === undefined ? this._authority : originAuthority}`;
874
- stream.endAfterHeaders = endStream;
894
+ // The request-side record that HEADERS carried END_STREAM. Not node's public
895
+ // `endAfterHeaders` -- that flag is set only on an inbound stream whose HEADERS
896
+ // carried END_STREAM (core.js onSessionHeaders), and a PUSH_PROMISE cannot carry
897
+ // it (RFC 9113 6.6), so on a client request it never reads true. The pump reads
898
+ // this internal one to suppress an empty trailing DATA (lib/client-stream.js).
899
+ stream._endOnHeaders = endStream;
875
900
  // node's ClientHttp2Session.request() reads options.waitForTrailers to set
876
901
  // STREAM_FLAGS_HAS_TRAILERS on the stream, which is what defers the END_STREAM
877
902
  // on the last DATA and emits 'wantTrailers'. The flag is only meaningful while
@@ -967,6 +992,7 @@ class ClientHttp2Session extends EventEmitter {
967
992
  // Taking the window here, where the stream is actually opened, is what makes it
968
993
  // the peer's number and not the 65535 default the peer may never have chosen.
969
994
  req.stream._sendWin = this.remoteSettings.initialWindowSize;
995
+ req.stream._opened = true;
970
996
  this._streams.set(req.stream.id, req.stream);
971
997
  this._sendRequest(req.stream, req.list, req.nl, req.end, req.hp);
972
998
  }
@@ -986,6 +1012,14 @@ class ClientHttp2Session extends EventEmitter {
986
1012
  'New streams cannot be created after receiving a GOAWAY'));
987
1013
  continue;
988
1014
  }
1015
+ if (req.stream.destroyed) {
1016
+ // The 'connect' tick skips a request the application abandoned while the
1017
+ // socket was still connecting (node's requestOnConnect destroy check); a
1018
+ // request queued behind the concurrency limit abandoned the same way must
1019
+ // not open either -- opening it would frame HEADERS for a stream nobody
1020
+ // holds and set _opened on a torn-down object.
1021
+ continue;
1022
+ }
989
1023
  this._openStream(req);
990
1024
  }
991
1025
  }
@@ -1156,7 +1190,7 @@ class ClientHttp2Session extends EventEmitter {
1156
1190
  if (ul === 0) {
1157
1191
  return buf.subarray(0, off);
1158
1192
  }
1159
- update.copy(buf, 0);
1193
+ f.copyInto(buf, 0, update, 0, update.length);
1160
1194
  return buf.subarray(0, off);
1161
1195
  }
1162
1196
 
@@ -1308,7 +1342,7 @@ class ClientHttp2Session extends EventEmitter {
1308
1342
  // unless the GET put it on HEADERS already.
1309
1343
  if (stream._pending === null && stream._finalCb !== null && stream._writeCb === null
1310
1344
  && !stream._endSent) {
1311
- if (stream.endAfterHeaders) {
1345
+ if (stream._endOnHeaders) {
1312
1346
  stream._writableDone(); return;
1313
1347
  }
1314
1348
  if (deferEs) {
@@ -1402,7 +1436,7 @@ class ClientHttp2Session extends EventEmitter {
1402
1436
  } else {
1403
1437
  // the frame's header is still incomplete: its octets wait in the
1404
1438
  // scratch until the header is whole
1405
- chunk.copy(this._fragHdr, this._frag, i, i + take);
1439
+ f.copyInto(this._fragHdr, this._frag, chunk, i, i + take);
1406
1440
  }
1407
1441
  this._frag += take;
1408
1442
  i += take;
@@ -1438,7 +1472,7 @@ class ClientHttp2Session extends EventEmitter {
1438
1472
  this._fragTarget = null;
1439
1473
  this._fragPieces = null;
1440
1474
  this._frag = n - i;
1441
- chunk.copy(this._fragHdr, 0, i, n);
1475
+ f.copyInto(this._fragHdr, 0, chunk, i, n);
1442
1476
  break;
1443
1477
  }
1444
1478
 
@@ -1573,11 +1607,11 @@ class ClientHttp2Session extends EventEmitter {
1573
1607
  // allocUnsafe rather than Buffer.from(subarray): the pooled allocation is the
1574
1608
  // cheaper way to get a fresh buffer (OPTIMIZATION.md item 18)
1575
1609
  const out = Buffer.allocUnsafe(this._wuLen);
1576
- this._wuBuf.copy(out, 0, 0, this._wuLen);
1610
+ f.copyInto(out, 0, this._wuBuf, 0, this._wuLen);
1577
1611
  this._socket.write(out);
1578
1612
  } else {
1579
1613
  this._need(this._wuLen);
1580
- this._wuBuf.copy(this._stage, this._stageLen, 0, this._wuLen);
1614
+ f.copyInto(this._stage, this._stageLen, this._wuBuf, 0, this._wuLen);
1581
1615
  this._stageLen += this._wuLen;
1582
1616
  this._outLen += this._wuLen;
1583
1617
  this._schedule();
@@ -1642,10 +1676,9 @@ class ClientHttp2Session extends EventEmitter {
1642
1676
  return this._fatal(FRAME_SIZE_ERROR, 'PING payload must be 8 octets');
1643
1677
  }
1644
1678
  if (flags & F_ACK) {
1645
- const key = latin1(buf, start, start + 8);
1646
- const entry = this._pings.get(key);
1679
+ // the oldest ping this side has outstanding, in node's queue order (see _pingQ)
1680
+ const entry = this._pingQ.shift();
1647
1681
  if (entry !== undefined) {
1648
- this._pings.delete(key);
1649
1682
  // node's measured callback shape is (err, duration, pong): duration is a
1650
1683
  // millisecond number and pong is the echoed 8-octet buffer.
1651
1684
  const duration = Number(process.hrtime.bigint() - entry.at) / 1e6;
@@ -1655,15 +1688,26 @@ class ClientHttp2Session extends EventEmitter {
1655
1688
  // application (AGENTS.md 5: issued buffers stay valid). Node's copy
1656
1689
  // comes out of the C++ layer as a fresh buffer, so it does not move
1657
1690
  // under the application there.
1658
- // a fresh 8-octet buffer for the callback; allocUnsafe + copy rather
1659
- // than Buffer.from(subarray) for the pooled allocation
1660
- // (OPTIMIZATION.md item 18)
1691
+ // a fresh 8-octet buffer for the callback; allocUnsafe rather than
1692
+ // Buffer.from(subarray) for the pooled allocation (OPTIMIZATION.md item 18),
1693
+ // and f.copyInto rather than buf.copy because at eight octets the native
1694
+ // call's JS validation floor is the whole cost (26.0 ns against 12.1,
1695
+ // OPTIMIZATION.md item 56). The length check above is load-bearing for the
1696
+ // call -- copy clamps a range past the source, the stores do not.
1661
1697
  const pong = Buffer.allocUnsafe(8);
1662
- buf.copy(pong, 0, start, start + 8);
1698
+ f.copyInto(pong, 0, buf, start, start + 8);
1663
1699
  entry.cb(null, duration, pong);
1664
1700
  }
1665
1701
  } else {
1666
- this._frame(PING, F_ACK, 0, buf.subarray(start, start + 8), true);
1702
+ // A PING the peer originated is answered and then handed to the application: node's
1703
+ // onPing runs on both halves of a connection and emits ('ping', payload). The payload
1704
+ // is a buffer of its own rather than a view of the socket buffer, because the
1705
+ // application may keep it (AGENTS.md 5: issued buffers stay valid), and the same
1706
+ // octets go into the ACK, which _frame copies into the staging buffer.
1707
+ const payload = Buffer.allocUnsafe(8);
1708
+ f.copyInto(payload, 0, buf, start, start + 8);
1709
+ this._frame(PING, F_ACK, 0, payload, true);
1710
+ this.emit('ping', payload);
1667
1711
  }
1668
1712
  return this._open;
1669
1713
  case HEADERS:
@@ -1816,11 +1860,39 @@ class ClientHttp2Session extends EventEmitter {
1816
1860
  for (let i = 0; i + 6 <= len; i += 6) {
1817
1861
  const id = buf.readUInt16BE(start + i);
1818
1862
  const value = buf.readUInt32BE(start + i + 2);
1863
+ // A custom id the session DECLARED via remoteCustomSettings is remembered with its
1864
+ // value and reported back through remoteSettings.customSettings -- node's
1865
+ // HandleSettingsFrame stores received entries whose id is in the list
1866
+ // remoteCustomSettingsToBuffer imported at setupHandle. Id 8 double-reports: the
1867
+ // named enableConnectProtocol AND customSettings {"8": value} (measured on a live
1868
+ // node client declared [7, 8, 1001]). An undeclared id surfaces nowhere.
1869
+ if (id >= 7 && this._remoteCustomIds.has(id)) {
1870
+ this._remoteCustomValues.set(id, value);
1871
+ }
1819
1872
  const name = SETTINGS_BY_ID[id];
1820
1873
  if (name === undefined) {
1821
1874
  continue;
1822
1875
  }
1823
- seen[name] = value;
1876
+ // RFC 9113 6.5.2: SETTINGS_ENABLE_PUSH is a client-only setting; a server that
1877
+ // sends it violates the protocol. Measured on node: GOAWAY(PROTOCOL_ERROR).
1878
+ if (id === 0x2) {
1879
+ this._fatal(PROTOCOL_ERROR, 'SETTINGS_ENABLE_PUSH from server'); return;
1880
+ }
1881
+ // The two boolean settings land in remoteSettings as booleans, the way node's
1882
+ // getSettings turns them (`enablePush: !!slot`, `enableConnectProtocol: !!slot`,
1883
+ // internal/http2/util.js): the wire is a uint32, and handing the raw 0/1 to the
1884
+ // application diverged from node.
1885
+ if (id === 0x2 || id === 0x8) {
1886
+ seen[name] = value !== 0;
1887
+ } else {
1888
+ seen[name] = value;
1889
+ }
1890
+ }
1891
+ // getSettings' mirror: maxHeaderSize always reports maxHeaderListSize, whether or
1892
+ // not the frame carried id 6.
1893
+ seen.maxHeaderSize = seen.maxHeaderListSize;
1894
+ if (this._remoteCustomValues.size !== 0) {
1895
+ this.remoteSettings.customSettings = customView(this._remoteCustomValues);
1824
1896
  }
1825
1897
  // A new INITIAL_WINDOW_SIZE shifts every open stream window by the delta (RFC 9113
1826
1898
  // 6.9.2), and may drive it negative -- the same rule the server applies inbound.
@@ -1936,10 +2008,10 @@ class ClientHttp2Session extends EventEmitter {
1936
2008
  cap *= 2;
1937
2009
  }
1938
2010
  const bigger = Buffer.allocUnsafe(cap);
1939
- this._hdr.copy(bigger, 0, 0, this._hdrLen);
2011
+ f.copyInto(bigger, 0, this._hdr, 0, this._hdrLen);
1940
2012
  this._hdr = bigger;
1941
2013
  }
1942
- buf.copy(this._hdr, this._hdrLen, start, start + len);
2014
+ f.copyInto(this._hdr, this._hdrLen, buf, start, start + len);
1943
2015
  this._hdrLen += len;
1944
2016
  }
1945
2017
 
@@ -2095,6 +2167,7 @@ class ClientHttp2Session extends EventEmitter {
2095
2167
  stream.rstCode = 0;
2096
2168
  stream._headersSent = true;
2097
2169
  stream._endSent = true;
2170
+ stream._opened = true;
2098
2171
  if (promisedSid > this._maxPushSid) {
2099
2172
  this._maxPushSid = promisedSid;
2100
2173
  }
@@ -2378,14 +2451,10 @@ class ClientHttp2Session extends EventEmitter {
2378
2451
  if (stream === undefined) {
2379
2452
  return;
2380
2453
  }
2381
- // Handed over as a view, the way the server hands DATA to its application: it is
2382
- // a slice of the chunk node gave us, which node never rewrites after delivery.
2383
- // A padded frame's payload is a view too -- the pad length and the padding are
2384
- // taken off the views before this point (frames.js trimPadding). The old
2385
- // copy-out existed only because the client used to accumulate every read into a
2386
- // shared buffer it reused -- that buffer is gone.
2387
- stream._onData(buf.subarray(p, p + l));
2388
- // Book the consumed bytes as credit owed to BOTH windows; the frames themselves
2454
+ // Book the consumed bytes as credit owed to BOTH windows ahead of the hand-over:
2455
+ // a synchronous consumer inside the 'data' event must see the window already
2456
+ // shrunken, node's shape (16384 consumed reads 49151 from the state getter at
2457
+ // the last data event, before any credit pass could run). The frames themselves
2389
2458
  // wait for the half-window threshold at the end of this read batch. Marking the
2390
2459
  // stream in _debt is what tells that pass which streams to visit.
2391
2460
  if (l > 0) {
@@ -2395,6 +2464,13 @@ class ClientHttp2Session extends EventEmitter {
2395
2464
  stream._debtMarked = true; this._debt.push(stream);
2396
2465
  }
2397
2466
  }
2467
+ // Handed over as a view, the way the server hands DATA to its application: it is
2468
+ // a slice of the chunk node gave us, which node never rewrites after delivery.
2469
+ // A padded frame's payload is a view too -- the pad length and the padding are
2470
+ // taken off the views before this point (frames.js trimPadding). The old
2471
+ // copy-out existed only because the client used to accumulate every read into a
2472
+ // shared buffer it reused -- that buffer is gone.
2473
+ stream._onData(buf.subarray(p, p + l));
2398
2474
  if (flags & F_END_STREAM) {
2399
2475
  stream._endRead(); this._dropStream(sid);
2400
2476
  }
@@ -2408,16 +2484,8 @@ class ClientHttp2Session extends EventEmitter {
2408
2484
  if (stream === undefined) {
2409
2485
  return;
2410
2486
  }
2411
- for (let i = 0; i < pieces.length; i++) {
2412
- // A piece the padding took all of is empty, and an empty chunk is not a
2413
- // chunk: node emits no 'data' for one.
2414
- if (pieces[i] !== null) {
2415
- stream._onData(pieces[i]);
2416
- }
2417
- }
2418
- // Book the consumed bytes as credit owed to BOTH windows; the frames themselves
2419
- // wait for the half-window threshold at the end of this read batch. Marking the
2420
- // stream in _debt is what tells that pass which streams to visit.
2487
+ // Book ahead of the hand-over, the same shape _onDataFrame uses: a synchronous
2488
+ // 'data' consumer sees the window already shrunken, node's shape.
2421
2489
  if (total > 0) {
2422
2490
  this._connRecvUsed += total;
2423
2491
  stream._recvUsed += total;
@@ -2425,6 +2493,13 @@ class ClientHttp2Session extends EventEmitter {
2425
2493
  stream._debtMarked = true; this._debt.push(stream);
2426
2494
  }
2427
2495
  }
2496
+ for (let i = 0; i < pieces.length; i++) {
2497
+ // A piece the padding took all of is empty, and an empty chunk is not a
2498
+ // chunk: node emits no 'data' for one.
2499
+ if (pieces[i] !== null) {
2500
+ stream._onData(pieces[i]);
2501
+ }
2502
+ }
2428
2503
  if (flags & F_END_STREAM) {
2429
2504
  stream._endRead(); this._dropStream(sid);
2430
2505
  }
@@ -2496,7 +2571,7 @@ class ClientHttp2Session extends EventEmitter {
2496
2571
  // allocUnsafe + copy rather than Buffer.from(subarray) for the pooled
2497
2572
  // allocation (OPTIMIZATION.md item 18)
2498
2573
  debug = Buffer.allocUnsafe(len - 8);
2499
- buf.copy(debug, 0, start + 8, start + len);
2574
+ f.copyInto(debug, 0, buf, start + 8, start + len);
2500
2575
  }
2501
2576
  this._goawayCode = code;
2502
2577
  this._goawayLastStreamID = lastStreamID;
@@ -2573,7 +2648,7 @@ class ClientHttp2Session extends EventEmitter {
2573
2648
  const len = this._wuLen;
2574
2649
  if (len + HEADER_LEN + 4 > buf.length) {
2575
2650
  const bigger = Buffer.allocUnsafe((len + HEADER_LEN + 4) * 2);
2576
- buf.copy(bigger, 0, 0, len);
2651
+ f.copyInto(bigger, 0, buf, 0, len);
2577
2652
  buf = this._wuBuf = bigger;
2578
2653
  }
2579
2654
  writeHeader(buf, len, 4, WINDOW_UPDATE, 0, sid);
@@ -2582,35 +2657,49 @@ class ClientHttp2Session extends EventEmitter {
2582
2657
  }
2583
2658
 
2584
2659
  // ---- session API ------------------------------------------------------------
2660
+ // node cancels the pings whose pong can no longer arrive with ERR_HTTP2_PING_CANCEL, off the
2661
+ // synchronous teardown: measured unfired both inside destroy() and on process.nextTick, fired
2662
+ // by setImmediate. Without it an application's ping callback simply never runs when the
2663
+ // connection dies with a ping outstanding, and the entry stays in the map.
2664
+ _cancelPings() {
2665
+ if (this._pingQ.length === 0) {
2666
+ return;
2667
+ }
2668
+ const pending = this._pingQ;
2669
+ this._pingQ = [];
2670
+ setImmediate(() => {
2671
+ for (const entry of pending) {
2672
+ entry.cb(pingCancelled());
2673
+ }
2674
+ });
2675
+ }
2676
+
2677
+ // The validation is the server's checkPing, shared so the two halves of this library answer
2678
+ // the same call the same way -- which is also how node does it, since ping() lives on
2679
+ // Http2Session and both classes inherit it.
2585
2680
  ping(payload, cb) {
2586
2681
  if (this.destroyed) {
2587
2682
  throw httpErr('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed');
2588
2683
  }
2589
- // node lets a caller pass the callback as the only argument: ping(cb).
2590
- if (typeof payload === 'function') {
2591
- cb = payload; payload = undefined;
2592
- }
2593
- const body = Buffer.allocUnsafe(8);
2594
- if (payload === undefined) {
2595
- const seq = this._pingSeq++;
2596
- body.writeUInt32BE(seq >>> 0, 0);
2597
- body.writeUInt32BE(0, 4);
2598
- } else {
2599
- // Buffer.from(payload) would clone the caller's whole buffer just to take the
2600
- // first eight octets out of it; when the caller already passed a Buffer, copy
2601
- // straight out of it. The fallback keeps whatever else a caller may pass
2602
- // (a Uint8Array, a string) working the way Buffer.from decoded it.
2603
- if (Buffer.isBuffer(payload)) {
2604
- payload.copy(body, 0, 0, 8);
2605
- } else {
2606
- Buffer.from(payload).copy(body, 0, 0, 8);
2607
- }
2608
- }
2609
- if (typeof cb === 'function') {
2610
- this._pings.set(latin1(body, 0, 8), { cb, at: process.hrtime.bigint() });
2611
- }
2684
+ [payload, cb] = checkPing(payload, cb);
2685
+ // A falsy payload sends eight zero octets: node skips the checks there and lets nghttp2
2686
+ // choose them, and nothing depends on the choice, since the pong is matched by position in
2687
+ // the queue rather than by value.
2688
+ const body = payload ? Buffer.allocUnsafe(8) : Buffer.alloc(8);
2689
+ if (payload) {
2690
+ // The length is exactly 8, checked by checkPing. A caller's Buffer is indexed straight;
2691
+ // any other view is re-based onto one first, because a DataView has no numeric indexing
2692
+ // and reading through a TypedArray's backing store would copy the wrong octets.
2693
+ const src = Buffer.isBuffer(payload)
2694
+ ? payload
2695
+ : Buffer.from(payload.buffer, payload.byteOffset, 8);
2696
+ f.copyInto(body, 0, src, 0, 8);
2697
+ }
2698
+ this._pingQ.push({ cb, at: process.hrtime.bigint() });
2612
2699
  this._frame(PING, 0, 0, body, true);
2613
- return body;
2700
+ // node hands back what nghttp2's submit returned (measured: a live node session answers
2701
+ // true), not the octets it put on the wire.
2702
+ return true;
2614
2703
  }
2615
2704
 
2616
2705
  // node's settings() takes a settings OBJECT, not a SETTINGS payload (core.js
@@ -2618,8 +2707,8 @@ class ClientHttp2Session extends EventEmitter {
2618
2707
  // in ascending setting-id order rather than the object's key order: measured on a live
2619
2708
  // node 26 client against a raw peer, {headerTableSize, maxConcurrentStreams, enablePush}
2620
2709
  // arrived as headerTableSize=8192, enablePush=0, maxConcurrentStreams=7. The server
2621
- // side's settings() (lib/session.js) re-advertises everything it has ever advertised
2622
- // instead; this is the client following node, not the server's shape.
2710
+ // side's settings() (lib/session.js) submits only the current call's entries too --
2711
+ // node's shape, measured on a live node server (two calls produced 5=32768 then 3=5).
2623
2712
  settings(settings, cb) {
2624
2713
  if (this.destroyed) {
2625
2714
  throw httpErr('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed');
@@ -2630,6 +2719,11 @@ class ClientHttp2Session extends EventEmitter {
2630
2719
  throw extError('ERR_INVALID_ARG_TYPE',
2631
2720
  `The "callback" argument must be of type function. Received ${received(cb)}`);
2632
2721
  }
2722
+ // node copies the object at the call (submitSettings.bind(this, { ...settings }),
2723
+ // core.js settings()), so a caller mutation between the call and a deferred submit
2724
+ // changes nothing for the named values; the customSettings bag is read at pack time
2725
+ // through the same reference either way.
2726
+ const snapshot = settings && { ...settings };
2633
2727
  const submit = () => {
2634
2728
  // submitSettings returns without submitting on a destroyed session, and the
2635
2729
  // 'connect' listener below can fire after one (core.js).
@@ -2641,44 +2735,21 @@ class ClientHttp2Session extends EventEmitter {
2641
2735
  'Maximum number of pending settings acknowledgements'));
2642
2736
  return;
2643
2737
  }
2644
- const entries = [];
2645
- const values = [];
2646
- if (settings) {
2647
- // maxHeaderSize is the deprecated alias of maxHeaderListSize: it wins when the
2648
- // two differ, and node warns exactly then (internal/http2/util.js
2649
- // updateSettingsBuffer). The wire entry is id 6 either way.
2650
- let listSize = settings.maxHeaderListSize;
2651
- if (typeof settings.maxHeaderSize === 'number') {
2652
- if (settings.maxHeaderSize !== listSize) {
2653
- process.emitWarning('settings.maxHeaderSize overwrite settings.maxHeaderListSize');
2654
- }
2655
- listSize = settings.maxHeaderSize;
2656
- }
2657
- // ID_BY_SETTING is built from SETTINGS_BY_ID in id order, so walking its keys
2658
- // produces the ascending order node submits in without a sort.
2659
- for (const name of Object.keys(ID_BY_SETTING)) {
2660
- const value = name === 'maxHeaderListSize' ? listSize : settings[name];
2661
- if (value === undefined) {
2662
- continue;
2663
- }
2664
- values.push(name, value);
2665
- entries.push(ID_BY_SETTING[name], typeof value === 'boolean' ? (value ? 1 : 0) : value);
2666
- }
2667
- }
2668
- const body = Buffer.allocUnsafe(entries.length * 3);
2669
- for (let i = 0; i < entries.length; i += 2) {
2670
- const at = i * 3;
2671
- body.writeUInt16BE(entries[i], at);
2672
- body.writeUInt32BE(entries[i + 1] >>> 0, at + 2);
2673
- }
2738
+ const built = buildSubmission(submissionValues(snapshot || {}),
2739
+ snapshot?.customSettings);
2740
+ // The custom view accumulates at SUBMIT, not at the ACK: measured on a live node
2741
+ // client, 'connect' already reports the submitted customs while the named values
2742
+ // still read nghttp2's defaults.
2743
+ this._addCustomEntries(built.rest);
2674
2744
  // The values are applied when THIS submit's ACK arrives, not now: measured on a
2675
2745
  // live node 26 client for all seven settings, the first 'localSettings' event (the
2676
2746
  // ACK for the connection's own initial frame) still reports the old value and the
2677
2747
  // second reports the new one -- headerTableSize 8192 arrived as [4096, 8192],
2678
2748
  // maxHeaderListSize 1234 as [4294967295, 1234]. A setting takes effect when it is
2679
- // acknowledged, so the queue entry carries what it will change.
2680
- this._settingsAcks.push({ cb, values });
2681
- this._frame(SETTINGS, 0, 0, body, true);
2749
+ // acknowledged, so the queue entry carries what it will change; a fold lands
2750
+ // converted the way getSettings reports it (buildSubmission's ackValues).
2751
+ this._settingsAcks.push({ cb, values: built.ackValues });
2752
+ this._frame(SETTINGS, 0, 0, built.body, true);
2682
2753
  this._settingsPending++;
2683
2754
  this.pendingSettingsAck = true;
2684
2755
  };
@@ -2896,6 +2967,7 @@ class ClientHttp2Session extends EventEmitter {
2896
2967
  }
2897
2968
  }
2898
2969
  this._streams.clear();
2970
+ this._cancelPings();
2899
2971
  // Requests whose HEADERS never went on the wire are cancelled, not handed the
2900
2972
  // session's error: node distinguishes the two (internal/http2/core.js:1254-1260,
2901
2973
  // state.pendingStreams.forEach((stream) => stream.destroy(cancel))) so an
@@ -3169,6 +3241,7 @@ class ClientHttp2Session extends EventEmitter {
3169
3241
  }
3170
3242
  }
3171
3243
  }
3244
+ this._cancelPings();
3172
3245
  this._queuedReq = null;
3173
3246
  // reassigned, not length-cleared (OPTIMIZATION.md item 38)
3174
3247
  this._outboundQueue = [];