h2lean 0.19.7 → 0.19.9

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.
@@ -33,10 +33,11 @@
33
33
  // consumer's waiter has registered.
34
34
  // * Writable backpressure is the queue length, not node's highWaterMark
35
35
  // arithmetic: write() returns false while a chunk is parked or queued and
36
- // 'drain' fires once when the queue empties. `writableLength`,
37
- // `writableBuffer` and `bufferSize` report the octets still queued in the
38
- // writable queue; the one chunk in flight lives in the session's `_pending`
39
- // slot (write-through), which is where node's nghttp2 queue would hold it.
36
+ // 'drain' fires once when the queue empties. `writableLength` and
37
+ // `writableBuffer` report the octets still queued in the writable queue;
38
+ // `bufferSize` adds the unwritten remainder of the one chunk in flight in
39
+ // the session's `_pending` slot (write-through), which is where node's
40
+ // nghttp2 queue holds it (core.js:2215, writeQueueSize + writableLength).
40
41
  // * `cork()`/`uncork()` are counting stubs like the server's; the cross-tick
41
42
  // deferral node's Writable.cork does is a known divergence (pinned
42
43
  // server-side by test/cork-parity.test.js).
@@ -58,19 +59,18 @@
58
59
  // END_STREAM" knowledge lives in `_endOnHeaders`, which the request pump
59
60
  // reads to suppress an empty trailing DATA.
60
61
  // * `state`, `headRequest` and `close(code, callback)` are node's Http2Stream
61
- // surface, provided here too. Three divergences, all on shapes node can
62
+ // surface, provided here too. Two divergences, both on shapes node can
62
63
  // observe and h2lean cannot produce: node spends one loop turn reporting
63
64
  // state:1/weight:0/localWindowSize:0 between request() and the session's
64
65
  // first flush -- the HEADERS are framed inside the call here, so the getter
65
- // reports the post-HEADERS state immediately; a close() on a request queued
66
- // behind a still-connecting session destroys it without anything going out,
67
- // where node sends the HEADERS once the session is ready and resets the
68
- // stream right after; and `state.localWindowSize` shrinks when DATA ARRIVES
66
+ // reports the post-HEADERS state immediately; and `state.localWindowSize` shrinks when DATA ARRIVES
69
67
  // rather than when the application consumes it (node consumes inside
70
68
  // nghttp2_session_consume, called at delivery), so an unread body already
71
69
  // counts against the reported number -- a reading that also stands behind
72
70
  // the client's no-partial-credit accounting, the same deliberate shape the
73
- // 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.
74
74
  //
75
75
  // The ported surface below -- pipe()/unpipe() (the Readable.prototype.pipe
76
76
  // port, not the legacy base pipe), push(), compose(), wrap(),
@@ -436,6 +436,10 @@ class Http2ClientStream extends Http2Stream {
436
436
  // reserved here at request() time, which is the one queued-shape
437
437
  // divergence and it is carried on the id, not on pending).
438
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;
439
443
  // Whether this stream is already in the session's _debt list, i.e. whether the
440
444
  // next credit pass has to visit it. Declared here so every stream shares one
441
445
  // V8 object shape; only lib/client/Http2ClientSession.js reads or writes it.
@@ -694,6 +698,34 @@ class Http2ClientStream extends Http2Stream {
694
698
  return this;
695
699
  }
696
700
 
701
+ // node's nghttp2 discards a body still queued when closeStream leaves the
702
+ // writable unfinished: measured on the wire for close(0) on a 1 MB body behind
703
+ // a 16384-octet window (captured frame by frame), no DATA or
704
+ // END_STREAM follows the close and the deferred reset never reaches the wire,
705
+ // because the 'finish' it waits for never arrives. Settle the parked callbacks
706
+ // here so the application is not left waiting for bytes that will not go out.
707
+ _dropQueuedBody() {
708
+ this._pending = null;
709
+ this._pendingOff = 0;
710
+ this._wq = null;
711
+ this._endSent = true;
712
+ const cb = this._writeCb;
713
+ this._writeCb = null;
714
+ if (cb !== null) {
715
+ cb();
716
+ }
717
+ const final = this._finalCb;
718
+ this._finalCb = null;
719
+ if (final !== null) {
720
+ final();
721
+ }
722
+ const end = this._endCb;
723
+ this._endCb = undefined;
724
+ if (end !== undefined) {
725
+ end();
726
+ }
727
+ }
728
+
697
729
  _driveW() {
698
730
  if (this._pending !== null) {
699
731
  return;
@@ -1267,9 +1299,31 @@ class Http2ClientStream extends Http2Stream {
1267
1299
  }
1268
1300
  const ending = this._endQueued === true;
1269
1301
  this._closeStream(code);
1302
+ // node's submitRstStream (core.js:512) checks kHandle: a destroy() from the
1303
+ // 'aborted' event closeStream just emitted removes the handle before
1304
+ // finishCloseStream runs, so no RST_STREAM goes out. _destroyFlag is h2lean's
1305
+ // handle-gone reading (the destroy already skipped a reset of its own here).
1306
+ if (this._destroyFlag) {
1307
+ return;
1308
+ }
1309
+ // node's finishCloseStream (core.js:2113) pushes the EOF first and queues the
1310
+ // reset on 'ready' while the handle is unassigned: HEADERS still go out at
1311
+ // connect, followed by RST_STREAM, and the application sees 'end' before the
1312
+ // error. Keep the stream in the session's connect queue instead of destroying
1313
+ // it here -- a pending stream has no id to reset yet.
1314
+ if (!this._opened) {
1315
+ this._pendingCloseCode = code;
1316
+ this.push(null);
1317
+ return;
1318
+ }
1270
1319
  if (ending && this.writableFinished !== true && code === NO_ERROR) {
1320
+ this._dropQueuedBody();
1271
1321
  this.once('finish', () => {
1272
- this.session.rstStream(this.id, code);
1322
+ // A destroy() on this turn (or before this tick) is node's handle gone:
1323
+ // submitRstStream's guard then finds nothing to reset.
1324
+ if (!this._destroyFlag) {
1325
+ this.session.rstStream(this.id, code);
1326
+ }
1273
1327
  this._tick(() => this.destroy());
1274
1328
  });
1275
1329
  return;
@@ -1554,7 +1608,7 @@ class Http2ClientStream extends Http2Stream {
1554
1608
  if (this._destroyFlag) {
1555
1609
  throw errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed');
1556
1610
  }
1557
- return true;
1611
+ // node's prototype method has no return statement; measured v26.12.1.
1558
1612
  }
1559
1613
 
1560
1614
  get destroyed() {
@@ -1657,6 +1711,16 @@ class Http2ClientStream extends Http2Stream {
1657
1711
  return out;
1658
1712
  }
1659
1713
 
1714
+ // node's bufferSize is writeQueueSize + writableLength (core.js:2215). The
1715
+ // chunk parked in _pending is in our write queue, not an already-written one,
1716
+ // so leaving it out undercounted by exactly one chunk (test/upstream/
1717
+ // buffersize.test.js). _pendingOff is how much of it the session has framed.
1718
+ get bufferSize() {
1719
+ const pending = this._pending;
1720
+ return this.writableLength +
1721
+ (pending === null ? 0 : pending.length - this._pendingOff);
1722
+ }
1723
+
1660
1724
  get writableNeedDrain() {
1661
1725
  return this._needDrain === true && this._destroyFlag !== true &&
1662
1726
  this._endQueued !== true;
@@ -16,6 +16,7 @@
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
21
  const { strictSingleValueFields, received, outOfRangeValue, validateRemoteCustomSettings } = require('../server/Http2ServerSession');
21
22
 
@@ -101,7 +102,7 @@ function connect(authority, options, listener) {
101
102
  if (typeof options.createConnection === 'function') {
102
103
  socket = options.createConnection(authority, options);
103
104
  } else if (protocol === 'http:') {
104
- socket = net.connect({ port: Number(port), host, ...options });
105
+ socket = net.connect({ port, host, ...options });
105
106
  } else if (protocol === 'https:') {
106
107
  // core.js initializeTLSOptions: the ALPN list belongs to the protocol, not
107
108
  // to the application -- only an ALPNCallback keeps ours out. servername is
@@ -114,7 +115,7 @@ function connect(authority, options, listener) {
114
115
  if (!tlsOptions.servername && !net.isIP(host)) {
115
116
  tlsOptions.servername = host;
116
117
  }
117
- socket = tls.connect({ port: Number(port), host, ...tlsOptions });
118
+ socket = tls.connect({ port, host, ...tlsOptions });
118
119
  } else {
119
120
  throw notImplemented(`connect over ${protocol}`);
120
121
  }
@@ -129,4 +130,25 @@ function connect(authority, options, listener) {
129
130
  return session;
130
131
  }
131
132
 
133
+ // node's connect carries util.promisify.custom (internal/http2/core.js): the
134
+ // promisified form resolves with the session on 'connect' and rejects with the
135
+ // very same error object on its first 'error'. Without it util.promisify installs
136
+ // the callback as a third-argument 'connect' listener and resolves undefined.
137
+ Object.defineProperty(connect, promisify.custom, {
138
+ value: function connectAsync(authority, options) {
139
+ return new Promise((resolve, reject) => {
140
+ const session = connect(authority, options, () => {
141
+ session.removeListener('error', reject);
142
+ resolve(session);
143
+ });
144
+ session.once('error', reject);
145
+ });
146
+ }
147
+ });
148
+ // node names the custom function `connect` (assignFunctionName in core.js), and
149
+ // that name is visible through util.promisify(connect).name.
150
+ Object.defineProperty(connect[promisify.custom], 'name', {
151
+ value: 'connect', configurable: true
152
+ });
153
+
132
154
  module.exports = { connect };
@@ -57,7 +57,7 @@ const {
57
57
  DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY,
58
58
  WINDOW_UPDATE, CONTINUATION, ALTSVC, ORIGIN,
59
59
  F_END_STREAM, F_ACK, F_END_HEADERS, F_PADDED, F_PRIORITY,
60
- NO_ERROR, PROTOCOL_ERROR, INTERNAL_ERROR, FLOW_CONTROL_ERROR, STREAM_CLOSED,
60
+ NO_ERROR, CANCEL, PROTOCOL_ERROR, INTERNAL_ERROR, FLOW_CONTROL_ERROR, STREAM_CLOSED,
61
61
  FRAME_SIZE_ERROR, REFUSED_STREAM, COMPRESSION_ERROR, ENHANCE_YOUR_CALM,
62
62
  PREFACE_LEN, HEADER_LEN, readHeader, writeHeader, trimPadding
63
63
  } = f;
@@ -702,7 +702,7 @@ function parseOrigins(buf, start, len) {
702
702
  // getDefaultSettings() so the numbers the guards compare against are the ones node's guards compare
703
703
  // against. They are NOT advertised by default: what goes into a SETTINGS frame is decided by
704
704
  // _advertised, because an advertised value is a promise to the peer rather than a local choice.
705
- const OUR_DEFAULTS = { ...require('node:http2').getDefaultSettings(), enablePush: false };
705
+ const OUR_DEFAULTS = { ...require('node:http2').getDefaultSettings() };
706
706
 
707
707
  // What node actually has in effect before the peer's SETTINGS arrives. Read off
708
708
  // a live session: doc/api/http2.md quotes different numbers for
@@ -1302,10 +1302,13 @@ class Http2ServerSession extends EventEmitter {
1302
1302
  this._addCustomEntries(built.rest);
1303
1303
  this.remoteSettings = { ...PEER_DEFAULTS };
1304
1304
  this.state = {
1305
- effectiveLocalWindowSize: this.localSettings.initialWindowSize,
1305
+ // SETTINGS_INITIAL_WINDOW_SIZE is per-stream: node's connection receive
1306
+ // window stays at 65535 (measured at 'session' on the running binary with
1307
+ // { initialWindowSize: 16384 }), and only new streams take the setting.
1308
+ effectiveLocalWindowSize: 65535,
1306
1309
  effectiveRecvDataLength: 0,
1307
1310
  nextStreamID: 2,
1308
- localWindowSize: this.localSettings.initialWindowSize,
1311
+ localWindowSize: 65535,
1309
1312
  lastProcStreamID: 0,
1310
1313
  remoteWindowSize: 65535,
1311
1314
  outboundQueueSize: 0,
@@ -1568,7 +1571,16 @@ class Http2ServerSession extends EventEmitter {
1568
1571
  this._onWrittenCb = () => this._onWritten();
1569
1572
 
1570
1573
  socket.on('error', (err) => this._onSocketError(err));
1571
- socket.on('end', () => this.destroy(NO_ERROR));
1574
+ socket.on('end', () => {
1575
+ // node has no socket 'end' teardown: its socketOnClose (core.js:3653)
1576
+ // sweeps live streams with NGHTTP2_CANCEL before closeSession destroys
1577
+ // the session. Here 'end' is the first half of that same close, so the
1578
+ // sweep has to precede the NO_ERROR destroy the next line performs.
1579
+ for (const stream of [...this._streams.values()]) {
1580
+ stream.close(CANCEL);
1581
+ }
1582
+ this.destroy(NO_ERROR);
1583
+ });
1572
1584
  // 'finish' means everything we wrote reached the OS, so the GOAWAY of a close() is never
1573
1585
  // cut off by a destroy -- but it is not the end of the session either. node keeps reading
1574
1586
  // until the PEER closes, which is what lets it receive and report the peer's answer to that
@@ -3513,6 +3525,14 @@ class Http2ServerSession extends EventEmitter {
3513
3525
  const trailers = this._share
3514
3526
  ? this._sharedObject(fields, fcount, neverNames(fields, fcount, blockFlags))
3515
3527
  : this._toObject(fields, fcount, neverNames(fields, fcount, blockFlags));
3528
+ // node's inbound trailers callback delivers (trailers, flags, rawTrailers)
3529
+ // to compat. The compat dispatch takes one argument, so the flat raw
3530
+ // name/value list travels on a private event first; the merged map stays
3531
+ // the single argument of the public 'trailers' event. The slice owns the
3532
+ // pairs (the decoder reuses its backing array on the next block).
3533
+ if (existing._compatDispatch !== null) {
3534
+ existing.emit(Symbol.for('h2lean.compat.rawTrailers'), fields.slice(0, fcount));
3535
+ }
3516
3536
  existing.emit('trailers', trailers);
3517
3537
  if (end) {
3518
3538
  existing._remoteEnded();
@@ -4584,6 +4604,14 @@ class Http2ServerSession extends EventEmitter {
4584
4604
  // node cleanupSession also nulls the socket proxy so session.socket reads gone after close
4585
4605
  this._proxySocket = undefined;
4586
4606
  this._open = false;
4607
+ // node's socketOnClose (internal/http2/core.js:3653) sweeps every live and
4608
+ // pending stream with NGHTTP2_CANCEL *before* closeSession destroys the
4609
+ // session with NO_ERROR. closeStream records the code at entry and the later
4610
+ // destroy sees an already-closed stream, so rstCode stays 8. Do the same here;
4611
+ // the socket is already gone, and _destroy() skips sendRst once _open is false.
4612
+ for (const stream of [...this._streams.values()]) {
4613
+ stream.close(CANCEL);
4614
+ }
4587
4615
  if (!this.destroyed) {
4588
4616
  this.destroy(NO_ERROR);
4589
4617
  }
@@ -4642,8 +4670,27 @@ class Http2ServerSession extends EventEmitter {
4642
4670
  return this;
4643
4671
  }
4644
4672
 
4673
+ // Http2Session.setNextStreamID (core.js:1441-1452) moves the handle's next id,
4674
+ // which is also the id nghttp2 reserves for the next PUSH_PROMISE. h2lean's
4675
+ // reservation counter is _nextPushSid, so both have to move together; the
4676
+ // state field is the read-only view of the same handle value. node validates
4677
+ // and returns undefined on every session, server half included.
4645
4678
  setNextStreamID(id) {
4646
- this.state.nextStreamID = id; return this;
4679
+ if (this.destroyed) {
4680
+ throw invalidSession();
4681
+ }
4682
+ if (typeof id !== 'number') {
4683
+ throw extError('ERR_INVALID_ARG_TYPE',
4684
+ `The "id" argument must be of type number. Received ${received(id)}`);
4685
+ }
4686
+ if (id <= 0 || id > 0xffffffff) {
4687
+ const err = new RangeError('The value of "id" is out of range. '
4688
+ + `It must be > 0 and <= 4294967295. Received ${outOfRangeValue(id)}`);
4689
+ err.code = 'ERR_OUT_OF_RANGE';
4690
+ throw err;
4691
+ }
4692
+ this.state.nextStreamID = id;
4693
+ this._nextPushSid = id;
4647
4694
  }
4648
4695
 
4649
4696
  // Advertise new settings to the peer. node's session.settings() returns nothing -- measured
@@ -96,7 +96,7 @@ const {
96
96
  PROTOCOL_ERROR, INTERNAL_ERROR, HEADERS
97
97
  } = frames;
98
98
  const hdr = require('../headers');
99
- const { Http2Stream, EMPTY, READABLE_HWM, emitCloseNT, emitErrorCloseNT, emitErrorOnlyNT, emitEndNT, wantTrailersNT, finishNT, emitEndCloseNT, emitCloseDeliveredNT, autoCloseNT, noopClose, FILE_CHUNK, isFileHandle, argTypeError, fdOptions, prepareResponseHeadersObject, errorOf, validateRstCode, abortError, validateObjectArg, validateSignalArg, streamErrorOf, createStreamIterator } = require('../Http2Stream');
99
+ const { Http2Stream, EMPTY, kCompatSocket, READABLE_HWM, emitCloseNT, emitErrorCloseNT, emitErrorOnlyNT, emitEndNT, wantTrailersNT, finishNT, emitEndCloseNT, emitCloseDeliveredNT, autoCloseNT, noopClose, FILE_CHUNK, isFileHandle, argTypeError, fdOptions, prepareResponseHeadersObject, errorOf, validateRstCode, abortError, validateObjectArg, validateSignalArg, streamErrorOf, createStreamIterator } = require('../Http2Stream');
100
100
 
101
101
  class Http2ServerStream extends Http2Stream {
102
102
  constructor(session, id) {
@@ -205,6 +205,10 @@ class Http2ServerStream extends Http2Stream {
205
205
  // The finish work carried into a close-delivery tick scheduled by the same call
206
206
  // of _endLocalSide (see the fuse there) instead of a nextTick of its own.
207
207
  this._finishFuse = false;
208
+ // Reserved here, as node reserves kProxySocket in its stream constructor, so
209
+ // the compat layer's first `.socket` read fills a slot instead of adding one
210
+ // to an already-live object. Only filled when the application reads it.
211
+ this[kCompatSocket] = null;
208
212
  }
209
213
 
210
214
  get destroyed() {
@@ -945,13 +949,13 @@ class Http2ServerStream extends Http2Stream {
945
949
 
946
950
  priority() {
947
951
  // RFC 9218 deprecates the priority scheme; node still accepts the call but
948
- // refuses a destroyed stream (internal/http2/core.js:2617). Returning true
949
- // without reordering anything is the honest v1 answer. The DEP0194 warning
950
- // is attached below the class, byte-identical to node's (typo included).
952
+ // refuses a destroyed stream (internal/http2/core.js:2617) and returns
953
+ // undefined -- the shared prototype method has no return statement. The
954
+ // DEP0194 warning is attached below the class, byte-identical to node's
955
+ // (typo included).
951
956
  if (this._destroyed) {
952
957
  throw errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed');
953
958
  }
954
- return true;
955
959
  }
956
960
 
957
961
  get pushAllowed() {