h2lean 0.19.5 → 0.19.7

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.
@@ -61,13 +61,15 @@
61
61
  // (measured, tools/probe-client-status.js; this closes the empty-block
62
62
  // divergence).
63
63
  //
64
- // KNOWN DIVERGENCE: a stream leaves _streams when its response ends (_dropStream on
65
- // END_STREAM), while node keeps it in state.streams until the Duplex is destroyed. A
66
- // RST_STREAM that arrives after END_STREAM therefore finds nothing here and is ignored,
67
- // so a request whose body was never ended -- or whose response body is still buffered
68
- // unread -- never closes: node reports aborted/finish/close, h2lean waits forever.
69
- // _wireDone already tracks these streams for the graceful close; the reset path does not
70
- // consult it. Pinned as the excluded shape in test/client/client-rst.test.js.
64
+ // A stream leaves _streams only when its Duplex closes (_trackClose), the way node
65
+ // removes it from state.streams only in the stream's destroy path (core.js:2531). END_STREAM
66
+ // ends the wire half but not the stream: a request whose writable was never ended, or
67
+ // whose response body is still buffered unread, stays reachable so a later RST_STREAM
68
+ // still reaches onStreamClose (core.js:607) -- aborted/finish/close with rstCode 0 on a
69
+ // NO_ERROR reset, or a deferred close once the buffered body is consumed. _dropStream's
70
+ // `keep` argument is that half-closed state; the bookkeeping it still does is what the
71
+ // graceful close needs. Measured with tools/probe-client-unfinished-post.js and pinned in
72
+ // test/client/client-rst.test.js.
71
73
  //
72
74
  // settings() and the initial submission take customSettings, node-shaped and measured on
73
75
  // a live node 26 client against a raw frame-decoding peer (test/custom-settings.test.js):
@@ -334,6 +336,12 @@ class Http2ClientSession extends EventEmitter {
334
336
  this._maxReservedRemoteStreams = opts.maxReservedRemoteStreams === undefined
335
337
  ? 200 : opts.maxReservedRemoteStreams;
336
338
  this._streams = new Map();
339
+ // Streams whose wire life is still open. A stream that took END_STREAM stops
340
+ // counting against the peer's max_concurrent_streams as soon as nghttp2 closes
341
+ // its C-side handle, even while its Duplex is finishing on the JS side. The id
342
+ // stays in _streams until 'close' (so a late RST can find it), so concurrency
343
+ // has to use this count rather than the map's size.
344
+ this._liveWire = 0;
337
345
  // Streams whose wire life is over (_dropStream) but whose Duplex has not
338
346
  // emitted 'close' yet -- an unread response body keeps the readable half
339
347
  // open. node's session counts a stream until it is destroyed, not until
@@ -1062,7 +1070,7 @@ class Http2ClientSession extends EventEmitter {
1062
1070
  _enqueue(req) {
1063
1071
  const max = this.remoteSettings.maxConcurrentStreams;
1064
1072
  if (this._outboundQueue.length === 0
1065
- && (max === undefined || this._streams.size < max)) {
1073
+ && (max === undefined || this._liveWire < max)) {
1066
1074
  this._openStream(req);
1067
1075
  } else {
1068
1076
  this._outboundQueue.push(req);
@@ -1078,6 +1086,7 @@ class Http2ClientSession extends EventEmitter {
1078
1086
  // the peer's number and not the 65535 default the peer may never have chosen.
1079
1087
  req.stream._sendWin = this.remoteSettings.initialWindowSize;
1080
1088
  req.stream._opened = true;
1089
+ this._liveWire++;
1081
1090
  this._streams.set(req.stream.id, req.stream);
1082
1091
  this._sendRequest(req.stream, req.list, req.nl, req.end, req.hp);
1083
1092
  }
@@ -1089,7 +1098,7 @@ class Http2ClientSession extends EventEmitter {
1089
1098
  return;
1090
1099
  }
1091
1100
  const max = this.remoteSettings.maxConcurrentStreams;
1092
- while (this._outboundQueue.length > 0 && (max === undefined || this._streams.size < max)) {
1101
+ while (this._outboundQueue.length > 0 && (max === undefined || this._liveWire < max)) {
1093
1102
  const req = this._outboundQueue.shift();
1094
1103
  if (this.closed && req.stream.id > (this._goawayLastStreamID || 0)) {
1095
1104
  // past the peer's GOAWAY mark: this request will not be carried; surface it.
@@ -2180,10 +2189,17 @@ class Http2ClientSession extends EventEmitter {
2180
2189
  this._hdrLen += len;
2181
2190
  return;
2182
2191
  }
2192
+ // Size the first buffer for the frame in hand: a 16 KiB HEADERS would
2193
+ // otherwise allocate the 8 KiB default and immediately discard it for a
2194
+ // doubled one. The backing store stays with the session, so the first
2195
+ // capacity is the one the whole block is assembled into.
2183
2196
  if (this._hdr === null) {
2184
- this._hdr = Buffer.allocUnsafe(8192);
2185
- }
2186
- if (this._hdrLen + len > this._hdr.length) {
2197
+ let cap = STAGE_MIN;
2198
+ while (cap < len) {
2199
+ cap *= 2;
2200
+ }
2201
+ this._hdr = Buffer.allocUnsafe(cap);
2202
+ } else if (this._hdrLen + len > this._hdr.length) {
2187
2203
  let cap = this._hdr.length * 2;
2188
2204
  while (cap < this._hdrLen + len) {
2189
2205
  cap *= 2;
@@ -2497,6 +2513,13 @@ class Http2ClientSession extends EventEmitter {
2497
2513
  }
2498
2514
  return this._fatal(PROTOCOL_ERROR, 'response HEADERS on an unopened stream id');
2499
2515
  }
2516
+ // nghttp2 silently drops a block for a stream both of whose wire halves are
2517
+ // done (client-fatal.test.js: a second HEADERS/ES on a completed id). The id
2518
+ // stays in _streams until the Duplex closes, so the old "no stream" branch no
2519
+ // longer catches this shape; without this guard it would read as trailers.
2520
+ if (stream._rEof && stream._endSent) {
2521
+ return;
2522
+ }
2500
2523
  if (this._refuseHeaders(sid, stream, fields, fcount)) {
2501
2524
  return;
2502
2525
  }
@@ -2527,7 +2550,7 @@ class Http2ClientSession extends EventEmitter {
2527
2550
  }
2528
2551
  stream._onHeaders(status, fields, fcount, sensitive, end, flags);
2529
2552
  if (end) {
2530
- this._dropStream(sid);
2553
+ this._dropStream(sid, true);
2531
2554
  }
2532
2555
  }
2533
2556
 
@@ -2653,7 +2676,7 @@ class Http2ClientSession extends EventEmitter {
2653
2676
  // shared buffer it reused -- that buffer is gone.
2654
2677
  stream._onData(buf.subarray(p, p + l));
2655
2678
  if (flags & F_END_STREAM) {
2656
- stream._endRead(); this._dropStream(sid);
2679
+ stream._endRead(); this._dropStream(sid, true);
2657
2680
  }
2658
2681
  }
2659
2682
 
@@ -2682,7 +2705,7 @@ class Http2ClientSession extends EventEmitter {
2682
2705
  }
2683
2706
  }
2684
2707
  if (flags & F_END_STREAM) {
2685
- stream._endRead(); this._dropStream(sid);
2708
+ stream._endRead(); this._dropStream(sid, true);
2686
2709
  }
2687
2710
  }
2688
2711
 
@@ -2720,9 +2743,17 @@ class Http2ClientSession extends EventEmitter {
2720
2743
 
2721
2744
  _onRst(sid, code) {
2722
2745
  const stream = this._streams.get(sid);
2723
- if (stream === undefined) {
2746
+ // node's onStreamClose guard (core.js:609): a stream already destroyed -- including
2747
+ // one whose END_STREAM and finished writable just auto-destroyed it on a tick that
2748
+ // has not reached its 'close' yet -- is gone at the C layer; its reset is ignored.
2749
+ // So is one whose two wire halves are both done: nghttp2 has closed that stream and
2750
+ // hands no further close callback to JS, which is why the reset after a completed
2751
+ // request keeps rstCode 0 (test/client/client-rst.test.js).
2752
+ if (stream === undefined || stream._destroyFlag ||
2753
+ (stream._rEof && stream._endSent)) {
2724
2754
  return;
2725
2755
  }
2756
+ stream._flushWireEnd();
2726
2757
  this._dropStream(sid);
2727
2758
  stream._onRst(code);
2728
2759
  }
@@ -2732,7 +2763,12 @@ class Http2ClientSession extends EventEmitter {
2732
2763
  // is gone -- including the inbound-RST path, where _onRst has already dropped it,
2733
2764
  // so we never answer a reset with a reset of our own.
2734
2765
  rstStream(sid, code) {
2735
- if (this.destroyed || !this._open || !this._streams.has(sid)) {
2766
+ const stream = this._streams.get(sid);
2767
+ // A stream whose two wire halves are done is closed in nghttp2 even while its
2768
+ // Duplex is finishing: an application destroy then finds no handle to submit a
2769
+ // reset through (client-destroy-code.test.js, the closed-stream cases).
2770
+ if (this.destroyed || !this._open || stream === undefined ||
2771
+ (stream._rEof && stream._endSent)) {
2736
2772
  return;
2737
2773
  }
2738
2774
  const body = Buffer.allocUnsafe(4);
@@ -3296,11 +3332,18 @@ class Http2ClientSession extends EventEmitter {
3296
3332
 
3297
3333
  // The 'close' subscription is installed at construction, before any event can
3298
3334
  // fire, so the wire-done bookkeeping never races the Duplex's own teardown.
3299
- // It is the one subscription per stream the session keeps: the mark it clears
3300
- // is what lets a graceful close outlive an unread response body (see _wireDone).
3335
+ // It is the one subscription per stream the session keeps: the marks it clears are
3336
+ // what let a graceful close outlive an unread response body (see _wireDone) and what
3337
+ // finally retire a half-closed stream from the id map (see _dropStream's `keep`).
3301
3338
  _trackClose(stream) {
3302
3339
  stream.on('close', () => {
3303
3340
  this._wireDone.delete(stream);
3341
+ if (this._streams.get(stream.id) === stream) {
3342
+ this._streams.delete(stream.id);
3343
+ // A queued request was waiting for this stream's concurrency slot. The old
3344
+ // _dropStream did the draining at END_STREAM; now the id is retired here.
3345
+ this._drainQueue();
3346
+ }
3304
3347
  if (this.destroyed && !this._closeEmitted && !this._destroyScheduled
3305
3348
  && this._wireDone.size === 0) {
3306
3349
  // The socket is already gone (_onSocketClose deferred to this moment):
@@ -3337,16 +3380,28 @@ class Http2ClientSession extends EventEmitter {
3337
3380
  }
3338
3381
  }
3339
3382
 
3340
- _dropStream(sid) {
3383
+ // `keep` is the inbound END_STREAM shape: the remote half is done but the Duplex may
3384
+ // still owe its own 'finish'/'close', and a RST_STREAM can arrive in that window. node
3385
+ // keeps the id in state.streams until the stream's destroy (core.js:2531), so the id
3386
+ // stays here too; _trackClose retires it. Every other caller has finished the stream's
3387
+ // wire life for good and drops the id at once.
3388
+ _dropStream(sid, keep) {
3341
3389
  const stream = this._streams.get(sid);
3342
3390
  if (stream !== undefined && stream._debtMarked) {
3343
3391
  this._removeDebt(stream);
3344
3392
  }
3345
- this._streams.delete(sid);
3393
+ if (!keep) {
3394
+ this._streams.delete(sid);
3395
+ }
3346
3396
  if (stream !== undefined) {
3347
- // The wire life is over; the Duplex may still owe 'end'/'close' (an unread
3348
- // body). The session's graceful close waits for that 'close' (_wireDone).
3349
- this._wireDone.add(stream);
3397
+ if (!this._wireDone.has(stream)) {
3398
+ // Counted once: a second _dropStream for the same half-closed stream must
3399
+ // not free the concurrency slot twice.
3400
+ this._liveWire--;
3401
+ // The wire life is over; the Duplex may still owe 'end'/'close' (an unread
3402
+ // body). The session's graceful close waits for that 'close' (_wireDone).
3403
+ this._wireDone.add(stream);
3404
+ }
3350
3405
  }
3351
3406
  this._drainQueue();
3352
3407
  this._maybeClose();
@@ -924,7 +924,7 @@ class Http2ClientStream extends Http2Stream {
924
924
  // iterator's settle(null) outruns the destroy's 'error' pair and a
925
925
  // helper started mid-teardown answers a clean done (the some/every
926
926
  // shape, measured on node v26.12.1: every() rejects ABORT_ERR).
927
- if (this._errored !== undefined) {
927
+ if (this._errored !== undefined || this._endDelivered === true) {
928
928
  return;
929
929
  }
930
930
  this._endDelivered = true;
@@ -933,6 +933,19 @@ class Http2ClientStream extends Http2Stream {
933
933
  });
934
934
  }
935
935
 
936
+ // The wire's END_STREAM is delivered inside node's socket read (onStreamClose calls
937
+ // stream.read(0) there), so a RST_STREAM in the same read batch is reported after 'end'.
938
+ // h2lean queues that 'end' on a tick; flush it first when the reset arrives, or the
939
+ // reset's 'aborted' would invert the pair. The scheduled tick then sees _endDelivered
940
+ // and delivers nothing twice.
941
+ _flushWireEnd() {
942
+ if (this._endEmitted === true && this._endDelivered !== true) {
943
+ this._endDelivered = true;
944
+ this.emit('end');
945
+ this._maybeAutoClose();
946
+ }
947
+ }
948
+
936
949
  _endRead() {
937
950
  if (this._remoteEnded) {
938
951
  return;
@@ -1043,14 +1043,22 @@ const DEFAULT_MAX_OUTSTANDING_PINGS = 10;
1043
1043
  // (util.js:279, MathMax(1, ...)) and multiplied by 1 000 000 by the C++ layer
1044
1044
  // (node_http2.cc:210), whose default is 10 000 000 (node_http2.h:40).
1045
1045
  const DEFAULT_MAX_SESSION_MEMORY = 10 * 1000 * 1000;
1046
- // node charges sizeof(Http2Stream) for each live stream (node_http2.cc:915/925)
1047
- // plus name.length + value.length + 32 for each header (:2745). sizeof is a C++
1048
- // compile-time constant not present in the JS source; it was derived from a
1049
- // live node 26 server at a 1 MB budget with a minimal request block: 1028
1050
- // streams were accepted, and the block costs ~180 bytes, leaving ~794 for the
1051
- // stream record. 800 is the rounded charge; the budget is a bound, not a byte
1052
- // counter, and the test pins the refusal shape rather than the exact stream.
1053
- const STREAM_MEM_CHARGE = 800;
1046
+ // node checks and charges sizeof(Http2Stream) per live stream
1047
+ // (node_http2.cc:915/925) plus name.length + value.length + 32 per header
1048
+ // (:2745). sizeof is a C++ compile-time constant: compiled against the v26.12.1
1049
+ // headers it is 360 octets, not the ~800 an earlier indirect estimate assigned
1050
+ // it. nghttp2 also charges its own per-stream allocation to the same budget
1051
+ // (current_session_memory(), node_http2.h:792); h2lean has no nghttp2, so it
1052
+ // adds a 131-octet allowance derived from the live trip point with this test's
1053
+ // header block. The sum is a bound, not a byte-exact model: indexed
1054
+ // pseudo-headers and nghttp2's hash-table growth move node's trip point.
1055
+ const STREAM_MEM_CHARGE = 360 + 131;
1056
+ // The session's own persistent buffers count against node's budget too: node
1057
+ // includes sizeof(Http2Session) (760 octets in the same probe) in
1058
+ // current_session_memory(). h2lean's JS counterpart is the pair of scratch
1059
+ // buffers plus the first staging buffer; the header assembly buffer is charged
1060
+ // when it is actually allocated, in _appendHdr.
1061
+ const SESSION_MEM_CHARGE = HEADER_LEN + 6 + STAGE_MIN;
1054
1062
  // nghttp2 answers a failed stream-open callback with this session error
1055
1063
  // (node_http2.cc:1073-1085, NGHTTP2_ERR_CALLBACK_FAILURE). Measured on a live
1056
1064
  // node 26 server: ERR_HTTP2_ERROR with this message on both 'sessionError' and
@@ -1335,10 +1343,12 @@ class Http2ServerSession extends EventEmitter {
1335
1343
  // would cross the budget (node_http2.cc CanAddStream / OnHeader). The charge
1336
1344
  // leaves with the stream in _dropStream, so a connection that drains can open
1337
1345
  // new streams again. node counts queued outbound bytes too; those are already
1338
- // bounded separately by _heldCost (MAX_SESSION_HOLD).
1346
+ // bounded separately by _heldCost (MAX_SESSION_HOLD). The session's own
1347
+ // scratch and staging buffers open the budget, as sizeof(Http2Session) does
1348
+ // on node; _appendHdr adds the header assembly buffer when it exists.
1339
1349
  this._memLimit = typeof opts.maxSessionMemory === 'number'
1340
1350
  ? Math.max(1, opts.maxSessionMemory) * 1000000 : DEFAULT_MAX_SESSION_MEMORY;
1341
- this._memUsed = 0;
1351
+ this._memUsed = SESSION_MEM_CHARGE;
1342
1352
  // Outbound padding: node's C++ switch only acts on 0/1/2; every other
1343
1353
  // number is an unpadded session (measured on a live node 26 server).
1344
1354
  this._padding = opts.paddingStrategy === f.PADDING_ALIGNED ? f.PADDING_ALIGNED
@@ -2912,9 +2922,6 @@ class Http2ServerSession extends EventEmitter {
2912
2922
  this._hdrLen += len;
2913
2923
  return;
2914
2924
  }
2915
- if (this._hdr === null) {
2916
- this._hdr = Buffer.allocUnsafe(8192);
2917
- }
2918
2925
  // No maxHeaderListSize test here, although this is where the octets are counted: the limit
2919
2926
  // is about the size of the header LIST, which is only known once the block is decoded, and
2920
2927
  // h2lean applies it there (_processHeaders). Measured against node, an over-limit block
@@ -2923,14 +2930,28 @@ class Http2ServerSession extends EventEmitter {
2923
2930
  // which turns one bad request into an error for every other client on the session. The
2924
2931
  // buffer is bounded without it: MAX_CONTINUATIONS frames of at most
2925
2932
  // localSettings.maxFrameSize octets each, 8 x 16 KiB by default.
2926
- if (this._hdrLen + len > this._hdr.length) {
2927
- let cap = this._hdr.length * 2;
2933
+ // Size the first buffer for the frame in hand: a 16 KiB HEADERS would
2934
+ // otherwise allocate the 8 KiB default and immediately throw it away for
2935
+ // a doubled one. STAGE_MIN is the same starting size as the staging buffer,
2936
+ // and the backing store stays with the session for its whole life, so its
2937
+ // octets join the other persistent buffers in the maxSessionMemory budget.
2938
+ if (this._hdr === null) {
2939
+ let cap = STAGE_MIN;
2940
+ while (cap < len) {
2941
+ cap *= 2;
2942
+ }
2943
+ this._hdr = Buffer.allocUnsafe(cap);
2944
+ this._memUsed += cap;
2945
+ } else if (this._hdrLen + len > this._hdr.length) {
2946
+ const old = this._hdr.length;
2947
+ let cap = old * 2;
2928
2948
  while (cap < this._hdrLen + len) {
2929
2949
  cap *= 2;
2930
2950
  }
2931
2951
  const bigger = Buffer.allocUnsafe(cap);
2932
2952
  f.copyInto(bigger, 0, this._hdr, 0, this._hdrLen);
2933
2953
  this._hdr = bigger;
2954
+ this._memUsed += cap - old;
2934
2955
  }
2935
2956
  f.copyInto(this._hdr, this._hdrLen, buf, start, start + len);
2936
2957
  this._hdrLen += len;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h2lean",
3
- "version": "0.19.5",
3
+ "version": "0.19.7",
4
4
  "description": "Pure-JavaScript HTTP/2 for Node.js — a drop-in node:http2 replacement (server and client, h2c and TLS) with zero dependencies",
5
5
  "main": "index.js",
6
6
  "files": [