h2lean 0.19.8 → 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.
@@ -59,19 +59,18 @@
59
59
  // END_STREAM" knowledge lives in `_endOnHeaders`, which the request pump
60
60
  // reads to suppress an empty trailing DATA.
61
61
  // * `state`, `headRequest` and `close(code, callback)` are node's Http2Stream
62
- // surface, provided here too. Three divergences, all on shapes node can
62
+ // surface, provided here too. Two divergences, both on shapes node can
63
63
  // observe and h2lean cannot produce: node spends one loop turn reporting
64
64
  // state:1/weight:0/localWindowSize:0 between request() and the session's
65
65
  // first flush -- the HEADERS are framed inside the call here, so the getter
66
- // reports the post-HEADERS state immediately; a close() on a request queued
67
- // behind a still-connecting session destroys it without anything going out,
68
- // where node sends the HEADERS once the session is ready and resets the
69
- // stream right after; and `state.localWindowSize` shrinks when DATA ARRIVES
66
+ // reports the post-HEADERS state immediately; and `state.localWindowSize` shrinks when DATA ARRIVES
70
67
  // rather than when the application consumes it (node consumes inside
71
68
  // nghttp2_session_consume, called at delivery), so an unread body already
72
69
  // counts against the reported number -- a reading that also stands behind
73
70
  // the client's no-partial-credit accounting, the same deliberate shape the
74
- // server documents in lib/server/compat.js.
71
+ // server documents in lib/server/compat.js. A close() before connect is no
72
+ // longer one of them: it parks the code on the stream and the session submits
73
+ // RST_STREAM right after the queued HEADERS, node's finishCloseStream shape.
75
74
  //
76
75
  // The ported surface below -- pipe()/unpipe() (the Readable.prototype.pipe
77
76
  // port, not the legacy base pipe), push(), compose(), wrap(),
@@ -412,7 +411,7 @@ function createStreamIterator(stream, options) {
412
411
  // list: the object comes into being at the first read, which is what keeps a
413
412
  // body-only client free of per-response allocations (OPTIMIZATION.md item 48).
414
413
  const { Http2Stream, errorOf, validateRstCode, ASYNC_ITERATOR_PROTO, noop,
415
- validateObjectArg, validateSignalArg, streamErrorOf } = require('../Http2Stream');
414
+ validateObjectArg, validateSignalArg, streamErrorOf, WRITABLE_HWM } = require('../Http2Stream');
416
415
 
417
416
  class Http2ClientStream extends Http2Stream {
418
417
  constructor(session, id, _opts) {
@@ -437,6 +436,10 @@ class Http2ClientStream extends Http2Stream {
437
436
  // reserved here at request() time, which is the one queued-shape
438
437
  // divergence and it is carried on the id, not on pending).
439
438
  this._opened = false;
439
+ // A close() on a request that has no id on the wire yet parks its reset here;
440
+ // the session submits it in _openStream once the id is assigned, the way node's
441
+ // finishCloseStream waits for 'ready' (core.js:2113-2122).
442
+ this._pendingCloseCode = undefined;
440
443
  // Whether this stream is already in the session's _debt list, i.e. whether the
441
444
  // next credit pass has to visit it. Declared here so every stream shares one
442
445
  // V8 object shape; only lib/client/Http2ClientSession.js reads or writes it.
@@ -450,16 +453,21 @@ class Http2ClientStream extends Http2Stream {
450
453
  // The hand-written writable half's queue: chunks waiting behind the one parked
451
454
  // in `_pending`, plus the end() bookkeeping node keeps in _writableState.
452
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;
453
461
  this._endQueued = false; // node's _writableState.ending; `aborted` reads it
454
462
  this._endCb = undefined;
455
463
  this._needDrain = false;
456
464
  this._finishScheduled = false;
457
- // The two stubs the session pokes: `_writableState.finished` settled
465
+ // The three stubs the session pokes: `_writableState.finished` settled
458
466
  // synchronously on the push path (client-session.js, node settles it at the
459
- // 'stream' event) and `errorEmitted` read by the captureRejection routing.
460
- // Two small objects instead of the machinery's two large ones -- that share
461
- // of the remaining cost is what this hand-written construction still saves.
462
- 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 };
463
471
  this._readableState = { errorEmitted: false };
464
472
  // Whether the request HEADERS frame has been committed to the outbound queue.
465
473
  // _pump() returns early until this is true, so a write() that lands before the
@@ -530,7 +538,6 @@ class Http2ClientStream extends Http2Stream {
530
538
  // response block emits 'push' instead of 'response' (node's event model,
531
539
  // measured v26.12.1).
532
540
  this._pushed = false;
533
- this.additionalHeaders = [];
534
541
  // The response and trailer objects are built at the first read, not when
535
542
  // the block arrives -- the getters below. The slots start undefined so the
536
543
  // object shape is stable from construction.
@@ -649,7 +656,12 @@ class Http2ClientStream extends Http2Stream {
649
656
  }
650
657
  this._wq.push([buf, cb]);
651
658
  this._driveW();
652
- 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) {
653
665
  this._needDrain = true;
654
666
  return false;
655
667
  }
@@ -695,36 +707,79 @@ class Http2ClientStream extends Http2Stream {
695
707
  return this;
696
708
  }
697
709
 
710
+ // node's nghttp2 discards a body still queued when closeStream leaves the
711
+ // writable unfinished: measured on the wire for close(0) on a 1 MB body behind
712
+ // a 16384-octet window (captured frame by frame), no DATA or
713
+ // END_STREAM follows the close and the deferred reset never reaches the wire,
714
+ // because the 'finish' it waits for never arrives. Settle the parked callbacks
715
+ // here so the application is not left waiting for bytes that will not go out.
716
+ _dropQueuedBody() {
717
+ this._pending = null;
718
+ this._pendingOff = 0;
719
+ this._wq = null;
720
+ this._endSent = true;
721
+ const cb = this._writeCb;
722
+ this._writeCb = null;
723
+ if (cb !== null) {
724
+ cb();
725
+ }
726
+ const final = this._finalCb;
727
+ this._finalCb = null;
728
+ if (final !== null) {
729
+ final();
730
+ }
731
+ const end = this._endCb;
732
+ this._endCb = undefined;
733
+ if (end !== undefined) {
734
+ end();
735
+ }
736
+ }
737
+
698
738
  _driveW() {
699
739
  if (this._pending !== null) {
700
740
  return;
701
741
  }
702
- if (this._wq !== null && this._wq.length > 0) {
703
- const [buf, cb] = this._wq.shift();
704
- this._pending = buf;
705
- this._pendingOff = 0;
706
- this._writeCb = () => {
707
- if (cb !== undefined) {
708
- cb();
709
- }
710
- this._driveW();
711
- if ((this._wq === null || this._wq.length === 0) && this._pending === null &&
712
- this._needDrain) {
713
- this._needDrain = false;
714
- this._tick(() => {
715
- if (!this._destroyFlag) {
716
- this.emit('drain');
717
- }
718
- });
719
- }
720
- };
721
- 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;
722
746
  return;
723
747
  }
724
- if (this._endQueued && this._finalCb === null && !this._endSent) {
725
- this._finalCb = this._endCb;
726
- this._endCb = undefined;
727
- 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;
728
783
  }
729
784
  }
730
785
 
@@ -1267,10 +1322,40 @@ class Http2ClientStream extends Http2Stream {
1267
1322
  this.once('close', callback);
1268
1323
  }
1269
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
+ }
1270
1333
  this._closeStream(code);
1334
+ // node's submitRstStream (core.js:512) checks kHandle: a destroy() from the
1335
+ // 'aborted' event closeStream just emitted removes the handle before
1336
+ // finishCloseStream runs, so no RST_STREAM goes out. _destroyFlag is h2lean's
1337
+ // handle-gone reading (the destroy already skipped a reset of its own here).
1338
+ if (this._destroyFlag) {
1339
+ return;
1340
+ }
1341
+ // node's finishCloseStream (core.js:2113) pushes the EOF first and queues the
1342
+ // reset on 'ready' while the handle is unassigned: HEADERS still go out at
1343
+ // connect, followed by RST_STREAM, and the application sees 'end' before the
1344
+ // error. Keep the stream in the session's connect queue instead of destroying
1345
+ // it here -- a pending stream has no id to reset yet.
1346
+ if (!this._opened) {
1347
+ this._pendingCloseCode = code;
1348
+ this.push(null);
1349
+ return;
1350
+ }
1271
1351
  if (ending && this.writableFinished !== true && code === NO_ERROR) {
1352
+ this._dropQueuedBody();
1272
1353
  this.once('finish', () => {
1273
- this.session.rstStream(this.id, code);
1354
+ // A destroy() on this turn (or before this tick) is node's handle gone:
1355
+ // submitRstStream's guard then finds nothing to reset.
1356
+ if (!this._destroyFlag) {
1357
+ this.session.rstStream(this.id, code);
1358
+ }
1274
1359
  this._tick(() => this.destroy());
1275
1360
  });
1276
1361
  return;
@@ -1555,7 +1640,7 @@ class Http2ClientStream extends Http2Stream {
1555
1640
  if (this._destroyFlag) {
1556
1641
  throw errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed');
1557
1642
  }
1558
- return true;
1643
+ // node's prototype method has no return statement; measured v26.12.1.
1559
1644
  }
1560
1645
 
1561
1646
  get destroyed() {
@@ -1685,10 +1770,10 @@ class Http2ClientStream extends Http2Stream {
1685
1770
  if (status !== undefined && status >= 100 && status < 200 && !this.responseEmitted) {
1686
1771
  // 1xx informational (including the 100 Continue that node surfaces as
1687
1772
  // 'continue'): built eagerly -- the blocks are rare and the one object
1688
- // feeds the two events and the additionalHeaders field. The 100-Continue
1689
- // 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.
1690
1776
  const headers = this.session._toObject(fields, fcount, sensitive);
1691
- this.additionalHeaders.push(headers);
1692
1777
  // node's inbound emit carries the frame flags as the second argument
1693
1778
  // (`emit(stream, event, obj, flags, headers)`, internal/http2/core.js), which is
1694
1779
  // what the upstream sent-headers test asserts is a number.
@@ -1702,13 +1787,15 @@ class Http2ClientStream extends Http2Stream {
1702
1787
  this._respFields = fields;
1703
1788
  this._respFcount = fcount;
1704
1789
  this._respSensitive = sensitive;
1705
- // node passes the raw HEADERS frame flags as the second argument and a
1706
- // rawHeaders array as the third (core.js: emit(stream, event, obj, flags,
1707
- // headers)); the rawHeaders array is deliberately not built -- one flat
1708
- // 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.
1709
1796
  const event = this._pushed ? 'push' : 'response';
1710
1797
  if (this.listenerCount(event) > 0) {
1711
- this.emit(event, this.responseHeaders, flags);
1798
+ this.emit(event, this.responseHeaders, flags, fields);
1712
1799
  }
1713
1800
  } else {
1714
1801
  // A second final-status block after the response is the trailer block.
@@ -16,14 +16,10 @@
16
16
 
17
17
  const net = require('node:net');
18
18
  const tls = require('node:tls');
19
+ const { promisify } = require('node:util');
19
20
  const { Http2ClientSession } = require('./Http2ClientSession');
20
- const { strictSingleValueFields, received, outOfRangeValue, validateRemoteCustomSettings } = require('../server/Http2ServerSession');
21
-
22
- function notImplemented(what) {
23
- const err = new Error(`h2lean: not implemented: ${what}`);
24
- err.code = 'ERR_H2LEAN_NOT_IMPLEMENTED';
25
- return err;
26
- }
21
+ const { strictSingleValueFields, received, outOfRangeValue, validateRemoteCustomSettings,
22
+ validateConnectionWindowSize } = require('../server/Http2ServerSession');
27
23
 
28
24
  function connect(authority, options, listener) {
29
25
  if (typeof options === 'function') {
@@ -84,6 +80,12 @@ function connect(authority, options, listener) {
84
80
  options.maxOriginSetSize = 128;
85
81
  }
86
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
+
87
89
  const protocol = authority.protocol || options.protocol || 'https:';
88
90
  const port = '' + (authority.port !== ''
89
91
  ? authority.port : (authority.protocol === 'http:' ? 80 : 443));
@@ -101,7 +103,7 @@ function connect(authority, options, listener) {
101
103
  if (typeof options.createConnection === 'function') {
102
104
  socket = options.createConnection(authority, options);
103
105
  } else if (protocol === 'http:') {
104
- socket = net.connect({ port: Number(port), host, ...options });
106
+ socket = net.connect({ port, host, ...options });
105
107
  } else if (protocol === 'https:') {
106
108
  // core.js initializeTLSOptions: the ALPN list belongs to the protocol, not
107
109
  // to the application -- only an ALPNCallback keeps ours out. servername is
@@ -114,13 +116,18 @@ function connect(authority, options, listener) {
114
116
  if (!tlsOptions.servername && !net.isIP(host)) {
115
117
  tlsOptions.servername = host;
116
118
  }
117
- socket = tls.connect({ port: Number(port), host, ...tlsOptions });
119
+ socket = tls.connect({ port, host, ...tlsOptions });
118
120
  } else {
119
- throw notImplemented(`connect over ${protocol}`);
121
+ const err = new Error(`protocol "${protocol}" is unsupported.`);
122
+ err.code = 'ERR_HTTP2_UNSUPPORTED_PROTOCOL';
123
+ throw err;
120
124
  }
121
125
 
122
126
  const scheme = protocol === 'https:' ? 'https' : 'http';
123
- 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}`;
124
131
  const session = new Http2ClientSession(socket, options, scheme, authorityHeader);
125
132
 
126
133
  if (typeof listener === 'function') {
@@ -129,4 +136,25 @@ function connect(authority, options, listener) {
129
136
  return session;
130
137
  }
131
138
 
139
+ // node's connect carries util.promisify.custom (internal/http2/core.js): the
140
+ // promisified form resolves with the session on 'connect' and rejects with the
141
+ // very same error object on its first 'error'. Without it util.promisify installs
142
+ // the callback as a third-argument 'connect' listener and resolves undefined.
143
+ Object.defineProperty(connect, promisify.custom, {
144
+ value: function connectAsync(authority, options) {
145
+ return new Promise((resolve, reject) => {
146
+ const session = connect(authority, options, () => {
147
+ session.removeListener('error', reject);
148
+ resolve(session);
149
+ });
150
+ session.once('error', reject);
151
+ });
152
+ }
153
+ });
154
+ // node names the custom function `connect` (assignFunctionName in core.js), and
155
+ // that name is visible through util.promisify(connect).name.
156
+ Object.defineProperty(connect[promisify.custom], 'name', {
157
+ value: 'connect', configurable: true
158
+ });
159
+
132
160
  module.exports = { connect };
package/lib/headers.js CHANGED
@@ -243,8 +243,11 @@ function neverNames(fields, count, flags) {
243
243
  return names;
244
244
  }
245
245
 
246
- function httpError(code, msg) {
247
- const err = new Error(msg);
246
+ // node's internal/errors.js gives these codes fixed classes; most of this module's
247
+ // validation errors are plain Error, so callers opt into node's class explicitly rather
248
+ // than changing the helper's default for every other site.
249
+ function httpError(code, msg, Ctor = Error) {
250
+ const err = new Ctor(msg);
248
251
  err.code = code;
249
252
  return err;
250
253
  }
@@ -384,7 +387,8 @@ function parse(headers,
384
387
  // pseudo-headers are the ones RFC 9113 8.3.1 defines.
385
388
  if (key !== ':method' && key !== ':path' && key !== ':scheme'
386
389
  && key !== ':authority' && key !== ':protocol') {
387
- throw httpError('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', `cannot send ${key} in a request`);
390
+ throw httpError('ERR_HTTP2_INVALID_PSEUDOHEADER',
391
+ `"${key}" is an invalid pseudoheader or is used incorrectly`, TypeError);
388
392
  }
389
393
  const val = String(Array.isArray(raw) ? raw[0] : raw);
390
394
  if (key === ':method' && !isToken.test(val)) {
@@ -400,7 +404,8 @@ function parse(headers,
400
404
  continue;
401
405
  }
402
406
  if (key !== ':status') {
403
- throw httpError('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', `cannot send ${key} in a response`);
407
+ throw httpError('ERR_HTTP2_INVALID_PSEUDOHEADER',
408
+ `"${key}" is an invalid pseudoheader or is used incorrectly`, TypeError);
404
409
  }
405
410
  const single = Array.isArray(raw) ? raw[0] : raw;
406
411
  // node coerces with `statusCode | 0` -- not Number(), and not a range check on the
@@ -419,11 +424,12 @@ function parse(headers,
419
424
  // upgrade can only be expressed as a connection-specific field, and RFC 9113 8.2.2
420
425
  // removes those from this protocol.
421
426
  if (code === 101) {
422
- throw httpError('ERR_HTTP2_STATUS_101', 'HTTP status code 101 is disallowed');
427
+ throw httpError('ERR_HTTP2_STATUS_101',
428
+ 'HTTP status code 101 (Switching Protocols) is forbidden in HTTP/2');
423
429
  }
424
430
  if (code < 100 || code >= 200) {
425
431
  throw httpError('ERR_HTTP2_INVALID_INFO_STATUS',
426
- `invalid informational status code: ${single}`);
432
+ `Invalid informational status code: ${single}`, RangeError);
427
433
  }
428
434
  }
429
435
  status = code;
@@ -432,7 +438,8 @@ function parse(headers,
432
438
  }
433
439
 
434
440
  if (!isFieldName(key)) {
435
- throw httpError('ERR_INVALID_HTTP_TOKEN', `${key} is an invalid header token`);
441
+ throw httpError('ERR_INVALID_HTTP_TOKEN',
442
+ `Header name must be a valid HTTP token ["${key}"]`, TypeError);
436
443
  }
437
444
  if (CONNECTION_SPECIFIC.has(key)) {
438
445
  // node's ERR_HTTP2_INVALID_CONNECTION_HEADERS is a TypeError with the