h2lean 0.19.9 → 0.19.14

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.
@@ -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') {
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
  }
@@ -376,7 +379,10 @@ function parse(headers,
376
379
 
377
380
  if (key[0] === ':') {
378
381
  if (trailer) {
379
- throw httpError('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', 'cannot send trailers with pseudo-headers');
382
+ // node's assertValidPseudoHeaderTrailer (internal/http2/util.js) rejects
383
+ // every ':' key, including the request and response pseudo-headers.
384
+ throw httpError('ERR_HTTP2_INVALID_PSEUDOHEADER',
385
+ `"${key}" is an invalid pseudoheader or is used incorrectly`, TypeError);
380
386
  }
381
387
  if (request) {
382
388
  // Request pseudo-headers for PUSH_PROMISE (node: assertValidPseudoHeader,
@@ -384,7 +390,8 @@ function parse(headers,
384
390
  // pseudo-headers are the ones RFC 9113 8.3.1 defines.
385
391
  if (key !== ':method' && key !== ':path' && key !== ':scheme'
386
392
  && key !== ':authority' && key !== ':protocol') {
387
- throw httpError('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', `cannot send ${key} in a request`);
393
+ throw httpError('ERR_HTTP2_INVALID_PSEUDOHEADER',
394
+ `"${key}" is an invalid pseudoheader or is used incorrectly`, TypeError);
388
395
  }
389
396
  const val = String(Array.isArray(raw) ? raw[0] : raw);
390
397
  if (key === ':method' && !isToken.test(val)) {
@@ -400,7 +407,8 @@ function parse(headers,
400
407
  continue;
401
408
  }
402
409
  if (key !== ':status') {
403
- throw httpError('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', `cannot send ${key} in a response`);
410
+ throw httpError('ERR_HTTP2_INVALID_PSEUDOHEADER',
411
+ `"${key}" is an invalid pseudoheader or is used incorrectly`, TypeError);
404
412
  }
405
413
  const single = Array.isArray(raw) ? raw[0] : raw;
406
414
  // node coerces with `statusCode | 0` -- not Number(), and not a range check on the
@@ -419,11 +427,12 @@ function parse(headers,
419
427
  // upgrade can only be expressed as a connection-specific field, and RFC 9113 8.2.2
420
428
  // removes those from this protocol.
421
429
  if (code === 101) {
422
- throw httpError('ERR_HTTP2_STATUS_101', 'HTTP status code 101 is disallowed');
430
+ throw httpError('ERR_HTTP2_STATUS_101',
431
+ 'HTTP status code 101 (Switching Protocols) is forbidden in HTTP/2');
423
432
  }
424
433
  if (code < 100 || code >= 200) {
425
434
  throw httpError('ERR_HTTP2_INVALID_INFO_STATUS',
426
- `invalid informational status code: ${single}`);
435
+ `Invalid informational status code: ${single}`, RangeError);
427
436
  }
428
437
  }
429
438
  status = code;
@@ -432,7 +441,8 @@ function parse(headers,
432
441
  }
433
442
 
434
443
  if (!isFieldName(key)) {
435
- throw httpError('ERR_INVALID_HTTP_TOKEN', `${key} is an invalid header token`);
444
+ throw httpError('ERR_INVALID_HTTP_TOKEN',
445
+ `Header name must be a valid HTTP token ["${key}"]`, TypeError);
436
446
  }
437
447
  if (CONNECTION_SPECIFIC.has(key)) {
438
448
  // node's ERR_HTTP2_INVALID_CONNECTION_HEADERS is a TypeError with the