h2lean 0.17.4 → 0.17.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.
package/lib/headers.js CHANGED
@@ -595,39 +595,144 @@ function encode(parsed, enc) {
595
595
  // The same pass, written at `at` instead of at the front of the scratch -- the place a
596
596
  // size update's octets took, so that the announcement and the block are one buffer and
597
597
  // one write. Returns the offset the block ends at.
598
- function encodeAt(parsed, enc, at) {
598
+ function encodeAt(parsed, enc, at, dst, base) {
599
+ dst = dst === undefined ? scratch : dst;
600
+ base = base === undefined ? 0 : base;
599
601
  enc.unsettled = false;
600
602
  const pseudo = parsed.pseudo;
601
603
  const fields = parsed.fields;
602
- let cap = 16 + at;
603
- // nghttp2's outbound estimate, accumulated in the same pass that sizes the scratch:
604
- // nghttp2_hd_deflate_bound (nghttp2_hd.c) is `12 + 6*2*nvlen + sum(namelen+valuelen)`,
605
- // the 12 being two possible 6-octet table-size updates and the 6*2 the two literal
606
- // length prefixes per field. It counts the *string lengths* node handed down, not the
607
- // UTF-8 octets the encoder writes -- measured on v26.12.1: a value of n 'é' (2 octets
608
- // each) and of n '€' (3 each) hit the same boundary as n 'X'. The caller adds the
609
- // per-frame-kind `additional` and compares against maxSendHeaderBlockLength.
604
+ const cap = capOf(parsed, at);
605
+ sent.bound = boundOf(parsed);
606
+ if (dst.length < base + cap) {
607
+ // scratch is allowed to grow; a caller-owned destination reserved its room
608
+ // already, so a short one is a bug in the reservation, not a size to adapt to.
609
+ if (dst !== scratch) {
610
+ throw new Error('header destination smaller than the encoded estimate');
611
+ }
612
+ scratch = Buffer.allocUnsafe(cap);
613
+ dst = scratch;
614
+ base = 0;
615
+ }
616
+ let off = at;
617
+ for (let i = 0; i < pseudo.length; i += 2) {
618
+ off = enc.write(dst, base + off, pseudo[i], pseudo[i + 1], false) - base;
619
+ }
620
+ for (let i = 0; i < fields.length; i += 3) {
621
+ off = enc.write(dst, base + off, fields[i], fields[i + 1], fields[i + 2]) - base;
622
+ }
623
+ return off;
624
+ }
625
+
626
+ // nghttp2_hd_deflate_bound (nghttp2_hd.c) is `12 + 6*2*nvlen + sum(namelen+valuelen)`:
627
+ // the 12 is two possible 6-octet table-size updates, the 6*2 the two literal length
628
+ // prefixes per field. It counts the string lengths node handed down, not the UTF-8
629
+ // octets the encoder writes -- measured on v26.12.1: n 'é' (2 octets) and n '€' (3)
630
+ // hit the same boundary as n 'X'. The caller adds the per-frame-kind `additional`.
631
+ function boundOf(parsed) {
610
632
  let bound = 12;
633
+ const pseudo = parsed.pseudo;
634
+ const fields = parsed.fields;
611
635
  for (let i = 0; i < pseudo.length; i += 2) {
612
- cap += Encoder.maxBytesOf(pseudo[i], pseudo[i + 1]);
613
636
  bound += 12 + pseudo[i].length + pseudo[i + 1].length;
614
637
  }
615
638
  for (let i = 0; i < fields.length; i += 3) {
616
- cap += Encoder.maxBytesOf(fields[i], fields[i + 1]);
617
639
  bound += 12 + fields[i].length + fields[i + 1].length;
618
640
  }
619
- sent.bound = bound;
620
- if (scratch.length < cap) {
621
- scratch = Buffer.allocUnsafe(cap);
641
+ return bound;
642
+ }
643
+
644
+ // Worst-case octets the encoder can write for this parsed block, including the
645
+ // optional size update at `at`. The session uses it to reserve room in its one
646
+ // output scratch before any byte is written.
647
+ function capOf(parsed, at) {
648
+ let cap = 16 + at;
649
+ const pseudo = parsed.pseudo;
650
+ const fields = parsed.fields;
651
+ for (let i = 0; i < pseudo.length; i += 2) {
652
+ cap += Encoder.maxBytesOf(pseudo[i], pseudo[i + 1]);
622
653
  }
623
- let off = at;
654
+ for (let i = 0; i < fields.length; i += 3) {
655
+ cap += Encoder.maxBytesOf(fields[i], fields[i + 1]);
656
+ }
657
+ return cap;
658
+ }
659
+
660
+ // The cache-hit plan has no getters to read on the way to writePrepared(), so unlike
661
+ // the parse path it cannot be re-entered between prepare() and writePrepared(). Keep
662
+ // one object and fill it in place: block()'s cache hit returns hit.bytes without
663
+ // allocating, so the direct-write path does not pay for a plan object there either.
664
+ let hitPlan = null;
665
+
666
+ // Two-phase form of block() for a caller that owns the destination buffer (the
667
+ // session's single scratch). prepare() reads the caller's header map -- including
668
+ // getters -- and returns everything needed to write; writePrepared() then touches
669
+ // only parsed values, so no reentrant call can move the destination under it.
670
+ // OPTIMIZATION.md item 68.
671
+ function prepare(headers, opts, session) {
672
+ const sendDate = !!(opts && opts.sendDate);
673
+ const enc = session._encoder;
674
+ const stamp = sendDate ? touchDate() : -1;
675
+ const cacheable = Object.isFrozen(headers) && enc.pendingSize === null;
676
+ if (cacheable) {
677
+ const hit = session._blocks.get(headers);
678
+ if (hit !== undefined && hit.epoch === enc.epoch && hit.stamp === stamp) {
679
+ sent.status = hit.status;
680
+ sent.date = hit.date;
681
+ sent.bound = hit.bound;
682
+ const plan = hitPlan === null ? (hitPlan = {}) : hitPlan;
683
+ plan.headers = headers;
684
+ plan.hit = hit;
685
+ plan.bound = hit.bound;
686
+ plan.status = hit.status;
687
+ plan.date = hit.date;
688
+ return plan;
689
+ }
690
+ }
691
+ const parsed = parse(headers,
692
+ { trailer: !!(opts && opts.trailer), sendDate, info: !!(opts && opts.info),
693
+ strict: session._strictSingle });
694
+ sent.status = parsed.status;
695
+ sent.date = parsed.genDate;
696
+ // The size update is NOT consumed here: writePrepared() writes its octets into the
697
+ // destination itself. Reserve the maximum the 5-bit prefix can need (the same
698
+ // bound takeSizeUpdate() allocates) so the encoder has room before a byte is written.
699
+ const at = enc.pendingSize === null ? 0 : 5;
700
+ let bound = 12;
701
+ let cap = 16 + at;
702
+ const pseudo = parsed.pseudo;
703
+ const fields = parsed.fields;
624
704
  for (let i = 0; i < pseudo.length; i += 2) {
625
- off = enc.write(scratch, off, pseudo[i], pseudo[i + 1], false);
705
+ bound += 12 + pseudo[i].length + pseudo[i + 1].length;
706
+ cap += Encoder.maxBytesOf(pseudo[i], pseudo[i + 1]);
626
707
  }
627
708
  for (let i = 0; i < fields.length; i += 3) {
628
- off = enc.write(scratch, off, fields[i], fields[i + 1], fields[i + 2]);
709
+ bound += 12 + fields[i].length + fields[i + 1].length;
710
+ cap += Encoder.maxBytesOf(fields[i], fields[i + 1]);
629
711
  }
630
- return off;
712
+ sent.bound = bound;
713
+ return { headers, parsed, at, cacheable, stamp, epoch: enc.epoch,
714
+ cap, bound, status: parsed.status, date: parsed.genDate };
715
+ }
716
+
717
+ function writePrepared(prep, session, dst, off) {
718
+ const enc = session._encoder;
719
+ // Same octets as takeSizeUpdate(), written into the caller's buffer: no 5-octet
720
+ // Buffer and no subarray. The encoder consumes the pending update here, so the
721
+ // announcement cannot be repeated by a later block.
722
+ const at = enc.takeSizeUpdateInto(dst, off) - off;
723
+ if (prep.hit !== undefined) {
724
+ copyInto(dst, off + at, prep.hit.bytes, 0, prep.hit.bytes.length);
725
+ return off + at + prep.hit.bytes.length;
726
+ }
727
+ const end = encodeAt(prep.parsed, enc, at, dst, off);
728
+ if (prep.cacheable && enc.epoch === prep.epoch && !enc.unsettled) {
729
+ const bytes = Buffer.allocUnsafe(end - at);
730
+ copyInto(bytes, 0, dst, off + at, off + end);
731
+ session._blocks.set(prep.headers,
732
+ { bytes, epoch: enc.epoch, stamp: prep.stamp, status: prep.status,
733
+ date: prep.date, bound: prep.bound });
734
+ }
735
+ return off + end;
631
736
  }
632
737
 
633
738
  // The HPACK block for a PUSH_PROMISE payload: request-style pseudo-headers, no date,
@@ -782,6 +887,7 @@ function requestView(src, scheme, authority) {
782
887
  return view;
783
888
  }
784
889
 
785
- module.exports = { block, pushBlock, encode, parse, nullProto, isFieldName, trimName, lowerName,
890
+ module.exports = { block, pushBlock, encode, parse, prepare, writePrepared, capOf, boundOf,
891
+ nullProto, isFieldName, trimName, lowerName,
786
892
  nameCacheSize, hasBadValue, neverNames, CONNECTION_SPECIFIC, KSensitiveHeaders, SINGLE_VALUE_FIELDS,
787
893
  sent, responseView, requestView };
package/lib/hpack.js CHANGED
@@ -1238,6 +1238,21 @@ class Encoder {
1238
1238
  return b.subarray(0, writeInt(b, 0, n, 5, 0x20));
1239
1239
  }
1240
1240
 
1241
+ // The size update written straight into the caller's destination. Same octets as
1242
+ // takeSizeUpdate(), but the direct-write path has no intermediate 5-octet Buffer
1243
+ // and no subarray to hand to the staging buffer.
1244
+ takeSizeUpdateInto(dst, off) {
1245
+ const n = this.pendingSize;
1246
+ if (n === null) {
1247
+ return off;
1248
+ }
1249
+ this.pendingSize = null;
1250
+ if (off + 5 > dst.length) {
1251
+ throw new HPackError('hpack: output buffer too small');
1252
+ }
1253
+ return writeInt(dst, off, n, 5, 0x20);
1254
+ }
1255
+
1241
1256
  touch() {
1242
1257
  this.epoch++;
1243
1258
  this.cache.clear();
@@ -1253,11 +1268,15 @@ class Encoder {
1253
1268
  }
1254
1269
 
1255
1270
  // Appends one field line to `dst` at `off`, returns the new offset.
1256
- // Cached bytes are only valid for the table state that produced them: see touch().
1271
+ // Cached values are only valid for the table state that produced them: see touch().
1272
+ // A cached full index is a NUMBER, not bytes: the direct-write path keeps the
1273
+ // same octets without rebuilding them or paying for a 4-octet Buffer each time.
1257
1274
  write(dst, off, name, value, neverIndex) {
1258
1275
  const bytes = this.lookup(name, value, neverIndex);
1259
1276
  if (bytes !== undefined) {
1260
- return this.put(dst, off, bytes);
1277
+ return typeof bytes === 'number'
1278
+ ? this.indexedInto(dst, off, bytes)
1279
+ : this.put(dst, off, bytes);
1261
1280
  }
1262
1281
  return this.emit(dst, off, name, value, neverIndex);
1263
1282
  }
@@ -1292,9 +1311,11 @@ class Encoder {
1292
1311
  }
1293
1312
  const hit = this.fullIndex(name, value);
1294
1313
  if (hit !== undefined) {
1295
- const bytes = this.indexed(hit);
1296
- this.remember(name, value, neverIndex, bytes);
1297
- return this.put(dst, off, bytes);
1314
+ // Remember the index as a number in the epoch-scoped cache, so the next
1315
+ // sighting of the pair takes lookup() + indexedInto() instead of another
1316
+ // fullIndex()/findFull() walk.
1317
+ this.remember(name, value, neverIndex, hit);
1318
+ return this.indexedInto(dst, off, hit);
1298
1319
  }
1299
1320
  // nghttp2's entropy rule (lib/nghttp2_hd.c deflate_nv): authorization always,
1300
1321
  // and a cookie whose value is under 20 octets with it, go out never-indexed
@@ -1415,6 +1436,17 @@ class Encoder {
1415
1436
  return b.subarray(0, writeInt(b, 0, index, 7, 0x80));
1416
1437
  }
1417
1438
 
1439
+ // An indexed reference is one prefixed integer and nothing else. Writing it into
1440
+ // the destination removes both the 4-octet Buffer and the memcpy from the cached
1441
+ // bytes -- and the cache entry itself, which cannot survive an epoch change while
1442
+ // an index written at emit time is always current. OPTIMIZATION.md item 68.
1443
+ indexedInto(dst, off, index) {
1444
+ if (off + 4 > dst.length) {
1445
+ throw new HPackError('hpack: output buffer too small');
1446
+ }
1447
+ return writeInt(dst, off, index, 7, 0x80);
1448
+ }
1449
+
1418
1450
  // prefix 0x00 = without indexing (4-bit name field), 0x10 = never indexed,
1419
1451
  // 0x40 = with incremental indexing (6-bit name field). A never-indexed line names
1420
1452
  // its field in full as well: nothing about the field may be left in a table.
@@ -1488,8 +1520,12 @@ class Encoder {
1488
1520
  }
1489
1521
 
1490
1522
  // Upper bound on the bytes one field line can produce, for capacity planning.
1523
+ // literalStrInto() picks the shorter of the raw and Huffman forms, so a string
1524
+ // costs its own length in octets plus a 7-bit prefix; four spare prefix octets
1525
+ // cover any length that fits in an outbound header block. An indexed line is one
1526
+ // prefixed integer, well below this.
1491
1527
  static maxBytesOf(name, value) {
1492
- return 1 + 4 + (name.length + 5) * 2 + (value.length + 5) * 2;
1528
+ return 11 + name.length + value.length;
1493
1529
  }
1494
1530
  }
1495
1531
 
@@ -40,6 +40,7 @@ const fastTick = require('../fast-tick');
40
40
  const FLAT = new FlatList(64);
41
41
  const { pieceCopyTo, pieceSlice, pieceConcat, pieceEquals } = require('../pieces');
42
42
  const { nullProto, neverNames, SINGLE_VALUE_FIELDS, KSensitiveHeaders } = require('../headers');
43
+ const hdr = require('../headers');
43
44
 
44
45
  // The socket's ownership mark, shared with the client session (node keeps it as
45
46
  // socket[kBoundSession] in the one Http2Session base constructor both kinds run
@@ -817,7 +818,7 @@ const BODY_MIN = 4096;
817
818
 
818
819
  // First size of the staging buffer; doubled per frame that does not fit, so a batch of
819
820
  // header blocks costs one allocation and one copy of each block.
820
- const STAGE_MIN = 1024;
821
+ const STAGE_MIN = 8192;
821
822
 
822
823
  // The 'stream' event carries node's options object. Two constants instead of a
823
824
  // literal per request: the payload never changes, and 1.9M requests is 1.9M
@@ -1366,6 +1367,14 @@ class Http2ServerSession extends EventEmitter {
1366
1367
  this._stage = null;
1367
1368
  this._stageLen = 0; // bytes of _stage not yet queued
1368
1369
  this._stageCap = STAGE_MIN; // size of the next staging buffer
1370
+ // Buffers that have been handed to the socket and completed are kept here and
1371
+ // handed back to _need instead of allocating a new one. _pending collects the
1372
+ // full stage buffers of a batch; _returning is the batch whose write callback
1373
+ // is still owed, so only one list is in flight at a time.
1374
+ // OPTIMIZATION.md item 69: this buys memory, not request-level time.
1375
+ this._recycled = [];
1376
+ this._pending = [];
1377
+ this._returning = null;
1369
1378
  this._outLen = 0; // queued bytes the socket has not been given
1370
1379
  this._heldBytes = 0; // bytes of response parked on streams that lack credit
1371
1380
  this._frozenLen = 0; // bytes handed over, callback still owed
@@ -1647,7 +1656,9 @@ class Http2ServerSession extends EventEmitter {
1647
1656
  cap *= 2;
1648
1657
  }
1649
1658
  this._stageCap = Math.min(cap, MAX_OUT_BATCH);
1650
- this._stage = Buffer.allocUnsafe(cap);
1659
+ const reused = this._recycled.pop();
1660
+ this._stage = reused !== undefined && reused.length >= cap
1661
+ ? reused : Buffer.allocUnsafe(cap);
1651
1662
  }
1652
1663
 
1653
1664
  _commit() {
@@ -1666,6 +1677,7 @@ class Http2ServerSession extends EventEmitter {
1666
1677
  }
1667
1678
  }
1668
1679
  this._outQ.push(chunk);
1680
+ this._pending.push(this._stage); // keep the whole buffer, for reuse after the write
1669
1681
  this._stage = null; // the queued bytes are not ours to write
1670
1682
  this._stageLen = 0;
1671
1683
  }
@@ -1714,6 +1726,9 @@ class Http2ServerSession extends EventEmitter {
1714
1726
  this._writing = false;
1715
1727
  this._esMarkers.clear();
1716
1728
  this._esRequeue = [];
1729
+ this._pending = [];
1730
+ this._returning = null;
1731
+ this._recycled = [];
1717
1732
  return;
1718
1733
  }
1719
1734
  if (this._writing) {
@@ -1723,6 +1738,9 @@ class Http2ServerSession extends EventEmitter {
1723
1738
  this._commit();
1724
1739
  const batch = this._outQ;
1725
1740
  this._outQ = [];
1741
+ const buffers = this._pending;
1742
+ this._pending = [];
1743
+ this._returning = buffers;
1726
1744
  // from here the bytes belong to the socket; there is nothing left to reorder
1727
1745
  this._esMarkers.clear();
1728
1746
  // END_STREAM frames cut out for a push go last: nghttp2's cycle flushes control
@@ -1761,6 +1779,15 @@ class Http2ServerSession extends EventEmitter {
1761
1779
 
1762
1780
  _onWritten() {
1763
1781
  this._writing = false;
1782
+ // The callback is the ownership boundary: every buffer of the batch is the
1783
+ // socket's no longer, so _need can write into one of them again.
1784
+ const done = this._returning;
1785
+ this._returning = null;
1786
+ if (done !== null && this._recycled.length < 4) {
1787
+ for (const b of done) {
1788
+ this._recycled.push(b);
1789
+ }
1790
+ }
1764
1791
  // Dropping the batch is the whole release: the frames were never assembled into
1765
1792
  // anything shared, so there is no tail to move down and nothing to reset.
1766
1793
  this._frozenLen = 0;
@@ -1852,6 +1879,53 @@ class Http2ServerSession extends EventEmitter {
1852
1879
  }
1853
1880
  }
1854
1881
 
1882
+ // Single-scratch form of sendHeaders: prepare() reads the caller's map (getters and
1883
+ // all) BEFORE any room is reserved, then writePrepared() writes HPACK octets straight
1884
+ // into this session's staging buffer. There is no module-level scratch view, no
1885
+ // subarray and no memcpy for the block; the 9-octet frame headers are inserted into
1886
+ // the reserved region in place, from the last CONTINUATION backwards.
1887
+ // OPTIMIZATION.md item 68.
1888
+ sendHeadersAt(sid, headers, opts, end) {
1889
+ const prep = hdr.prepare(headers, opts, this);
1890
+ if (prep.bound + PRIORITY_SPECLEN > this._maxSendBlock) {
1891
+ this._refuseBlock(sid, HEADERS);
1892
+ return true;
1893
+ }
1894
+ const max = this.remoteSettings.maxFrameSize;
1895
+ const cap = prep.hit === undefined ? prep.cap : prep.hit.bytes.length;
1896
+ const frames = Math.max(1, Math.ceil(cap / max));
1897
+ this._need(HEADER_LEN + cap + HEADER_LEN * (frames - 1));
1898
+ const dst = this._stage;
1899
+ const off = this._stageLen;
1900
+ const payloadOff = off + HEADER_LEN;
1901
+ const payloadEnd = hdr.writePrepared(prep, this, dst, payloadOff);
1902
+ const n = payloadEnd - payloadOff;
1903
+ const used = Math.max(1, Math.ceil(n / max));
1904
+ if (used === 1) {
1905
+ writeHeader(dst, off, n, HEADERS, F_END_HEADERS | (end ? F_END_STREAM : 0), sid);
1906
+ } else {
1907
+ for (let i = used - 1; i >= 1; i--) {
1908
+ const src = payloadOff + i * max;
1909
+ const stop = Math.min(payloadEnd, src + max);
1910
+ dst.copyWithin(src + i * HEADER_LEN, src, stop);
1911
+ }
1912
+ for (let i = 0; i < used; i++) {
1913
+ const take = Math.min(n - i * max, max);
1914
+ const flags = i === 0 ? (end ? F_END_STREAM : 0)
1915
+ : (i === used - 1 ? F_END_HEADERS : 0);
1916
+ writeHeader(dst, off + i * (HEADER_LEN + max), take,
1917
+ i === 0 ? HEADERS : CONTINUATION, flags, sid);
1918
+ }
1919
+ }
1920
+ const total = HEADER_LEN * used + n;
1921
+ this._stageLen = off + total;
1922
+ this._outLen += total;
1923
+ if (!this._inBatch) {
1924
+ this._schedule();
1925
+ }
1926
+ return false;
1927
+ }
1928
+
1855
1929
  // node's onFrameError (internal/http2/core.js): the emitter is the stream while the
1856
1930
  // session still holds it and the session otherwise, 'frameError' goes out synchronously,
1857
1931
  // and the close is deferred a turn -- node's own comment says the delay is there to let
@@ -353,13 +353,24 @@ class Http2ServerStream extends Http2Stream {
353
353
  // node reads the never-indexed names only off the headers object's sensitiveHeaders
354
354
  // symbol (buildNgHeaderString reads arrayOrMap[kSensitiveHeaders],
355
355
  // internal/http2/util.js) -- there is no options.sensitiveHeaders for node to ignore.
356
- const block = hdr.block(headers, { sendDate }, this.session);
356
+ // A refused PUSH_PROMISE closed the promised stream at submit time: node never
357
+ // submits its response block, so sending it here would put HEADERS on a stream
358
+ // the peer never opened (GOAWAY(PROTOCOL_ERROR) there). Keep building the block
359
+ // -- it sets sentHeaders and advances the encoder as block() does -- but do not
360
+ // write it: sendHeadersAt() writes straight into the session's stage and cannot
361
+ // be called and then discarded.
362
+ let refused = this._blockRefused;
363
+ if (refused) {
364
+ hdr.block(headers, { sendDate }, this.session);
365
+ } else {
366
+ refused = this.session.sendHeadersAt(this.id, headers, { sendDate },
367
+ opts.endStream === true || head || this._endQueued);
368
+ }
357
369
  // Read the encoder's result slots before anything else can build a block: they are
358
370
  // what `sentHeaders` reports, so they have to be this response's, not a later one's.
359
371
  this._sentSrc = headers;
360
372
  this._sentStatus = hdr.sent.status;
361
373
  this._sentDate = hdr.sent.date;
362
- const bound = hdr.sent.bound;
363
374
  this.headersSent = true;
364
375
  this.pending = false;
365
376
  this._waitForTrailers = !!opts.waitForTrailers;
@@ -367,7 +378,7 @@ class Http2ServerStream extends Http2Stream {
367
378
  // side only closes when the application says so -- except for the two shapes
368
379
  // above, where node's own end() has already run or runs inside respond().
369
380
  const empty = opts.endStream === true || head || this._endQueued;
370
- if (this._blockRefused || this.session.sendHeaders(this.id, block, empty, bound)) {
381
+ if (this._blockRefused || refused) {
371
382
  // The response HEADERS never reached the wire, so the stream never opened for a
372
383
  // body: nghttp2's response-DATA predicate requires NGHTTP2_STREAM_OPENED
373
384
  // (nghttp2_session_predicate_data_send, nghttp2_session.c), which only a sent
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h2lean",
3
- "version": "0.17.4",
3
+ "version": "0.17.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": [