h2lean 0.19.9 → 0.19.13

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.
package/index.js CHANGED
@@ -82,15 +82,15 @@ function getUnpackedSettings(buf, options) {
82
82
  err.code = 'ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH';
83
83
  throw err;
84
84
  }
85
- // The octets are read through a Buffer over the same memory: a Uint8Array is the same
86
- // bytes, and nothing is copied either way.
87
- const src = Buffer.isBuffer(buf)
88
- ? buf
89
- : Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
85
+ // node passes the view straight to internal/buffer's readUInt16BE/readUInt32BE, which
86
+ // index the view by element. For a Buffer (a Uint8Array) element and octet coincide; for
87
+ // a wider typed array node reads word-sized values. Match that instead of wrapping the
88
+ // view in a Buffer, which would change a Uint16Array's meaning (getpackedsettings.test.js).
90
89
  const out = {};
91
90
  for (let i = 0; i + 6 <= buf.length; i += 6) {
92
- const id = src.readUInt16BE(i);
93
- const value = src.readUInt32BE(i + 2);
91
+ const id = buf[i] * 2 ** 8 + buf[i + 1];
92
+ const value = buf[i + 2] * 2 ** 24 + buf[i + 3] * 2 ** 16 +
93
+ buf[i + 4] * 2 ** 8 + buf[i + 5];
94
94
  switch (id) {
95
95
  case 1: out.headerTableSize = value; break;
96
96
  case 2: out.enablePush = value !== 0; break;
@@ -210,6 +210,7 @@ function payloadMeaningless(method) {
210
210
  // supply one. Hoisted for reuse, not for speed: V8 interns string literals, so the
211
211
  // measured position is unchanged (OPTIMIZATION.md item 36).
212
212
  const DEFAULT_METHOD = 'GET';
213
+ const TOO_MANY_INVALID_FRAMES = 'Too many invalid HTTP/2 frames';
213
214
 
214
215
  // node's request() deprecates the priority `weight` option with DEP0194
215
216
  // (internal/http2/core.js setAndValidatePriorityOptions). A module-level
@@ -347,6 +348,14 @@ class Http2ClientSession extends EventEmitter {
347
348
  // counter in node, the count is rebuilt from the live streams here.
348
349
  this._maxReservedRemoteStreams = opts.maxReservedRemoteStreams === undefined
349
350
  ? 200 : opts.maxReservedRemoteStreams;
351
+ // nghttp2 keeps one session-lifetime invalid-frame budget on the client too
352
+ // (node_http2.cc: invalid_frame_count_, default 1000). The counted class on
353
+ // this path is zero-length DATA without END_STREAM; immediate protocol
354
+ // violations are fatal on their own. Measured on v26.12.1: the (limit+2)-th
355
+ // counted frame trips, valid frames never reset the count.
356
+ this._invalidFrames = 0;
357
+ this._maxInvalidFrames = typeof opts.maxSessionInvalidFrames === 'number'
358
+ ? opts.maxSessionInvalidFrames : 1000;
350
359
  this._streams = new Map();
351
360
  // Streams whose wire life is still open. A stream that took END_STREAM stops
352
361
  // counting against the peer's max_concurrent_streams as soon as nghttp2 closes
@@ -397,6 +406,20 @@ class Http2ClientSession extends EventEmitter {
397
406
  // connection's available window: setLocalWindowSize lowers only this one, while
398
407
  // the connection window never shrinks (core.js:1457, measured on v26.12.1).
399
408
  this._effectiveLocalWindowSize = this.localSettings.initialWindowSize;
409
+ // node's connectionWindowSize option (IDX_OPTIONS_CONNECTION_WINDOW_SIZE in
410
+ // internal/http2/util.js) is the connection RECEIVE window, not the send window:
411
+ // it seeds the window we maintain and the size the state getter reports, and
412
+ // _start() grants the peer the delta above 65535 with one WINDOW_UPDATE(0).
413
+ // Node leaves the per-stream windows (SETTINGS_INITIAL_WINDOW_SIZE) and the
414
+ // connection SEND window at their defaults. connect() validates the option.
415
+ if (opts.connectionWindowSize !== undefined) {
416
+ // A WINDOW_UPDATE cannot shrink a live window, so the available connection
417
+ // credit starts at the default even when the option (and the size reported
418
+ // by effectiveLocalWindowSize) is smaller. Measured on v26.12.1: with 1024,
419
+ // localWindowSize stays 65535 while effectiveLocalWindowSize reports 1024.
420
+ this._connRecvWin = Math.max(DEFAULT_WINDOW, opts.connectionWindowSize);
421
+ this._effectiveLocalWindowSize = opts.connectionWindowSize;
422
+ }
400
423
  // Streams that took DATA since the last credit pass. _creditRecv() visits only
401
424
  // these instead of scanning every open stream: with the default 100 concurrent
402
425
  // streams a download that touches one of them used to pay ~100 property reads per
@@ -462,6 +485,9 @@ class Http2ClientSession extends EventEmitter {
462
485
  // the memcpy (BODY_MIN). See _frame/_need/_commit/_writePending, which mirror the
463
486
  // server's queue exactly.
464
487
  this._outQ = [];
488
+ // Bodies of requests whose HEADERS were staged in the current turn. Drained by
489
+ // _flush so every HEADERS of a burst precedes every DATA (see _flush).
490
+ this._bodyQ = null;
465
491
  this._stage = null;
466
492
  this._stageLen = 0; // bytes of _stage not yet queued
467
493
  this._stageCap = STAGE_MIN; // size of the next staging buffer
@@ -631,6 +657,17 @@ class Http2ClientSession extends EventEmitter {
631
657
  this._stageLen += PREFACE_LEN;
632
658
  this._outLen += PREFACE_LEN;
633
659
  this._sendSettings();
660
+ // node's connectionWindowSize raises the connection receive window above the
661
+ // 65535 default by granting the difference with one WINDOW_UPDATE(0) at setup
662
+ // (nghttp2_session_set_local_window_size on stream 0). A value at or below the
663
+ // default cannot shrink the live window: no update goes out (an increment must
664
+ // be positive), which is why the peer still reports 65535 on an upload.
665
+ const cws = this._opts.connectionWindowSize;
666
+ if (cws !== undefined && cws > DEFAULT_WINDOW) {
667
+ const wu = Buffer.allocUnsafe(4);
668
+ wu.writeUInt32BE(cws - DEFAULT_WINDOW, 0);
669
+ this._frame(WINDOW_UPDATE, 0, 0, wu, true);
670
+ }
634
671
  this._flush();
635
672
  if (preQueued.length !== 0) {
636
673
  this._outQ = preQueued;
@@ -783,6 +820,25 @@ class Http2ClientSession extends EventEmitter {
783
820
  }
784
821
 
785
822
  _flush() {
823
+ // Bodies of requests framed in this turn wait until here. node's C++ submits every
824
+ // HEADERS produced by a run of request() calls before it pumps any queued body DATA
825
+ // (measured on v26.12.1 with two requests and end()/write()/end('x') bodies: HEADERS
826
+ // 1, HEADERS 3, then DATA 1 on the wire in all three shapes). Releasing the body in
827
+ // _afterRequestHeaders would instead put DATA 1 between the two HEADERS, so a peer
828
+ // with SETTINGS_MAX_CONCURRENT_STREAMS=1 frees the slot and dispatches a second
829
+ // 'stream' handler where node refuses the second stream (test/upstream/
830
+ // max-concurrent-streams.test.js).
831
+ if (this._bodyQ !== null) {
832
+ const q = this._bodyQ;
833
+ this._bodyQ = null;
834
+ // Frames produced by the pump belong to this flush: the write they schedule
835
+ // is the one just below, not a new microtask.
836
+ this._inBatch = true;
837
+ for (let i = 0; i < q.length; i++) {
838
+ q[i]._bodyDeferred = false;
839
+ this._pump(q[i]);
840
+ }
841
+ }
786
842
  // leaving a batch, whatever the reason: from here on frames are produced outside a
787
843
  // socket read and have to schedule their own write
788
844
  this._inBatch = false;
@@ -1171,7 +1227,12 @@ class Http2ClientSession extends EventEmitter {
1171
1227
  // while pending (core.js:2113). _sendRequest has framed the HEADERS by now;
1172
1228
  // rstStream() would skip the stream because push(null) set _rEof and the
1173
1229
  // empty body set _endSent, so submit the frame here and retire the id the
1174
- // same way rstStream does, before the stream's own teardown runs.
1230
+ // same way rstStream does, before the stream's own teardown runs. The body is
1231
+ // still owed (close(NO_ERROR) after end()), so release it before the reset
1232
+ // retires the id.
1233
+ if (req.stream._bodyDeferred) {
1234
+ this._releaseBody(req.stream);
1235
+ }
1175
1236
  const code = req.stream._pendingCloseCode;
1176
1237
  const body = Buffer.allocUnsafe(4);
1177
1238
  body.writeUInt32BE(code >>> 0, 0);
@@ -1254,13 +1315,15 @@ class Http2ClientSession extends EventEmitter {
1254
1315
  if (key.charCodeAt(0) === 58 /* : */) {
1255
1316
  if (key !== ':method' && key !== ':path' && key !== ':scheme' && key !== ':authority'
1256
1317
  && key !== ':protocol') {
1257
- throw httpErr('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', `cannot send ${key}`);
1318
+ throw httpErr('ERR_HTTP2_INVALID_PSEUDOHEADER',
1319
+ `"${key}" is an invalid pseudoheader or is used incorrectly`, TypeError);
1258
1320
  }
1259
1321
  list.push(key, String(isArray ? rawValue[0] : rawValue), never);
1260
1322
  return;
1261
1323
  }
1262
1324
  if (!isFieldName(key)) {
1263
- throw httpErr('ERR_INVALID_HTTP_TOKEN', `${key} is an invalid header token`);
1325
+ throw httpErr('ERR_INVALID_HTTP_TOKEN',
1326
+ `Header name must be a valid HTTP token ["${key}"]`, TypeError);
1264
1327
  }
1265
1328
  if (CONNECTION_SPECIFIC.has(key)) {
1266
1329
  throw httpErr('ERR_HTTP2_INVALID_CONNECTION_HEADERS',
@@ -1352,15 +1415,39 @@ class Http2ClientSession extends EventEmitter {
1352
1415
  this._afterRequestHeaders(stream);
1353
1416
  }
1354
1417
 
1355
- // HEADERS is now queued; release any body the application wrote before the socket
1356
- // connected (or before this queued request was framed). The DATA frames land in _out
1357
- // behind the HEADERS, so the wire order stays HEADERS -> DATA.
1418
+ // Release a body parked for the flush ahead of a local stream close (NO_ERROR
1419
+ // after end()). The body is still owed to the peer; only the write() queue the
1420
+ // close drops is what this settles.
1421
+ _releaseBody(stream) {
1422
+ if (!stream._bodyDeferred) {
1423
+ return;
1424
+ }
1425
+ stream._bodyDeferred = false;
1426
+ if (this._bodyQ !== null) {
1427
+ const i = this._bodyQ.indexOf(stream);
1428
+ if (i !== -1) {
1429
+ this._bodyQ.splice(i, 1);
1430
+ }
1431
+ }
1432
+ const was = this._inBatch;
1433
+ this._inBatch = true;
1434
+ this._pump(stream);
1435
+ this._inBatch = was;
1436
+ }
1437
+
1438
+ // HEADERS is now queued. The application may still write to the stream later in
1439
+ // this same turn; node's C++ submits every HEADERS of such a burst before any body
1440
+ // DATA, so hold this stream's pump until _flush (which runs after the turn).
1358
1441
  _afterRequestHeaders(stream) {
1359
1442
  stream._headersSent = true;
1360
1443
  stream.headersSent = true;
1361
- if (stream._pending !== null || stream._finalCb !== null) {
1362
- this._pump(stream);
1444
+ if (this._bodyQ === null) {
1445
+ this._bodyQ = [stream];
1446
+ } else {
1447
+ this._bodyQ.push(stream);
1363
1448
  }
1449
+ stream._bodyDeferred = true;
1450
+ this._schedule();
1364
1451
  }
1365
1452
 
1366
1453
  _encodeRequest(list) {
@@ -1548,6 +1635,12 @@ class Http2ClientSession extends EventEmitter {
1548
1635
  // Flow-controlled send for the writable half of a stream. Called from the Duplex's
1549
1636
  // _write/_final and again from WINDOW_UPDATE / SETTINGS to resume a stalled body.
1550
1637
  _pump(stream) {
1638
+ // A body written in the same turn as the request's HEADERS waits for _flush,
1639
+ // which releases it behind every HEADERS of that turn (node's frame order).
1640
+ // Once released the flag is clear and later writes pump inline as before.
1641
+ if (stream._bodyDeferred) {
1642
+ return;
1643
+ }
1551
1644
  // The peer reset this stream. nghttp2 refuses DATA and HEADERS on a closed stream
1552
1645
  // ("After calling close ... no DATA and HEADERS frames may be sent",
1553
1646
  // internal/http2/core.js), but closeStream called end() anyway, so the Duplex still
@@ -1614,6 +1707,12 @@ class Http2ClientSession extends EventEmitter {
1614
1707
  break; // a further write may follow
1615
1708
  }
1616
1709
  }
1710
+ // The write callback asked _driveW for the next chunk. In the trampoline that
1711
+ // request is deferred to the active loop, so do not finalize END_STREAM here
1712
+ // while queued bytes are still owed -- the outer loop frames them first.
1713
+ if (stream._driveAgain) {
1714
+ return;
1715
+ }
1617
1716
  // Everything is framed and we are finalizing: close the message with END_STREAM,
1618
1717
  // unless the GET put it on HEADERS already.
1619
1718
  if (stream._pending === null && stream._finalCb !== null && stream._writeCb === null
@@ -1842,7 +1941,15 @@ class Http2ClientSession extends EventEmitter {
1842
1941
  // out: the release is due when EITHER the half-window step says so or the window the
1843
1942
  // peer may fill without hearing from us drops under the step.
1844
1943
  _creditRecv() {
1845
- const step = Math.min(this._effectiveLocalWindowSize, DEFAULT_WINDOW) >> 1;
1944
+ // The per-stream step stays the conservative half of the smaller of what we
1945
+ // advertise and the 65535 a peer runs with until it reads our SETTINGS:
1946
+ // connectionWindowSize grows the CONNECTION window only, never a stream's
1947
+ // (measured on node: with a 2^21 connection window a stream still releases at
1948
+ // 32767 octets). The connection step is half the window we actually maintain --
1949
+ // with the option that is half the option, node's measured cadence, because the
1950
+ // one setup WINDOW_UPDATE grants the peer that window without waiting for SETTINGS.
1951
+ const streamStep = Math.min(this.localSettings.initialWindowSize, DEFAULT_WINDOW) >> 1;
1952
+ const step = this._effectiveLocalWindowSize >> 1;
1846
1953
  const debt = this._debt;
1847
1954
  // Compacted in place: a stream whose bytes have not yet crossed the half-window
1848
1955
  // step STAYS in the list (and stays marked), because the credit it owes is only
@@ -1851,7 +1958,7 @@ class Http2ClientSession extends EventEmitter {
1851
1958
  let k = 0;
1852
1959
  for (let i = 0; i < debt.length; i++) {
1853
1960
  const stream = debt[i];
1854
- if (stream._recvUsed >= step) {
1961
+ if (stream._recvUsed >= streamStep) {
1855
1962
  const inc = stream._recvUsed;
1856
1963
  stream._recvUsed = 0;
1857
1964
  stream._debtMarked = false;
@@ -2160,6 +2267,19 @@ class Http2ClientSession extends EventEmitter {
2160
2267
  if (id === 0x2) {
2161
2268
  this._fatal(PROTOCOL_ERROR, 'SETTINGS_ENABLE_PUSH from server'); return;
2162
2269
  }
2270
+ // Extended CONNECT cannot be turned off once the peer advertised it. node's
2271
+ // client ends the session with ERR_HTTP2_ERROR "Protocol error" when a server
2272
+ // sends SETTINGS_ENABLE_CONNECT_PROTOCOL=0 after having sent 1 (measured,
2273
+ // test/upstream/connect-method-extended-cant-turn-off.test.js). The fatal is
2274
+ // deferred to an immediate: the SETTINGS frame must finish -- 'remoteSettings'
2275
+ // still reports the value it had when the request was submitted -- and a tick
2276
+ // would run before the request's promise microtasks and report
2277
+ // ERR_HTTP2_INVALID_SESSION instead of node's error. _fatal() supplies the
2278
+ // GOAWAY, the session error and the request error with rstCode 2.
2279
+ if (id === 0x8 && value === 0 && seen.enableConnectProtocol === true) {
2280
+ setImmediate(() => this._fatal(PROTOCOL_ERROR,
2281
+ 'SETTINGS: server attempted to disable SETTINGS_ENABLE_CONNECT_PROTOCOL'));
2282
+ }
2163
2283
  // The two boolean settings land in remoteSettings as booleans, the way node's
2164
2284
  // getSettings turns them (`enablePush: !!slot`, `enableConnectProtocol: !!slot`,
2165
2285
  // internal/http2/util.js): the wire is a uint32, and handing the raw 0/1 to the
@@ -2539,7 +2659,11 @@ class Http2ClientSession extends EventEmitter {
2539
2659
  ? hit.block.equals(block)
2540
2660
  : pieceEquals(hit.block, pieces, from, to))) {
2541
2661
  this._shapeHits++;
2542
- fields = hit.flat;
2662
+ // The cached flat array is shared by every response of this shape. The
2663
+ // stream hands it out as the third 'response' argument (rawHeaders), which
2664
+ // the application may mutate, so each response gets its own copy. On a
2665
+ // decode the field list is already a per-response slice and needs none.
2666
+ fields = hit.flat.slice();
2543
2667
  fcount = fields.length;
2544
2668
  blockFlags = hit.flags;
2545
2669
  } else {
@@ -2553,8 +2677,10 @@ class Http2ClientSession extends EventEmitter {
2553
2677
  blockFlags = this._decoder.neverCount > 0 ? this._decoder.neverFlags : null;
2554
2678
  // The field list the stream holds must outlive this decode: the
2555
2679
  // scratch's backing array is cleared in place by the next one. The copy
2556
- // that caches the shape serves the stream too; without a cache entry
2557
- // the copy is the stream's own.
2680
+ // that caches the shape is a separate snapshot -- handing the same array
2681
+ // to the stream would let a 'response'/'push' listener mutate the cache
2682
+ // entry and poison every later response of that shape. Without a cache
2683
+ // entry the copy is the stream's own.
2558
2684
  let copy = null;
2559
2685
  if (shapes !== null) {
2560
2686
  if (++this._shapeMisses > 64 && this._shapeHits * 4 < this._shapeMisses) {
@@ -2573,7 +2699,7 @@ class Http2ClientSession extends EventEmitter {
2573
2699
  });
2574
2700
  }
2575
2701
  }
2576
- fields = copy !== null ? copy : fields.slice(0, fcount);
2702
+ fields = copy !== null ? copy.slice() : fields.slice(0, fcount);
2577
2703
  }
2578
2704
  } catch (err) {
2579
2705
  if (err instanceof HPackError) {
@@ -2747,6 +2873,17 @@ class Http2ClientSession extends EventEmitter {
2747
2873
  if (stream === undefined) {
2748
2874
  return;
2749
2875
  }
2876
+ // A zero-length DATA without END_STREAM is one of the two frame classes nghttp2
2877
+ // counts against maxSessionInvalidFrames (node_http2.cc HandleDataFrame). On the
2878
+ // trip the stream and the session both report node's custom error code and the
2879
+ // session answers GOAWAY(INTERNAL_ERROR) with no debug data.
2880
+ if (l === 0 && (flags & F_END_STREAM) === 0 && this._recordInvalidFrame()) {
2881
+ const err = httpErr('ERR_HTTP2_TOO_MANY_INVALID_FRAMES', TOO_MANY_INVALID_FRAMES);
2882
+ stream.destroy(err);
2883
+ this._fatal(INTERNAL_ERROR, '', 'ERR_HTTP2_TOO_MANY_INVALID_FRAMES',
2884
+ TOO_MANY_INVALID_FRAMES);
2885
+ return this._open;
2886
+ }
2750
2887
  // Book the consumed bytes as credit owed to BOTH windows ahead of the hand-over:
2751
2888
  // a synchronous consumer inside the 'data' event must see the window already
2752
2889
  // shrunken, node's shape (16384 consumed reads 49151 from the state getter at
@@ -3077,7 +3214,7 @@ class Http2ClientSession extends EventEmitter {
3077
3214
  if (code === undefined) {
3078
3215
  code = NO_ERROR;
3079
3216
  }
3080
- if (lastStreamID === undefined || lastStreamID === null) {
3217
+ if (lastStreamID === undefined || lastStreamID === null || lastStreamID <= 0) {
3081
3218
  // node's goaway() defaults lastStreamID to 0 and the C layer substitutes
3082
3219
  // nghttp2_session_get_last_proc_stream_id (src/node_http2.cc Http2Session::Goaway:
3083
3220
  // `if (lastStreamID <= 0) lastStreamID = ...get_last_proc_stream_id`). For a
@@ -3088,14 +3225,24 @@ class Http2ClientSession extends EventEmitter {
3088
3225
  // graceful close() echo after the peer's GOAWAY then killed the peer's open
3089
3226
  // stream (measured on live node: its client sends last=0,
3090
3227
  // h2lean sent last=1 and the node server answered ERR_HTTP2_ERROR).
3228
+ // The C++ substitution also applies to an explicitly non-positive id
3229
+ // (node_http2.cc Http2Session::Goaway), so -1 is not sent as 0xffffffff.
3091
3230
  lastStreamID = this._maxPushSid;
3092
3231
  }
3093
- const tail = reason ? Buffer.byteLength(reason) : 0;
3094
- const body = Buffer.alloc(8 + tail);
3232
+ // node accepts Buffer and any TypedArray/DataView as opaqueData; keep the
3233
+ // older string form accepted here too (see the server's sendGoaway).
3234
+ let opaque;
3235
+ if (reason !== undefined && reason !== null) {
3236
+ opaque = ArrayBuffer.isView(reason)
3237
+ ? Buffer.from(reason.buffer, reason.byteOffset, reason.byteLength)
3238
+ : Buffer.from(String(reason), 'latin1');
3239
+ }
3240
+ const tail = opaque === undefined ? 0 : opaque.length;
3241
+ const body = Buffer.allocUnsafe(8 + tail);
3095
3242
  body.writeUInt32BE(lastStreamID >>> 0, 0);
3096
3243
  body.writeUInt32BE(code >>> 0, 4);
3097
3244
  if (tail) {
3098
- body.write(reason, 8);
3245
+ opaque.copy(body, 8);
3099
3246
  }
3100
3247
  this._frame(GOAWAY, 0, 0, body, true);
3101
3248
  // No closed marking here: node's goaway() (core.js:1602-1618) validates and submits
@@ -3531,7 +3678,11 @@ class Http2ClientSession extends EventEmitter {
3531
3678
  this._maybeClose();
3532
3679
  }
3533
3680
 
3534
- _fatal(code, reason) {
3681
+ _recordInvalidFrame() {
3682
+ return this._invalidFrames++ > this._maxInvalidFrames;
3683
+ }
3684
+
3685
+ _fatal(code, reason, errCode, errMessage) {
3535
3686
  if (!this._open) {
3536
3687
  return false;
3537
3688
  }
@@ -3566,8 +3717,9 @@ class Http2ClientSession extends EventEmitter {
3566
3717
  // them: measured off v26.12.1, every fatal code reports 'Protocol error'
3567
3718
  // except FLOW_CONTROL_ERROR's 'Flow control error' (the GOAWAY debug string
3568
3719
  // still carries this frame's own reason).
3569
- const err = httpErr('ERR_HTTP2_ERROR',
3570
- code === FLOW_CONTROL_ERROR ? 'Flow control error' : 'Protocol error');
3720
+ const err = httpErr(errCode !== undefined ? errCode : 'ERR_HTTP2_ERROR',
3721
+ errMessage !== undefined ? errMessage
3722
+ : (code === FLOW_CONTROL_ERROR ? 'Flow control error' : 'Protocol error'));
3571
3723
  err.http2Code = code;
3572
3724
  this.destroy(err);
3573
3725
  return false;
@@ -3807,8 +3959,10 @@ function checkRequestOptions(options) {
3807
3959
  }
3808
3960
  }
3809
3961
 
3810
- function httpErr(code, msg) {
3811
- const err = new Error(msg);
3962
+ // node's internal/errors.js gives these two codes fixed classes; the default stays
3963
+ // Error for the many other callers.
3964
+ function httpErr(code, msg, Ctor = Error) {
3965
+ const err = new Ctor(msg);
3812
3966
  err.code = code;
3813
3967
  return err;
3814
3968
  }
@@ -411,7 +411,7 @@ function createStreamIterator(stream, options) {
411
411
  // list: the object comes into being at the first read, which is what keeps a
412
412
  // body-only client free of per-response allocations (OPTIMIZATION.md item 48).
413
413
  const { Http2Stream, errorOf, validateRstCode, ASYNC_ITERATOR_PROTO, noop,
414
- validateObjectArg, validateSignalArg, streamErrorOf } = require('../Http2Stream');
414
+ validateObjectArg, validateSignalArg, streamErrorOf, WRITABLE_HWM } = require('../Http2Stream');
415
415
 
416
416
  class Http2ClientStream extends Http2Stream {
417
417
  constructor(session, id, _opts) {
@@ -453,16 +453,21 @@ class Http2ClientStream extends Http2Stream {
453
453
  // The hand-written writable half's queue: chunks waiting behind the one parked
454
454
  // in `_pending`, plus the end() bookkeeping node keeps in _writableState.
455
455
  this._wq = null;
456
+ // Trampoline for the write queue: _pump frames one chunk and calls back into
457
+ // _driveW, which used to recurse once per write and overflowed the stack at
458
+ // ~1700 queued writes. A loop here keeps the stack flat (4000 writes in node).
459
+ this._driveWActive = false;
460
+ this._driveAgain = false;
456
461
  this._endQueued = false; // node's _writableState.ending; `aborted` reads it
457
462
  this._endCb = undefined;
458
463
  this._needDrain = false;
459
464
  this._finishScheduled = false;
460
- // The two stubs the session pokes: `_writableState.finished` settled
465
+ // The three stubs the session pokes: `_writableState.finished` settled
461
466
  // synchronously on the push path (client-session.js, node settles it at the
462
- // 'stream' event) and `errorEmitted` read by the captureRejection routing.
463
- // Two small objects instead of the machinery's two large ones -- that share
464
- // of the remaining cost is what this hand-written construction still saves.
465
- this._writableState = { finished: false, errorEmitted: false };
467
+ // 'stream' event), `errorEmitted` read by the captureRejection routing, and
468
+ // `decodeStrings` at node's false. Small objects instead of the machinery's
469
+ // two large ones -- that share is what this construction still saves.
470
+ this._writableState = { finished: false, errorEmitted: false, decodeStrings: false };
466
471
  this._readableState = { errorEmitted: false };
467
472
  // Whether the request HEADERS frame has been committed to the outbound queue.
468
473
  // _pump() returns early until this is true, so a write() that lands before the
@@ -533,7 +538,6 @@ class Http2ClientStream extends Http2Stream {
533
538
  // response block emits 'push' instead of 'response' (node's event model,
534
539
  // measured v26.12.1).
535
540
  this._pushed = false;
536
- this.additionalHeaders = [];
537
541
  // The response and trailer objects are built at the first read, not when
538
542
  // the block arrives -- the getters below. The slots start undefined so the
539
543
  // object shape is stable from construction.
@@ -652,7 +656,12 @@ class Http2ClientStream extends Http2Stream {
652
656
  }
653
657
  this._wq.push([buf, cb]);
654
658
  this._driveW();
655
- if (this._pending !== null || this._wq.length > 0) {
659
+ // node's Writable answers false only when its buffered length reaches the
660
+ // high-water mark, not whenever anything is parked. A synchronous loop of
661
+ // 4000 six-byte writes stays under 65536 and is all accepted on node.
662
+ const queued = this.writableLength +
663
+ (this._pending === null ? 0 : this._pending.length - this._pendingOff);
664
+ if (queued >= WRITABLE_HWM) {
656
665
  this._needDrain = true;
657
666
  return false;
658
667
  }
@@ -730,32 +739,47 @@ class Http2ClientStream extends Http2Stream {
730
739
  if (this._pending !== null) {
731
740
  return;
732
741
  }
733
- if (this._wq !== null && this._wq.length > 0) {
734
- const [buf, cb] = this._wq.shift();
735
- this._pending = buf;
736
- this._pendingOff = 0;
737
- this._writeCb = () => {
738
- if (cb !== undefined) {
739
- cb();
740
- }
741
- this._driveW();
742
- if ((this._wq === null || this._wq.length === 0) && this._pending === null &&
743
- this._needDrain) {
744
- this._needDrain = false;
745
- this._tick(() => {
746
- if (!this._destroyFlag) {
747
- this.emit('drain');
748
- }
749
- });
750
- }
751
- };
752
- this.session._pump(this);
742
+ if (this._driveWActive) {
743
+ // The write callback re-enters from inside _pump. Mark the turn and let the
744
+ // active loop frame the next chunk instead of growing the stack.
745
+ this._driveAgain = true;
753
746
  return;
754
747
  }
755
- if (this._endQueued && this._finalCb === null && !this._endSent) {
756
- this._finalCb = this._endCb;
757
- this._endCb = undefined;
758
- this.session._pump(this);
748
+ this._driveWActive = true;
749
+ try {
750
+ do {
751
+ this._driveAgain = false;
752
+ if (this._wq !== null && this._wq.length > 0) {
753
+ const [buf, cb] = this._wq.shift();
754
+ this._pending = buf;
755
+ this._pendingOff = 0;
756
+ this._writeCb = () => {
757
+ if (cb !== undefined) {
758
+ cb();
759
+ }
760
+ this._driveW();
761
+ if ((this._wq === null || this._wq.length === 0) && this._pending === null &&
762
+ this._needDrain) {
763
+ this._needDrain = false;
764
+ this._tick(() => {
765
+ if (!this._destroyFlag) {
766
+ this.emit('drain');
767
+ }
768
+ });
769
+ }
770
+ };
771
+ this.session._pump(this);
772
+ continue;
773
+ }
774
+ if (this._endQueued && this._finalCb === null && !this._endSent) {
775
+ this._finalCb = this._endCb;
776
+ this._endCb = undefined;
777
+ this.session._pump(this);
778
+ }
779
+ } while (this._driveAgain && this._pending === null);
780
+ } finally {
781
+ this._driveWActive = false;
782
+ this._driveAgain = false;
759
783
  }
760
784
  }
761
785
 
@@ -1298,6 +1322,14 @@ class Http2ClientStream extends Http2Stream {
1298
1322
  this.once('close', callback);
1299
1323
  }
1300
1324
  const ending = this._endQueued === true;
1325
+ // A body written in this same turn is parked until the session's flush, which
1326
+ // is what puts every HEADERS of a burst ahead of every DATA (node's order).
1327
+ // close(NO_ERROR) after end() still owes that body to the peer -- the upstream
1328
+ // buffersize port reads all 600 octets before its two streams close -- so
1329
+ // release it here before the close drops the queue.
1330
+ if (this._bodyDeferred) {
1331
+ this.session._releaseBody(this);
1332
+ }
1301
1333
  this._closeStream(code);
1302
1334
  // node's submitRstStream (core.js:512) checks kHandle: a destroy() from the
1303
1335
  // 'aborted' event closeStream just emitted removes the handle before
@@ -1738,10 +1770,10 @@ class Http2ClientStream extends Http2Stream {
1738
1770
  if (status !== undefined && status >= 100 && status < 200 && !this.responseEmitted) {
1739
1771
  // 1xx informational (including the 100 Continue that node surfaces as
1740
1772
  // 'continue'): built eagerly -- the blocks are rare and the one object
1741
- // feeds the two events and the additionalHeaders field. The 100-Continue
1742
- // translation node does is a 'headers' whose :status is 100.
1773
+ // feeds the two events. The 100-Continue translation node does is a
1774
+ // 'headers' whose :status is 100. node keeps these blocks private; h2lean
1775
+ // used to expose them in an additionalHeaders array, which it no longer does.
1743
1776
  const headers = this.session._toObject(fields, fcount, sensitive);
1744
- this.additionalHeaders.push(headers);
1745
1777
  // node's inbound emit carries the frame flags as the second argument
1746
1778
  // (`emit(stream, event, obj, flags, headers)`, internal/http2/core.js), which is
1747
1779
  // what the upstream sent-headers test asserts is a number.
@@ -1755,13 +1787,15 @@ class Http2ClientStream extends Http2Stream {
1755
1787
  this._respFields = fields;
1756
1788
  this._respFcount = fcount;
1757
1789
  this._respSensitive = sensitive;
1758
- // node passes the raw HEADERS frame flags as the second argument and a
1759
- // rawHeaders array as the third (core.js: emit(stream, event, obj, flags,
1760
- // headers)); the rawHeaders array is deliberately not built -- one flat
1761
- // array per response is a cost no h2lean consumer has asked for.
1790
+ // node passes the raw HEADERS frame flags as the second argument and the
1791
+ // decoded flat field list as the third (core.js: emit(stream, event, obj,
1792
+ // flags, headers)): pseudo-headers, duplicates and wire order, one array
1793
+ // per response owned by the application. The session's field list is that
1794
+ // per-response copy (its own slice on a decode, a copy of the shared shape
1795
+ // cache entry on a hit), so it can be handed over directly.
1762
1796
  const event = this._pushed ? 'push' : 'response';
1763
1797
  if (this.listenerCount(event) > 0) {
1764
- this.emit(event, this.responseHeaders, flags);
1798
+ this.emit(event, this.responseHeaders, flags, fields);
1765
1799
  }
1766
1800
  } else {
1767
1801
  // A second final-status block after the response is the trailer block.
@@ -18,13 +18,8 @@ const net = require('node:net');
18
18
  const tls = require('node:tls');
19
19
  const { promisify } = require('node:util');
20
20
  const { Http2ClientSession } = require('./Http2ClientSession');
21
- const { strictSingleValueFields, received, outOfRangeValue, validateRemoteCustomSettings } = require('../server/Http2ServerSession');
22
-
23
- function notImplemented(what) {
24
- const err = new Error(`h2lean: not implemented: ${what}`);
25
- err.code = 'ERR_H2LEAN_NOT_IMPLEMENTED';
26
- return err;
27
- }
21
+ const { strictSingleValueFields, received, outOfRangeValue, validateRemoteCustomSettings,
22
+ validateConnectionWindowSize } = require('../server/Http2ServerSession');
28
23
 
29
24
  function connect(authority, options, listener) {
30
25
  if (typeof options === 'function') {
@@ -85,6 +80,12 @@ function connect(authority, options, listener) {
85
80
  options.maxOriginSetSize = 128;
86
81
  }
87
82
 
83
+ // core.js validateSessionOptions (called by connect after maxOriginSetSize) gates
84
+ // connectionWindowSize with validateInt32(value, name, 1, 2^31-1). The shared helper
85
+ // in the server session keeps node's error class, code and received-value wording on
86
+ // both halves; undefined is the one value that skips it (null reaches the type check).
87
+ validateConnectionWindowSize(options);
88
+
88
89
  const protocol = authority.protocol || options.protocol || 'https:';
89
90
  const port = '' + (authority.port !== ''
90
91
  ? authority.port : (authority.protocol === 'http:' ? 80 : 443));
@@ -117,11 +118,16 @@ function connect(authority, options, listener) {
117
118
  }
118
119
  socket = tls.connect({ port, host, ...tlsOptions });
119
120
  } else {
120
- throw notImplemented(`connect over ${protocol}`);
121
+ const err = new Error(`protocol "${protocol}" is unsupported.`);
122
+ err.code = 'ERR_HTTP2_UNSUPPORTED_PROTOCOL';
123
+ throw err;
121
124
  }
122
125
 
123
126
  const scheme = protocol === 'https:' ? 'https' : 'http';
124
- const authorityHeader = `${host}:${port}`;
127
+ // core.js connect() derives kAuthority from the caller's `options.servername`
128
+ // or the host -- not from the name tls.connect uses for SNI. initializeTLSOptions
129
+ // defaults servername on a copy, so only an explicitly supplied option wins here.
130
+ const authorityHeader = `${options.servername || host}:${port}`;
125
131
  const session = new Http2ClientSession(socket, options, scheme, authorityHeader);
126
132
 
127
133
  if (typeof listener === 'function') {