h2lean 0.10.2 → 0.11.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.
@@ -116,6 +116,7 @@ const tls = require('node:tls');
116
116
  const f = require('./frames');
117
117
  const { Decoder, Encoder, HPackError, latin1 } = require('./hpack');
118
118
  const FlatList = require('./flat-list');
119
+ const fastTick = require('./fast-tick');
119
120
  // The process-wide inbound decode scratch, same shape and size as the server
120
121
  // session's; the full why-sharing-is-safe argument lives with the server's
121
122
  // instance (lib/session.js). A module-level instance here too, not the server's
@@ -258,6 +259,11 @@ class ClientHttp2Session extends EventEmitter {
258
259
  }
259
260
  socket[kBoundSession] = this;
260
261
  this._socket = socket;
262
+ // Every deferred callback this session schedules runs through ONE route:
263
+ // node's own tick queue (default) or the shared batched pump of
264
+ // lib/fast-tick.js (`batchNextTick: true`) -- see session.js. Streams and
265
+ // anything else derived from the session copy this reference.
266
+ this._tick = fastTick.resolve(opts);
261
267
  // public `socket` returns node's safe Proxy, built lazily; close drops it (see session.js)
262
268
  this._proxySocket = null;
263
269
  this.type = 1; // NGHTTP2_SESSION_CLIENT
@@ -557,7 +563,7 @@ class ClientHttp2Session extends EventEmitter {
557
563
  // event fires. Without the deferral, this pattern misses the event:
558
564
  // const sess = lite.connect(url, { createConnection: () => alreadyOpenSocket });
559
565
  // sess.on('connect', handler); // attached after emit already ran synchronously
560
- process.nextTick(() => {
566
+ this._tick(() => {
561
567
  if (this.destroyed || this._closeEmitted) {
562
568
  return;
563
569
  }
@@ -916,7 +922,7 @@ class ClientHttp2Session extends EventEmitter {
916
922
  // node's requestOnError: destroy the stream with the captured error on the
917
923
  // next tick, and submit nothing. The id reserved above is never used -- the
918
924
  // session is destroyed or past its GOAWAY mark, so no later request takes it.
919
- process.nextTick(() => stream.destroy(requestError));
925
+ this._tick(() => stream.destroy(requestError));
920
926
  } else if (this._started) {
921
927
  this._enqueue(req);
922
928
  } else {
@@ -2077,7 +2083,9 @@ class ClientHttp2Session extends EventEmitter {
2077
2083
  this._frame(RST_STREAM, 0, promisedSid, body, true);
2078
2084
  return;
2079
2085
  }
2080
- const headers = this._toObject(fields, fcount, neverNames(fields, fcount, flags));
2086
+ const pushHeaders = this.listenerCount('stream') === 0
2087
+ ? null
2088
+ : this._toObject(fields, fcount, neverNames(fields, fcount, flags));
2081
2089
  // Create the pushed stream. Its writable half is pre-ended: the client never
2082
2090
  // sends a request body for a push (node: writableEnded=true, writableFinished=true
2083
2091
  // at the 'stream' event, measured v26.12.1).
@@ -2102,8 +2110,9 @@ class ClientHttp2Session extends EventEmitter {
2102
2110
  // flags 4 = NGHTTP2_FLAG_END_HEADERS, the only flag PUSH_PROMISE carries that
2103
2111
  // the JS layer surfaces (measured v26.12.1). Synchronous so the application's
2104
2112
  // 'push' subscription is in place before the response HEADERS arrive in the
2105
- // same read batch.
2106
- this.emit('stream', stream, headers, 4);
2113
+ // same read batch. The promise headers object exists only for that argument,
2114
+ // so with no listener the build above skips -- unobservable either way.
2115
+ this.emit('stream', stream, pushHeaders, 4);
2107
2116
  }
2108
2117
 
2109
2118
  // The shape cache: the server's design, ported. A block whose bytes have been
@@ -2180,6 +2189,11 @@ class ClientHttp2Session extends EventEmitter {
2180
2189
  fields = flat.items;
2181
2190
  fcount = flat.count;
2182
2191
  blockFlags = this._decoder.neverCount > 0 ? this._decoder.neverFlags : null;
2192
+ // The field list the stream holds must outlive this decode: the
2193
+ // scratch's backing array is cleared in place by the next one. The copy
2194
+ // that caches the shape serves the stream too; without a cache entry
2195
+ // the copy is the stream's own.
2196
+ let copy = null;
2183
2197
  if (shapes !== null) {
2184
2198
  if (++this._shapeMisses > 64 && this._shapeHits * 4 < this._shapeMisses) {
2185
2199
  this._shapes = null;
@@ -2187,15 +2201,17 @@ class ClientHttp2Session extends EventEmitter {
2187
2201
  if (shapes.size >= MAX_SHAPES) {
2188
2202
  shapes.clear();
2189
2203
  }
2204
+ copy = fields.slice(0, fcount);
2190
2205
  shapes.set(slot, {
2191
2206
  block: block !== null ? Buffer.from(block) : pieceConcat(pieces, from, to),
2192
- flat: fields.slice(0, fcount),
2207
+ flat: copy,
2193
2208
  // a snapshot copy, not the decoder's live array: the next decode
2194
2209
  // clears the array in place, and this entry must survive it
2195
2210
  flags: blockFlags !== null ? blockFlags.slice() : null
2196
2211
  });
2197
2212
  }
2198
2213
  }
2214
+ fields = copy !== null ? copy : fields.slice(0, fcount);
2199
2215
  }
2200
2216
  } catch (err) {
2201
2217
  if (err instanceof HPackError) {
@@ -2230,7 +2246,20 @@ class ClientHttp2Session extends EventEmitter {
2230
2246
  if (this._refuseHeaders(sid, stream, fields, fcount)) {
2231
2247
  return;
2232
2248
  }
2233
- const headers = this._toObject(fields, fcount, neverNames(fields, fcount, blockFlags));
2249
+ const sensitive = neverNames(fields, fcount, blockFlags);
2250
+ // The response object is not built here: the stream builds it at the first
2251
+ // read (lib/client-stream.js _onHeaders), so a client that only consumes
2252
+ // the body pays no per-response object at all -- the paired marginal is in
2253
+ // OPTIMIZATION.md item 48. This block still needs :status, read off the
2254
+ // same field list _refuseHeaders has just vouched for: exactly one on a
2255
+ // response, none on a trailer.
2256
+ let status;
2257
+ for (let i = 0; i < fcount; i += 2) {
2258
+ if (fields[i] === ':status') {
2259
+ status = fields[i + 1] | 0;
2260
+ break;
2261
+ }
2262
+ }
2234
2263
  // RFC 8336 3.2 + core.js emitStreamEvent: a 421 (Misdirected Request) answer
2235
2264
  // deletes the origin the request carried from originSet, and it does so here --
2236
2265
  // before 'response' is scheduled, so a handler that reads `session.originSet`
@@ -2238,12 +2267,11 @@ class ClientHttp2Session extends EventEmitter {
2238
2267
  // its lazy-seed side effect exactly as node's `session[kState].originSet =
2239
2268
  // initOriginSet(session)` assignment does: on the first 421 of a session the set
2240
2269
  // is created from the socket before the delete, and over h2c both stacks leave
2241
- // the set unobservable (the getter is encrypted-gated). `:status` is a number by
2242
- // now, so the comparison is node's numeric `status === 421`.
2243
- if (headers[':status'] === 421) {
2270
+ // the set unobservable (the getter is encrypted-gated).
2271
+ if (status === 421) {
2244
2272
  this._initOriginSet().delete(stream._origin);
2245
2273
  }
2246
- stream._onHeaders(headers, end, flags);
2274
+ stream._onHeaders(status, fields, fcount, sensitive, end, flags);
2247
2275
  if (end) {
2248
2276
  this._dropStream(sid);
2249
2277
  }
@@ -2743,7 +2771,7 @@ class ClientHttp2Session extends EventEmitter {
2743
2771
  this._maybeClose();
2744
2772
  if (typeof cb === 'function') {
2745
2773
  if (this._streams.size === 0) {
2746
- process.nextTick(cb);
2774
+ this._tick(cb);
2747
2775
  } else {
2748
2776
  this.once('close', cb);
2749
2777
  }
@@ -2926,7 +2954,7 @@ class ClientHttp2Session extends EventEmitter {
2926
2954
  socket.destroy();
2927
2955
  }
2928
2956
  }
2929
- process.nextTick(() => {
2957
+ this._tick(() => {
2930
2958
  if (!this._closeEmitted) {
2931
2959
  this._emitClose(err);
2932
2960
  }
@@ -38,15 +38,23 @@ class AbortError extends Error {
38
38
  }
39
39
  }
40
40
 
41
- // `sentHeaders`/`sentTrailers`/`responseHeaders` and the state flags node exposes
42
- // through symbols are kept as plain fields here; they are not part of the
43
- // documented client surface an application is expected to touch, and pinning them
44
- // to node's symbol identity is an M2 compatibility decision, not a round-trip one.
41
+ // `sentHeaders`/`sentTrailers` and the state flags node exposes through symbols
42
+ // are kept as plain fields here; they are not part of the documented client
43
+ // surface an application is expected to touch, and pinning them to node's symbol
44
+ // identity is an M2 compatibility decision, not a round-trip one. The inbound
45
+ // response/trailer objects node does not keep on the stream at all (they pass
46
+ // through the events only, core.js emitStreamEvent) are prototype getters over
47
+ // the unbuilt field list: the object comes into being at the first read, which
48
+ // is what keeps a body-only client free of per-response allocations
49
+ // (OPTIMIZATION.md item 48).
45
50
  class ClientHttp2Stream extends Duplex {
46
51
  constructor(session, id, _opts) {
47
52
  super({ allowHalfOpen: true, decodeStrings: false });
48
53
  this.id = id;
49
54
  this.session = session;
55
+ // The session's one tick route -- node's queue or the batched pump of
56
+ // lib/fast-tick.js; see stream.js.
57
+ this._tick = session._tick;
50
58
  // Per-stream flow-control state; the connection window lives on the session.
51
59
  // Both start at the peer's advertised initial window (65535 until its SETTINGS
52
60
  // land) exactly as the server side does. The value written here is the
@@ -107,7 +115,17 @@ class ClientHttp2Stream extends Duplex {
107
115
  // measured v26.12.1).
108
116
  this._pushed = false;
109
117
  this.additionalHeaders = [];
110
- this.trailers = null;
118
+ // The response and trailer objects are built at the first read, not when
119
+ // the block arrives -- the getters below. The slots start undefined so the
120
+ // object shape is stable from construction.
121
+ this._respFields = undefined;
122
+ this._respFcount = 0;
123
+ this._respSensitive = undefined;
124
+ this._responseObject = undefined;
125
+ this._trailerFields = undefined;
126
+ this._trailerFcount = 0;
127
+ this._trailerSensitive = undefined;
128
+ this._trailersObject = undefined;
111
129
  // Set by session.request() when the application passed waitForTrailers: the last
112
130
  // DATA on the wire does not carry END_STREAM; instead 'wantTrailers' fires and
113
131
  // the app is expected to call sendTrailers() (or close()) to finish the message.
@@ -144,6 +162,43 @@ class ClientHttp2Stream extends Duplex {
144
162
  return this._sentView;
145
163
  }
146
164
 
165
+ // node's client keeps no response object on the stream at all -- core.js
166
+ // emitStreamEvent passes the objects through the events only -- so these two
167
+ // are prototype getters over the raw field list: the object comes into being
168
+ // at the first read (an event argument when a listener exists, or the getter),
169
+ // and one build serves every later read. A body-only client pays no
170
+ // per-response object (OPTIMIZATION.md item 48). Object.keys(stream) lists
171
+ // neither, which is closer to node than the plain fields this replaces were.
172
+ get responseHeaders() {
173
+ if (this._responseObject !== undefined) {
174
+ return this._responseObject;
175
+ }
176
+ const fields = this._respFields;
177
+ if (fields === undefined) {
178
+ return undefined;
179
+ }
180
+ const o = this.session._toObject(fields, this._respFcount, this._respSensitive);
181
+ this._respFields = undefined;
182
+ this._respSensitive = undefined;
183
+ this._responseObject = o;
184
+ return o;
185
+ }
186
+
187
+ get trailers() {
188
+ if (this._trailersObject !== undefined) {
189
+ return this._trailersObject;
190
+ }
191
+ const fields = this._trailerFields;
192
+ if (fields === undefined) {
193
+ return null;
194
+ }
195
+ const o = this.session._toObject(fields, this._trailerFcount, this._trailerSensitive);
196
+ this._trailerFields = undefined;
197
+ this._trailerSensitive = undefined;
198
+ this._trailersObject = o;
199
+ return o;
200
+ }
201
+
147
202
  // ---- writable side ----------------------------------------------------------
148
203
  // The application's bytes go to the session, which frames them as DATA inside
149
204
  // the two windows. If there is no credit, `_pump` leaves `_pending` set and the
@@ -181,15 +236,19 @@ class ClientHttp2Stream extends Duplex {
181
236
  _read() {}
182
237
 
183
238
  // The session decoded a response (or informational / trailer) block for us.
184
- // `headers` is a null-prototype object with `:status` coerced to a number and
185
- // `set-cookie` as an array, built the way the server's `_toObject` builds a
186
- // request, so both stacks hand the application the same shape.
187
- _onHeaders(headers, end, flags) {
188
- const status = headers[':status'];
239
+ // The field list arrives unbuilt: the null-prototype object with `:status`
240
+ // coerced to a number and `set-cookie` as an array is what the session's
241
+ // _toObject builds, and it is built here at the first read -- an event
242
+ // argument when a listener exists, or the responseHeaders/trailers getter.
243
+ // A body-only client (no 'response' subscription, no getter read) pays no
244
+ // per-response object at all; the paired marginal is OPTIMIZATION.md item 48.
245
+ _onHeaders(status, fields, fcount, sensitive, end, flags) {
189
246
  if (status !== undefined && status >= 100 && status < 200 && !this.responseEmitted) {
190
247
  // 1xx informational (including the 100 Continue that node surfaces as
191
- // 'continue'): emit 'headers', keep waiting for the final response. The
192
- // 100-Continue translation node does is a 'headers' whose :status is 100.
248
+ // 'continue'): built eagerly -- the blocks are rare and the one object
249
+ // feeds the two events and the additionalHeaders field. The 100-Continue
250
+ // translation node does is a 'headers' whose :status is 100.
251
+ const headers = this.session._toObject(fields, fcount, sensitive);
193
252
  this.additionalHeaders.push(headers);
194
253
  // node's inbound emit carries the frame flags as the second argument
195
254
  // (`emit(stream, event, obj, flags, headers)`, internal/http2/core.js), which is
@@ -200,17 +259,26 @@ class ClientHttp2Stream extends Duplex {
200
259
  }
201
260
  } else if (!this.responseEmitted) {
202
261
  this.responseEmitted = true;
203
- this.responseHeaders = headers;
204
262
  this.sentStatus = status;
263
+ this._respFields = fields;
264
+ this._respFcount = fcount;
265
+ this._respSensitive = sensitive;
205
266
  // node passes the raw HEADERS frame flags as the second argument and a
206
267
  // rawHeaders array as the third (core.js: emit(stream, event, obj, flags,
207
268
  // headers)); the rawHeaders array is deliberately not built -- one flat
208
269
  // array per response is a cost no h2lean consumer has asked for.
209
- this.emit(this._pushed ? 'push' : 'response', headers, flags);
270
+ const event = this._pushed ? 'push' : 'response';
271
+ if (this.listenerCount(event) > 0) {
272
+ this.emit(event, this.responseHeaders, flags);
273
+ }
210
274
  } else {
211
275
  // A second final-status block after the response is the trailer block.
212
- this.trailers = headers;
213
- this.emit('trailers', headers);
276
+ this._trailerFields = fields;
277
+ this._trailerFcount = fcount;
278
+ this._trailerSensitive = sensitive;
279
+ if (this.listenerCount('trailers') > 0) {
280
+ this.emit('trailers', this.trailers);
281
+ }
214
282
  }
215
283
  if (end) {
216
284
  this._endRead();
package/lib/compat.js CHANGED
@@ -53,7 +53,7 @@
53
53
  'use strict';
54
54
 
55
55
  const { Readable, Stream } = require('node:stream');
56
- const { emitNT } = require('./stream');
56
+
57
57
  const { nullProto, trimName } = require('./headers');
58
58
 
59
59
  function err(code, msg) {
@@ -201,13 +201,17 @@ function onRequestClose() {
201
201
  // 'close' after 'end', so queue it behind the end the push above scheduled.
202
202
  // node emits it right here instead, so the two stacks differ in the order of
203
203
  // these two: see the difference list at the top of this file.
204
- process.nextTick(emitCloseNT, req);
204
+ req._tick(emitCloseNT, req);
205
205
  }
206
206
 
207
207
  function emitCloseNT(target) {
208
208
  target.emit('close');
209
209
  }
210
210
 
211
+ function emitFinishNT(target) {
212
+ target.emit('finish');
213
+ }
214
+
211
215
  function onRequestTimeout() {
212
216
  const req = this._request;
213
217
  if (req !== undefined && !req._closed) {
@@ -256,6 +260,9 @@ class Http2ServerRequest extends Readable {
256
260
  constructor(stream, headers, rawHeaders) {
257
261
  super({ autoDestroy: false });
258
262
  this._stream = stream;
263
+ // The stream's one tick route -- node's queue or the batched pump of
264
+ // lib/fast-tick.js; the deferred callbacks of the compat layer go through it.
265
+ this._tick = stream._tick;
259
266
  this._headers = headers;
260
267
  this._rawHeaders = rawHeaders === null ? [] : rawHeaders;
261
268
  this._trailers = { __proto__: null };
@@ -446,6 +453,9 @@ function onResponseTimeout() {
446
453
  class Http2ServerResponse extends Stream {
447
454
  constructor(stream) {
448
455
  super();
456
+ // The stream's one tick route -- node's queue or the batched pump of
457
+ // lib/fast-tick.js; the deferred callbacks of the compat layer go through it.
458
+ this._tick = stream._tick;
449
459
  this._state = {
450
460
  closed: false,
451
461
  ending: false,
@@ -758,14 +768,14 @@ class Http2ServerResponse extends Stream {
758
768
  }
759
769
  if (failure) {
760
770
  if (typeof cb === 'function') {
761
- process.nextTick(cb, failure);
771
+ this._tick(cb, failure);
762
772
  }
763
773
  this.destroy(failure);
764
774
  return false;
765
775
  }
766
776
  if (state.headRequest) {
767
777
  if (typeof cb === 'function') {
768
- process.nextTick(cb);
778
+ this._tick(cb);
769
779
  }
770
780
  return true; // a HEAD response has no body
771
781
  }
@@ -786,7 +796,7 @@ class Http2ServerResponse extends Stream {
786
796
 
787
797
  if (state.closed || state.ending) {
788
798
  if (typeof cb === 'function') {
789
- process.nextTick(cb);
799
+ this._tick(cb);
790
800
  }
791
801
  return this;
792
802
  }
@@ -807,7 +817,7 @@ class Http2ServerResponse extends Stream {
807
817
  }
808
818
  if (!state.closed && !state.finishEmitted) {
809
819
  state.finishEmitted = true;
810
- process.nextTick(emitNT, this, 'finish');
820
+ this._tick(emitFinishNT, this);
811
821
  }
812
822
 
813
823
  // node's compat end() ends the stream and does nothing else
@@ -892,7 +902,7 @@ class Http2ServerResponse extends Stream {
892
902
  throw e;
893
903
  }
894
904
  if (this._state.closed) {
895
- process.nextTick(callback, err('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed'));
905
+ this._tick(callback, err('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed'));
896
906
  return;
897
907
  }
898
908
  this._stream.pushStream(headers, {}, (e, stream) => {
@@ -0,0 +1,192 @@
1
+ 'use strict';
2
+
3
+ // A batched replacement for process.nextTick, built like lib/fast-timer.js is
4
+ // built: one module, one class, one pump shared by every session in the
5
+ // process, and the callback order as the contract. The module exports a
6
+ // process-wide instance plus the class itself, so the pump can be lifted into
7
+ // a standalone module by moving the file; sessions never construct their own,
8
+ // because per-instance pumps would put a tick entry back on every server --
9
+ // the cost this exists to remove. The application opts in per server or
10
+ // client with `batchNextTick: true` (default false = node's own
11
+ // process.nextTick); H2LEAN_BATCH_TICKS=1 turns it on wherever the option is
12
+ // left undefined, so the whole suite can run under the pump and pin its event
13
+ // orders.
14
+ //
15
+ // What it changes: instead of one tick-queue entry per callback, callbacks
16
+ // land in a flat array and ONE real nextTick -- the pump -- drains them, so a
17
+ // busy server pays the scheduler entry once per event-loop turn instead of
18
+ // once per request. bench/micro/tick-cost.js prices the entry at ~0.1 us
19
+ // isolated while the server-measured marginal of one merged tick is
20
+ // 0.03-0.05 us (OPTIMIZATION.md item 46, the pump's paired numbers in item
21
+ // 47), which is why this removes ALL of a session's entries rather than
22
+ // merging two. The queues are cursor-filled preallocated stores that reset
23
+ // instead of right-trimming (`length = 0` makes the next fill re-grow the
24
+ // store from scratch on V8, item 38) -- bench/micro/tick-queue-shape.js puts
25
+ // the trimmed shape at 27 ns/schedule against 12 for the cursor store at the
26
+ // 2-entries-per-turn size a quiet connection produces, and shows the class
27
+ // method layer costing nothing over the flat cursor. The scheduler itself is
28
+ // a constructor closure rather than a bound method -- the reason is at the
29
+ // closure. The literal FlatList API
30
+ // (one push() per item) measured slower than the pair write, and its
31
+ // setImmediate shrink would rebuild a store that can already hold the next
32
+ // generation's entries -- so the technique is re-implemented here with a
33
+ // release-when-idle rule (an oversized store is replaced only after its
34
+ // generation has drained), not by requiring lib/flat-list.js.
35
+ //
36
+ // What it keeps: FIFO order exactly as node's single queue gives it --
37
+ // including callbacks scheduled while the pump drains, which land in the next
38
+ // generation (the double buffer below). That reproduces node's tail-of-the-
39
+ // queue semantics for everything h2lean schedules, which is why the suite
40
+ // passes with the pump on: test/event-order.test.js and the teardown traces
41
+ // pin the orders this depends on.
42
+ //
43
+ // What it cannot keep, and the option documents: node's ONE queue interleaves
44
+ // foreign ticks -- an application's own process.nextTick called from inside
45
+ // an event handler -- with ours in schedule order, while a pump generation
46
+ // runs as one queue entry, so such a foreign tick can observe a different
47
+ // position between two of our callbacks. And async-context propagation: a
48
+ // callback runs in the pump's context, not in the context that was current
49
+ // when it was scheduled, so an application reading AsyncLocalStorage inside
50
+ // a deferred 'finish' handler needs the default mode.
51
+ //
52
+ // The callback shape is (fn, arg), the shape every h2lean site schedules
53
+ // through: one argument, no per-callback closure or argument array, which is
54
+ // the allocation the entry price is made of. A site that needs more
55
+ // arguments -- the pushStream callback, the error paths -- wraps them in a
56
+ // closure at that site, the way the rare paths always have. A variadic
57
+ // schedule(callback, ...args) would allocate an args array per call and give
58
+ // back what the pump removes.
59
+ //
60
+ // On an exception inside the pump, the throwing pair is dropped and the
61
+ // callbacks after it are carried into the next generation -- ahead of
62
+ // whatever the aborted drain scheduled there, the order node's tail-of-the-
63
+ // queue semantics give them. Measured on a live node: an exception escaping a
64
+ // tick aborts that turn's drain -- the ticks behind it stay in the queue and
65
+ // run at the next tick phase only if the event loop gets there (a pending
66
+ // tick queue alone does not start a turn, and without an uncaughtException
67
+ // handler the process dies), so the pump reproduces exactly that shape.
68
+ //
69
+ // const fastTick = require('./fast-tick');
70
+ // this._tick = fastTick.resolve(opts); // schedule | process.nextTick
71
+ // this._tick(fn, arg); // (fn, arg) shape, like nextTick
72
+
73
+ // Read at resolve() time, not at module load, so a process can turn the mode
74
+ // on after the library is required (the suite gate runs the whole tree under
75
+ // the pump this way). One env getter per session construction, never per tick.
76
+ function envForced() {
77
+ return process.env.H2LEAN_BATCH_TICKS === '1';
78
+ }
79
+
80
+ class FastTick {
81
+ // 64 slots = 32 pairs per generation before the store grows; at saturation
82
+ // the generations reach a few dozen entries, at low load they hold one or
83
+ // two -- the microbench's losing size, which is exactly what the cursor
84
+ // store fixes.
85
+ constructor(capacity) {
86
+ this.capacity = capacity;
87
+ this.ready = new Array(capacity); // [fn, arg, fn, arg, ...] up to readyCount
88
+ this.readyCount = 0;
89
+ this.idle = new Array(capacity); // the drained store, empty between turns
90
+ this.scheduled = false; // a pump entry exists in the real tick queue
91
+ // The reference the sessions hold: one closure per process, never per
92
+ // schedule. Sessions must not mix routes -- a pump generation reordering
93
+ // against its own native entries is the incoherence resolve() exists to
94
+ // prevent -- so the resolved reference is copied through streams and the
95
+ // compat objects unchanged. A closure rather than a bound method: one
96
+ // call frame instead of two, and a raw call-shape probe prices the bound
97
+ // wrapper at ~7 ns against ~5 for the closure. Paired rounds of this tree
98
+ // against the shipped flat pump, both under the pump, put the whole
99
+ // conversion within noise on all three server arms -- the shape claim is
100
+ // the probe's, not the server's.
101
+ this.schedule = (fn, arg) => {
102
+ const c = this.readyCount;
103
+ if (c + 2 > this.ready.length) {
104
+ this._grow(c);
105
+ }
106
+ const store = this.ready;
107
+ store[c] = fn;
108
+ store[c + 1] = arg;
109
+ this.readyCount = c + 2;
110
+ if (!this.scheduled) {
111
+ this.scheduled = true;
112
+ process.nextTick(this._pumpBound);
113
+ }
114
+ };
115
+ this._pumpBound = this.pump.bind(this);
116
+ }
117
+
118
+ _grow(count) {
119
+ // Rare: a generation larger than the preallocation. The store is replaced
120
+ // under the caller with the live entries carried over; the oversized size
121
+ // is given back when the store finishes draining (see pump's finally).
122
+ const old = this.ready;
123
+ const bigger = new Array(old.length * 2);
124
+ for (let i = 0; i < count; i++) {
125
+ bigger[i] = old[i];
126
+ }
127
+ this.ready = bigger;
128
+ }
129
+
130
+ pump() {
131
+ this.scheduled = false;
132
+ const items = this.ready;
133
+ const count = this.readyCount;
134
+ // Re-entrant schedules during the drain push into `this.ready` -- the
135
+ // next generation -- and queue the next pump, which is node's
136
+ // tail-of-the-queue semantics: a callback scheduled while tick A runs
137
+ // executes after the ticks that were queued before A did.
138
+ this.ready = this.idle;
139
+ this.readyCount = 0;
140
+ this.idle = items;
141
+ let i = 0;
142
+ try {
143
+ while (i < count) {
144
+ items[i](items[i + 1]);
145
+ i += 2;
146
+ }
147
+ } catch (err) {
148
+ // The ticks behind the throwing one stay queued on node too -- the
149
+ // drain aborts, the leftovers run at the next tick phase, if the loop
150
+ // gets there. Carry ours to the FRONT of the next generation, ahead of
151
+ // whatever the aborted drain scheduled there, and make sure a pump is
152
+ // queued. The failed pair is gone the way node's throwing tick is gone
153
+ // -- carrying it too re-runs the thrower at the head of every later
154
+ // generation and starves the survivors.
155
+ const rest = count - (i + 2);
156
+ if (rest > 0) {
157
+ const ahead = this.readyCount;
158
+ if (ahead > 0) {
159
+ this.ready.copyWithin(rest, 0, ahead);
160
+ }
161
+ for (let k = 0; k < rest; k++) {
162
+ this.ready[k] = items[i + 2 + k];
163
+ }
164
+ this.readyCount = ahead + rest;
165
+ }
166
+ if (!this.scheduled && this.readyCount !== 0) {
167
+ this.scheduled = true;
168
+ process.nextTick(this._pumpBound);
169
+ }
170
+ throw err;
171
+ } finally {
172
+ // The drained store is idle: empty in the cursor sense (readyCount of
173
+ // the other store is 0), and if one generation grew it past the
174
+ // preallocation, the size is released now -- the same
175
+ // one-oversized-generation-does-not-pin-it rule FlatList applies to
176
+ // header blocks (lib/flat-list.js), at the point where the store is
177
+ // provably empty.
178
+ if (items.length > this.capacity) {
179
+ this.idle = new Array(this.capacity);
180
+ }
181
+ }
182
+ }
183
+
184
+ resolve(opts) {
185
+ return ((opts && opts.batchNextTick) ?? envForced()) ? this.schedule : process.nextTick;
186
+ }
187
+ }
188
+
189
+ // One pump for the whole process; the class is exported beside it so the
190
+ // module can be lifted out as-is.
191
+ module.exports = new FastTick(64);
192
+ module.exports.FastTick = FastTick;
package/lib/server.js CHANGED
@@ -15,6 +15,15 @@
15
15
  // keep-alive policy it served is session.setTimeout() plus
16
16
  // the application destroying the session, which both stacks
17
17
  // do implement. Harmless to keep, surprising to drop.
18
+ // * batchNextTick (createServer and createSecureServer; connect takes it too) is
19
+ // additive: with true, every deferred callback the session schedules runs through the
20
+ // shared pump of lib/fast-tick.js -- one real process.nextTick per event-loop turn
21
+ // instead of one per callback (OPTIMIZATION.md item 47: the stream arm -3.8%, the
22
+ // compat arm no measurable gain at saturation, which is why the default is node's own
23
+ // tick). The two behaviours the pump cannot reproduce -- a foreign tick's position
24
+ // between two of ours, and async-context propagation into the deferred callbacks --
25
+ // are in the fast-tick.js header; H2LEAN_BATCH_TICKS=1 fills in for an undefined
26
+ // option, so the suite pins the event orders with the pump on as well.
18
27
  // * what this server advertises on the wire matches node: the first SETTINGS frame carries only
19
28
  // the values the application asked for -- an EMPTY payload when it asked for nothing -- and a
20
29
  // later server.updateSettings() reaches the NEXT connection, not the live sessions. The local
@@ -107,6 +116,10 @@ function initHttp2Server(server, options) {
107
116
  // (internal/http2/util.js) takes it on a `typeof === 'number'` test alone -- so it rides
108
117
  // through raw and the session constructor applies the same test and the same coercion.
109
118
  maxSendHeaderBlockLength: opts.maxSendHeaderBlockLength,
119
+ // Rides through raw: the session resolves undefined (the default, node's own
120
+ // process.nextTick), true (the shared batched pump of lib/fast-tick.js) and
121
+ // explicit false alike, and H2LEAN_BATCH_TICKS=1 fills in for undefined only.
122
+ batchNextTick: opts.batchNextTick,
110
123
  // The server `origins` option: each session sends one ORIGIN frame with these origins at
111
124
  // connect. node only does it when the value is an array (core.js setupHandle), so it rides
112
125
  // through unvalidated and Http2Session._start applies the same Array.isArray test.
package/lib/session.js CHANGED
@@ -22,8 +22,9 @@ const { EventEmitter } = require('node:events');
22
22
  const tls = require('node:tls');
23
23
  const f = require('./frames');
24
24
  const { Decoder, Encoder, HPackError, latin1, latin1Into } = require('./hpack');
25
- const { Http2Stream, errorOf, streamErrorOf, emitNT } = require('./stream');
25
+ const { Http2Stream, errorOf, streamErrorOf, emitCloseNT, emitDrainNT } = require('./stream');
26
26
  const FlatList = require('./flat-list');
27
+ const fastTick = require('./fast-tick');
27
28
  // The process-wide inbound decode scratch: one list per module instance, shared by
28
29
  // every session it serves, instead of one array per live session. Why sharing is
29
30
  // safe: a header block's fill and its consumption are synchronous -- they happen
@@ -659,6 +660,12 @@ class Http2Session extends EventEmitter {
659
660
  }
660
661
  socket[kBoundSession] = this;
661
662
  this._socket = socket;
663
+ // Every deferred callback this session schedules runs through ONE route:
664
+ // node's own tick queue (default) or the shared batched pump of
665
+ // lib/fast-tick.js (`batchNextTick: true`). Mixing routes inside one
666
+ // session would let a pump generation reorder against its own native
667
+ // entries, so streams and the compat objects copy this reference.
668
+ this._tick = fastTick.resolve(opts);
662
669
  // The public `socket` accessor builds node's safe Proxy lazily and caches it here;
663
670
  // close sets it to undefined so `session.socket` reads gone afterwards, as node does.
664
671
  this._proxySocket = null;
@@ -946,7 +953,7 @@ class Http2Session extends EventEmitter {
946
953
  // do the same, then subscribe. 'connect' was queued by _start ahead of this drain, so
947
954
  // it fires first. An accepted createServer socket has nothing buffered here and takes
948
955
  // the synchronous subscription below, the read path this file always had.
949
- process.nextTick(() => {
956
+ this._tick(() => {
950
957
  if (this.destroyed) {
951
958
  return;
952
959
  }
@@ -976,7 +983,7 @@ class Http2Session extends EventEmitter {
976
983
  // (setupHandle's destroyed branch), so the handlers at least run and clear out.
977
984
  if (!this._connectEmitted) {
978
985
  this._connectEmitted = true;
979
- process.nextTick(() => this.emit('connect', this, this._socket));
986
+ this._tick(() => this.emit('connect', this, this._socket));
980
987
  }
981
988
  return;
982
989
  }
@@ -998,7 +1005,7 @@ class Http2Session extends EventEmitter {
998
1005
  this.origin(...this._origins);
999
1006
  }
1000
1007
  this._connectEmitted = true;
1001
- process.nextTick(() => this.emit('connect', this, this._socket));
1008
+ this._tick(() => this.emit('connect', this, this._socket));
1002
1009
  }
1003
1010
 
1004
1011
  // ---- outbound queue --------------------------------------------------------
@@ -3065,7 +3072,7 @@ class Http2Session extends EventEmitter {
3065
3072
  }
3066
3073
  // the writable side accepted bytes again: res.on('drain') is how an
3067
3074
  // application is allowed to resume writing after write() returned false
3068
- process.nextTick(emitNT, stream, 'drain');
3075
+ stream._tick(emitDrainNT, stream);
3069
3076
  if (stream._endQueued) {
3070
3077
  stream._endLocalSide();
3071
3078
  }
@@ -3291,7 +3298,7 @@ class Http2Session extends EventEmitter {
3291
3298
  // any of the five (out/probe-frameerror.js). This used to emit one on the session with
3292
3299
  // the id and the code swapped and DATA hardcoded as the type; the outbound sites
3293
3300
  // (_refuseSend, the PUSH_PROMISE bound) are the ones that match node's event.
3294
- process.nextTick(emitNT, stream, 'error', errorOf('ERR_HTTP2_STREAM_ERROR', msg));
3301
+ stream._tick(() => stream.emit('error', errorOf('ERR_HTTP2_STREAM_ERROR', msg)));
3295
3302
  }
3296
3303
 
3297
3304
  _fatal(code, msg) {
@@ -3497,7 +3504,7 @@ class Http2Session extends EventEmitter {
3497
3504
  // finishSessionClose() afterwards, which is the order the application sees: stream 'error',
3498
3505
  // stream 'close', session 'error', session 'close'.
3499
3506
  if (appError !== undefined) {
3500
- process.nextTick(emitNT, this, 'error', appError);
3507
+ this._tick(() => this.emit('error', appError));
3501
3508
  }
3502
3509
  return this;
3503
3510
  }
@@ -3517,7 +3524,7 @@ class Http2Session extends EventEmitter {
3517
3524
  return;
3518
3525
  }
3519
3526
  this._closeEmitted = true;
3520
- process.nextTick(emitNT, this, 'close');
3527
+ this._tick(emitCloseNT, this);
3521
3528
  }
3522
3529
 
3523
3530
  _onSocketError(err) {
@@ -3623,7 +3630,7 @@ class Http2Session extends EventEmitter {
3623
3630
  }
3624
3631
  this._sendSettings();
3625
3632
  if (cb) {
3626
- process.nextTick(cb);
3633
+ this._tick(cb);
3627
3634
  }
3628
3635
  }
3629
3636
 
package/lib/stream.js CHANGED
@@ -120,6 +120,18 @@ function emitNT(target, name, arg) {
120
120
  }
121
121
  }
122
122
 
123
+ // One-arg emitters for the per-request deliveries: the batched tick route of
124
+ // lib/fast-tick.js carries (fn, arg) pairs, so these replace the
125
+ // `emitNT(target, 'close' | 'drain')` calls the hot paths used, without
126
+ // paying a closure per event (the reason emitNT exists, item 41).
127
+ function emitCloseNT(target) {
128
+ target.emit('close');
129
+ }
130
+
131
+ function emitDrainNT(target) {
132
+ target.emit('drain');
133
+ }
134
+
123
135
  function emitErrorCloseNT(target, err) {
124
136
  target._errorEmitted = true;
125
137
  target._streamErrored = err;
@@ -236,7 +248,7 @@ function autoCloseNT(stream) {
236
248
  if (stream._destroyed) {
237
249
  return;
238
250
  }
239
- process.nextTick(emitEndNT, stream);
251
+ stream._tick(emitEndNT, stream);
240
252
  stream._destroy(NO_ERROR, undefined, true);
241
253
  }
242
254
 
@@ -382,6 +394,9 @@ class Http2Stream extends Stream {
382
394
  super();
383
395
  this.id = id;
384
396
  this.session = session;
397
+ // The session's one tick route -- node's queue or the batched pump of
398
+ // lib/fast-tick.js; every deferred callback of this stream goes through it.
399
+ this._tick = session._tick;
385
400
  this.rstCode = 0;
386
401
  // What respond() put on the wire, for the `sentHeaders` getter below: the caller's map
387
402
  // plus the two values the encoder resolved. node keeps the same three pieces
@@ -1034,7 +1049,7 @@ class Http2Stream extends Stream {
1034
1049
  // test/upstream-push.test.js, session-destroy).
1035
1050
  const err = errorOf('ERR_STREAM_WRITE_AFTER_END', 'write after end');
1036
1051
  if (cb) {
1037
- process.nextTick(cb, err);
1052
+ this._tick(cb, err);
1038
1053
  }
1039
1054
  if (!this._destroyed) {
1040
1055
  this.destroy(err);
@@ -1046,7 +1061,7 @@ class Http2Stream extends Stream {
1046
1061
  // the event is owed here instead. A reset or a session destroy is not
1047
1062
  // this shape -- there node's errorOrDestroy is a no-op and no 'error'
1048
1063
  // goes out (the session-destroy case of test/upstream-push.test.js).
1049
- process.nextTick(emitErrorOnlyNT, this, err);
1064
+ this._tick(() => emitErrorOnlyNT(this, err));
1050
1065
  }
1051
1066
  return false;
1052
1067
  }
@@ -1060,7 +1075,7 @@ class Http2Stream extends Stream {
1060
1075
  // session's drain path). It reports the credit stall, nothing else.
1061
1076
  this._needDrain = !canContinue;
1062
1077
  if (cb) {
1063
- process.nextTick(cb);
1078
+ this._tick(cb);
1064
1079
  }
1065
1080
  return canContinue;
1066
1081
  }
@@ -1083,7 +1098,7 @@ class Http2Stream extends Stream {
1083
1098
  // _pumpEnd() for exactly that reason; write() after end IS the error -- see
1084
1099
  // write() above.
1085
1100
  if (cb) {
1086
- process.nextTick(cb);
1101
+ this._tick(cb);
1087
1102
  }
1088
1103
  return this;
1089
1104
  }
@@ -1102,7 +1117,7 @@ class Http2Stream extends Stream {
1102
1117
  // the auto-respond above already carried END_STREAM (a HEAD request):
1103
1118
  // there is no body to send, RFC 9113 8.1 forbids one on a HEAD answer
1104
1119
  if (cb) {
1105
- process.nextTick(cb);
1120
+ this._tick(cb);
1106
1121
  }
1107
1122
  return this;
1108
1123
  }
@@ -1120,7 +1135,7 @@ class Http2Stream extends Stream {
1120
1135
  this._endLocalSide();
1121
1136
  }
1122
1137
  if (cb) {
1123
- process.nextTick(cb);
1138
+ this._tick(cb);
1124
1139
  }
1125
1140
  return this;
1126
1141
  }
@@ -1405,7 +1420,7 @@ class Http2Stream extends Stream {
1405
1420
  try {
1406
1421
  promisedId = this.session._allocPushSid();
1407
1422
  } catch (err) {
1408
- process.nextTick(callback, err);
1423
+ this._tick(callback, err);
1409
1424
  return;
1410
1425
  }
1411
1426
 
@@ -1445,7 +1460,7 @@ class Http2Stream extends Stream {
1445
1460
  // what keeps that shape; respond() reads _endQueued, write() refuses it.
1446
1461
  stream._endQueued = true;
1447
1462
  }
1448
- process.nextTick(callback, null, stream, h, 0);
1463
+ this._tick(() => callback(null, stream, h, 0));
1449
1464
  }
1450
1465
 
1451
1466
  // Readable-side control, node's contract: while paused no credit is released,
@@ -1474,7 +1489,7 @@ class Http2Stream extends Stream {
1474
1489
  return;
1475
1490
  }
1476
1491
  this._resumeScheduled = true;
1477
- process.nextTick(() => {
1492
+ this._tick(() => {
1478
1493
  this._resumeScheduled = false;
1479
1494
  if (this._destroyed || this._flowing === false) {
1480
1495
  return;
@@ -1893,7 +1908,7 @@ class Http2Stream extends Stream {
1893
1908
  dest !== process.stdout && dest !== process.stderr;
1894
1909
  const endFn = doEnd ? onend : unpipe;
1895
1910
  if (src._eofEmitted === true) {
1896
- process.nextTick(endFn);
1911
+ src._tick(endFn);
1897
1912
  } else {
1898
1913
  src.once('end', endFn);
1899
1914
  }
@@ -2294,7 +2309,7 @@ class Http2Stream extends Stream {
2294
2309
  return;
2295
2310
  }
2296
2311
  this._readableScheduled = true;
2297
- process.nextTick(() => {
2312
+ this._tick(() => {
2298
2313
  this._readableScheduled = false;
2299
2314
  if (this._destroyed || this._flowing === true ||
2300
2315
  this.listenerCount('readable') === 0) {
@@ -2316,7 +2331,7 @@ class Http2Stream extends Stream {
2316
2331
  return;
2317
2332
  }
2318
2333
  this._eofScheduled = true;
2319
- process.nextTick(() => {
2334
+ this._tick(() => {
2320
2335
  this._eofScheduled = false;
2321
2336
  if (this._destroyed || this._eofEmitted === true) {
2322
2337
  return;
@@ -2384,7 +2399,7 @@ class Http2Stream extends Stream {
2384
2399
  // the stream close after both; ending here sent the HEADERS only and the client
2385
2400
  // waited for an answer that never came.
2386
2401
  this._closeNow();
2387
- process.nextTick(emitEndCloseNT, this);
2402
+ this._tick(emitEndCloseNT, this);
2388
2403
  return;
2389
2404
  }
2390
2405
  if (this._state.state === ST_OPEN) {
@@ -2406,7 +2421,7 @@ class Http2Stream extends Stream {
2406
2421
  }
2407
2422
  return;
2408
2423
  }
2409
- process.nextTick(emitEndNT, this);
2424
+ this._tick(emitEndNT, this);
2410
2425
  }
2411
2426
 
2412
2427
  // The writable-side 'finish' -- node's Writable fires it once every write has been
@@ -2423,7 +2438,7 @@ class Http2Stream extends Stream {
2423
2438
  return;
2424
2439
  }
2425
2440
  this._finishQueued = true;
2426
- process.nextTick(finishNT, this);
2441
+ this._tick(finishNT, this);
2427
2442
  }
2428
2443
 
2429
2444
  _endLocalSide() {
@@ -2462,7 +2477,7 @@ class Http2Stream extends Stream {
2462
2477
  // one shot: a later end() must not ask for trailers a second time. The flag
2463
2478
  // itself stays set, because sendTrailers() is only allowed while it is set.
2464
2479
  if (first) {
2465
- process.nextTick(wantTrailersNT, this);
2480
+ this._tick(wantTrailersNT, this);
2466
2481
  }
2467
2482
  return;
2468
2483
  }
@@ -2520,10 +2535,10 @@ class Http2Stream extends Stream {
2520
2535
  // stream.end then stream.close (test/event-order.test.js, scenario eof).
2521
2536
  if (this._endPending || this._eofSeen === true) {
2522
2537
  this._endPending = false;
2523
- process.nextTick(emitEndCloseNT, this);
2538
+ this._tick(emitEndCloseNT, this);
2524
2539
  return;
2525
2540
  }
2526
- process.nextTick(emitCloseDeliveredNT, this);
2541
+ this._tick(emitCloseDeliveredNT, this);
2527
2542
  }
2528
2543
 
2529
2544
  _closeNow() {
@@ -2552,7 +2567,7 @@ class Http2Stream extends Stream {
2552
2567
  // position (and the post-destroy session view) finishNT had when it was always
2553
2568
  // scheduled from _endLocalSide.
2554
2569
  this._finishFuse = false;
2555
- process.nextTick(finishNT, this);
2570
+ this._tick(finishNT, this);
2556
2571
  }
2557
2572
  this._destroyed = true;
2558
2573
  // node's destroy does not touch state.flowing — the readableFlowing getter keeps
@@ -2597,7 +2612,7 @@ class Http2Stream extends Stream {
2597
2612
  // node's closeStream emits 'aborted' before _destroy runs.
2598
2613
  this.session = undefined;
2599
2614
  if (err) {
2600
- process.nextTick(emitErrorCloseNT, this, err);
2615
+ this._tick(() => emitErrorCloseNT(this, err));
2601
2616
  } else if (this._isConsuming() &&
2602
2617
  (this._endPending || code === NO_ERROR || code === frames.CANCEL)) {
2603
2618
  // node's _destroy (internal/http2/core.js:2527) calls `this.push(null)`
@@ -2615,9 +2630,9 @@ class Http2Stream extends Stream {
2615
2630
  // reader is cancelled by the destroy bit and the owed 'end' never goes out
2616
2631
  // (test/event-order.test.js, scenario reset).
2617
2632
  this._endPending = false;
2618
- process.nextTick(emitEndCloseNT, this);
2633
+ this._tick(emitEndCloseNT, this);
2619
2634
  } else {
2620
- process.nextTick(emitNT, this, 'close');
2635
+ this._tick(emitCloseNT, this);
2621
2636
  }
2622
2637
  }
2623
2638
 
@@ -2984,9 +2999,9 @@ function createStreamIterator(stream, options) {
2984
2999
  // The one-shot trio below can never fire again, so this is where that
2985
3000
  // verdict is reproduced.
2986
3001
  if (stream.readableEnded === true) {
2987
- process.nextTick(() => settle(null));
3002
+ stream._tick(() => settle(null));
2988
3003
  } else if (stream.destroyed === true) {
2989
- process.nextTick(() => settle(errorOf('ERR_STREAM_PREMATURE_CLOSE', 'Premature close')));
3004
+ stream._tick(() => settle(errorOf('ERR_STREAM_PREMATURE_CLOSE', 'Premature close')));
2990
3005
  }
2991
3006
  }
2992
3007
 
@@ -3468,4 +3483,4 @@ function streamErrorOf(code) {
3468
3483
  `Stream closed with error code ${frames.ERROR_NAMES[code] || code}`);
3469
3484
  }
3470
3485
 
3471
- module.exports = { Http2Stream, errorOf, streamErrorOf, emitNT };
3486
+ module.exports = { Http2Stream, errorOf, streamErrorOf, emitNT, emitCloseNT, emitDrainNT };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h2lean",
3
- "version": "0.10.2",
3
+ "version": "0.11.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": [