h2lean 0.17.5 → 0.18.1

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
@@ -670,9 +670,12 @@ let hitPlan = null;
670
670
  // OPTIMIZATION.md item 68.
671
671
  function prepare(headers, opts, session) {
672
672
  const sendDate = !!(opts && opts.sendDate);
673
+ const request = !!(opts && opts.request);
673
674
  const enc = session._encoder;
674
675
  const stamp = sendDate ? touchDate() : -1;
675
- const cacheable = Object.isFrozen(headers) && enc.pendingSize === null;
676
+ // A PUSH_PROMISE is one-shot: node never caches its block, and the request
677
+ // pseudo-headers would otherwise share a cache key with a response's map.
678
+ const cacheable = Object.isFrozen(headers) && enc.pendingSize === null && !request;
676
679
  if (cacheable) {
677
680
  const hit = session._blocks.get(headers);
678
681
  if (hit !== undefined && hit.epoch === enc.epoch && hit.stamp === stamp) {
@@ -690,7 +693,7 @@ function prepare(headers, opts, session) {
690
693
  }
691
694
  const parsed = parse(headers,
692
695
  { trailer: !!(opts && opts.trailer), sendDate, info: !!(opts && opts.info),
693
- strict: session._strictSingle });
696
+ request, strict: session._strictSingle });
694
697
  sent.status = parsed.status;
695
698
  sent.date = parsed.genDate;
696
699
  // The size update is NOT consumed here: writePrepared() writes its octets into the
@@ -819,6 +819,9 @@ const BODY_MIN = 4096;
819
819
  // First size of the staging buffer; doubled per frame that does not fit, so a batch of
820
820
  // header blocks costs one allocation and one copy of each block.
821
821
  const STAGE_MIN = 8192;
822
+ // Cap on the server-wide pool of completed staging buffers, so the memory retained
823
+ // for reuse is bounded independently of how many sessions the server accepts.
824
+ const MAX_STAGE_POOL = 32;
822
825
 
823
826
  // The 'stream' event carries node's options object. Two constants instead of a
824
827
  // literal per request: the payload never changes, and 1.9M requests is 1.9M
@@ -1367,12 +1370,14 @@ class Http2ServerSession extends EventEmitter {
1367
1370
  this._stage = null;
1368
1371
  this._stageLen = 0; // bytes of _stage not yet queued
1369
1372
  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.
1373
+ this._reuseBuffers = opts.reuseBuffers !== false;
1374
+ // The pool belongs to the server: a stage completed on one session can be reused
1375
+ // by another. performServerHandshake has no server and carries its own pool.
1374
1376
  // OPTIMIZATION.md item 69: this buys memory, not request-level time.
1375
- this._recycled = [];
1377
+ this._pool = this._reuseBuffers
1378
+ ? (opts.stagingPool === undefined ? [] : opts.stagingPool) : null;
1379
+ // _pending collects the full stage buffers of a batch; _returning is the batch
1380
+ // whose write callback is still owed, so only one list is in flight at a time.
1376
1381
  this._pending = [];
1377
1382
  this._returning = null;
1378
1383
  this._outLen = 0; // queued bytes the socket has not been given
@@ -1656,7 +1661,7 @@ class Http2ServerSession extends EventEmitter {
1656
1661
  cap *= 2;
1657
1662
  }
1658
1663
  this._stageCap = Math.min(cap, MAX_OUT_BATCH);
1659
- const reused = this._recycled.pop();
1664
+ const reused = this._pool === null ? undefined : this._pool.pop();
1660
1665
  this._stage = reused !== undefined && reused.length >= cap
1661
1666
  ? reused : Buffer.allocUnsafe(cap);
1662
1667
  }
@@ -1728,7 +1733,6 @@ class Http2ServerSession extends EventEmitter {
1728
1733
  this._esRequeue = [];
1729
1734
  this._pending = [];
1730
1735
  this._returning = null;
1731
- this._recycled = [];
1732
1736
  return;
1733
1737
  }
1734
1738
  if (this._writing) {
@@ -1783,9 +1787,12 @@ class Http2ServerSession extends EventEmitter {
1783
1787
  // socket's no longer, so _need can write into one of them again.
1784
1788
  const done = this._returning;
1785
1789
  this._returning = null;
1786
- if (done !== null && this._recycled.length < 4) {
1790
+ if (done !== null && this._pool !== null) {
1787
1791
  for (const b of done) {
1788
- this._recycled.push(b);
1792
+ if (this._pool.length >= MAX_STAGE_POOL) {
1793
+ break;
1794
+ }
1795
+ this._pool.push(b);
1789
1796
  }
1790
1797
  }
1791
1798
  // Dropping the batch is the whole release: the frames were never assembled into
@@ -1834,78 +1841,55 @@ class Http2ServerSession extends EventEmitter {
1834
1841
  }
1835
1842
 
1836
1843
  // Returns true when the block was refused, so the caller knows the wire state its
1837
- // HEADERS would have advanced never happened (see _blockRefused in lib/server/Http2ServerStream.js).
1838
- sendHeaders(sid, block, end, bound) {
1839
- // nghttp2 refuses an outbound header block whose estimate exceeds the session's
1840
- // maxSendHeaderBlockLength, and it does so at *prep* time -- after the JS call that
1841
- // submitted it returned (nghttp2_session.c, the NGHTTP2_HEADERS case of
1842
- // session_prep_frame). So this is not a throw: node emits 'frameError' on the stream
1843
- // and closes both it and the session a turn later (onFrameError,
1844
- // internal/http2/core.js). Measured on v26.12.1 for an oversize trailer block:
1845
- // frameError(1, 6, sid), ERR_HTTP2_STREAM_ERROR naming NGHTTP2_FRAME_SIZE_ERROR,
1846
- // rstCode 6, and RST_STREAM(6) then GOAWAY(0) on the wire.
1847
- if (bound + PRIORITY_SPECLEN > this._maxSendBlock) {
1848
- this._refuseBlock(sid, HEADERS);
1849
- return true;
1850
- }
1851
- this.state.deflateDynamicTableSize = this._encoder.size;
1852
- const max = this.remoteSettings.maxFrameSize;
1853
- // END_STREAM rides on the HEADERS frame even when CONTINUATION frames follow it:
1854
- // RFC 9113 6.2 ("a HEADERS frame with the END_STREAM flag set can be followed by
1855
- // CONTINUATION frames ... logically, the CONTINUATION frames are part of the HEADERS
1856
- // frame"), 5.1 ("CONTINUATION frames do not result in state transitions") and 8.1,
1857
- // which says it outright for trailers -- "a sequence starting with a HEADERS frame,
1858
- // followed by zero or more CONTINUATION frames, where the HEADERS frame bears an
1859
- // END_STREAM flag". Measured on node's wire for a trailer block over one frame:
1860
- // HEADERS flags 0x1 len 16384, CONTINUATION flags 0x4. On the last CONTINUATION
1861
- // instead, node's client answers ERR_HTTP2_STREAM_ERROR / rstCode 1 and h2lean's own
1862
- // receiver -- which reads the flag off HEADERS -- never sees the message end.
1863
- const es = end ? F_END_STREAM : 0;
1864
- if (block.length <= max) {
1865
- this._frame(HEADERS, F_END_HEADERS | es, sid, block);
1866
- return false;
1867
- }
1868
- this._frame(HEADERS, es, sid, block.subarray(0, max));
1869
- let off = max;
1870
- for (;;) {
1871
- const n = Math.min(block.length - off, max);
1872
- const last = off + n >= block.length;
1873
- this._frame(CONTINUATION, last ? F_END_HEADERS : 0,
1874
- sid, block.subarray(off, off + n));
1875
- off += n;
1876
- if (last) {
1877
- return false;
1844
+ // The single-scratch form of every outbound header block: prepare() reads the
1845
+ // caller's map (getters and all) BEFORE any room is reserved, then writePrepared()
1846
+ // writes the HPACK octets straight into this session's staging buffer. No module-level
1847
+ // scratch view, no subarray and no memcpy; the 9-octet frame headers are inserted in
1848
+ // place, from the last CONTINUATION backwards. END_STREAM rides on the first frame
1849
+ // even when CONTINUATIONs follow it (RFC 9113 6.2/5.1/8.1, measured on node's wire).
1850
+ // `prefixSid` adds PUSH_PROMISE's four-octet promised-id prefix; `priority` adds the
1851
+ // allowance node reserves on HEADERS only. `prep` lets a caller that already parsed
1852
+ // (respondWithFD, to keep its error handling around the parse) skip a second pass.
1853
+ // An over-estimate is refused at prep time, not thrown (nghttp2_session.c,
1854
+ // session_prep_frame): node emits 'frameError' and closes a turn later. Measured for
1855
+ // an oversize trailer on v26.12.1: frameError(1, 6, sid), rstCode 6, RST_STREAM(6)
1856
+ // then GOAWAY(0). OPTIMIZATION.md item 68.
1857
+ _writeBlockAt(sid, headers, opts, type, end, prefixSid, priority, prep) {
1858
+ if (prep === undefined) {
1859
+ prep = hdr.prepare(headers, opts, this);
1860
+ }
1861
+ if (prep.bound + (priority ? PRIORITY_SPECLEN : 0) > this._maxSendBlock) {
1862
+ if (type === PUSH_PROMISE) {
1863
+ this._refusePush(sid, prefixSid);
1864
+ } else {
1865
+ this._refuseBlock(sid, type);
1878
1866
  }
1879
- }
1880
- }
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
1867
  return true;
1893
1868
  }
1869
+ this.state.deflateDynamicTableSize = this._encoder.size;
1894
1870
  const max = this.remoteSettings.maxFrameSize;
1871
+ const prefix = prefixSid === undefined ? 0 : 4;
1895
1872
  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));
1873
+ const frames = Math.max(1, Math.ceil((prefix + cap) / max));
1874
+ this._need(HEADER_LEN + prefix + cap + HEADER_LEN * (frames - 1));
1898
1875
  const dst = this._stage;
1899
1876
  const off = this._stageLen;
1900
- const payloadOff = off + HEADER_LEN;
1877
+ if (prefix !== 0) {
1878
+ dst.writeUInt32BE(prefixSid, off + HEADER_LEN);
1879
+ }
1880
+ const payloadOff = off + HEADER_LEN + prefix;
1901
1881
  const payloadEnd = hdr.writePrepared(prep, this, dst, payloadOff);
1902
- const n = payloadEnd - payloadOff;
1882
+ const n = payloadEnd - payloadOff + prefix;
1903
1883
  const used = Math.max(1, Math.ceil(n / max));
1904
1884
  if (used === 1) {
1905
- writeHeader(dst, off, n, HEADERS, F_END_HEADERS | (end ? F_END_STREAM : 0), sid);
1885
+ writeHeader(dst, off, n, type, F_END_HEADERS | (end ? F_END_STREAM : 0), sid);
1906
1886
  } else {
1887
+ // The first payload octet is the prefix, not the HPACK block: every later
1888
+ // frame starts max octets after the FIRST frame's payload, which is prefix
1889
+ // octets earlier than payloadOff.
1890
+ const bodyStart = payloadOff - prefix;
1907
1891
  for (let i = used - 1; i >= 1; i--) {
1908
- const src = payloadOff + i * max;
1892
+ const src = bodyStart + i * max;
1909
1893
  const stop = Math.min(payloadEnd, src + max);
1910
1894
  dst.copyWithin(src + i * HEADER_LEN, src, stop);
1911
1895
  }
@@ -1914,7 +1898,7 @@ class Http2ServerSession extends EventEmitter {
1914
1898
  const flags = i === 0 ? (end ? F_END_STREAM : 0)
1915
1899
  : (i === used - 1 ? F_END_HEADERS : 0);
1916
1900
  writeHeader(dst, off + i * (HEADER_LEN + max), take,
1917
- i === 0 ? HEADERS : CONTINUATION, flags, sid);
1901
+ i === 0 ? type : CONTINUATION, flags, sid);
1918
1902
  }
1919
1903
  }
1920
1904
  const total = HEADER_LEN * used + n;
@@ -1926,6 +1910,10 @@ class Http2ServerSession extends EventEmitter {
1926
1910
  return false;
1927
1911
  }
1928
1912
 
1913
+ sendHeadersAt(sid, headers, opts, end) {
1914
+ return this._writeBlockAt(sid, headers, opts, HEADERS, end, undefined, true);
1915
+ }
1916
+
1929
1917
  // node's onFrameError (internal/http2/core.js): the emitter is the stream while the
1930
1918
  // session still holds it and the session otherwise, 'frameError' goes out synchronously,
1931
1919
  // and the close is deferred a turn -- node's own comment says the delay is there to let
@@ -1993,7 +1981,7 @@ class Http2ServerSession extends EventEmitter {
1993
1981
  // with the first frame carrying the 4-octet prefix and the block fragment that fits.
1994
1982
  // Returns true when the block was refused, so pushStream can mark the promised stream
1995
1983
  // before its callback runs (the same contract sendHeaders has with respond()).
1996
- sendPushPromise(parentSid, promisedSid, block, bound) {
1984
+ sendPushPromise(parentSid, promisedSid, headers) {
1997
1985
  // nghttp2's send cycle flushes control frames before DATA, so a PUSH_PROMISE
1998
1986
  // opened in the same turn as the parent's end() rides ahead of the parent's
1999
1987
  // END_STREAM on node's wire. An nghttp2 client refuses a push whose parent is
@@ -2036,47 +2024,19 @@ class Http2ServerSession extends EventEmitter {
2036
2024
  this._esRequeue.push(esBytes !== null ? { bytes: esBytes } : { pair: esPair });
2037
2025
  }
2038
2026
  }
2039
- // The same prep-time estimate sendHeaders refuses on, with no priority spec:
2040
- // session_estimate_headers_payload passes 0 for PUSH_PROMISE. Measured on v26.12.1
2041
- // with a push of {':path':'/pushed', ':authority':'a', 'x-big':'X'.repeat(n)} -- node
2042
- // fills :method and :scheme, so five fields and an estimate of 121+n: under a bound of
2027
+ // The prep-time estimate node uses has no priority allowance on PUSH_PROMISE
2028
+ // (session_estimate_headers_payload passes 0), so _writeBlockAt is called with
2029
+ // priority=false. Measured on v26.12.1 with a push of
2030
+ // {':path':'/pushed', ':authority':'a', 'x-big':'X'.repeat(n)} -- node fills
2031
+ // :method and :scheme, so five fields and an estimate of 121+n: under a bound of
2043
2032
  // 150 n=29 is pushed and n=30 is refused, and under the default n=65415 / 65416
2044
- // (test/outbound-bound.test.js). The refusal lands on the PARENT's
2045
- // 'frameError' (the frame rides on its id) and closes the PROMISED stream with
2046
- // INTERNAL_ERROR, while the parent's own response still goes out and closes it with
2047
- // NO_ERROR -- nghttp2_session_close_stream(promised_sid, NGHTTP2_INTERNAL_ERROR) on
2048
- // the PUSH_PROMISE prep-error path, nghttp2_session.c.
2049
- if (bound > this._maxSendBlock) {
2050
- this._refusePush(parentSid, promisedSid);
2051
- return true;
2052
- }
2053
- this.state.deflateDynamicTableSize = this._encoder.size;
2054
- const max = this.remoteSettings.maxFrameSize;
2055
- // The payload is the 4-byte promised id + the block. The first frame can carry
2056
- // max - 4 bytes of block; the rest goes into CONTINUATION frames.
2057
- const firstCap = max - 4;
2058
- if (block.length <= firstCap) {
2059
- const payload = Buffer.allocUnsafe(4 + block.length);
2060
- payload.writeUInt32BE(promisedSid, 0);
2061
- f.copyInto(payload, 4, block, 0, block.length);
2062
- this._frame(PUSH_PROMISE, F_END_HEADERS, parentSid, payload);
2063
- return false;
2064
- }
2065
- const first = Buffer.allocUnsafe(4 + firstCap);
2066
- first.writeUInt32BE(promisedSid, 0);
2067
- f.copyInto(first, 4, block, 0, firstCap);
2068
- this._frame(PUSH_PROMISE, 0, parentSid, first);
2069
- let off = firstCap;
2070
- for (;;) {
2071
- const n = Math.min(block.length - off, max);
2072
- const last = off + n >= block.length;
2073
- this._frame(CONTINUATION, last ? F_END_HEADERS : 0, parentSid,
2074
- block.subarray(off, off + n));
2075
- off += n;
2076
- if (last) {
2077
- return false;
2078
- }
2079
- }
2033
+ // (test/outbound-bound.test.js). The refusal lands on the PARENT's 'frameError'
2034
+ // and closes the PROMISED stream with INTERNAL_ERROR while the parent's own answer
2035
+ // still goes out: nghttp2_session_close_stream(promised_sid, NGHTTP2_INTERNAL_ERROR).
2036
+ // The promised id is written as the four-octet prefix of the first frame; the rest
2037
+ // of the block is split into CONTINUATIONs by _writeBlockAt.
2038
+ return this._writeBlockAt(parentSid, headers, { request: true },
2039
+ PUSH_PROMISE, false, promisedSid, false);
2080
2040
  }
2081
2041
 
2082
2042
  // Remove a not-yet-committed END_STREAM frame that _frame staged for sid, the
@@ -3901,11 +3861,11 @@ class Http2ServerSession extends EventEmitter {
3901
3861
  // all, the withheld END_STREAM rides on an empty DATA (lib/server/Http2ServerStream.js sendTrailers).
3902
3862
  if (stream._pendingTrailers !== null) {
3903
3863
  const trailers = stream._pendingTrailers;
3904
- const bound = stream._pendingTrailersBound;
3905
3864
  stream._pendingTrailers = null;
3906
3865
  if (trailers.length === 0) {
3907
3866
  this._frame(DATA, F_END_STREAM, stream.id, null);
3908
- } else if (this.sendHeaders(stream.id, trailers, true, bound)) {
3867
+ } else if (this._writeBlockAt(stream.id, trailers, { trailer: true },
3868
+ HEADERS, true, undefined, true)) {
3909
3869
  // The bound is checked when the block is framed, not when sendTrailers() stashed
3910
3870
  // it: nghttp2 compares the estimate at prep time, whenever that happens. Measured
3911
3871
  // on v26.12.1 with a 200 000-octet body ahead of a 64 KiB trailer: frameError
@@ -93,7 +93,7 @@ const { inspect, deprecate } = require('node:util');
93
93
  const frames = require('../frames');
94
94
  const {
95
95
  ST_OPEN, ST_HALF_CLOSED_LOCAL, ST_HALF_CLOSED_REMOTE, ST_CLOSED, NO_ERROR,
96
- PROTOCOL_ERROR, INTERNAL_ERROR
96
+ PROTOCOL_ERROR, INTERNAL_ERROR, HEADERS
97
97
  } = frames;
98
98
  const hdr = require('../headers');
99
99
  const { Http2Stream, EMPTY, READABLE_HWM, emitCloseNT, emitErrorCloseNT, emitErrorOnlyNT, emitEndNT, wantTrailersNT, finishNT, emitEndCloseNT, emitCloseDeliveredNT, autoCloseNT, noopClose, FILE_CHUNK, isFileHandle, argTypeError, fdOptions, prepareResponseHeadersObject, errorOf, validateRstCode, abortError, validateObjectArg, validateSignalArg, streamErrorOf, createStreamIterator } = require('../Http2Stream');
@@ -174,8 +174,7 @@ class Http2ServerStream extends Http2Stream {
174
174
  // batch, so sendTrailers() closes the stream without staging a second one, and
175
175
  // addTrailers() after end() recalls the frame instead
176
176
  this._esStaged = false;
177
- this._pendingTrailers = null; // trailer block waiting behind a queued body
178
- this._pendingTrailersBound = 0; // ...and its outbound estimate, checked when it drains
177
+ this._pendingTrailers = null; // trailer map waiting behind a queued body
179
178
  // A refused outbound HEADERS (session._refuseBlock) left the wire a step behind the
180
179
  // application: no response HEADERS means no DATA may follow, and no END_STREAM means
181
180
  // the stream must not close gracefully. An informational block sets neither.
@@ -560,9 +559,11 @@ class Http2ServerStream extends Http2Stream {
560
559
  this.headersSent = true;
561
560
  this.pending = false;
562
561
  this._ending = true;
563
- let block;
562
+ let prep;
564
563
  try {
565
- block = hdr.block(prepared, { sendDate }, this.session);
564
+ // prepare() reads the map here, inside the descriptor's error handling, and
565
+ // _writeBlockAt writes the octets straight into the session's staging buffer.
566
+ prep = hdr.prepare(prepared, { sendDate }, this.session);
566
567
  } catch (err) {
567
568
  if (this.ownsFd) {
568
569
  fs.close(fd, noopClose);
@@ -573,8 +574,9 @@ class Http2ServerStream extends Http2Stream {
573
574
  this._sentSrc = prepared;
574
575
  this._sentStatus = hdr.sent.status;
575
576
  this._sentDate = hdr.sent.date;
576
- const bound = hdr.sent.bound;
577
- if (this._blockRefused || this.session.sendHeaders(this.id, block, false, bound)) {
577
+ if (this._blockRefused ||
578
+ this.session._writeBlockAt(this.id, prepared, { sendDate }, HEADERS,
579
+ false, undefined, true, prep)) {
578
580
  this._blockRefused = true;
579
581
  // node has already called self.end() by this point (processRespondWithFD ends
580
582
  // the writable before the wire write), so the half-close happens even here.
@@ -794,16 +796,12 @@ class Http2ServerStream extends Http2Stream {
794
796
  throw errorOf('ERR_HTTP2_TRAILERS_NOT_READY',
795
797
  'Trailing headers cannot be sent until after the wantTrailers event is emitted');
796
798
  }
797
- let block;
798
- let bound;
799
- // An empty trailer map is skipped, not run through block(): nothing in it can fail
800
- // validation (no name to check, no single-value rule to trip) and it encodes to zero
801
- // octets, while block() allocates the parse key list, the strict-singles scratch and
802
- // the parse result for every one of them -- and every compat response ends with an
803
- // empty trailer map, because the (req,res) layer always answers 'wantTrailers' with
804
- // what it recorded: nothing at all when the application added none (item 44).
805
- // hdr.sent must not be read for the skipped case: it still holds the previous
806
- // block's result.
799
+ // An empty trailer map is skipped, not run through the encoder: nothing in it can
800
+ // fail validation (no name to check, no single-value rule to trip) and it encodes to
801
+ // zero octets, while prepare() still allocates the parse key list, the
802
+ // strict-singles scratch and the parse result -- and every compat response ends with
803
+ // an empty trailer map, because the (req,res) layer always answers 'wantTrailers'
804
+ // with what it recorded: nothing at all when the application added none (item 44).
807
805
  let empty = true;
808
806
  for (const key in trailers) {
809
807
  if (Object.prototype.hasOwnProperty.call(trailers, key)) {
@@ -811,23 +809,12 @@ class Http2ServerStream extends Http2Stream {
811
809
  break;
812
810
  }
813
811
  }
814
- if (empty) {
815
- block = EMPTY;
816
- bound = 0;
817
- } else {
818
- block = hdr.block(trailers, { trailer: true }, this.session);
819
- bound = hdr.sent.bound;
820
- // Own these octets before the copy below reads the caller's getters. A getter
821
- // can call block() for another response, and block() returns a view into the
822
- // module-level scratch shared by every session: the bytes would be rewritten
823
- // before sendHeaders() stages this frame (reproduced with a reentrant getter
824
- // in the trailers object -- the peer saw COMPRESSION_ERROR instead of them).
825
- // The queued path below uses this copy too, so it still copies only once.
826
- block = Buffer.from(block);
827
- }
828
812
  // node records a null-prototype copy, not the caller's map (`ObjectAssign({
829
813
  // __proto__: null }, headers)`, internal/http2/core.js sendTrailers -- the shared
830
- // base method, so the client stream records the same shape).
814
+ // base method, so the client stream records the same shape). Reading the getters
815
+ // here once also fixes the values for a body that is still queued: the block is
816
+ // encoded when that body drains, and prepare()/writePrepared() write straight into
817
+ // the session's stage from parsed values, so a reentrant getter cannot rewrite it.
831
818
  this.sentTrailers = Object.assign({ __proto__: null }, trailers);
832
819
  // the trailers are out: the flag that permitted this call must not keep asking for
833
820
  // wantTrailers, whatever happens to the bytes below
@@ -848,15 +835,12 @@ class Http2ServerStream extends Http2Stream {
848
835
  // because node's (req,res) layer always asks for trailers (internal/http2/compat.js
849
836
  // kBeginSend passes waitForTrailers: true) and answers with the empty trailer map
850
837
  // when the application added none.
851
- empty = block.length === 0;
852
838
  if (this._queued !== null) {
853
839
  // The body is still waiting for credit or for the socket, and this block has to
854
840
  // follow it: END_STREAM rides on the trailers, so a HEADERS sent now would outrun
855
- // DATA that has not gone out. The block was already made owned above (the
856
- // zero-length marker needs none); let the session put it on the wire when the
857
- // queue drains.
858
- this._pendingTrailers = empty ? EMPTY : block;
859
- this._pendingTrailersBound = bound;
841
+ // DATA that has not gone out. Stash the fixed copy; the session encodes it when
842
+ // the queue drains. A zero-length stash is the empty-map marker above.
843
+ this._pendingTrailers = empty ? EMPTY : this.sentTrailers;
860
844
  return this;
861
845
  }
862
846
  if (empty) {
@@ -864,7 +848,7 @@ class Http2ServerStream extends Http2Stream {
864
848
  this.session.sendData(this, EMPTY, true);
865
849
  return this;
866
850
  }
867
- if (this.session.sendHeaders(this.id, block, true, bound)) {
851
+ if (this.session.sendHeadersAt(this.id, this.sentTrailers, { trailer: true }, true)) {
868
852
  // The END_STREAM this block carried never went out, so the stream has not finished
869
853
  // on the wire and must not close on its own terms ahead of the deferred
870
854
  // FRAME_SIZE_ERROR close (session._refuseBlock).
@@ -926,12 +910,10 @@ class Http2ServerStream extends Http2Stream {
926
910
  }
927
911
  // `{ info: true }` is node's separate rule for these blocks: :status must be 100..199
928
912
  // (101 has its own error), there is no default status and no generated date.
929
- const block = hdr.block(headers, { info: true }, this.session);
930
- const bound = hdr.sent.bound;
931
- // Own the bytes before Object.assign reads the caller's getters: one of them
932
- // can build another block and overwrite the shared scratch this view points
933
- // into (the trailers path above has the same window).
934
- const owned = Buffer.from(block);
913
+ // prepare() performs that validation before the copy is made, and the plan it
914
+ // returns lets _writeBlockAt write the octets straight into the session's stage
915
+ // without a scratch view or a second walk over getters.
916
+ const prep = hdr.prepare(headers, { info: true }, this.session);
935
917
  // node stores a null-proto copy of each informational block, created at the
936
918
  // first call (internal/http2/core.js:3265, 3285) -- the caller's object is
937
919
  // not retained, and the array does not exist before the first call.
@@ -941,7 +923,8 @@ class Http2ServerStream extends Http2Stream {
941
923
  } else {
942
924
  this.sentInfoHeaders.push(copy);
943
925
  }
944
- this.session.sendHeaders(this.id, owned, false, bound);
926
+ this.session._writeBlockAt(this.id, copy, { info: true }, HEADERS, false,
927
+ undefined, true, prep);
945
928
  return this;
946
929
  }
947
930
 
@@ -1057,8 +1040,9 @@ class Http2ServerStream extends Http2Stream {
1057
1040
  // the frame is submitted). The id was already reserved; it stays consumed.
1058
1041
  // Like respond(), the never-indexed names come only off the headers object's
1059
1042
  // sensitiveHeaders symbol -- node's pushStream has no options.sensitiveHeaders.
1060
- const block = hdr.pushBlock(h, this.session);
1061
- const refused = this.session.sendPushPromise(this.id, promisedId, block, hdr.sent.bound);
1043
+ // sendPushPromise prepares the request-shaped block itself and writes its
1044
+ // promised-id prefix plus the HPACK octets straight into the session's stage.
1045
+ const refused = this.session.sendPushPromise(this.id, promisedId, h);
1062
1046
 
1063
1047
  // Create the pushed stream and register it. The readable side is pre-ended:
1064
1048
  // remoteClose=1 means _endLocalSide() takes the graceful close path (no RST),
@@ -102,7 +102,14 @@ function initHttp2Server(server, options) {
102
102
  const opts = { ...(options || {}) };
103
103
  validateRemoteCustomSettings(opts);
104
104
  server.settings = { ...OUR_DEFAULTS, ...opts.settings };
105
+ // One pool for every session of this server: a staging buffer completed under one
106
+ // connection can be taken by another, and the cap is server-wide rather than
107
+ // per-session. performServerHandshake carries its own single-session pool.
108
+ server._stagingPool = [];
105
109
  server._sessionOptions = {
110
+ stagingPool: server._stagingPool,
111
+ // Default on; `false` keeps the allocate-per-batch behaviour of the pool opt-out.
112
+ reuseBuffers: opts.reuseBuffers !== false,
106
113
  settings: server.settings,
107
114
  // Which values the application asked for. server.settings is what the session's guards read,
108
115
  // this list is what the peer is told, and the two are deliberately not the same object: node
@@ -601,6 +608,8 @@ function performServerHandshake(socket, options) {
601
608
  throw err;
602
609
  }
603
610
  const opts = { ...options };
611
+ // No server object here: give this one session its own staging-buffer pool.
612
+ opts.stagingPool = [];
604
613
  if (opts.settings !== undefined &&
605
614
  (opts.settings === null || typeof opts.settings !== 'object' || Array.isArray(opts.settings))) {
606
615
  const err = new TypeError(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h2lean",
3
- "version": "0.17.5",
3
+ "version": "0.18.1",
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": [