h2lean 0.17.2 → 0.17.4

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.
@@ -16,8 +16,8 @@
16
16
 
17
17
  const net = require('node:net');
18
18
  const tls = require('node:tls');
19
- const { ClientHttp2Session } = require('./client-session');
20
- const { strictSingleValueFields, received, outOfRangeValue, validateRemoteCustomSettings } = require('./session');
19
+ const { Http2ClientSession } = require('./Http2ClientSession');
20
+ const { strictSingleValueFields, received, outOfRangeValue, validateRemoteCustomSettings } = require('../server/Http2ServerSession');
21
21
 
22
22
  function notImplemented(what) {
23
23
  const err = new Error(`h2lean: not implemented: ${what}`);
@@ -60,7 +60,7 @@ function connect(authority, options, listener) {
60
60
  // the two failure classes: a non-number is ERR_INVALID_ARG_TYPE / TypeError,
61
61
  // a number that is NaN or negative is ERR_OUT_OF_RANGE / RangeError. Both
62
62
  // received-value strings are node's own wording -- determineSpecificType and
63
- // the ERR_OUT_OF_RANGE formatter, shared with lib/session.js -- because a
63
+ // the ERR_OUT_OF_RANGE formatter, shared with lib/server/Http2ServerSession.js -- because a
64
64
  // paraphrase is a visible difference: `Received type object` where node says
65
65
  // `Received an instance of Array`. Measured against a live node connect() over
66
66
  // the 16 values node's own origin-set-max-size test passes plus the huge ones.
@@ -121,7 +121,7 @@ function connect(authority, options, listener) {
121
121
 
122
122
  const scheme = protocol === 'https:' ? 'https' : 'http';
123
123
  const authorityHeader = `${host}:${port}`;
124
- const session = new ClientHttp2Session(socket, options, scheme, authorityHeader);
124
+ const session = new Http2ClientSession(socket, options, scheme, authorityHeader);
125
125
 
126
126
  if (typeof listener === 'function') {
127
127
  session.once('connect', listener);
package/lib/fast-timer.js CHANGED
@@ -9,7 +9,7 @@
9
9
  //
10
10
  // What h2lean uses it for: one shared 499 ms clock for all idle/keep-alive
11
11
  // timeouts, instead of one libuv timer handle per connection. See
12
- // Http2Session.setTimeout() in lib/session.js.
12
+ // Http2ServerSession.setTimeout() in lib/server/Http2ServerSession.js.
13
13
 
14
14
  /**
15
15
  * This module offers an optimized timer implementation designed for scenarios
package/lib/headers.js CHANGED
@@ -67,8 +67,8 @@ const VALID_NAMES_MAX = 1024;
67
67
 
68
68
  // The fields node's toHeaderObject (internal/http2/util.js, kSingleValueFields) reads
69
69
  // as a single value in BOTH directions: inbound, a second copy on the wire is IGNORED
70
- // and the first copy stays the value the application sees (lib/session.js _toObject and
71
- // lib/client-session.js _toObject); outbound, node refuses a repeated copy or a
70
+ // and the first copy stays the value the application sees (lib/server/Http2ServerSession.js _toObject and
71
+ // lib/client/Http2ClientSession.js _toObject); outbound, node refuses a repeated copy or a
72
72
  // multi-element array outright (parse() below, and the client's request list). Cookie
73
73
  // and set-cookie are NOT in the set, measured on v26.12.1 by putting duplicate lines on
74
74
  // the wire and reading the header object back (test/share-headers.test.js): cookie
@@ -143,7 +143,7 @@ const NAME_CACHE_MAX = 1024;
143
143
 
144
144
  // The compat layer's shape. A name that is not a string throws here, the way
145
145
  // node's private kSetHeader does (name.trim() is not a function), and the
146
- // public accessors in lib/compat.js refuse it before they get here.
146
+ // public accessors in lib/server/compat.js refuse it before they get here.
147
147
  function trimName(name) {
148
148
  let out = NAME_CACHE.get(name);
149
149
  if (out === undefined) {
@@ -201,7 +201,7 @@ const badValue = /[\u0000-\u0008\u000a-\u001f\u007f]/;
201
201
  // runs no callback, so no call can observe another's list. The shape is node's
202
202
  // own (buildNgHeaderString checks a lazily-grown array inline in its one pass,
203
203
  // internal/http2/util.js) and the one the client's request() carries
204
- // (lib/client-session.js, OPTIMIZATION.md item 36). Measured honestly: at the
204
+ // (lib/client/Http2ClientSession.js, OPTIMIZATION.md item 36). Measured honestly: at the
205
205
  // granularity parse() acts on, the swap from a per-call Set is inside the noise
206
206
  // -- item 36's win came from removing request()'s second pass over the flat
207
207
  // list, which parse() never had; the component costs are in OPTIMIZATION.md
@@ -221,7 +221,7 @@ const CONNECTION_SPECIFIC = new Set(['connection', 'keep-alive', 'proxy-connecti
221
221
  'transfer-encoding', 'upgrade']);
222
222
 
223
223
  // Whether a field value carries a character that may not appear in one. The server's
224
- // inbound path asks the same question (lib/session.js) and answers it the way nghttp2
224
+ // inbound path asks the same question (lib/server/Http2ServerSession.js) and answers it the way nghttp2
225
225
  // does: the field is ignored, the stream lives.
226
226
  function hasBadValue(value) {
227
227
  return badValue.test(value);
@@ -567,7 +567,7 @@ function block(headers, opts, session) {
567
567
  // The announcement goes in front of the block, in the same buffer: the old form was
568
568
  // Buffer.concat([update, out]) -- a second allocation, a copy of the whole block and a
569
569
  // temporary array, on the one path where the peer changed the table size. The client
570
- // does the same thing in its own _encodeRequest (lib/client-session.js).
570
+ // does the same thing in its own _encodeRequest (lib/client/Http2ClientSession.js).
571
571
  const at = update === null ? 0 : update.length;
572
572
  const end = encodeAt(parsed, enc, at);
573
573
  if (at !== 0) {
package/lib/hpack.js CHANGED
@@ -35,7 +35,7 @@
35
35
  //
36
36
  // The encoder therefore holds per-connection state and must not be shared between
37
37
  // sessions: the table has to match the one the peer's decoder builds from the same
38
- // stream. lib/session.js owns one Encoder per session, exactly as it owns a Decoder.
38
+ // stream. lib/server/Http2ServerSession.js owns one Encoder per session, exactly as it owns a Decoder.
39
39
  //
40
40
  // Where this differs from nghttp2, which is what node:http2 embeds, and why. Read from
41
41
  // lib/nghttp2_hd.c v1.70.0 (hd_deflate_decide_indexing(), deflate_nv()); the differences
@@ -250,25 +250,43 @@ function huffEncode(src, start, end, dst, off) {
250
250
  // so the byte of a character is its code unit & 0xff -- the byte the buffer version
251
251
  // above would have been handed. Coding straight from the string saves the copy into
252
252
  // a scratch buffer and the view of it that the copy needed (OPTIMIZATION.md item 12).
253
+ // The accumulator is kept below 2^31 so emitting an octet is two bitwise ops
254
+ // instead of a floating-point division by POW2[nbits]. A code that does not fit
255
+ // in the remaining room is split: its high bits fill the accumulator, the whole
256
+ // octets are flushed, then its low bits are appended. Only the rare 19-30 bit
257
+ // codes take that path; digits and letters are 5-8 bits and never split.
253
258
  function huffEncodeStr(s, dst, off) {
254
259
  let acc = 0;
255
260
  let nbits = 0;
256
261
  for (let i = 0; i < s.length; i++) {
257
262
  const sym = s.charCodeAt(i) & 0xff;
258
263
  const b = HUFF_BITS[sym];
259
- acc = acc * POW2[b] + HUFF_CODES[sym];
260
- nbits += b;
264
+ const code = HUFF_CODES[sym];
265
+ const room = 31 - nbits;
266
+ if (b <= room) {
267
+ acc = (acc << b) | code;
268
+ nbits += b;
269
+ } else {
270
+ acc = (acc << room) | (code >>> (b - room));
271
+ nbits = 31;
272
+ while (nbits >= 8) {
273
+ nbits -= 8;
274
+ dst[off++] = (acc >>> nbits) & 0xff;
275
+ acc &= (1 << nbits) - 1;
276
+ }
277
+ const rest = b - room;
278
+ acc = (acc << rest) | (code & (2 ** rest - 1));
279
+ nbits += rest;
280
+ }
261
281
  while (nbits >= 8) {
262
282
  nbits -= 8;
263
- const byte = Math.floor(acc / POW2[nbits]);
264
- dst[off++] = byte;
265
- acc -= byte * POW2[nbits];
283
+ dst[off++] = (acc >>> nbits) & 0xff;
284
+ acc &= (1 << nbits) - 1;
266
285
  }
267
286
  }
268
287
  // EOS is the all-ones code, so padding the last byte with ones *is* EOS
269
288
  if (nbits > 0) {
270
- const pad = POW2[8 - nbits] - 1;
271
- dst[off++] = acc * POW2[8 - nbits] + pad;
289
+ dst[off++] = (acc << (8 - nbits)) | (2 ** (8 - nbits) - 1);
272
290
  }
273
291
  return off;
274
292
  }
@@ -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,8 @@ 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');
42
43
 
43
44
  // The socket's ownership mark, shared with the client session (node keeps it as
44
45
  // socket[kBoundSession] in the one Http2Session base constructor both kinds run
@@ -48,7 +49,7 @@ const kBoundSession = Symbol('h2lean.boundSession');
48
49
  // One shared 499 ms clock for the long idle timeouts, instead of a libuv timer
49
50
  // handle per connection. Vendored verbatim; see lib/fast-timer.js.
50
51
  const { setTimeout: idleSetTimeout, clearTimeout: idleClearTimeout } =
51
- require('./fast-timer');
52
+ require('../fast-timer');
52
53
 
53
54
  const {
54
55
  DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY,
@@ -752,7 +753,7 @@ const PRIORITY_SPECLEN = 5;
752
753
  // node's strictSingleValueFields option (validateSessionOptions, internal/http2/core.js):
753
754
  // undefined is true, and a non-boolean is ERR_INVALID_ARG_TYPE at createServer/connect
754
755
  // 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
756
+ // (parse in lib/headers.js) and the client's request list (lib/client/Http2ClientSession.js), while
756
757
  // the inbound first-wins reading of a repeated field is not optional -- node's
757
758
  // toHeaderObject always reads it that way (SINGLE_VALUE_FIELDS in lib/headers.js).
758
759
  function strictSingleValueFields(opts) {
@@ -1158,7 +1159,7 @@ const proxySocketHandler = {
1158
1159
  }
1159
1160
  };
1160
1161
 
1161
- class Http2Session extends EventEmitter {
1162
+ class Http2ServerSession extends EventEmitter {
1162
1163
  constructor(socket, options) {
1163
1164
  super();
1164
1165
  const opts = options || {};
@@ -1287,7 +1288,7 @@ class Http2Session extends EventEmitter {
1287
1288
  // outstanding pings in the C++ session rather than on the emitter and the event belongs to
1288
1289
  // the application: a listener per ping both competes with the application's own handler and
1289
1290
  // 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).
1291
+ // queue order is node's answer rule too (lib/client/Http2ClientSession.js, _pingQ).
1291
1292
  this._pingQ = [];
1292
1293
  // Unbounded-work-per-peer guards (SECURITY §8B): node bounds these, h2lean must too.
1293
1294
  // maxOutstandingPings defaults to 10 (initializeOptions, internal/http2/util.js).
@@ -1774,7 +1775,7 @@ class Http2Session extends EventEmitter {
1774
1775
  // does -- see the silent-peer case in test/goaway.test.js), and it also destroys the session
1775
1776
  // before the peer's answer to the GOAWAY can be read, which costs seventeen event-order
1776
1777
  // 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
1778
+ // which is how node re-runs it (`setImmediate(() => session[kMaybeDestroy]())` in Http2ServerStream's
1778
1779
  // teardown, "Delay with setImmediate so we don't do it on the nghttp2 stack"), still costs
1779
1780
  // seven: the session 'close' then goes out ahead of the peer's, in the idle-timeout and goaway
1780
1781
  // traces. The read-side finish (`_onGoaway` -> close) and the stream teardown are therefore the
@@ -1806,7 +1807,7 @@ class Http2Session extends EventEmitter {
1806
1807
  }
1807
1808
 
1808
1809
  // 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).
1810
+ // HEADERS would have advanced never happened (see _blockRefused in lib/server/Http2ServerStream.js).
1810
1811
  sendHeaders(sid, block, end, bound) {
1811
1812
  // nghttp2 refuses an outbound header block whose estimate exceeds the session's
1812
1813
  // maxSendHeaderBlockLength, and it does so at *prep* time -- after the JS call that
@@ -2067,7 +2068,7 @@ class Http2Session extends EventEmitter {
2067
2068
  // owned: a view of the application's buffer, which is not copied any more. A frame
2068
2069
  // that takes the whole body needs no view at all -- `take === total` is only
2069
2070
  // 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
2071
+ // is the ~28 ns item 57 prices. The same skip the pump in lib/server/Http2ServerStream.js and the
2071
2072
  // client's `_pending` loop already make.
2072
2073
  this._frame(DATA, last ? F_END_STREAM : 0, stream.id,
2073
2074
  take === total ? buf : buf.subarray(off, off + take), true);
@@ -3305,7 +3306,7 @@ class Http2Session extends EventEmitter {
3305
3306
  // RST_STREAM(PROTOCOL_ERROR) on the wire AND ERR_HTTP2_STREAM_ERROR + 'close'
3306
3307
  // on the stream -- the same shape as the missing-END_STREAM refusal above --
3307
3308
  // and the closed stream is what keeps the unread-request auto-close
3308
- // (Http2Stream[kMaybeDestroy], see lib/stream.js _maybeAutoClose) from
3309
+ // (Http2Stream[kMaybeDestroy], see lib/server/Http2ServerStream.js _maybeAutoClose) from
3309
3310
  // putting a second RST(NO_ERROR) on the wire behind the refusal's.
3310
3311
  //
3311
3312
  // The refusal is also a counted invalid frame (node's OnInvalidFrame counts
@@ -3424,7 +3425,7 @@ class Http2Session extends EventEmitter {
3424
3425
 
3425
3426
  // The request object is built here only when a reader is already known: a
3426
3427
  // 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),
3428
+ // request materializes it at the first req.headers access (lib/server/compat.js),
3428
3429
  // so a handler that only consumes the body and routes on req.url pays no
3429
3430
  // per-request object -- the paired marginal is OPTIMIZATION.md item 49. The
3430
3431
  // build still happens eagerly under shareHeaders, whose frozen shared
@@ -3437,7 +3438,7 @@ class Http2Session extends EventEmitter {
3437
3438
  : this._toObject(fields, fcount, sensitive)))
3438
3439
  : undefined;
3439
3440
  // 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
3441
+ // lib/server/Http2ServerStream.js and the compat CONNECT check), :path (req.url) and
3441
3442
  // content-length (the promise checked below). When the object was built
3442
3443
  // these are its own property reads, exactly what the eager code did; the
3443
3444
  // one-pass scan is the lazy path's only walk, and it takes the first copy
@@ -3466,7 +3467,7 @@ class Http2Session extends EventEmitter {
3466
3467
  // refused -- is what makes the verdict match node's: measured (probe case P7, and T4 of
3467
3468
  // tools/probe-inbound-limits.js for the reading handler), node answers RST_STREAM
3468
3469
  // (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
3470
+ // Letting it through to Http2ServerStream._remoteEnded() instead resets the stream and then hands
3470
3471
  // the handler a destroyed one, and a handler that answers it puts a response on the wire for a
3471
3472
  // request this side has already refused.
3472
3473
  if (end && promised !== undefined && +promised > 0) {
@@ -3482,7 +3483,7 @@ class Http2Session extends EventEmitter {
3482
3483
  }
3483
3484
  return;
3484
3485
  }
3485
- const stream = new Http2Stream(this, sid);
3486
+ const stream = new Http2ServerStream(this, sid);
3486
3487
  stream._reqMethod = reqMethod;
3487
3488
  stream._reqPath = reqPath;
3488
3489
  stream._reqSensitive = sensitive;
@@ -3639,7 +3640,7 @@ class Http2Session extends EventEmitter {
3639
3640
  // on node (h2spec http2/8.1.2.6): the frame that crosses the line ends the CONNECTION --
3640
3641
  // GOAWAY(INTERNAL_ERROR) -- rather than the stream, because nghttp2 reads an overflow as a
3641
3642
  // 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()
3643
+ // cannot be seen before the message ends: that one is caught in Http2ServerStream._remoteEnded()
3643
3644
  // and is a stream error. Both compare against the octets of this stream's body, padding
3644
3645
  // excluded, which is what `l` is here.
3645
3646
  if (stream._expLen >= 0 && stream._bodyLen + l > stream._expLen) {
@@ -3823,7 +3824,7 @@ class Http2Session extends EventEmitter {
3823
3824
  // carries the END_STREAM the body was not allowed to send (RFC 9113 6.1: a trailing
3824
3825
  // HEADERS precedes the close -- measured against node: HEADERS/EH DATA HEADERS/ES/EH).
3825
3826
  // 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).
3827
+ // all, the withheld END_STREAM rides on an empty DATA (lib/server/Http2ServerStream.js sendTrailers).
3827
3828
  if (stream._pendingTrailers !== null) {
3828
3829
  const trailers = stream._pendingTrailers;
3829
3830
  const bound = stream._pendingTrailersBound;
@@ -3899,7 +3900,7 @@ class Http2Session extends EventEmitter {
3899
3900
  }
3900
3901
  // The peer's RST_STREAM closes both halves at once: same teardown as our own
3901
3902
  // reset. Whether the application hears 'aborted' is decided there, by
3902
- // whether the response was still open (lib/stream.js, _destroy). The error it
3903
+ // whether the response was still open (lib/server/Http2ServerStream.js, _destroy). The error it
3903
3904
  // hears is the code's own name, and codes 0 and 8 are not errors at all.
3904
3905
  stream._destroy(code, false, streamErrorOf(code));
3905
3906
  }
@@ -4529,7 +4530,7 @@ class Http2Session extends EventEmitter {
4529
4530
  const [payload, callback] = checkPing(opaque, cb);
4530
4531
  // A falsy payload sends eight zero octets: node lets nghttp2 choose them, and nothing
4531
4532
  // 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).
4533
+ // value (see _pingQ in lib/client/Http2ClientSession.js for the measurement that fixes the rule).
4533
4534
  const body = payload ? Buffer.allocUnsafe(8) : Buffer.alloc(8);
4534
4535
  if (payload) {
4535
4536
  // The only two shapes are a caller's Buffer, which copyInto indexes directly, and any
@@ -4651,7 +4652,7 @@ class Http2Session extends EventEmitter {
4651
4652
  }
4652
4653
  }
4653
4654
 
4654
- module.exports = { Http2Session, OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID,
4655
+ module.exports = { Http2ServerSession, OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID,
4655
4656
  ID_BY_SETTING, MAX_OUT_BATCH, MAX_SESSION_HOLD, STREAM_HOLD_CHARGE, BODY_MIN,
4656
4657
  STAGE_MIN, MAX_SHAPES, MAX_SEND_BLOCK, PRIORITY_SPECLEN,
4657
4658
  strictSingleValueFields, hashBlock, hashPieces, kBoundSession,