h2lean 0.2.3 → 0.2.5

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.
@@ -66,6 +66,13 @@ const { EventEmitter } = require('node:events');
66
66
  const tls = require('node:tls');
67
67
  const f = require('./frames');
68
68
  const { Decoder, Encoder, HPackError } = require('./hpack');
69
+ const FlatList = require('./flat-list');
70
+ // The process-wide inbound decode scratch, same shape and size as the server
71
+ // session's; the full why-sharing-is-safe argument lives with the server's
72
+ // instance (lib/session.js). A module-level instance here too, not the server's
73
+ // list: the two never meet the same fill, and coupling the client module to the
74
+ // server's scratch would buy nothing.
75
+ const FLAT = new FlatList(64);
69
76
  const { nullProto, isFieldName, lowerName, CONNECTION_SPECIFIC, SINGLE_VALUE_FIELDS } = require('./headers');
70
77
  const { ClientHttp2Stream } = require('./client-stream');
71
78
  const { pieceByteAt, pieceSlice, pieceConcat, pieceEquals } = require('./pieces');
@@ -146,7 +153,6 @@ class ClientHttp2Session extends EventEmitter {
146
153
  this._encoder = new Encoder(this.remoteSettings.headerTableSize,
147
154
  this.localSettings.headerTableSize);
148
155
  this._blocks = new WeakMap();
149
- this._flat = [];
150
156
  // node's strictSingleValueFields option (validateSessionOptions, default true,
151
157
  // internal/http2/core.js): gates the strict-single-value rule on the request list
152
158
  // (_addField below). The connect() call surfaces the validation the way
@@ -519,8 +525,9 @@ class ClientHttp2Session extends EventEmitter {
519
525
  if (this._strictSingle) {
520
526
  // the duplicate check rides _addField's own loop, the way node's
521
527
  // processHeader runs it inside buildNgHeaderString's one pass; the scratch
522
- // survives between calls and is cleared here
523
- this._singlesSeen.length = 0;
528
+ // is dropped here -- reassigned, not length-cleared, for the same
529
+ // right-trim reason as the module scratch in headers.js (OPTIMIZATION.md item 38)
530
+ this._singlesSeen = [];
524
531
  }
525
532
  if (Array.isArray(src)) {
526
533
  for (let i = 0; i + 1 < src.length; i += 2) {
@@ -1423,7 +1430,7 @@ class ClientHttp2Session extends EventEmitter {
1423
1430
 
1424
1431
  _processBlock(sid, end, block, pieces, from, to) {
1425
1432
  const stream = this._streams.get(sid);
1426
- const flat = this._flat;
1433
+ const flat = FLAT;
1427
1434
  // The cache is disabled (null) when stream === undefined (we must decode for
1428
1435
  // HPACK state but there is nothing to cache it for) and when the application
1429
1436
  // opted out via shapeCache: false.
@@ -1431,19 +1438,26 @@ class ClientHttp2Session extends EventEmitter {
1431
1438
  const slot = shapes === null ? 0
1432
1439
  : (block !== null ? this._shapeSlot(block) : this._shapeSlotPieces(pieces, from, to));
1433
1440
  const hit = shapes === null ? undefined : shapes.get(slot);
1434
- let fields = flat;
1441
+ // where this response's field list comes from: the scratch's backing array
1442
+ // on a decode, a cached copy on a shape hit -- both read by index, so the
1443
+ // valid length travels next to the list (same as the server session)
1444
+ let fields;
1445
+ let fcount;
1435
1446
  try {
1436
1447
  if (hit !== undefined && (block !== null
1437
1448
  ? hit.block.equals(block)
1438
1449
  : pieceEquals(hit.block, pieces, from, to))) {
1439
1450
  this._shapeHits++;
1440
1451
  fields = hit.flat;
1452
+ fcount = fields.length;
1441
1453
  } else {
1442
1454
  if (block !== null) {
1443
1455
  this._decoder.decode(block, 0, block.length, flat);
1444
1456
  } else {
1445
1457
  this._decoder.decodePieces(pieces, from, to, flat);
1446
1458
  }
1459
+ fields = flat.items;
1460
+ fcount = flat.count;
1447
1461
  if (shapes !== null) {
1448
1462
  if (++this._shapeMisses > 64 && this._shapeHits * 4 < this._shapeMisses) {
1449
1463
  this._shapes = null;
@@ -1453,7 +1467,7 @@ class ClientHttp2Session extends EventEmitter {
1453
1467
  }
1454
1468
  shapes.set(slot, {
1455
1469
  block: block !== null ? Buffer.from(block) : pieceConcat(pieces, from, to),
1456
- flat: flat.slice(0)
1470
+ flat: fields.slice(0, fcount)
1457
1471
  });
1458
1472
  }
1459
1473
  }
@@ -1483,10 +1497,10 @@ class ClientHttp2Session extends EventEmitter {
1483
1497
  }
1484
1498
  return this._fatal(PROTOCOL_ERROR, 'response HEADERS on an unopened stream id');
1485
1499
  }
1486
- if (this._refuseHeaders(sid, stream, fields)) {
1500
+ if (this._refuseHeaders(sid, stream, fields, fcount)) {
1487
1501
  return;
1488
1502
  }
1489
- const headers = this._toObject(fields);
1503
+ const headers = this._toObject(fields, fcount);
1490
1504
  stream._onHeaders(headers, end);
1491
1505
  if (end) {
1492
1506
  this._dropStream(sid);
@@ -1503,10 +1517,10 @@ class ClientHttp2Session extends EventEmitter {
1503
1517
  // Both shapes used to reach the application unvalidated. Returns true when
1504
1518
  // the block was refused, so the caller does not build or hand over the
1505
1519
  // header object.
1506
- _refuseHeaders(sid, stream, fields) {
1520
+ _refuseHeaders(sid, stream, fields, count) {
1507
1521
  let status = 0;
1508
1522
  let bad = null;
1509
- for (let i = 0; i < fields.length; i += 2) {
1523
+ for (let i = 0; i < count; i += 2) {
1510
1524
  const name = fields[i];
1511
1525
  if (name.charCodeAt(0) !== 58) {
1512
1526
  continue;
@@ -1540,11 +1554,11 @@ class ClientHttp2Session extends EventEmitter {
1540
1554
  return true;
1541
1555
  }
1542
1556
 
1543
- _toObject(flat) {
1557
+ _toObject(fields, count) {
1544
1558
  const o = nullProto();
1545
- for (let i = 0; i < flat.length; i += 2) {
1546
- const name = flat[i];
1547
- let value = flat[i + 1];
1559
+ for (let i = 0; i < count; i += 2) {
1560
+ const name = fields[i];
1561
+ let value = fields[i + 1];
1548
1562
  if (name === ':status') {
1549
1563
  value = value | 0;
1550
1564
  }
@@ -1855,7 +1869,8 @@ class ClientHttp2Session extends EventEmitter {
1855
1869
  r.stream.destroy(cancelErr(err));
1856
1870
  }
1857
1871
  }
1858
- this._outboundQueue.length = 0;
1872
+ // reassigned, not length-cleared (OPTIMIZATION.md item 38)
1873
+ this._outboundQueue = [];
1859
1874
  const socket = this.socket;
1860
1875
  this._discardOut();
1861
1876
  if (!socket.destroyed) {
@@ -0,0 +1,61 @@
1
+ 'use strict';
2
+
3
+ // A preallocated field list filled through push. `new Array(capacity)` plus
4
+ // `items[count++] = value` never allocates per block and never right-trims the
5
+ // store the way `length = 0` does -- the trim makes the next fill re-grow it from
6
+ // scratch on V8 (OPTIMIZATION.md item 38) -- and a cursor write beats both
7
+ // Array#push shapes at the sizes a header block reaches (bench/micro/prealloc.js,
8
+ // item 39). This class keeps the cursor write, hidden inside push(); the cost is
9
+ // the array staying HOLEY_ELEMENTS forever, so every read carries a hole check,
10
+ // which the whole fill-then-read cycle still pays for.
11
+ //
12
+ // push() doubles as the overflow detector: a write past the preallocation grows
13
+ // the store under the caller, and the oversized store is kept for the rest of the
14
+ // event-loop turn (the other blocks of the same read batch reuse it) while one
15
+ // setImmediate later -- the check phase of the same iteration -- it is rebuilt at
16
+ // the preallocation again, so one oversized block cannot pin its size for the
17
+ // process lifetime. The re-grow a workload whose blocks all exceed the capacity
18
+ // pays is one small array per turn; the common workload never allocates at all.
19
+ //
20
+ // Only items[0..count) is valid after a fill. The class fixes neither a size nor
21
+ // an instance: the capacity is the caller's decision, made where the fill pattern
22
+ // is known.
23
+ class FlatList {
24
+ constructor(capacity) {
25
+ this.capacity = capacity;
26
+ this.items = new Array(capacity);
27
+ this.count = 0;
28
+ this._shrinkQueued = false;
29
+ }
30
+
31
+ // The decoder's write: appends one item, keeping count in lockstep with the
32
+ // slot writes, and answers the growth question at the exact write that grows
33
+ // the store -- no per-block tail check is needed.
34
+ push(value) {
35
+ if (this.count === this.items.length) {
36
+ this.grown();
37
+ }
38
+ this.items[this.count++] = value;
39
+ }
40
+
41
+ // A fill starts at slot 0: move the cursor back. The store is left alone --
42
+ // right-trimming it would make the next fill re-grow it from scratch (item 38).
43
+ reset() {
44
+ this.count = 0;
45
+ }
46
+
47
+ grown() {
48
+ if (this._shrinkQueued) {
49
+ return;
50
+ }
51
+ this._shrinkQueued = true;
52
+ setImmediate(() => {
53
+ this._shrinkQueued = false;
54
+ if (this.items.length > this.capacity) {
55
+ this.items = new Array(this.capacity);
56
+ }
57
+ });
58
+ }
59
+ }
60
+
61
+ module.exports = FlatList;
package/lib/headers.js CHANGED
@@ -195,6 +195,22 @@ function nameCacheSize() {
195
195
  // node does not make.
196
196
  const badValue = /[\u0000-\u0008\u000a-\u001f\u007f]/;
197
197
 
198
+ // The strict-single-value scratch for parse(): one array for the whole module,
199
+ // cleared at entry and never held across a call -- parse() is synchronous and
200
+ // runs no callback, so no call can observe another's list. The shape is node's
201
+ // own (buildNgHeaderString checks a lazily-grown array inline in its one pass,
202
+ // internal/http2/util.js) and the one the client's request() carries
203
+ // (lib/client-session.js, OPTIMIZATION.md item 36). Measured honestly: at the
204
+ // granularity parse() acts on, the swap from a per-call Set is inside the noise
205
+ // -- item 36's win came from removing request()'s second pass over the flat
206
+ // list, which parse() never had; the component costs are in OPTIMIZATION.md
207
+ // item 37. It is kept for the shape parity, not for speed
208
+ // (bench/micro/parse-singles.js).
209
+ // Reassigned, not length-cleared: `length = 0` right-trims the backing store so the
210
+ // next fill re-grows it, and the fresh allocation measures cheaper on both time and,
211
+ // at the sizes this sees, GC (OPTIMIZATION.md item 38).
212
+ let singlesSeen = [];
213
+
198
214
  // Kept as a Set: at five names the shape of the operation decides it, not the
199
215
  // size (OPTIMIZATION.md item 10).
200
216
  // RFC 9113 8.2.2 forbids these on an HTTP/2 connection: they are hop-by-hop in HTTP/1.1,
@@ -271,9 +287,16 @@ function parse(headers, sensitive,
271
287
  throw httpError('ERR_HTTP2_INVALID_HEADER_VALUE', 'headers must be an object');
272
288
  }
273
289
  const neverSet = sensitive || headers[KSensitiveHeaders];
274
- const neverList = Array.isArray(neverSet) && neverSet.length > 0
275
- ? new Set(neverSet.map((s) => lowerName(s)))
276
- : null;
290
+ // Inserted in one loop, not new Set(neverSet.map(...)): the map's intermediate array
291
+ // and its closure are one allocation each per sensitive response, measured at
292
+ // bench/micro/parse-singles.js.
293
+ let neverList = null;
294
+ if (Array.isArray(neverSet) && neverSet.length > 0) {
295
+ neverList = new Set();
296
+ for (let i = 0; i < neverSet.length; i++) {
297
+ neverList.add(lowerName(neverSet[i]));
298
+ }
299
+ }
277
300
 
278
301
  const pseudo = [];
279
302
  const fields = [];
@@ -294,7 +317,9 @@ function parse(headers, sensitive,
294
317
  // copy -- regular field or pseudo-header alike -- or for a multi-element array on
295
318
  // one, before any stream or octet exists. The singles walk stays in field order, so
296
319
  // the first problem in the caller's order is the one reported.
297
- const singles = strict ? new Set() : null;
320
+ if (strict) {
321
+ singlesSeen = [];
322
+ }
298
323
  for (let i = 0; i < keys.length; i++) {
299
324
  let key;
300
325
  let raw;
@@ -325,11 +350,11 @@ function parse(headers, sensitive,
325
350
  throw httpError('ERR_HTTP2_HEADER_SINGLE_VALUE',
326
351
  `Header field "${key}" must only have a single value`);
327
352
  }
328
- if (singles.has(key)) {
353
+ if (singlesSeen.indexOf(key) !== -1) {
329
354
  throw httpError('ERR_HTTP2_HEADER_SINGLE_VALUE',
330
355
  `Header field "${key}" must only have a single value`);
331
356
  }
332
- singles.add(key);
357
+ singlesSeen.push(key);
333
358
  }
334
359
 
335
360
  if (key[0] === ':') {
package/lib/hpack.js CHANGED
@@ -579,10 +579,22 @@ class Decoder {
579
579
  }
580
580
  }
581
581
 
582
- // Refills the reusable flat array `out` with name, value, name, value, ...
583
- // and returns the number of field lines.
582
+ // Refills `out` with name, value, name, value, ... and returns the number of
583
+ // field lines. `out` is either the caller's plain array or a FlatList scratch
584
+ // (lib/flat-list.js). The plain array is written through a local cursor and its
585
+ // length moves with the fill at the tail -- a reused array carries stale slots
586
+ // beyond n, and a preallocated backing store must never see `length = 0`, the
587
+ // store would be right-trimmed and the next block would re-grow it
588
+ // (OPTIMIZATION.md item 38). The FlatList is filled through out.push(), which
589
+ // keeps `count` in lockstep and doubles as the overflow detector, so its tail
590
+ // has nothing to do.
584
591
  decode(buf, start, end, out) {
585
- out.length = 0;
592
+ const scratch = out.items !== undefined;
593
+ const a = scratch ? out.items : out;
594
+ if (scratch) {
595
+ out.reset();
596
+ }
597
+ let n = 0;
586
598
  let p = start;
587
599
  while (p < end) {
588
600
  const b = buf[p];
@@ -592,32 +604,44 @@ class Decoder {
592
604
  if (e === undefined) {
593
605
  throw new HPackError(`hpack: invalid index ${RI}`);
594
606
  }
595
- out.push(e[0], e[1]);
607
+ if (scratch) {
608
+ out.push(e[0]);
609
+ out.push(e[1]);
610
+ n += 2;
611
+ } else {
612
+ a[n++] = e[0];
613
+ a[n++] = e[1];
614
+ }
596
615
  p = RP;
597
616
  } else if ((b & 0xc0) === 0x40) { // 01xxxxxx incremental
598
- p = this.literal(buf, p, end, out, 6);
599
- this.insert(out[out.length - 2], out[out.length - 1]);
617
+ p = this.literal(buf, p, end, out, scratch, n, 6);
618
+ n += 2;
619
+ this.insert(a[n - 2], a[n - 1]);
600
620
  } else if ((b & 0xe0) === 0x20) { // 001xxxxx size update
601
621
  // RFC 7541 6.3: a size update may only appear at the beginning of a header block --
602
- // before its first field line, and `out.length === 0` is exactly that. Measured on node
622
+ // before its first field line, and `n === 0` is exactly that. Measured on node
603
623
  // (h2spec hpack/4.2), one that follows a field line is GOAWAY(COMPRESSION_ERROR) whether
604
624
  // or not it changes anything: the indices of the lines already decoded name a table that
605
625
  // the update says was different, so a second decoder that reads the block in the order
606
626
  // the octets arrive would rebuild a different context from ours.
607
- if (out.length !== 0) {
627
+ if (n !== 0) {
608
628
  throw new HPackError('hpack: table size update after a field line');
609
629
  }
610
630
  readInt(buf, p, 5, end);
611
631
  this.setMaxSize(RI);
612
632
  p = RP;
613
633
  } else { // 0000/0001 literal
614
- p = this.literal(buf, p, end, out, 4);
634
+ p = this.literal(buf, p, end, out, scratch, n, 4);
635
+ n += 2;
615
636
  }
616
637
  }
617
- return out.length >> 1;
638
+ if (!scratch) {
639
+ out.length = n;
640
+ }
641
+ return n >> 1;
618
642
  }
619
643
 
620
- literal(buf, p, end, out, bits) {
644
+ literal(buf, p, end, out, scratch, n, bits) {
621
645
  readInt(buf, p, bits, end);
622
646
  let name;
623
647
  if (RI === 0) {
@@ -633,7 +657,13 @@ class Decoder {
633
657
  p = RP;
634
658
  }
635
659
  const v = this.str(buf, p, end);
636
- out.push(name, v.value);
660
+ if (scratch) {
661
+ out.push(name);
662
+ out.push(v.value);
663
+ } else {
664
+ out[n] = name;
665
+ out[n + 1] = v.value;
666
+ }
637
667
  return v.p;
638
668
  }
639
669
 
@@ -674,7 +704,12 @@ class Decoder {
674
704
  // Only a block that a socket read split takes this path. A block that arrived
675
705
  // whole is decoded out of the chunk it came in, with no cursor and no copy.
676
706
  decodePieces(pieces, start, end, out) {
677
- out.length = 0;
707
+ const scratch = out.items !== undefined;
708
+ const a = scratch ? out.items : out;
709
+ if (scratch) {
710
+ out.reset();
711
+ }
712
+ let n = 0;
678
713
  const cur = new PieceCursor(pieces, start, end);
679
714
  while (cur.left > 0) {
680
715
  const b = cur.peek();
@@ -684,26 +719,36 @@ class Decoder {
684
719
  if (e === undefined) {
685
720
  throw new HPackError(`hpack: invalid index ${cur.value}`);
686
721
  }
687
- out.push(e[0], e[1]);
722
+ if (scratch) {
723
+ out.push(e[0]);
724
+ out.push(e[1]);
725
+ n += 2;
726
+ } else {
727
+ a[n++] = e[0];
728
+ a[n++] = e[1];
729
+ }
688
730
  } else if ((b & 0xc0) === 0x40) { // 01xxxxxx incremental
689
- this.literalPieces(cur, out, 6);
690
- this.insert(out[out.length - 2], out[out.length - 1]);
731
+ n = this.literalPieces(cur, out, scratch, n, 6);
732
+ this.insert(a[n - 2], a[n - 1]);
691
733
  } else if ((b & 0xe0) === 0x20) { // 001xxxxx size update
692
734
  // RFC 7541 6.3: a size update may only appear at the beginning of a header
693
735
  // block -- before its first field line. See decode() for the measurement.
694
- if (out.length !== 0) {
736
+ if (n !== 0) {
695
737
  throw new HPackError('hpack: table size update after a field line');
696
738
  }
697
739
  cur.readInt(5);
698
740
  this.setMaxSize(cur.value);
699
741
  } else { // 0000/0001 literal
700
- this.literalPieces(cur, out, 4);
742
+ n = this.literalPieces(cur, out, scratch, n, 4);
701
743
  }
702
744
  }
703
- return out.length >> 1;
745
+ if (!scratch) {
746
+ out.length = n;
747
+ }
748
+ return n >> 1;
704
749
  }
705
750
 
706
- literalPieces(cur, out, bits) {
751
+ literalPieces(cur, out, scratch, n, bits) {
707
752
  cur.readInt(bits);
708
753
  let name;
709
754
  if (cur.value === 0) {
@@ -716,7 +761,14 @@ class Decoder {
716
761
  name = e[0];
717
762
  }
718
763
  const v = this.strPieces(cur);
719
- out.push(name, v);
764
+ if (scratch) {
765
+ out.push(name);
766
+ out.push(v);
767
+ return n + 2;
768
+ }
769
+ out[n++] = name;
770
+ out[n++] = v;
771
+ return n;
720
772
  }
721
773
 
722
774
  // A literal string out of the views: the length prefix, then the octets. The
package/lib/session.js CHANGED
@@ -22,6 +22,19 @@ const { EventEmitter } = require('node:events');
22
22
  const f = require('./frames');
23
23
  const { Decoder, Encoder, HPackError } = require('./hpack');
24
24
  const { Http2Stream, errorOf, emitNT } = require('./stream');
25
+ const FlatList = require('./flat-list');
26
+ // The process-wide inbound decode scratch: one list per module instance, shared by
27
+ // every session it serves, instead of one array per live session. Why sharing is
28
+ // safe: a header block's fill and its consumption are synchronous -- they happen
29
+ // inside one _processBlock call on one thread, and nothing on that path can reenter
30
+ // frame processing (bytes reach a decoder only from a socket's read path, which
31
+ // cannot run reentrantly), and every consumer that outlives the call takes a copy
32
+ // (the shape cache a slice, the raw list a slice, the header object fresh strings),
33
+ // never the store -- so no two fills can interleave, and one list serves them all.
34
+ // 64 items is 32 field lines, above every request the suite and the matrix benches
35
+ // serve; a larger block grows the store once, and end() schedules the end-of-turn
36
+ // shrink back to the preallocation.
37
+ const FLAT = new FlatList(64);
25
38
  const { pieceCopyTo, pieceSlice, pieceConcat, pieceEquals } = require('./pieces');
26
39
  const { nullProto, hasBadValue, SINGLE_VALUE_FIELDS } = require('./headers');
27
40
  // One shared 499 ms clock for the long idle timeouts, instead of a libuv timer
@@ -379,7 +392,6 @@ class Http2Session extends EventEmitter {
379
392
  // (OPTIMIZATION.md item 22 for both sides of the trade-off).
380
393
  this._share = opts.shareHeaders === true;
381
394
  this._strictSingle = strictSingleValueFields(opts);
382
- this._flat = [];
383
395
  // The compat layer needs the decoded field list as it came off the wire.
384
396
  // Copying it is a per-request allocation, so it only happens for servers
385
397
  // that actually listen for 'request'.
@@ -469,6 +481,23 @@ class Http2Session extends EventEmitter {
469
481
  this._rstSec = (Date.now() / 1000) | 0;
470
482
 
471
483
  this._maxInboundSid = 0;
484
+ // The highest id of a HEADERS frame this side has accepted -- nghttp2 opens the
485
+ // stream in prep_frame, after the length, padding and priority checks but BEFORE
486
+ // the block is decoded or any verdict on it is given, and its last-proc-stream-id
487
+ // (which node reports as state.lastProcStreamID and puts in GOAWAY's last-stream
488
+ // id) moves there. A GOAWAY sent for a frame refused after that point therefore
489
+ // names the stream of the refused frame, measured on v26.12.1 for an undecodable
490
+ // block and a header list over maxHeaderListSize (last=1 against h2lean's 0,
491
+ // out/probe-last-id.js) -- the shape a client reads as its retry boundary, so a
492
+ // lower id makes it resend a request that was already acted on. Control frames
493
+ // never move it -- measured on the same probe: WINDOW_UPDATE, RST_STREAM and DATA
494
+ // refused above the line all answer last=1, the served stream, on BOTH stacks --
495
+ // and frames refused before the acceptance point (over max frame size, malformed
496
+ // padding or priority, an even id) do not either: nghttp2 fails them before the
497
+ // open. Only _fatal reads it; the idle-state rules below stay keyed on
498
+ // _maxInboundSid, whose raise waits for the skip-record check (5.1.1) that must
499
+ // see the line as it was when the frame arrived.
500
+ this._reachedSid = 0;
472
501
  this._refused = [];
473
502
  this._dropped = null; // ids a reset ended, newest last
474
503
  // ids whose message ended in the read batch being processed, see _dropStream. Cleared by the
@@ -823,7 +852,9 @@ class Http2Session extends EventEmitter {
823
852
  const n = chunk.length;
824
853
  let i = 0;
825
854
  this._inBatch = true;
826
- this._ended.length = 0; // the last batch's finished streams are no longer here
855
+ // dropped, not length-cleared -- reassignment measures cheaper than the
856
+ // right-trim the length store does (OPTIMIZATION.md item 38)
857
+ this._ended = []; // the last batch's finished streams are no longer here
827
858
  this._touchIdleTimer();
828
859
 
829
860
  if (this._prefaceSeen < PREFACE_LEN) {
@@ -1297,6 +1328,11 @@ class Http2Session extends EventEmitter {
1297
1328
  return;
1298
1329
  }
1299
1330
  const l = this._hdrFrag;
1331
+ // the frame is accepted: nghttp2 opens its stream here, before the block is
1332
+ // decoded -- see _reachedSid
1333
+ if (sid > this._reachedSid) {
1334
+ this._reachedSid = sid;
1335
+ }
1300
1336
  if (flags & F_END_HEADERS) {
1301
1337
  this._processHeaders(sid, (flags & F_END_STREAM) !== 0, buf.subarray(start + p, start + p + l));
1302
1338
  return;
@@ -1324,6 +1360,11 @@ class Http2Session extends EventEmitter {
1324
1360
  return;
1325
1361
  }
1326
1362
  const l = this._hdrFrag;
1363
+ // the frame is accepted: nghttp2 opens its stream here, before the block is
1364
+ // decoded -- see _reachedSid
1365
+ if (sid > this._reachedSid) {
1366
+ this._reachedSid = sid;
1367
+ }
1327
1368
  if (flags & F_END_HEADERS) {
1328
1369
  this._processBlockPieces(sid, (flags & F_END_STREAM) !== 0, pieces, p, p + l);
1329
1370
  return;
@@ -1429,9 +1470,9 @@ class Http2Session extends EventEmitter {
1429
1470
  // The frozen headers object for one shape. Object.freeze is shallow and
1430
1471
  // node's toHeaderObject puts set-cookie in an array, so that array has to be
1431
1472
  // frozen too -- otherwise push() would corrupt every other request sharing it.
1432
- _sharedObject(fields) {
1433
- const o = this._toObject(fields);
1434
- for (let i = 0; i < fields.length; i += 2) {
1473
+ _sharedObject(fields, count) {
1474
+ const o = this._toObject(fields, count);
1475
+ for (let i = 0; i < count; i += 2) {
1435
1476
  const v = o[fields[i]];
1436
1477
  if (Array.isArray(v)) {
1437
1478
  Object.freeze(v);
@@ -1445,7 +1486,7 @@ class Http2Session extends EventEmitter {
1445
1486
  // refused, or { fields } when only fields with illegal names were dropped. See the
1446
1487
  // block comment on the constants above for why each rule exists and where the
1447
1488
  // behaviour came from.
1448
- _requestProblem(src, trailer) {
1489
+ _requestProblem(src, count, trailer) {
1449
1490
  let method = null, path = null, scheme = null, authority = null, host = null;
1450
1491
  let protocol = null, contentLength = null;
1451
1492
  // RFC 9113 8.1: pseudo-header fields, if any, come before all regular fields. Once
@@ -1454,7 +1495,7 @@ class Http2Session extends EventEmitter {
1454
1495
  let pseudoAllowed = !trailer;
1455
1496
  let kept = null; // copied list, only if something is dropped
1456
1497
 
1457
- for (let i = 0; i < src.length; i += 2) {
1498
+ for (let i = 0; i < count; i += 2) {
1458
1499
  const name = src[i];
1459
1500
  const value = src[i + 1];
1460
1501
 
@@ -1636,13 +1677,17 @@ class Http2Session extends EventEmitter {
1636
1677
 
1637
1678
  _processBlock(sid, end, block, pieces, from, to) {
1638
1679
  const existing = this._streams.get(sid);
1639
- const flat = this._flat;
1680
+ const flat = FLAT;
1640
1681
  const shapes = existing === undefined ? this._shapes : null;
1641
1682
  const slot = shapes === null ? 0
1642
1683
  : (block !== null ? this._shapeSlot(block) : this._shapeSlotPieces(pieces, from, to));
1643
1684
  const hit = shapes === null ? undefined : shapes.get(slot);
1644
- // where this request's field list and header object come from
1645
- let fields = flat;
1685
+ // where this request's field list comes from: the scratch's backing array on
1686
+ // a decode, a cached copy on a shape hit. Both are read by index, so the
1687
+ // valid length travels next to the list (a FlatList's count, an array's
1688
+ // length) instead of being re-derived at every use.
1689
+ let fields;
1690
+ let fcount;
1646
1691
  let shared = null;
1647
1692
  let bytes = 0;
1648
1693
  // verdict of the inbound validator: null means the fields may go to the application
@@ -1658,6 +1703,7 @@ class Http2Session extends EventEmitter {
1658
1703
  this._shapeHits++;
1659
1704
  bytes = hit.bytes;
1660
1705
  fields = hit.flat;
1706
+ fcount = fields.length;
1661
1707
  shared = hit.headers;
1662
1708
  verdict = hit.verdict;
1663
1709
  } else {
@@ -1666,14 +1712,17 @@ class Http2Session extends EventEmitter {
1666
1712
  } else {
1667
1713
  this._decoder.decodePieces(pieces, from, to, flat);
1668
1714
  }
1669
- for (let i = 0; i < flat.length; i++) {
1670
- bytes += flat[i].length;
1715
+ fields = flat.items;
1716
+ fcount = flat.count;
1717
+ for (let i = 0; i < fcount; i++) {
1718
+ bytes += fields[i].length;
1671
1719
  }
1672
- // flat is name, value, name, value: one entry overhead per field line
1673
- bytes += (flat.length >> 1) * ENTRY_OVERHEAD;
1674
- verdict = this._requestProblem(flat, existing !== undefined);
1720
+ // 'fields' is name, value, name, value: one entry overhead per field line
1721
+ bytes += (fcount >> 1) * ENTRY_OVERHEAD;
1722
+ verdict = this._requestProblem(fields, fcount, existing !== undefined);
1675
1723
  if (verdict !== null && verdict.fields !== undefined) {
1676
1724
  fields = verdict.fields;
1725
+ fcount = fields.length;
1677
1726
  }
1678
1727
  if (shapes !== null) {
1679
1728
  // A client that varies one header per request (x-request-id) makes
@@ -1688,11 +1737,11 @@ class Http2Session extends EventEmitter {
1688
1737
  } // bounded: clients vary
1689
1738
  const entry = {
1690
1739
  block: block !== null ? Buffer.from(block) : pieceConcat(pieces, from, to),
1691
- flat: fields.slice(0), bytes, headers: null,
1740
+ flat: fields.slice(0, fcount), bytes, headers: null,
1692
1741
  verdict
1693
1742
  };
1694
1743
  if (this._share) {
1695
- entry.headers = this._sharedObject(fields);
1744
+ entry.headers = this._sharedObject(fields, fcount);
1696
1745
  shared = entry.headers;
1697
1746
  }
1698
1747
  shapes.set(slot, entry);
@@ -1769,7 +1818,18 @@ class Http2Session extends EventEmitter {
1769
1818
  // between "the handler declined the request" and "the handler was never reached",
1770
1819
  // and only the second one denies a smuggling chain its second reader.
1771
1820
  if (verdict !== null && verdict.problem !== undefined) {
1772
- this.sendRst(sid, PROTOCOL_ERROR);
1821
+ // A live stream takes the stream error, not a bare reset: measured on node
1822
+ // (tools/probe-trailer-rst.js), a trailer block carrying a pseudo-header is
1823
+ // RST_STREAM(PROTOCOL_ERROR) on the wire AND ERR_HTTP2_STREAM_ERROR + 'close'
1824
+ // on the stream -- the same shape as the missing-END_STREAM refusal above --
1825
+ // and the closed stream is what keeps the unread-request auto-close
1826
+ // (Http2Stream[kMaybeDestroy], see lib/stream.js _maybeAutoClose) from
1827
+ // putting a second RST(NO_ERROR) on the wire behind the refusal's.
1828
+ if (existing !== undefined) {
1829
+ this._streamError(existing, PROTOCOL_ERROR, verdict.problem);
1830
+ } else {
1831
+ this.sendRst(sid, PROTOCOL_ERROR);
1832
+ }
1773
1833
  return;
1774
1834
  }
1775
1835
 
@@ -1782,7 +1842,8 @@ class Http2Session extends EventEmitter {
1782
1842
  this._streamError(existing, PROTOCOL_ERROR, 'trailing HEADERS without END_STREAM');
1783
1843
  return;
1784
1844
  }
1785
- const trailers = this._share ? this._sharedObject(fields) : this._toObject(fields);
1845
+ const trailers = this._share
1846
+ ? this._sharedObject(fields, fcount) : this._toObject(fields, fcount);
1786
1847
  existing.emit('trailers', trailers);
1787
1848
  if (end) {
1788
1849
  existing._remoteEnded();
@@ -1840,7 +1901,8 @@ class Http2Session extends EventEmitter {
1840
1901
  }
1841
1902
 
1842
1903
  const headers = shared !== null ? shared
1843
- : (this._share ? Object.freeze(this._toObject(fields)) : this._toObject(fields));
1904
+ : (this._share ? Object.freeze(this._toObject(fields, fcount))
1905
+ : this._toObject(fields, fcount));
1844
1906
  // The one shape in which the content-length promise is already broken before a single body
1845
1907
  // octet could have arrived: the field promises a body and the HEADERS frame ends the message.
1846
1908
  // Refusing at the accept decision -- the same place the parse failures and the size limits are
@@ -1884,7 +1946,7 @@ class Http2Session extends EventEmitter {
1884
1946
  // node's argument order; the field list is the session's shared decode array
1885
1947
  // or a cached one, so the raw list handed out is always a copy
1886
1948
  this.emit('stream', stream, headers, end ? OPT_END_STREAM : OPT_NO_END_STREAM,
1887
- this._wantRaw ? fields.slice(0) : null);
1949
+ this._wantRaw ? fields.slice(0, fcount) : null);
1888
1950
  }
1889
1951
 
1890
1952
  // node's toHeaderObject semantics: null prototype, :status coerced to a
@@ -1895,11 +1957,11 @@ class Http2Session extends EventEmitter {
1895
1957
  // { __proto__: null } literal: the literal is in V8's dictionary mode, and this
1896
1958
  // map is built once per request and read once per request by the application --
1897
1959
  // in the stream path and in the compat path alike (OPTIMIZATION.md item 4).
1898
- _toObject(flat) {
1960
+ _toObject(fields, count) {
1899
1961
  const o = nullProto();
1900
- for (let i = 0; i < flat.length; i += 2) {
1901
- const name = flat[i];
1902
- let value = flat[i + 1];
1962
+ for (let i = 0; i < count; i += 2) {
1963
+ const name = fields[i];
1964
+ let value = fields[i + 1];
1903
1965
  if (name === ':status') {
1904
1966
  value = value | 0;
1905
1967
  }
@@ -2396,7 +2458,12 @@ class Http2Session extends EventEmitter {
2396
2458
  if (!this._open) {
2397
2459
  return;
2398
2460
  }
2399
- this.sendGoaway(this._maxInboundSid, code, msg);
2461
+ // last-stream id names the far side of the retry boundary: a stream whose HEADERS
2462
+ // was accepted but whose block was refused was reached, and node names it (see
2463
+ // _reachedSid) -- naming only the streams a stream object was made for would tell
2464
+ // the peer it may retry a request that was already acted on
2465
+ const reached = this._maxInboundSid > this._reachedSid ? this._maxInboundSid : this._reachedSid;
2466
+ this.sendGoaway(reached, code, msg);
2400
2467
  this._flush();
2401
2468
  const err = errorOf('ERR_HTTP2_SESSION_ERROR', msg);
2402
2469
  err.http2Code = code;
package/lib/stream.js CHANGED
@@ -54,6 +54,19 @@ function emitEndCloseNT(target) {
54
54
  target.emit('close');
55
55
  }
56
56
 
57
+ // The scheduled half of the unread-request auto-close -- see _maybeAutoClose
58
+ // below for the rule and its measurement. The unread request half reports 'end'
59
+ // here, before the 'close' _destroy schedules behind it: node's trace for the
60
+ // shape does the same (test/event-order.test.js, scenario eof-body) -- the
61
+ // readable side is finished by the close, never having been read.
62
+ function autoCloseNT(stream) {
63
+ if (stream._destroyed) {
64
+ return;
65
+ }
66
+ process.nextTick(emitNT, stream, 'end');
67
+ stream._destroy(NO_ERROR, undefined, true);
68
+ }
69
+
57
70
  const {
58
71
  ST_OPEN, ST_HALF_CLOSED_LOCAL, ST_HALF_CLOSED_REMOTE, ST_CLOSED, NO_ERROR, PROTOCOL_ERROR
59
72
  } = frames;
@@ -340,7 +353,41 @@ class Http2Stream extends EventEmitter {
340
353
  }
341
354
  if (this.state.remoteClose === 1) {
342
355
  this._closeIfBothDone();
356
+ } else {
357
+ // the response is over and the peer's half is not: this is the shape node
358
+ // closes for the application (see _maybeAutoClose). A stream the peer has
359
+ // already ended takes the graceful close above, which is also what node's
360
+ // wire shows there -- no RST, because nghttp2 refuses to reset what both
361
+ // halves have closed (tools/probe-stream-teardown.js, 'request-ended').
362
+ this._maybeAutoClose();
363
+ }
364
+ }
365
+
366
+ // node's Http2Stream[kMaybeDestroy] (internal/http2/core.js): a response the
367
+ // server session has finished, with trailers neither requested nor sent
368
+ // (STREAM_FLAGS_HAS_TRAILERS) and a request side nobody ever started to consume
369
+ // (`!state.didRead && readableFlowing === null`), is closed by the session
370
+ // itself -- `setImmediate(callStreamClose)` off the writable side's 'finish',
371
+ // and closeStream submits RST_STREAM(NO_ERROR). Measured on v26.12.1
372
+ // (tools/probe-stream-teardown.js, 'answer-only'): HEADERS, DATA, then
373
+ // RST_STREAM(NO_ERROR) on the wire and the stream destroyed -- and the
374
+ // boundaries with it: 'resume-then-answer' shows that touching the readable
375
+ // side stops the auto-close, and 'request-ended' that a stream the peer already
376
+ // ended never gets one. Without it a peer that sends HEADERS without END_STREAM
377
+ // and no DATA holds a stream and a _liveStreams slot until the idle timeout,
378
+ // and a closing session waits for it forever (AGENTS.md 10, item 2).
379
+ // `_consumeState === 0` is this file's reading of `!didRead && flowing ===
380
+ // null`: no reader attached and no pause()/resume() called -- either has
381
+ // touched the request, and node stops there too.
382
+ _maybeAutoClose() {
383
+ if (this._destroyed || !this.headersSent || this._waitForTrailers ||
384
+ this._consumeState !== 0) {
385
+ return;
343
386
  }
387
+ // node's own deferral: the RST goes out a turn after the response, and the
388
+ // stream's 'close' with it (autoCloseNT above guards against a close() the
389
+ // application made in between)
390
+ setImmediate(autoCloseNT, this);
344
391
  }
345
392
 
346
393
  _closeIfBothDone() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h2lean",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
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": [