h2lean 0.17.3 → 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.
@@ -20,11 +20,12 @@
20
20
 
21
21
  const { EventEmitter } = require('node:events');
22
22
  const tls = require('node:tls');
23
- const f = require('./frames');
24
- const { Decoder, Encoder, HPackError, latin1, latin1Into } = require('./hpack');
25
- const { Http2Stream, errorOf, streamErrorOf, emitCloseNT, emitDrainNT } = require('./stream');
26
- const FlatList = require('./flat-list');
27
- const fastTick = require('./fast-tick');
23
+ const f = require('../frames');
24
+ const { Decoder, Encoder, HPackError, latin1, latin1Into } = require('../hpack');
25
+ const { Http2ServerStream } = require('./Http2ServerStream');
26
+ const { errorOf, streamErrorOf, emitCloseNT, emitDrainNT } = require('../Http2Stream');
27
+ const FlatList = require('../flat-list');
28
+ const fastTick = require('../fast-tick');
28
29
  // The process-wide inbound decode scratch: one list per module instance, shared by
29
30
  // every session it serves, instead of one array per live session. Why sharing is
30
31
  // safe: a header block's fill and its consumption are synchronous -- they happen
@@ -37,8 +38,9 @@ const fastTick = require('./fast-tick');
37
38
  // serve; a larger block grows the store once, and end() schedules the end-of-turn
38
39
  // shrink back to the preallocation.
39
40
  const FLAT = new FlatList(64);
40
- const { pieceCopyTo, pieceSlice, pieceConcat, pieceEquals } = require('./pieces');
41
- const { nullProto, neverNames, SINGLE_VALUE_FIELDS, KSensitiveHeaders } = require('./headers');
41
+ const { pieceCopyTo, pieceSlice, pieceConcat, pieceEquals } = require('../pieces');
42
+ const { nullProto, neverNames, SINGLE_VALUE_FIELDS, KSensitiveHeaders } = require('../headers');
43
+ const hdr = require('../headers');
42
44
 
43
45
  // The socket's ownership mark, shared with the client session (node keeps it as
44
46
  // socket[kBoundSession] in the one Http2Session base constructor both kinds run
@@ -48,7 +50,7 @@ const kBoundSession = Symbol('h2lean.boundSession');
48
50
  // One shared 499 ms clock for the long idle timeouts, instead of a libuv timer
49
51
  // handle per connection. Vendored verbatim; see lib/fast-timer.js.
50
52
  const { setTimeout: idleSetTimeout, clearTimeout: idleClearTimeout } =
51
- require('./fast-timer');
53
+ require('../fast-timer');
52
54
 
53
55
  const {
54
56
  DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY,
@@ -752,7 +754,7 @@ const PRIORITY_SPECLEN = 5;
752
754
  // node's strictSingleValueFields option (validateSessionOptions, internal/http2/core.js):
753
755
  // undefined is true, and a non-boolean is ERR_INVALID_ARG_TYPE at createServer/connect
754
756
  // time. It gates the strict-single-value rule in both directions: the outbound blocks
755
- // (parse in lib/headers.js) and the client's request list (lib/client-session.js), while
757
+ // (parse in lib/headers.js) and the client's request list (lib/client/Http2ClientSession.js), while
756
758
  // the inbound first-wins reading of a repeated field is not optional -- node's
757
759
  // toHeaderObject always reads it that way (SINGLE_VALUE_FIELDS in lib/headers.js).
758
760
  function strictSingleValueFields(opts) {
@@ -816,7 +818,7 @@ const BODY_MIN = 4096;
816
818
 
817
819
  // First size of the staging buffer; doubled per frame that does not fit, so a batch of
818
820
  // header blocks costs one allocation and one copy of each block.
819
- const STAGE_MIN = 1024;
821
+ const STAGE_MIN = 8192;
820
822
 
821
823
  // The 'stream' event carries node's options object. Two constants instead of a
822
824
  // literal per request: the payload never changes, and 1.9M requests is 1.9M
@@ -1158,7 +1160,7 @@ const proxySocketHandler = {
1158
1160
  }
1159
1161
  };
1160
1162
 
1161
- class Http2Session extends EventEmitter {
1163
+ class Http2ServerSession extends EventEmitter {
1162
1164
  constructor(socket, options) {
1163
1165
  super();
1164
1166
  const opts = options || {};
@@ -1287,7 +1289,7 @@ class Http2Session extends EventEmitter {
1287
1289
  // outstanding pings in the C++ session rather than on the emitter and the event belongs to
1288
1290
  // the application: a listener per ping both competes with the application's own handler and
1289
1291
  // reaches MaxListeners after eleven unanswered pings (measured: node warns for none). The
1290
- // queue order is node's answer rule too (lib/client-session.js, _pingQ).
1292
+ // queue order is node's answer rule too (lib/client/Http2ClientSession.js, _pingQ).
1291
1293
  this._pingQ = [];
1292
1294
  // Unbounded-work-per-peer guards (SECURITY §8B): node bounds these, h2lean must too.
1293
1295
  // maxOutstandingPings defaults to 10 (initializeOptions, internal/http2/util.js).
@@ -1365,6 +1367,14 @@ class Http2Session extends EventEmitter {
1365
1367
  this._stage = null;
1366
1368
  this._stageLen = 0; // bytes of _stage not yet queued
1367
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;
1368
1378
  this._outLen = 0; // queued bytes the socket has not been given
1369
1379
  this._heldBytes = 0; // bytes of response parked on streams that lack credit
1370
1380
  this._frozenLen = 0; // bytes handed over, callback still owed
@@ -1646,7 +1656,9 @@ class Http2Session extends EventEmitter {
1646
1656
  cap *= 2;
1647
1657
  }
1648
1658
  this._stageCap = Math.min(cap, MAX_OUT_BATCH);
1649
- this._stage = Buffer.allocUnsafe(cap);
1659
+ const reused = this._recycled.pop();
1660
+ this._stage = reused !== undefined && reused.length >= cap
1661
+ ? reused : Buffer.allocUnsafe(cap);
1650
1662
  }
1651
1663
 
1652
1664
  _commit() {
@@ -1665,6 +1677,7 @@ class Http2Session extends EventEmitter {
1665
1677
  }
1666
1678
  }
1667
1679
  this._outQ.push(chunk);
1680
+ this._pending.push(this._stage); // keep the whole buffer, for reuse after the write
1668
1681
  this._stage = null; // the queued bytes are not ours to write
1669
1682
  this._stageLen = 0;
1670
1683
  }
@@ -1713,6 +1726,9 @@ class Http2Session extends EventEmitter {
1713
1726
  this._writing = false;
1714
1727
  this._esMarkers.clear();
1715
1728
  this._esRequeue = [];
1729
+ this._pending = [];
1730
+ this._returning = null;
1731
+ this._recycled = [];
1716
1732
  return;
1717
1733
  }
1718
1734
  if (this._writing) {
@@ -1722,6 +1738,9 @@ class Http2Session extends EventEmitter {
1722
1738
  this._commit();
1723
1739
  const batch = this._outQ;
1724
1740
  this._outQ = [];
1741
+ const buffers = this._pending;
1742
+ this._pending = [];
1743
+ this._returning = buffers;
1725
1744
  // from here the bytes belong to the socket; there is nothing left to reorder
1726
1745
  this._esMarkers.clear();
1727
1746
  // END_STREAM frames cut out for a push go last: nghttp2's cycle flushes control
@@ -1760,6 +1779,15 @@ class Http2Session extends EventEmitter {
1760
1779
 
1761
1780
  _onWritten() {
1762
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
+ }
1763
1791
  // Dropping the batch is the whole release: the frames were never assembled into
1764
1792
  // anything shared, so there is no tail to move down and nothing to reset.
1765
1793
  this._frozenLen = 0;
@@ -1774,7 +1802,7 @@ class Http2Session extends EventEmitter {
1774
1802
  // does -- see the silent-peer case in test/goaway.test.js), and it also destroys the session
1775
1803
  // before the peer's answer to the GOAWAY can be read, which costs seventeen event-order
1776
1804
  // traces that agree with node today. Deferring the same look-over with `setImmediate(this...)`,
1777
- // which is how node re-runs it (`setImmediate(() => session[kMaybeDestroy]())` in Http2Stream's
1805
+ // which is how node re-runs it (`setImmediate(() => session[kMaybeDestroy]())` in Http2ServerStream's
1778
1806
  // teardown, "Delay with setImmediate so we don't do it on the nghttp2 stack"), still costs
1779
1807
  // seven: the session 'close' then goes out ahead of the peer's, in the idle-timeout and goaway
1780
1808
  // traces. The read-side finish (`_onGoaway` -> close) and the stream teardown are therefore the
@@ -1806,7 +1834,7 @@ class Http2Session extends EventEmitter {
1806
1834
  }
1807
1835
 
1808
1836
  // Returns true when the block was refused, so the caller knows the wire state its
1809
- // HEADERS would have advanced never happened (see _blockRefused in lib/stream.js).
1837
+ // HEADERS would have advanced never happened (see _blockRefused in lib/server/Http2ServerStream.js).
1810
1838
  sendHeaders(sid, block, end, bound) {
1811
1839
  // nghttp2 refuses an outbound header block whose estimate exceeds the session's
1812
1840
  // maxSendHeaderBlockLength, and it does so at *prep* time -- after the JS call that
@@ -1851,6 +1879,53 @@ class Http2Session extends EventEmitter {
1851
1879
  }
1852
1880
  }
1853
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
+
1854
1929
  // node's onFrameError (internal/http2/core.js): the emitter is the stream while the
1855
1930
  // session still holds it and the session otherwise, 'frameError' goes out synchronously,
1856
1931
  // and the close is deferred a turn -- node's own comment says the delay is there to let
@@ -2067,7 +2142,7 @@ class Http2Session extends EventEmitter {
2067
2142
  // owned: a view of the application's buffer, which is not copied any more. A frame
2068
2143
  // that takes the whole body needs no view at all -- `take === total` is only
2069
2144
  // reachable at off === 0, since take is bounded by total - off -- and the view object
2070
- // is the ~28 ns item 57 prices. The same skip the pump in lib/stream.js and the
2145
+ // is the ~28 ns item 57 prices. The same skip the pump in lib/server/Http2ServerStream.js and the
2071
2146
  // client's `_pending` loop already make.
2072
2147
  this._frame(DATA, last ? F_END_STREAM : 0, stream.id,
2073
2148
  take === total ? buf : buf.subarray(off, off + take), true);
@@ -3305,7 +3380,7 @@ class Http2Session extends EventEmitter {
3305
3380
  // RST_STREAM(PROTOCOL_ERROR) on the wire AND ERR_HTTP2_STREAM_ERROR + 'close'
3306
3381
  // on the stream -- the same shape as the missing-END_STREAM refusal above --
3307
3382
  // and the closed stream is what keeps the unread-request auto-close
3308
- // (Http2Stream[kMaybeDestroy], see lib/stream.js _maybeAutoClose) from
3383
+ // (Http2Stream[kMaybeDestroy], see lib/server/Http2ServerStream.js _maybeAutoClose) from
3309
3384
  // putting a second RST(NO_ERROR) on the wire behind the refusal's.
3310
3385
  //
3311
3386
  // The refusal is also a counted invalid frame (node's OnInvalidFrame counts
@@ -3424,7 +3499,7 @@ class Http2Session extends EventEmitter {
3424
3499
 
3425
3500
  // The request object is built here only when a reader is already known: a
3426
3501
  // session 'stream' listener takes it as the event argument, and the compat
3427
- // request materializes it at the first req.headers access (lib/compat.js),
3502
+ // request materializes it at the first req.headers access (lib/server/compat.js),
3428
3503
  // so a handler that only consumes the body and routes on req.url pays no
3429
3504
  // per-request object -- the paired marginal is OPTIMIZATION.md item 49. The
3430
3505
  // build still happens eagerly under shareHeaders, whose frozen shared
@@ -3437,7 +3512,7 @@ class Http2Session extends EventEmitter {
3437
3512
  : this._toObject(fields, fcount, sensitive)))
3438
3513
  : undefined;
3439
3514
  // What the stack reads without the object: :method (the HEAD checks in
3440
- // lib/stream.js and the compat CONNECT check), :path (req.url) and
3515
+ // lib/server/Http2ServerStream.js and the compat CONNECT check), :path (req.url) and
3441
3516
  // content-length (the promise checked below). When the object was built
3442
3517
  // these are its own property reads, exactly what the eager code did; the
3443
3518
  // one-pass scan is the lazy path's only walk, and it takes the first copy
@@ -3466,7 +3541,7 @@ class Http2Session extends EventEmitter {
3466
3541
  // refused -- is what makes the verdict match node's: measured (probe case P7, and T4 of
3467
3542
  // tools/probe-inbound-limits.js for the reading handler), node answers RST_STREAM
3468
3543
  // (PROTOCOL_ERROR) and the application never sees the stream, so nothing is answered on it.
3469
- // Letting it through to Http2Stream._remoteEnded() instead resets the stream and then hands
3544
+ // Letting it through to Http2ServerStream._remoteEnded() instead resets the stream and then hands
3470
3545
  // the handler a destroyed one, and a handler that answers it puts a response on the wire for a
3471
3546
  // request this side has already refused.
3472
3547
  if (end && promised !== undefined && +promised > 0) {
@@ -3482,7 +3557,7 @@ class Http2Session extends EventEmitter {
3482
3557
  }
3483
3558
  return;
3484
3559
  }
3485
- const stream = new Http2Stream(this, sid);
3560
+ const stream = new Http2ServerStream(this, sid);
3486
3561
  stream._reqMethod = reqMethod;
3487
3562
  stream._reqPath = reqPath;
3488
3563
  stream._reqSensitive = sensitive;
@@ -3639,7 +3714,7 @@ class Http2Session extends EventEmitter {
3639
3714
  // on node (h2spec http2/8.1.2.6): the frame that crosses the line ends the CONNECTION --
3640
3715
  // GOAWAY(INTERNAL_ERROR) -- rather than the stream, because nghttp2 reads an overflow as a
3641
3716
  // failure of the messaging layer, not of one request. The other direction, too few octets,
3642
- // cannot be seen before the message ends: that one is caught in Http2Stream._remoteEnded()
3717
+ // cannot be seen before the message ends: that one is caught in Http2ServerStream._remoteEnded()
3643
3718
  // and is a stream error. Both compare against the octets of this stream's body, padding
3644
3719
  // excluded, which is what `l` is here.
3645
3720
  if (stream._expLen >= 0 && stream._bodyLen + l > stream._expLen) {
@@ -3823,7 +3898,7 @@ class Http2Session extends EventEmitter {
3823
3898
  // carries the END_STREAM the body was not allowed to send (RFC 9113 6.1: a trailing
3824
3899
  // HEADERS precedes the close -- measured against node: HEADERS/EH DATA HEADERS/ES/EH).
3825
3900
  // A zero-length stash is the marker for an empty trailer map: no HEADERS goes out at
3826
- // all, the withheld END_STREAM rides on an empty DATA (lib/stream.js sendTrailers).
3901
+ // all, the withheld END_STREAM rides on an empty DATA (lib/server/Http2ServerStream.js sendTrailers).
3827
3902
  if (stream._pendingTrailers !== null) {
3828
3903
  const trailers = stream._pendingTrailers;
3829
3904
  const bound = stream._pendingTrailersBound;
@@ -3899,7 +3974,7 @@ class Http2Session extends EventEmitter {
3899
3974
  }
3900
3975
  // The peer's RST_STREAM closes both halves at once: same teardown as our own
3901
3976
  // reset. Whether the application hears 'aborted' is decided there, by
3902
- // whether the response was still open (lib/stream.js, _destroy). The error it
3977
+ // whether the response was still open (lib/server/Http2ServerStream.js, _destroy). The error it
3903
3978
  // hears is the code's own name, and codes 0 and 8 are not errors at all.
3904
3979
  stream._destroy(code, false, streamErrorOf(code));
3905
3980
  }
@@ -4529,7 +4604,7 @@ class Http2Session extends EventEmitter {
4529
4604
  const [payload, callback] = checkPing(opaque, cb);
4530
4605
  // A falsy payload sends eight zero octets: node lets nghttp2 choose them, and nothing
4531
4606
  // depends on the choice, since the pong is matched by position in the queue rather than by
4532
- // value (see _pingQ in lib/client-session.js for the measurement that fixes the rule).
4607
+ // value (see _pingQ in lib/client/Http2ClientSession.js for the measurement that fixes the rule).
4533
4608
  const body = payload ? Buffer.allocUnsafe(8) : Buffer.alloc(8);
4534
4609
  if (payload) {
4535
4610
  // The only two shapes are a caller's Buffer, which copyInto indexes directly, and any
@@ -4651,7 +4726,7 @@ class Http2Session extends EventEmitter {
4651
4726
  }
4652
4727
  }
4653
4728
 
4654
- module.exports = { Http2Session, OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID,
4729
+ module.exports = { Http2ServerSession, OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID,
4655
4730
  ID_BY_SETTING, MAX_OUT_BATCH, MAX_SESSION_HOLD, STREAM_HOLD_CHARGE, BODY_MIN,
4656
4731
  STAGE_MIN, MAX_SHAPES, MAX_SEND_BLOCK, PRIORITY_SPECLEN,
4657
4732
  strictSingleValueFields, hashBlock, hashPieces, kBoundSession,