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.
@@ -1,8 +1,9 @@
1
- // Http2Stream equivalent: the object a request handler is handed.
1
+ // Http2ServerStream: the stream a server request handler is handed.
2
2
  //
3
3
  // v1 deliberately implements the parts of the contract that can be honoured
4
4
  // honestly, and omits the ones that cannot:
5
- // * the base is `stream.Stream`, not Duplex and not a bare EventEmitter. node's Http2Stream
5
+ // * this class extends the shared `Http2Stream` base, which itself rests on
6
+ // `stream.Stream`, not Duplex and not a bare EventEmitter. node's Http2Stream
6
7
  // extends Duplex (internal/http2/core.js:2128), but the part of that surface real code reaches
7
8
  // for is pipe() on the readable half, and the Duplex machinery behind it -- two state objects
8
9
  // plus the nextTick read loop -- is what OPTIMIZATION.md item 41 measured as ~+1.4 us/req
@@ -86,310 +87,18 @@
86
87
  'use strict';
87
88
 
88
89
  const fs = require('node:fs');
89
- const { inspect } = require('node:util');
90
- const { Stream, Writable, Readable, Duplex, finished, addAbortSignal, destroy: destroyStream } =
91
- require('node:stream');
92
- const { deprecate } = require('node:util');
90
+ const { Duplex, finished, addAbortSignal, destroy: destroyStream } = require('node:stream');
93
91
  const { StringDecoder } = require('node:string_decoder');
94
- const frames = require('./frames');
95
- const hdr = require('./headers');
96
-
97
- const EMPTY = Buffer.alloc(0);
98
-
99
- // node's Http2Stream sets no highWaterMark (internal/http2/core.js constructor passes only
100
- // allowHalfOpen/decodeStrings/autoDestroy), so its writableHighWaterMark is the default
101
- // Writable one -- 16384 on node 20, 65536 from 22 on. Read it off node itself once rather
102
- // than hardcode a per-major constant that could drift; measured equal to a live node
103
- // stream's writableHighWaterMark on v26.12.1.
104
- const WRITABLE_HWM = new Writable().writableHighWaterMark;
105
-
106
- // The same for the readable half: node's Http2Stream sets no readable highWaterMark
107
- // either, so readableHighWaterMark is the Readable default -- 16384 on node 20, 65536
108
- // from 22 on, measured on live server streams of all four majors and equal to
109
- // `new Readable().readableHighWaterMark` on each.
110
- const READABLE_HWM = new Readable().readableHighWaterMark;
111
-
112
- // process.nextTick(fn, args) instead of an arrow closure per event: the arrow
113
- // allocated a new function object for every request, and in the compat layer
114
- // that showed up as GC time.
115
- function emitNT(target, name, arg) {
116
- if (arg === undefined) {
117
- target.emit(name);
118
- } else {
119
- target.emit(name, arg);
120
- }
121
- }
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
-
135
- function emitErrorCloseNT(target, err) {
136
- target._errorEmitted = true;
137
- target._streamErrored = err;
138
- target.emit('error', err);
139
- target.emit('close');
140
- }
141
-
142
- // The 'error' of the write-after-end shape: emitted on a stream that closes by itself
143
- // a moment later, so 'close' is NOT this helper's job -- but the Duplex getters read the
144
- // same two slots, and node's errorOrDestroy fills state.errored BEFORE the event, not at
145
- // the emit (destroy.js checkError). Same moment here: the nextTick that carries the
146
- // event is the nextTick that ran the flag set in emitErrorCloseNT anyway.
147
- function emitErrorOnlyNT(target, err) {
148
- target._errorEmitted = true;
149
- if (target._streamErrored === undefined) {
150
- target._streamErrored = err;
151
- }
152
- target.emit('error', err);
153
- }
154
-
155
- // 'end' with the Duplex bookkeeping: readableEnded/buffer-free readable read node's
156
- // endEmitted bit, and the bit flips at the delivery, not at the schedule.
157
- function emitEndNT(target) {
158
- if (target._eofEmitted === true) {
159
- return; // the 'end' of a Duplex is once-only; the drain paths can re-arm it
160
- }
161
- target._eofEmitted = true;
162
- target.emit('end');
163
- }
164
-
165
- // node's onStreamTrailers (internal/http2/core.js), the callback nghttp2 runs when the
166
- // writable half of a stream that asked for trailers finishes. Two parts of it are easy
167
- // to lose: `trailersReady` is set before the destroyed/closed check (so a stream that is
168
- // already gone is still marked ready), and when nothing is listening for the event node
169
- // does not leave the deferred END_STREAM outstanding -- it sends an empty trailer block
170
- // itself and closes. An empty block is not a header section on the wire: it is the withheld
171
- // END_STREAM on a zero-length DATA, see sendTrailers() below. Without that last part a
172
- // `respond({waitForTrailers:true})` followed by `end()` with no 'wantTrailers' handler hangs
173
- // the stream forever, which is exactly what upstream's
174
- // test-http2-no-wanttrailers-listener.js tests.
175
- //
176
- // h2lean's compat layer is not a subscriber (see emit() below), so `false` from emit()
177
- // does not by itself mean nobody answered: the compat handler calls sendTrailers() from
178
- // inside the dispatch, and the sentTrailers check is what sees that it did.
179
- function wantTrailersNT(stream) {
180
- stream._trailersReady = true;
181
- if (stream._destroyed || stream.closed) {
182
- return;
183
- }
184
- if (!stream.emit('wantTrailers') && !stream.sentTrailers) {
185
- stream.sendTrailers({});
186
- }
187
- }
188
-
189
- // The tick body of _scheduleFinish, a named function rather than a closure: it runs
190
- // once per finished stream, and a per-response allocation on the compat finish path
191
- // was measured into the regression item 44 closes.
192
- // Not _destroyed here: a stream whose both halves close in the same turn the
193
- // writable ends flips ST_CLOSED synchronously (_closeNow) while the close EVENTS
194
- // are deferred -- and node's order for that shape is 'finish' before 'close',
195
- // with writableFinished true at the close (measured). The only cancel is a
196
- // writable that never drained: octets still parked on window credit.
197
- function finishNT(stream) {
198
- stream._finishQueued = false;
199
- if (stream._writableFinished || stream._queued !== null) {
200
- return;
201
- }
202
- stream._writableFinished = true;
203
- stream.emit('finish');
204
- }
205
-
206
- // 'end' and 'close' for a stream whose two halves finished in the same turn.
207
- // They were already going to run in the same tick drain, so folding them into
208
- // one callback only removes one TickObject per request.
209
- function emitEndCloseNT(target) {
210
- if (target._finishFuse) {
211
- // the finish work rides here, ahead of every state this tick flips: the separate
212
- // tick it replaces ran in the same drain, directly before this callback, when the
213
- // session reference and _closeDelivered were still what end() left them.
214
- target._finishFuse = false;
215
- finishNT(target);
216
- }
217
- target._closeDelivered = true;
218
- // node clears the stream's session reference in _destroy, before any of the close
219
- // events go out (internal/http2/core.js:2546) -- see _closeNow for why the drop waits
220
- // for this tick here.
221
- target.session = undefined;
222
- if (target._eofEmitted !== true) {
223
- target._eofEmitted = true;
224
- target.emit('end');
225
- }
226
- target.emit('close');
227
- }
228
-
229
- // The plain-close half of the same pair: 'close' for a stream whose both halves finished
230
- // in one turn, with no 'end' owed. Marks the node-equivalent close moment -- see
231
- // _closeDelivered above.
232
- function emitCloseDeliveredNT(target) {
233
- if (target._finishFuse) {
234
- target._finishFuse = false;
235
- finishNT(target);
236
- }
237
- target._closeDelivered = true;
238
- target.session = undefined;
239
- target.emit('close');
240
- }
241
-
242
- // The scheduled half of the unread-request auto-close -- see _maybeAutoClose
243
- // below for the rule and its measurement. The unread request half reports 'end'
244
- // here, before the 'close' _destroy schedules behind it: node's trace for the
245
- // shape does the same (test/event-order.test.js, scenario eof-body) -- the
246
- // readable side is finished by the close, never having been read.
247
- function autoCloseNT(stream) {
248
- if (stream._destroyed) {
249
- return;
250
- }
251
- stream._tick(emitEndNT, stream);
252
- stream._destroy(NO_ERROR, true);
253
- }
254
-
255
- // node's onFileUnpipe closes an owned descriptor without caring about the error; the
256
- // same empty callback goes to every fs.close the file paths issue.
257
- function noopClose() {}
258
-
259
- // The read chunk of the file pump. node's StreamPipe sizes its reads internally; the
260
- // boundaries are not wire-visible here (each read feeds write(), which frames DATA by
261
- // maxFrameSize and the flow-control windows either way), so a plain 64 KiB read is used.
262
- const FILE_CHUNK = 65536;
263
-
264
- // node tests `fd instanceof fsPromisesInternal.FileHandle`, but node:fs/promises does
265
- // not export the class (it lives behind --expose-internals), so a real handle is
266
- // recognised by its constructor name and the numeric fd member: an fs.promises.open()
267
- // instance passes, a plain { fd } object does not. A subclass or a same-named replica
268
- // passes too, which is the same leniency node's instanceof shows to subclasses.
269
- const isFileHandle = (v) =>
270
- typeof v === 'object' && v !== null && typeof v.fd === 'number' &&
271
- typeof v.close === 'function' && v.constructor != null &&
272
- v.constructor.name === 'FileHandle';
273
-
274
- // node's ERR_INVALID_ARG_TYPE received-tail (lib/internal/errors.js), measured against
275
- // a live v26.12.1 respondWithFD: a named function renders `function ${name}` -- with
276
- // the trailing space an anonymous one keeps --, instances name their constructor,
277
- // primitives their typeof with the inspected value, null/undefined stand alone.
278
- function receivedArgType(v) {
279
- switch (typeof v) {
280
- case 'function':
281
- return `function ${v.name}`;
282
- case 'object':
283
- if (v === null) {
284
- return 'null';
285
- }
286
- return v.constructor != null
287
- ? `an instance of ${v.constructor.name}` : 'an object with null prototype';
288
- case 'undefined':
289
- return 'undefined';
290
- case 'string':
291
- return `type string (${inspect(v)})`;
292
- case 'symbol':
293
- return `type symbol (${String(v)})`;
294
- default:
295
- return `type ${typeof v} (${inspect(v)})`;
296
- }
297
- }
298
-
299
- // The two TypeError shapes the argument guards raise, measured on the same binary:
300
- // 'The "fd" argument must be of type number or an instance of FileHandle. Received ...'
301
- // and `The property 'options.offset' is invalid. Received ${inspect(v)}`.
302
- function argTypeError(msg, v) {
303
- const err = new TypeError(`${msg} Received ${receivedArgType(v)}`);
304
- err.code = 'ERR_INVALID_ARG_TYPE';
305
- return err;
306
- }
307
-
308
- function propertyValueError(name, v) {
309
- const err = new TypeError(
310
- `The property 'options.${name}' is invalid. Received ${inspect(v)}`);
311
- err.code = 'ERR_INVALID_ARG_VALUE';
312
- return err;
313
- }
314
-
315
- // node's options guard (assertIsObject plus the explicit checks of respondWithFD,
316
- // internal/http2/core.js): an undefined options is an empty one, null and primitives
317
- // are refused, and -- measured -- an array is refused for options (unlike the headers
318
- // argument). offset/length/statCheck keep node's `!== undefined` tests, so a null
319
- // offset is refused exactly the way a string one is.
320
- function fdOptions(options) {
321
- if (options !== undefined &&
322
- (options === null || typeof options !== 'object' || Array.isArray(options))) {
323
- throw argTypeError('The "options" argument must be of type object.', options);
324
- }
325
- const opts = options === undefined ? {} : { ...options };
326
- if (opts.offset !== undefined && typeof opts.offset !== 'number') {
327
- throw propertyValueError('offset', opts.offset);
328
- }
329
- if (opts.length !== undefined && typeof opts.length !== 'number') {
330
- throw propertyValueError('length', opts.length);
331
- }
332
- if (opts.statCheck !== undefined && typeof opts.statCheck !== 'function') {
333
- throw propertyValueError('statCheck', opts.statCheck);
334
- }
335
- return opts;
336
- }
337
-
338
- // node's prepareResponseHeadersObject (internal/http2/core.js): a null-prototype copy
339
- // of the caller's object with ':status' coerced in, so a statCheck that rewrites
340
- // 'content-length' lands on the copy -- which is also what sentHeaders reports,
341
- // exactly where node's kSentHeaders has it. The generated date is left to hdr.block,
342
- // whose sendDate rule is the one prepare applies too. Status validation happens here,
343
- // before the payload-forbidden check -- measured: ':status': 700 throws
344
- // ERR_HTTP2_STATUS_INVALID out of the call, and ':status': '700' is coerced to 700
345
- // first. The array form passes through untouched (hdr.block handles pairs natively);
346
- // node's for..in over an array copies the index keys into the copy and sends field
347
- // names '0', '1', ... instead -- the junk shape the header comment documents.
348
- function prepareResponseHeadersObject(headersParam) {
349
- if (headersParam !== undefined &&
350
- (headersParam === null || typeof headersParam !== 'object')) {
351
- throw argTypeError('The "headers" argument must be an instance of Array or Object.',
352
- headersParam);
353
- }
354
- if (Array.isArray(headersParam)) {
355
- return { headers: headersParam, statusCode: 0, isArray: true };
356
- }
357
- const copy = { __proto__: null };
358
- let statusCode;
359
- // node guards the copy on oldHeaders !== null && !== undefined (core.js): a missing
360
- // headers argument is a valid response -- respondWithFD(fd) with no fields -- and an
361
- // unguarded Object.keys would turn it into a session-killing TypeError
362
- if (headersParam !== undefined && headersParam !== null) {
363
- const keys = Object.keys(headersParam);
364
- for (let i = 0; i < keys.length; i++) {
365
- const key = keys[i];
366
- copy[key] = headersParam[key];
367
- if (key === ':status') {
368
- statusCode = copy[key];
369
- }
370
- }
371
- copy[hdr.KSensitiveHeaders] = headersParam[hdr.KSensitiveHeaders];
372
- }
373
- statusCode = copy[':status'] = (statusCode | 0) || 200;
374
- if (statusCode < 200 || statusCode > 599) {
375
- throw errorOf('ERR_HTTP2_STATUS_INVALID', `Invalid status code: ${statusCode}`);
376
- }
377
- const neverIndex = copy[hdr.KSensitiveHeaders];
378
- if (neverIndex !== undefined && !Array.isArray(neverIndex)) {
379
- const err = new TypeError(
380
- `The property 'headers[http2.neverIndex]' is invalid. Received ${inspect(neverIndex)}`);
381
- err.code = 'ERR_INVALID_ARG_VALUE';
382
- throw err;
383
- }
384
- return { headers: copy, statusCode, isArray: false };
385
- }
386
-
92
+ const { inspect, deprecate } = require('node:util');
93
+ const frames = require('../frames');
387
94
  const {
388
- ST_OPEN, ST_HALF_CLOSED_LOCAL, ST_HALF_CLOSED_REMOTE, ST_CLOSED, NO_ERROR, PROTOCOL_ERROR,
389
- INTERNAL_ERROR
95
+ ST_OPEN, ST_HALF_CLOSED_LOCAL, ST_HALF_CLOSED_REMOTE, ST_CLOSED, NO_ERROR,
96
+ PROTOCOL_ERROR, INTERNAL_ERROR
390
97
  } = frames;
98
+ const hdr = require('../headers');
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');
391
100
 
392
- class Http2Stream extends Stream {
101
+ class Http2ServerStream extends Http2Stream {
393
102
  constructor(session, id) {
394
103
  super();
395
104
  this.id = id;
@@ -411,7 +120,7 @@ class Http2Stream extends Stream {
411
120
  // (internal/http2/core.js:3285) and the getter reads undefined before it.
412
121
  this.sentTrailers = undefined;
413
122
  // The inbound request, as the session's accept path scanned it off the
414
- // field list in one pass (lib/session.js): the :method the HEAD checks
123
+ // field list in one pass (lib/server/Http2ServerSession.js): the :method the HEAD checks
415
124
  // here and the compat CONNECT check read, :path for req.url, and the
416
125
  // stable list the compat request object builds from at the first read
417
126
  // (OPTIMIZATION.md item 49). _reqFields is null when no compat server
@@ -502,25 +211,18 @@ class Http2Stream extends Stream {
502
211
  get destroyed() {
503
212
  return this._destroyed;
504
213
  }
214
+
505
215
  get closed() {
506
216
  // node's STREAM_FLAGS_CLOSED (core.js:2458) -- set by close() at entry, so the
507
217
  // second-call guard holds even while the teardown waits on 'finish'; the state
508
218
  // check keeps the machinery paths (peer RST, destroy) answering as they did.
509
219
  return this._closedFlag === true || this._state.state === ST_CLOSED;
510
220
  }
511
- // node's public state getter answers {} once the stream is destroyed
512
- // (internal/http2/core.js:2304, `if (this.destroyed || id === undefined)`);
513
- // internal code reads _state directly, the way node reads kState.
221
+
514
222
  get state() {
515
223
  return this._destroyed ? {} : this._state;
516
224
  }
517
225
 
518
- // node's sentHeaders is the message that went out, not the object respond() was given:
519
- // a null-prototype map carrying the coerced ':status' number and the `date` the stack
520
- // generated (prepareResponseHeadersObject, internal/http2/core.js:2677-2708). Built on
521
- // the first read and kept, so repeated reads give one object the way node's memoized
522
- // kSentHeaders does, and a response nobody inspects pays no copy. A pushed stream's map
523
- // is a request, not a response, and pushStream() fills it directly.
524
226
  get sentHeaders() {
525
227
  if (this._sentView !== undefined) {
526
228
  return this._sentView;
@@ -532,57 +234,14 @@ class Http2Stream extends Stream {
532
234
  return this._sentView;
533
235
  }
534
236
 
535
- // --- the Duplex state surface ------------------------------------------------
536
- //
537
- // Measured member-by-member off a live node server stream and read out of node's own
538
- // internals (internal/streams/readable.js, internal/streams/writable.js, core.js
539
- // bufferSize/headRequest; tools/probe-duplex-surface.js is the transcript, and
540
- // test/duplex-surface.test.js pins the table). Every getter is computed from state this
541
- // file already keeps, plus five lazily-set booleans (_eofEmitted, _errorEmitted,
542
- // _dataRead, _flowing, _needDrain) written at the event/decision points below --
543
- // no constructor additions, nothing allocated unless an application reads the member.
544
- //
545
- // The one deliberate divergence: writableLength/writableBuffer/bufferSize report the
546
- // octets THIS stream still parks on window credit. node counts the bytes sitting in the
547
- // JS Writable buffer before nghttp2 takes them (writableLength) PLUS the ones nghttp2
548
- // holds (core.js bufferSize = writeQueueSize + writableLength, which double-counts a
549
- // stalled write: measured 4096 queued reads 4096 and 8192); h2lean accepts a write into
550
- // the session's staging buffer inside the call, so there is no JS-side buffer to show.
551
- // Same write-through decision as the cork stub (header above, test/cork-parity.test.js).
552
-
553
- // node: `!r.destroyed && !r.errorEmitted && !r.endEmitted` -- readable-side, not
554
- // half-open-ness: a stream that has emitted 'end' reads false with both halves alive.
555
237
  get readable() {
556
238
  return !this._destroyed && this._errorEmitted !== true && this._eofEmitted !== true;
557
239
  }
558
240
 
559
- // node's readableDidRead is the dataEmitted bit (readable.js:1857): true once any
560
- // delivery of octets happened -- through a 'data' event OR a successful read(), because
561
- // node's read() itself emits 'data' on every chunk it hands back (readable.js read()
562
- // tail, measured: three reads delivered three data events to a listener attached for
563
- // the second one).
564
- get readableDidRead() {
565
- return this._dataRead === true;
566
- }
567
-
568
- // endEmitted, not "the peer's END arrived": false until THIS stream has emitted 'end'.
569
241
  get readableEnded() {
570
242
  return this._eofEmitted === true;
571
243
  }
572
244
 
573
- // node's tri-state (readable.js:1901): null until anything ever touches the readable
574
- // side, true while it flows, false while paused. Measured boundaries: attaching a
575
- // 'readable' listener reads false, a 'data' listener or resume() reads true, pause()
576
- // reads false again, and a destroyed stream reads false. The compat path never sets it
577
- // -- node's compat reads the stream through a 'readable' subscription, so a getter read
578
- // on a compat stream reports false there; h2lean's compat dispatch does not subscribe
579
- // (AGENTS.md 5), so an untouched compat-mode stream reads null. Written-up divergence,
580
- // invisible unless an application mixes the two APIs.
581
- get readableFlowing() {
582
- return this._flowing === undefined ? null : this._flowing;
583
- }
584
-
585
- // node: `readable !== false && (destroyed || errored) && !endEmitted`.
586
245
  get readableAborted() {
587
246
  return (this._destroyed || this._streamErrored !== undefined) &&
588
247
  this._eofEmitted !== true;
@@ -592,14 +251,6 @@ class Http2Stream extends Stream {
592
251
  return this._encoding === undefined ? null : this._encoding;
593
252
  }
594
253
 
595
- get readableHighWaterMark() {
596
- return READABLE_HWM;
597
- }
598
-
599
- get readableObjectMode() {
600
- return false;
601
- }
602
-
603
254
  get readableLength() {
604
255
  const pending = this._pending;
605
256
  if (pending === null) {
@@ -629,24 +280,14 @@ class Http2Stream extends Stream {
629
280
  return out;
630
281
  }
631
282
 
632
- // node: `(kEnding | kEnded | kDestroyed | kErrored) === 0`.
633
283
  get writable() {
634
284
  return !this._destroyed && !this._ending && this._streamErrored === undefined;
635
285
  }
636
286
 
637
- // node's kEnding bit. A plain destroy() ends the writable inside closeStream
638
- // (`if (!ending) stream.end()`, core.js:2088) -- h2lean reports that without touching
639
- // _ending (which carries the 'aborted' decision); a destroy WITH an error does not set
640
- // it, because node's end() skips kEnding on an errored writable (writable.js:876) --
641
- // measured: the push-after-EOF snapshot reads writableEnded false with writable false.
642
287
  get writableEnded() {
643
288
  return this._ending || (this._destroyed && this._streamErrored === undefined);
644
289
  }
645
290
 
646
- get writableObjectMode() {
647
- return false;
648
- }
649
-
650
291
  get writableLength() {
651
292
  const queued = this._queued;
652
293
  if (queued === null) {
@@ -663,29 +304,14 @@ class Http2Stream extends Stream {
663
304
  return this._queued === null ? [] : this._queued.slice();
664
305
  }
665
306
 
666
- // node: `kNeedDrain` set and neither destroyed nor ending. h2lean flips the flag from
667
- // the write()/end() accept verdict -- false when the window still takes bytes, true
668
- // when the send queue parked them -- and the session clears it as the queue drains.
669
307
  get writableNeedDrain() {
670
308
  return this._needDrain === true && !this._destroyed && !this._ending;
671
309
  }
672
310
 
673
- // core.js:2215: `writeQueueSize + writableLength`. The nghttp2 queue this file has no
674
- // equivalent for (write-through, header above), so the second term is the whole number.
675
- get bufferSize() {
676
- return this.writableLength;
677
- }
678
-
679
- // node keeps one `errored` per half; the public getter is the READABLE one
680
- // (readable.js:1939). It holds the Error an 'error' is delivering, set when destroy
681
- // runs with an error (destroy.js checkError), not when the event fires.
682
311
  get errored() {
683
312
  return this._streamErrored === undefined ? null : this._streamErrored;
684
313
  }
685
314
 
686
- // core.js: `!!(flags & STREAM_FLAGS_HEAD_REQUEST)`, set at stream creation from the
687
- // request line. Same fact in h2lean, read where respond() tests it already: the flag
688
- // source is the request map, so there is no state to keep out of sync.
689
315
  get headRequest() {
690
316
  return this._reqMethod === 'HEAD';
691
317
  }
@@ -763,21 +389,6 @@ class Http2Stream extends Stream {
763
389
  return this;
764
390
  }
765
391
 
766
- // --- file responses (respondWithFD / respondWithFile) ---
767
- //
768
- // The step order below is node's respondWithFD (internal/http2/core.js), each guard
769
- // measured against a live v26.12.1: stream guards, the options copy and its
770
- // offset/length/statCheck checks, the waitForTrailers flag (before the fd is
771
- // validated -- an invalid fd with waitForTrailers set still marks the stream for
772
- // trailers), the fd argument itself, ownsFd = false, the prepared header copy, and
773
- // the payload-forbidden statuses (204/205/304 and a HEAD request). respondWithFile
774
- // is the same list with fs.open in front, ownsFd = true, and its own
775
- // non-regular-file rules.
776
- //
777
- // A FileHandle instance is accepted wherever node accepts one; `this.ownsFd` is set
778
- // unconditionally on each path -- node does the same, so an application that pre-set
779
- // stream.ownsFd before respondWithFD has it clobbered there.
780
-
781
392
  respondWithFD(fd, headers, options) {
782
393
  if (this._destroyed || this.closed) {
783
394
  throw errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed');
@@ -934,14 +545,6 @@ class Http2Stream extends Stream {
934
545
  });
935
546
  }
936
547
 
937
- // node's processRespondWithFD: the HEADERS_SENT flag goes up BEFORE the fields are
938
- // validated, so a bad field name leaves headersSent true and takes the destroy path
939
- // below -- measured, the call does not throw. node also calls self.end() here --
940
- // the writable is "ending" from this turn on, which is why an interrupted file
941
- // pipe reports no 'aborted' -- while the END_STREAM itself waits for the pump's
942
- // EOF. The prepared copy is what sentHeaders reports (node's kSentHeaders = the
943
- // copy), and the encoding error and a refused block both leave the descriptor
944
- // with its owner.
945
548
  _processRespondWithFD(fd, prepared, offset, length, sendDate) {
946
549
  this.headersSent = true;
947
550
  this.pending = false;
@@ -970,14 +573,6 @@ class Http2Stream extends Stream {
970
573
  this._startFilePipe(fd, offset, length);
971
574
  }
972
575
 
973
- // node's startFilePipe: read the descriptor in chunks and hand each to the writable
974
- // side, end at EOF, honour the write path's backpressure; teardown closes an owned
975
- // descriptor (node's onFileUnpipe), and a read error other than EOF raises
976
- // NGHTTP2_INTERNAL_ERROR on the stream -- the client then reports
977
- // ERR_HTTP2_STREAM_ERROR with that rstCode, the shape upstream's
978
- // test-http2-respond-file-fd-invalid.js pins. The reads go through write()/end(),
979
- // so credit, the outbound batch and the session hold behave exactly as for a body
980
- // written by hand.
981
576
  _startFilePipe(fd, offset, length) {
982
577
  const pump = {
983
578
  remaining: length === undefined || length < 0 ? Infinity : length,
@@ -1028,12 +623,6 @@ class Http2Stream extends Stream {
1028
623
  step();
1029
624
  }
1030
625
 
1031
- // The file pump's EOF. node's pump never runs Writable.end: StreamPipe writes into
1032
- // the nghttp2 handle directly (core.js startFilePipe), the writable side was closed
1033
- // in processRespondWithFD (`self._final = null; self.end()`) and the application's
1034
- // end() is the no-op Writable.end() is on an ended stream. h2lean's pump shares the
1035
- // application's write()/sendData path, so its EOF mirrors end()'s body without the
1036
- // ended-guard, and the same waitForTrailers split applies.
1037
626
  _pumpEnd() {
1038
627
  const oweTrailers = this._waitForTrailers;
1039
628
  this.session.sendData(this, EMPTY, !oweTrailers);
@@ -1155,21 +744,6 @@ class Http2Stream extends Stream {
1155
744
  return this;
1156
745
  }
1157
746
 
1158
- // The compat layer's empty-trailer finish: stage the END_STREAM frame HERE, inside
1159
- // the read batch that produced the response, instead of from the 'wantTrailers'
1160
- // tick after the batch has left. The octets, the frame order and every event are
1161
- // the ones the deferred path produces -- _waitForTrailers stays set, so the tick
1162
- // still fires 'wantTrailers', the compat handler still answers through
1163
- // sendTrailers(), and the close machinery still runs from that tick; sendTrailers
1164
- // sees _esStaged and skips only the second staging. What changes is which socket
1165
- // batch the frame leaves in: measured, moving it out of the tick was worth ~2.4
1166
- // microseconds of cpuPerReq on the compat showcase arm (item 44). Only for a stream
1167
- // with nothing queued and nothing refused -- a body parked on window credit needs
1168
- // its END_STREAM behind the queued DATA, which the deferred path already arranges.
1169
- // addTrailers() after end() recalls the frame the way the pushStream cut does:
1170
- // node withholds END_STREAM until the tick, so a trailer legally added in the
1171
- // same turn as end() must supersede it; after the flush the frame is gone and the
1172
- // trailer is lost on node too, because its tick already answered the empty block.
1173
747
  endWithStagedEnd() {
1174
748
  // end() sets _ending before anything is sent, and the peer-reset 'aborted' rule
1175
749
  // reads it -- the fast path must carry the same state (test/compat.test.js).
@@ -1179,10 +753,6 @@ class Http2Stream extends Stream {
1179
753
  this._endLocalSide();
1180
754
  }
1181
755
 
1182
- // Undo endWithStagedEnd() while the frame is still in the staging buffer: cut it
1183
- // out the way the pushStream path cuts a parent's not-yet-written END_STREAM, and
1184
- // re-arm the deferred machinery. Returns false -- leaving everything as it is --
1185
- // when the frame has already been committed to the queue or written.
1186
756
  _recallStagedEnd() {
1187
757
  if (this.session._cutStagedES(this.id)) {
1188
758
  this._esStaged = false;
@@ -1190,31 +760,6 @@ class Http2Stream extends Stream {
1190
760
  }
1191
761
  }
1192
762
 
1193
- // Writable-side corking, as a counting stub. node's Http2Stream inherits Writable.cork,
1194
- // which buffers write()/end() and defers the DATA to the wire until corked reaches 0;
1195
- // h2lean's write() sends straight through (the per-read socket batch already coalesces a
1196
- // synchronous burst). Only the count is observable here -- the cross-tick deferral is a
1197
- // KNOWN DIVERGENCE written up in the header and pinned in test/cork-parity.test.js.
1198
- // cork()/uncork() return undefined like Writable's, and uncork() floors at 0 the way
1199
- // Writable's does (internal/streams/writable.js: `if (state.corked) state.corked--`).
1200
- cork() {
1201
- this._corked++;
1202
- }
1203
-
1204
- uncork() {
1205
- if (this._corked > 0) {
1206
- this._corked--;
1207
- }
1208
- }
1209
-
1210
- get writableCorked() {
1211
- return this._corked;
1212
- }
1213
-
1214
- get writableHighWaterMark() {
1215
- return WRITABLE_HWM;
1216
- }
1217
-
1218
763
  get writableFinished() {
1219
764
  return this._writableFinished;
1220
765
  }
@@ -1261,6 +806,13 @@ class Http2Stream extends Stream {
1261
806
  } else {
1262
807
  block = hdr.block(trailers, { trailer: true }, this.session);
1263
808
  bound = hdr.sent.bound;
809
+ // Own these octets before the copy below reads the caller's getters. A getter
810
+ // can call block() for another response, and block() returns a view into the
811
+ // module-level scratch shared by every session: the bytes would be rewritten
812
+ // before sendHeaders() stages this frame (reproduced with a reentrant getter
813
+ // in the trailers object -- the peer saw COMPRESSION_ERROR instead of them).
814
+ // The queued path below uses this copy too, so it still copies only once.
815
+ block = Buffer.from(block);
1264
816
  }
1265
817
  // node records a null-prototype copy, not the caller's map (`ObjectAssign({
1266
818
  // __proto__: null }, headers)`, internal/http2/core.js sendTrailers -- the shared
@@ -1289,10 +841,10 @@ class Http2Stream extends Stream {
1289
841
  if (this._queued !== null) {
1290
842
  // The body is still waiting for credit or for the socket, and this block has to
1291
843
  // follow it: END_STREAM rides on the trailers, so a HEADERS sent now would outrun
1292
- // DATA that has not gone out. Stash a copy (the block is a view into shared scratch;
1293
- // the zero-length marker needs none) and let the session put it on the wire when the
844
+ // DATA that has not gone out. The block was already made owned above (the
845
+ // zero-length marker needs none); let the session put it on the wire when the
1294
846
  // queue drains.
1295
- this._pendingTrailers = empty ? EMPTY : Buffer.from(block);
847
+ this._pendingTrailers = empty ? EMPTY : block;
1296
848
  this._pendingTrailersBound = bound;
1297
849
  return this;
1298
850
  }
@@ -1355,8 +907,6 @@ class Http2Stream extends Stream {
1355
907
  this._destroy(code, true, typeof codeOrError === 'object' ? codeOrError : null);
1356
908
  }
1357
909
 
1358
- // An informational (1xx) HEADERS block, sent before the final response.
1359
- // node: Http2Stream.additionalHeaders().
1360
910
  additionalHeaders(headers) {
1361
911
  // node: `if (this.destroyed || this.closed) throw new ERR_HTTP2_INVALID_STREAM()`
1362
912
  // (internal/http2/core.js additionalHeaders()).
@@ -1367,6 +917,10 @@ class Http2Stream extends Stream {
1367
917
  // (101 has its own error), there is no default status and no generated date.
1368
918
  const block = hdr.block(headers, { info: true }, this.session);
1369
919
  const bound = hdr.sent.bound;
920
+ // Own the bytes before Object.assign reads the caller's getters: one of them
921
+ // can build another block and overwrite the shared scratch this view points
922
+ // into (the trailers path above has the same window).
923
+ const owned = Buffer.from(block);
1370
924
  // node stores a null-proto copy of each informational block, created at the
1371
925
  // first call (internal/http2/core.js:3265, 3285) -- the caller's object is
1372
926
  // not retained, and the array does not exist before the first call.
@@ -1376,7 +930,7 @@ class Http2Stream extends Stream {
1376
930
  } else {
1377
931
  this.sentInfoHeaders.push(copy);
1378
932
  }
1379
- this.session.sendHeaders(this.id, block, false, bound);
933
+ this.session.sendHeaders(this.id, owned, false, bound);
1380
934
  return this;
1381
935
  }
1382
936
 
@@ -1391,10 +945,6 @@ class Http2Stream extends Stream {
1391
945
  return true;
1392
946
  }
1393
947
 
1394
- // node: ServerHttp2Stream.pushAllowed (internal/http2/core.js:2961).
1395
- // Truthiness of remoteSettings.enablePush: the CLIENT's advertisement decides whether
1396
- // the server may push. Measured on v26.12.1: a client with settings:{enablePush:false}
1397
- // makes pushAllowed false and pushStream throw ERR_HTTP2_PUSH_DISABLED synchronously.
1398
948
  get pushAllowed() {
1399
949
  // node's ServerHttp2Stream.pushAllowed (core.js) reads the same terms, but node's
1400
950
  // stream reaches `closed` only when nghttp2 has actually closed it -- for a local
@@ -1411,11 +961,6 @@ class Http2Stream extends Stream {
1411
961
  && !!this.session.remoteSettings.enablePush;
1412
962
  }
1413
963
 
1414
- // node: ServerHttp2Stream.pushStream (internal/http2/core.js:2971).
1415
- // Synchronous throws: ERR_HTTP2_PUSH_DISABLED, ERR_HTTP2_NESTED_PUSH.
1416
- // Asynchronous errors (allocation, closed stream) go to callback via nextTick.
1417
- // The pushed stream's readable side is pre-ended (a push has no request body);
1418
- // the application answers it through the normal respond()/write()/end() path.
1419
964
  pushStream(headers, options, callback) {
1420
965
  if (!this.pushAllowed) {
1421
966
  throw errorOf('ERR_HTTP2_PUSH_DISABLED', 'HTTP/2 client has disabled push streams');
@@ -1507,7 +1052,7 @@ class Http2Stream extends Stream {
1507
1052
  // Create the pushed stream and register it. The readable side is pre-ended:
1508
1053
  // remoteClose=1 means _endLocalSide() takes the graceful close path (no RST),
1509
1054
  // and no inbound credit is ever charged for a request body that does not exist.
1510
- const stream = new Http2Stream(this.session, promisedId);
1055
+ const stream = new Http2ServerStream(this.session, promisedId);
1511
1056
  if (refused) {
1512
1057
  // nghttp2 closed the promised stream at prep time, before the callback below runs,
1513
1058
  // so the respond()/end() the application makes there submit into a closed stream
@@ -1537,9 +1082,6 @@ class Http2Stream extends Stream {
1537
1082
  this._tick(() => callback(null, stream, h, 0));
1538
1083
  }
1539
1084
 
1540
- // Readable-side control, node's contract: while paused no credit is released,
1541
- // so the sender is the one that waits, and whatever arrives in the meantime is
1542
- // buffered and replayed on resume(). Returns this, like the Duplex does.
1543
1085
  pause() {
1544
1086
  this._flowing = false;
1545
1087
  this._pauseConsuming();
@@ -1552,11 +1094,6 @@ class Http2Stream extends Stream {
1552
1094
  return this;
1553
1095
  }
1554
1096
 
1555
- // node's resume() flips the flowing bit synchronously but the delivery itself
1556
- // runs on the kResumeScheduled next tick, and an attaching 'data' listener only
1557
- // calls resume when the stream is neither explicitly paused nor in pull mode --
1558
- // the 'readable' attach has set kHasFlowing, and measured: a 'data' attach
1559
- // inside a pull handler leaves the buffer for read() untouched.
1560
1097
  _scheduleResume() {
1561
1098
  if (this._resumeScheduled === true || this._flowing === false ||
1562
1099
  this._destroyed) {
@@ -1576,34 +1113,6 @@ class Http2Stream extends Stream {
1576
1113
  return this._consumeState === 2;
1577
1114
  }
1578
1115
 
1579
- // --- the readable pull surface: read() and push() -----------------------------
1580
- //
1581
- // A mini-Readable over the existing `_pending` queue, reproduced member by
1582
- // member from internal/streams/readable.js (v26) and pinned against a live
1583
- // node by tools/probe-duplex-surface.js: an arrival emits 'readable' and
1584
- // nothing else until the application pulls; read() with no argument returns
1585
- // the whole first chunk, read(n) merges across chunks and hands the
1586
- // remainder back, an ask past the buffered end returns what the queue can
1587
- // cover (nothing at all before the EOF is known), every data-returning read
1588
- // flips dataRead and emits 'data', and a read past the end of an empty,
1589
- // EOF-known queue schedules the end-of-stream. push() after the EOF errors
1590
- // with ERR_STREAM_PUSH_AFTER_EOF through 'error', push() on a destroyed
1591
- // stream is a silent false, push(null) always returns false. The queue holds
1592
- // two entry kinds: a bare Buffer is octets off the socket (credit-owed), a
1593
- // `{ data }` wrapper is octets the application pushed (never credited — they
1594
- // never came off the wire, and crediting them would let a peer send bytes we
1595
- // never advertised).
1596
- //
1597
- // The EOF becomes known to node when the END_STREAM is processed in the read
1598
- // callback — measured by stack (stream_base_commons:236 -> Readable.push ->
1599
- // onEofChunk): that push(null) emits 'readable' synchronously from
1600
- // onEofChunk's non-sync branch, and onStreamClose pushes it again for the
1601
- // paths that end without a final frame (reset, teardown). h2lean knows the
1602
- // EOF at the same frame and parks it in `_endPending` when no reader is
1603
- // watching, which matches the visible sequences (data, end, close, and the
1604
- // measured-identical push-after-EOF matrix) with the parked EOF standing in
1605
- // for the buffered one.
1606
-
1607
1116
  read(n) {
1608
1117
  // node's argument normalisation, kept exact: no argument is NaN and means
1609
1118
  // the whole first chunk; a non-integer goes through parseInt.
@@ -1677,11 +1186,6 @@ class Http2Stream extends Stream {
1677
1186
  return ret;
1678
1187
  }
1679
1188
 
1680
- // Pull `n` octets off the queue: the exact-first-chunk case returns the buffer
1681
- // view itself (no copy, the AGENTS.md 5 rule that a chunk the app holds is
1682
- // never recycled); a read that splits or merges allocates one buffer and
1683
- // re-queues the remainder with the origin it had. Credit goes out for the
1684
- // wire octets handed over, in one call, only for them.
1685
1189
  _takeQueued(n) {
1686
1190
  const pending = this._pending;
1687
1191
  const first = pending[0];
@@ -1780,9 +1284,6 @@ class Http2Stream extends Stream {
1780
1284
  return out;
1781
1285
  }
1782
1286
 
1783
- // node's Writable-side sibling call: push queued readable data with NO wire
1784
- // accounting — the octets did not come off the socket, so _release must never
1785
- // see them (a credit for them would advertise window the peer never spent).
1786
1287
  push(chunk, encoding) {
1787
1288
  if (chunk === null) {
1788
1289
  // push(null) is the EOF into the readable queue: it never returns true and
@@ -1868,8 +1369,6 @@ class Http2Stream extends Stream {
1868
1369
  return this._canPushMore();
1869
1370
  }
1870
1371
 
1871
- // node's canPushMore: below the watermark, or nothing buffered, and never
1872
- // past the EOF the readable queue has received.
1873
1372
  _canPushMore() {
1874
1373
  if (this._eofSeen === true) {
1875
1374
  return false;
@@ -1878,19 +1377,6 @@ class Http2Stream extends Stream {
1878
1377
  return n < READABLE_HWM || n === 0;
1879
1378
  }
1880
1379
 
1881
- // node's Readable.prototype.setEncoding (readable.js:631), member by member:
1882
- // a FRESH StringDecoder replaces whatever was set before (an unknown name
1883
- // throws ERR_UNKNOWN_ENCODING synchronously out of the StringDecoder
1884
- // constructor; `null` and `undefined` decode as utf8, and the getter reports
1885
- // what the decoder normalised, not what the caller passed), the octets
1886
- // already queued are decoded through it and merged into ONE string entry, and
1887
- // if the EOF is already known the decoder's flush rides along. From here the
1888
- // queue holds strings and `readableLength` counts characters -- node's
1889
- // state.length does the same once a decoder exists, which is why the
1890
- // watermark arithmetic in _canPushMore needs no special case. The wire
1891
- // octets the merged string stands for stay credited as a bundle on its
1892
- // consumption (the `bytes` field), so a setEncoding between DATA frames
1893
- // cannot leak or invent window.
1894
1380
  setEncoding(enc) {
1895
1381
  const decoder = new StringDecoder(enc);
1896
1382
  this._decoder = decoder;
@@ -1926,28 +1412,6 @@ class Http2Stream extends Stream {
1926
1412
  return this;
1927
1413
  }
1928
1414
 
1929
- // node's Writable.prototype.setDefaultEncoding (writable.js:537): the name is
1930
- // lower-cased first because node::ParseEncoding requires it, an unknown one
1931
- // throws ERR_UNKNOWN_ENCODING synchronously, and the call returns the stream.
1932
- // It is the WRITABLE half's default -- what an encoding-less write(string)
1933
- // encodes with; the readable side keeps its own 'utf8'.
1934
- setDefaultEncoding(encoding) {
1935
- if (typeof encoding === 'string') {
1936
- encoding = encoding.toLowerCase();
1937
- }
1938
- if (!Buffer.isEncoding(encoding)) {
1939
- const err = new TypeError(`Unknown encoding: ${encoding}`);
1940
- err.code = 'ERR_UNKNOWN_ENCODING';
1941
- throw err;
1942
- }
1943
- this._defaultEnc = encoding;
1944
- return this;
1945
- }
1946
-
1947
- // The EOF flush of the readable decoder -- node's onEofChunk head
1948
- // (readable.js:849): the tail a split multi-byte sequence left in the decoder
1949
- // becomes one last queue entry before the end machinery runs, carrying the
1950
- // octets held there as its credit.
1951
1415
  _flushDecoder() {
1952
1416
  if (this._decoder === undefined) {
1953
1417
  return;
@@ -1963,14 +1427,6 @@ class Http2Stream extends Stream {
1963
1427
  }
1964
1428
  }
1965
1429
 
1966
- // node's Readable.prototype.pipe (internal/streams/readable.js:978), not the
1967
- // legacy Stream.prototype.pipe the bare base would supply: the tracked
1968
- // destination list, the unpipe() surface, and the teardown that makes a
1969
- // destroyed or finished source end and unpipe its destinations -- measured
1970
- // on a live node the sink of a stream destroyed mid-pipe reports
1971
- // pipe,finish,unpipe,close where the legacy base stops at pipe,close
1972
- // (test/pipe-parity.test.js). The await-drain bookkeeping is node's
1973
- // single-dest fast value promoted to a Set for the second destination.
1974
1430
  pipe(dest, options) {
1975
1431
  const src = this;
1976
1432
  if (src._pipes === null) {
@@ -2106,120 +1562,6 @@ class Http2Stream extends Stream {
2106
1562
  return dest;
2107
1563
  }
2108
1564
 
2109
- // node's Readable.prototype.unpipe (readable.js:1180): no argument removes
2110
- // every destination and stops the flow; one argument removes that
2111
- // destination if it is piped to, and the call is its own 'unpipe' event
2112
- // onto the dest with the hasUnpiped record the pipe closure cleans up on.
2113
- unpipe(dest) {
2114
- const pipes = this._pipes;
2115
- if (pipes === null || pipes.length === 0) {
2116
- return this;
2117
- }
2118
- if (!dest) {
2119
- const dests = pipes;
2120
- this._pipes = [];
2121
- this.pause();
2122
- for (let i = 0; i < dests.length; i++) {
2123
- dests[i].emit('unpipe', this, { hasUnpiped: false });
2124
- }
2125
- return this;
2126
- }
2127
- const index = pipes.indexOf(dest);
2128
- if (index === -1) {
2129
- return this;
2130
- }
2131
- pipes.splice(index, 1);
2132
- if (pipes.length === 0) {
2133
- this.pause();
2134
- }
2135
- dest.emit('unpipe', this, { hasUnpiped: false });
2136
- return this;
2137
- }
2138
-
2139
- // --- the async-iteration surface -------------------------------------------
2140
- // node's readable-iteration protocol (internal/streams/readable.js:1552-1805)
2141
- // and the fourteen helpers the public `stream` module bolts onto the same
2142
- // prototype (stream.js:72-103, wrapping internal/streams/operators): the
2143
- // transform family returns `Readable.from(generator)` -- measured on a live
2144
- // node server stream: `map(fn)` yields an objectMode Readable -- and the
2145
- // promise family returns the operation's promise. The iterator itself is a
2146
- // pull machine over read(); break over for-await destroys through the
2147
- // iterator's return() (AbortError into _destroy, RST CANCEL(8), events
2148
- // aborted, error:ABORT_ERR, close), while a natural end leaves the stream
2149
- // alive -- node reaches finalize() in both cases, but Http2Stream sets
2150
- // autoDestroy false (core.js:2132), so only the still-active return()
2151
- // branch satisfies finalize's second clause (measured: destroyed false,
2152
- // readableEnded true after a clean loop; destroyed true, rstCode 8 after
2153
- // break, both read inside the same handler turn).
2154
- [Symbol.asyncIterator]() {
2155
- return createStreamIterator(this, undefined);
2156
- }
2157
-
2158
- iterator(options) {
2159
- if (options !== undefined) {
2160
- validateObjectArg(options, 'options');
2161
- }
2162
- return createStreamIterator(this, options);
2163
- }
2164
-
2165
- map(fn, options) {
2166
- return Readable.from(opMap(this, fn, options));
2167
- }
2168
-
2169
- filter(fn, options) {
2170
- return Readable.from(opFilter(this, fn, options));
2171
- }
2172
-
2173
- flatMap(fn, options) {
2174
- return Readable.from(opFlatMap(this, fn, options));
2175
- }
2176
-
2177
- drop(number, options) {
2178
- return Readable.from(opDrop(this, number, options));
2179
- }
2180
-
2181
- take(number, options) {
2182
- return Readable.from(opTake(this, number, options));
2183
- }
2184
-
2185
- reduce(reducer, initialValue, options) {
2186
- // node's reduce tests `arguments.length > 1` inside the operator to tell
2187
- // "no initial value" from "initial value undefined"; the arity has to be
2188
- // read at the call, which is here.
2189
- return opReduce(this, arguments.length > 1, reducer, initialValue, options);
2190
- }
2191
-
2192
- forEach(fn, options) {
2193
- return opForEach(this, fn, options);
2194
- }
2195
-
2196
- toArray(options) {
2197
- return opToArray(this, options);
2198
- }
2199
-
2200
- some(fn, options) {
2201
- return opSome(this, fn, options);
2202
- }
2203
-
2204
- every(fn, options) {
2205
- return opEvery(this, fn, options);
2206
- }
2207
-
2208
- find(fn, options) {
2209
- return opFind(this, fn, options);
2210
- }
2211
-
2212
- // node's Readable.prototype.compose (readable.js:1810 plus
2213
- // internal/streams/compose.js, the Node-stream branch): the composed Duplex
2214
- // writes into this and reads out of the chain behind it. h2lean drives the
2215
- // two-stream chain with its own pipe() -- the port of Readable.prototype.pipe
2216
- // above -- where node uses internal/streams/pipeline; for the prototype
2217
- // method's single argument those are the same chain (src 'end' -> dest.end(),
2218
- // src error -> dest teardown), and the rest is node's wiring verbatim:
2219
- // d._write into head with the drain callback, d._final = head.end(),
2220
- // tail 'data'/'end' into d.push, teardown destroying the tail. Web streams
2221
- // (TransformStream and friends) are refused here where node composes them --
2222
- // KNOWN DIVERGENCE, stated in the header of this file's difference list.
2223
1565
  compose(stream, options) {
2224
1566
  if (options != null) {
2225
1567
  validateObjectArg(options, 'options');
@@ -2326,58 +1668,6 @@ class Http2Stream extends Stream {
2326
1668
  return d;
2327
1669
  }
2328
1670
 
2329
- // node's legacy Readable.prototype.wrap (readable.js:1503) -- the "ugly
2330
- // unfortunate mess of history" that turns any event source into readable
2331
- // data on this stream. It is honest machinery here because push() is node's
2332
- // (task 39) and the pull-side resume hook fires where node's maybeReadMore
2333
- // would call _read.
2334
- wrap(stream) {
2335
- let paused = false;
2336
- stream.on('data', (chunk) => {
2337
- if (!this.push(chunk) && stream.pause) {
2338
- paused = true;
2339
- stream.pause();
2340
- }
2341
- });
2342
- stream.on('end', () => {
2343
- this.push(null);
2344
- });
2345
- stream.on('error', (err) => {
2346
- if (!this.destroyed) {
2347
- this.destroy(err);
2348
- }
2349
- });
2350
- stream.on('close', () => {
2351
- if (!this.destroyed) {
2352
- this.destroy();
2353
- }
2354
- });
2355
- stream.on('destroy', () => {
2356
- if (!this.destroyed) {
2357
- this.destroy();
2358
- }
2359
- });
2360
- this._read = () => {
2361
- if (paused && stream.resume) {
2362
- paused = false;
2363
- stream.resume();
2364
- }
2365
- };
2366
- const streamKeys = Object.keys(stream);
2367
- for (let j = 0; j < streamKeys.length; j++) {
2368
- const i = streamKeys[j];
2369
- if (this[i] === undefined && typeof stream[i] === 'function') {
2370
- this[i] = stream[i].bind(stream);
2371
- }
2372
- }
2373
- return this;
2374
- }
2375
-
2376
- // The pull model's arrival event: node's readable-mode consumer is woken by
2377
- // 'readable', never by the bytes themselves. Coalescing is node's
2378
- // needReadable/emitReadable pair — one event per un-observed stretch, so two
2379
- // DATA frames in one read batch produce one event (measured: readablePasses 2
2380
- // for three reads over one arrival).
2381
1671
  _scheduleReadable() {
2382
1672
  if (this._readableScheduled === true || this.listenerCount('readable') === 0) {
2383
1673
  return;
@@ -2398,8 +1688,6 @@ class Http2Stream extends Stream {
2398
1688
  });
2399
1689
  }
2400
1690
 
2401
- // The end-of-stream schedule — node's endReadable: the 'end' never overtakes
2402
- // buffered octets, and one schedule is enough (the kEndScheduled bit).
2403
1691
  _scheduleEOF() {
2404
1692
  if (this._eofEmitted === true || this._eofScheduled === true) {
2405
1693
  return;
@@ -2422,18 +1710,6 @@ class Http2Stream extends Stream {
2422
1710
  });
2423
1711
  }
2424
1712
 
2425
- // node maps a per-stream timeout onto the connection's idle timeout.
2426
- setTimeout(ms, cb) {
2427
- this.session.setTimeout(ms, cb);
2428
- return this;
2429
- }
2430
-
2431
- // --- internals used by the session ------------------------------------------
2432
- // Both halves have to converge: a handler that answers synchronously inside
2433
- // the 'stream' emit closes the local side BEFORE the peer's END_STREAM is
2434
- // reported, and vice versa. Whichever call sees both halves closed is the one
2435
- // that removes the stream from the session -- without it every request leaks
2436
- // an Http2Stream (and _liveStreams never falls, so close() never finishes).
2437
1713
  _remoteEnded() {
2438
1714
  if (this._state.remoteClose === 1) {
2439
1715
  return;
@@ -2498,15 +1774,6 @@ class Http2Stream extends Stream {
2498
1774
  this._tick(emitEndNT, this);
2499
1775
  }
2500
1776
 
2501
- // The writable-side 'finish' -- node's Writable fires it once every write has been
2502
- // accepted by the stream machinery and the writable half has ended; a destroy in
2503
- // the same turn as the end() cancels it (upstream's test-http2-respond-with-fd-finish.js
2504
- // pins both shapes: finish, then close with writableFinished true on a clean send;
2505
- // close with writableFinished false and no 'finish' on an abort). The tick is also
2506
- // what keeps the event behind 'wantTrailers' -- measured on v26.12.1, 'finish'
2507
- // precedes 'wantTrailers' on the trailers shape. A body still queued on window
2508
- // credit re-runs _endLocalSide when the queue drains (session._release), which is
2509
- // where the second scheduling comes from.
2510
1777
  _scheduleFinish() {
2511
1778
  if (this._writableFinished || this._finishQueued) {
2512
1779
  return;
@@ -2567,22 +1834,6 @@ class Http2Stream extends Stream {
2567
1834
  }
2568
1835
  }
2569
1836
 
2570
- // node's Http2Stream[kMaybeDestroy] (internal/http2/core.js): a response the
2571
- // server session has finished, with trailers neither requested nor sent
2572
- // (STREAM_FLAGS_HAS_TRAILERS) and a request side nobody ever started to consume
2573
- // (`!state.didRead && readableFlowing === null`), is closed by the session
2574
- // itself -- `setImmediate(callStreamClose)` off the writable side's 'finish',
2575
- // and closeStream submits RST_STREAM(NO_ERROR). Measured on v26.12.1
2576
- // (tools/probe-stream-teardown.js, 'answer-only'): HEADERS, DATA, then
2577
- // RST_STREAM(NO_ERROR) on the wire and the stream destroyed -- and the
2578
- // boundaries with it: 'resume-then-answer' shows that touching the readable
2579
- // side stops the auto-close, and 'request-ended' that a stream the peer already
2580
- // ended never gets one. Without it a peer that sends HEADERS without END_STREAM
2581
- // and no DATA holds a stream and a _liveStreams slot until the idle timeout,
2582
- // and a closing session waits for it forever (AGENTS.md 10, item 2).
2583
- // `_consumeState === 0` is this file's reading of `!didRead && flowing ===
2584
- // null`: no reader attached and no pause()/resume() called -- either has
2585
- // touched the request, and node stops there too.
2586
1837
  _maybeAutoClose() {
2587
1838
  if (this._destroyed || !this.headersSent || this._waitForTrailers ||
2588
1839
  this._consumeState !== 0 || this._flowing === false ||
@@ -2710,15 +1961,6 @@ class Http2Stream extends Stream {
2710
1961
  }
2711
1962
  }
2712
1963
 
2713
- // --- the compat layer's handlers ------------------------------------------------
2714
- // The compat layer does not subscribe to the stream's events: it installs one
2715
- // dispatch function and the stream calls it -- subscriptions are an order of
2716
- // magnitude more expensive per request than the dispatch (OPTIMIZATION.md
2717
- // item 5) -- and the handlers want the stream as `this` anyway.
2718
- //
2719
- // The dispatch runs BEFORE the event reaches the emitter, which is the order
2720
- // the subscriptions had: the compat layer's own handlers first, the
2721
- // application's listeners after.
2722
1964
  emit(name, arg) {
2723
1965
  const dispatch = this._compatDispatch;
2724
1966
  if (dispatch !== null) {
@@ -2735,12 +1977,6 @@ class Http2Stream extends Stream {
2735
1977
  return super.emit.apply(this, arguments);
2736
1978
  }
2737
1979
 
2738
- // --- inbound flow control ----------------------------------------------------
2739
- // Attaching a reader is how the application says "send me the body": whatever
2740
- // arrived before it did is replayed -- on the next tick, like node's
2741
- // kResumeScheduled resume_, not inside the on() call (measured: a read() in the
2742
- // same turn as the attach still sees the buffer). once()/addListener are
2743
- // covered by the listenerCount() check at delivery time.
2744
1980
  on(name, fn) {
2745
1981
  const firstReader = (name === 'data' || name === 'readable') &&
2746
1982
  this.listenerCount(name) === 0;
@@ -2777,11 +2013,6 @@ class Http2Stream extends Stream {
2777
2013
  return r;
2778
2014
  }
2779
2015
 
2780
- // node's Readable.prototype.on: attaching 'data' resumes, unless the stream was
2781
- // explicitly paused; attaching 'readable' takes the stream out of flowing mode
2782
- // even after resume() (measured: resume() then on('readable') reads false).
2783
- // Both rules show up on the readableFlowing getter only — the replay that
2784
- // actually moves the bytes stayed where it was.
2785
2016
  _readerFlow(name) {
2786
2017
  if (name === 'data') {
2787
2018
  if (this._flowing !== false) {
@@ -2792,16 +2023,6 @@ class Http2Stream extends Stream {
2792
2023
  }
2793
2024
  }
2794
2025
 
2795
- // Credit goes back when the application takes the bytes, so a body nobody
2796
- // reads closes the sender's window instead of growing our heap. The buffer of
2797
- // unread chunks cannot exceed the window we advertised, because the peer is
2798
- // not allowed to send more than that without a credit we never gave.
2799
- // A 'readable' listener is NOT consuming: the pull model buffers and waits
2800
- // for read(), which is where that credit comes back (node's readable mode
2801
- // releases nothing until the app pulls). A 'data' listener is not consuming
2802
- // either while the stream sits in pull or paused mode (_flowing === false) --
2803
- // node's kHasFlowing rule measured in the merge arm: the chunks stay in the
2804
- // buffer for read() and only read()'s own data emission delivers them.
2805
2026
  _isConsuming() {
2806
2027
  if (this._consumeState === 2) {
2807
2028
  return false;
@@ -2810,8 +2031,6 @@ class Http2Stream extends Stream {
2810
2031
  (this._flowing !== false && this.listenerCount('data') > 0);
2811
2032
  }
2812
2033
 
2813
- // Called when a reader shows up: replay what was buffered, in order, and let
2814
- // later frames through directly.
2815
2034
  _startConsuming() {
2816
2035
  this._consumeState = 1;
2817
2036
  const pending = this._pending;
@@ -2840,8 +2059,6 @@ class Http2Stream extends Stream {
2840
2059
  }
2841
2060
  }
2842
2061
 
2843
- // Internal pause, used by the compat layer when its Readable is full. There is
2844
- // no public pause()/resume() yet, and this is the only reason it exists.
2845
2062
  _pauseConsuming() {
2846
2063
  this._consumeState = 2;
2847
2064
  }
@@ -2906,755 +2123,22 @@ class Http2Stream extends Stream {
2906
2123
  // 'readable', not through the bytes (node's needReadable/emitReadable).
2907
2124
  this._scheduleReadable();
2908
2125
  }
2126
+
2127
+ _abortError() {
2128
+ return abortError();
2129
+ }
2130
+
2131
+ _createIterator(options) {
2132
+ return createStreamIterator(this, options);
2133
+ }
2909
2134
  }
2910
2135
 
2911
2136
  // node wraps the whole method in util.deprecate, so the warning fires once per
2912
2137
  // process with this exact message -- typo included, byte-identical to
2913
2138
  // internal/http2/core.js:2620 (DEP0194).
2914
- Http2Stream.prototype.priority = deprecate(
2915
- Http2Stream.prototype.priority,
2139
+ Http2ServerStream.prototype.priority = deprecate(
2140
+ Http2ServerStream.prototype.priority,
2916
2141
  'http2Stream.priority is longer supported after priority signalling was deprecated in RFC 9113',
2917
2142
  'DEP0194');
2918
2143
 
2919
- function errorOf(code, msg) {
2920
- const err = new Error(msg);
2921
- err.code = code;
2922
- return err;
2923
- }
2924
-
2925
- // node's Http2Stream.close validates its code with validateInteger(code, 'code', 0,
2926
- // kMaxInt) and the callback with validateFunction (internal/http2/core.js:2474,
2927
- // kMaxInt = 2^32 - 1 at core.js:239). The messages are internal/validators', read
2928
- // out of it in the same session: a non-number is ERR_INVALID_ARG_TYPE, a
2929
- // non-integer or an out-of-range integer is ERR_OUT_OF_RANGE.
2930
- // The Received-tail is determineSpecificType (internal/errors.js), ported from the
2931
- // bundled source and measured through Http2Stream.close on a live v26.12.1 client:
2932
- // strings quote with '' and flip to JSON.stringify when the value itself carries a
2933
- // quote, both truncated at 28 octets to 25 plus '...'; -0/NaN/Infinity are named;
2934
- // an object reports `an instance of ${constructor.name}` only when that name is a
2935
- // non-empty string, else the inspect fallback at depth -1; `function ${name}` keeps
2936
- // the trailing space for an anonymous function; the generic tail inspects, it does
2937
- // not String().
2938
- function specType(v) {
2939
- if (v === null) {
2940
- return 'null';
2941
- }
2942
- if (v === undefined) {
2943
- return 'undefined';
2944
- }
2945
- const t = typeof v;
2946
- if (t === 'string') {
2947
- if (v.length > 28) {
2948
- v = `${v.slice(0, 25)}...`;
2949
- }
2950
- return v.indexOf("'") === -1 ? `type string ('${v}')`
2951
- : `type string (${JSON.stringify(v)})`;
2952
- }
2953
- if (t === 'number') {
2954
- if (v === 0) {
2955
- return 1 / v === -Infinity ? 'type number (-0)' : 'type number (0)';
2956
- }
2957
- if (v !== v) {
2958
- return 'type number (NaN)';
2959
- }
2960
- if (v === Infinity) {
2961
- return 'type number (Infinity)';
2962
- }
2963
- if (v === -Infinity) {
2964
- return 'type number (-Infinity)';
2965
- }
2966
- return `type number (${v})`;
2967
- }
2968
- if (t === 'boolean') {
2969
- return v ? 'type boolean (true)' : 'type boolean (false)';
2970
- }
2971
- if (t === 'bigint') {
2972
- return `type bigint (${v}n)`;
2973
- }
2974
- if (t === 'symbol') {
2975
- return `type symbol (${String(v)})`;
2976
- }
2977
- if (t === 'function') {
2978
- return `function ${v.name}`;
2979
- }
2980
- if (t === 'object') {
2981
- // `constructor` may be user-controlled: node reads it once and only trusts a
2982
- // non-empty string name (internal/errors.js).
2983
- const name = v.constructor?.name;
2984
- if (typeof name === 'string' && name !== '') {
2985
- return `an instance of ${name}`;
2986
- }
2987
- return inspect(v, { depth: -1 });
2988
- }
2989
- let shown = inspect(v, { colors: false });
2990
- if (shown.length > 28) {
2991
- shown = `${shown.slice(0, 25)}...`;
2992
- }
2993
- return `type ${t} (${shown})`;
2994
- }
2995
-
2996
- // node's Http2Stream.close (core.js:2474) validates its code through
2997
- // validateInteger(code, 'code', 0, kMaxInt) -- kMaxInt is 2^32-1 (core.js:239) -- and
2998
- // its callback through validateFunction; the three verdicts and their exact texts are
2999
- // measured on a live v26.12.1 client: a non-number code is ERR_INVALID_ARG_TYPE
3000
- // ("must be of type number"), a non-integer number is ERR_OUT_OF_RANGE ("It must be an
3001
- // integer"), and a code outside [0, 2^32-1] is ERR_OUT_OF_RANGE ("It must be >= 0 &&
3002
- // <= 4294967295"). The callback's own message names "callback" and follows the same
3003
- // determineSpecificType shapes (measured: string, null, number).
3004
- function validateRstCode(code, callback) {
3005
- if (typeof code !== 'number') {
3006
- throw errorOf('ERR_INVALID_ARG_TYPE',
3007
- `The "code" argument must be of type number. Received ${specType(code)}`);
3008
- }
3009
- if (!Number.isInteger(code)) {
3010
- throw errorOf('ERR_OUT_OF_RANGE',
3011
- `The value of "code" is out of range. It must be an integer. Received ${code}`);
3012
- }
3013
- if (code < 0 || code > 4294967295) {
3014
- throw errorOf('ERR_OUT_OF_RANGE',
3015
- `The value of "code" is out of range. It must be >= 0 && <= 4294967295. Received ${code}`);
3016
- }
3017
- if (callback !== undefined && typeof callback !== 'function') {
3018
- throw errorOf('ERR_INVALID_ARG_TYPE',
3019
- `The "callback" argument must be of type function. Received ${specType(callback)}`);
3020
- }
3021
- }
3022
-
3023
- // --- the async-iteration machinery ----------------------------------------------
3024
- // Everything below reproduces node's internal/streams/readable.js:1552-1805
3025
- // (streamToAsyncIterator/createAsyncIterator) and internal/streams/operators,
3026
- // read from the binary in the same session as the measurements cited at the
3027
- // methods. Two simplifications are honest, not inventions: (a) the iterator
3028
- // never meets a thenable chunk -- push() validates its argument, so the queue
3029
- // holds only Buffer/string/null and node's `chunk?.then` unwrapping and the
3030
- // two-error AggregateError race it guards cannot occur (measured: an errored
3031
- // iteration rejects with the bare error); (b) the FixedQueue node parks
3032
- // queued requests in is an array here -- queue depth is a behaviour of the
3033
- // consumer, not of the protocol.
3034
-
3035
- const kEmpty = Symbol('kEmpty');
3036
- const kEof = Symbol('kEof');
3037
- // %AsyncIteratorPrototype% in V8: the function's .prototype is an INSTANCE of
3038
- // the (shared) async-generator prototype, so the intrinsic with
3039
- // [Symbol.asyncIterator]/[Symbol.asyncDispose] and no own methods sits TWO
3040
- // levels up. Verified identity with the proto of a live node v26 iterator
3041
- // object; the single getPrototypeOf lands on the generator prototype instead.
3042
- // Node's own iterator is NOT this shape on every major: 22 and 24 hand back a
3043
- // real async-generator instance, whose proto has no own keys at all. The
3044
- // intrinsic is the only anchor stable across majors, and the behaviour that
3045
- // depends on it ([Symbol.asyncIterator] resolving through the chain,
3046
- // self-identical) is verified per major; exact proto identity is unportable.
3047
- const ASYNC_ITERATOR_PROTO =
3048
- Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}.prototype));
3049
-
3050
- function noop() {}
3051
-
3052
- // node's internal AbortError as the stream machinery constructs it (measured
3053
- // on a live node break: name 'AbortError', code 'ABORT_ERR'). core.js:2516
3054
- // maps it onto RST CANCEL(8) inside _destroy.
3055
- function abortError(cause) {
3056
- const err = new Error('The operation was aborted',
3057
- cause === undefined ? undefined : { cause });
3058
- err.name = 'AbortError';
3059
- err.code = 'ABORT_ERR';
3060
- return err;
3061
- }
3062
-
3063
- function validateObjectArg(value, name) {
3064
- if (value === null || typeof value !== 'object') {
3065
- throw errorOf('ERR_INVALID_ARG_TYPE',
3066
- `The "${name}" argument must be of type object. Received ${inspect(value)}`);
3067
- }
3068
- }
3069
-
3070
- function validateFunctionArg(value, name) {
3071
- if (typeof value !== 'function') {
3072
- throw errorOf('ERR_INVALID_ARG_TYPE',
3073
- `The "${name}" argument must be of type function. Received ${inspect(value)}`);
3074
- }
3075
- }
3076
-
3077
- // node's pair in every operator: validateObject(options) then
3078
- // validateAbortSignal(options.signal).
3079
- function validateSignalArg(options) {
3080
- if (options != null && options.signal != null && !(options.signal instanceof AbortSignal)) {
3081
- throw errorOf('ERR_INVALID_ARG_TYPE',
3082
- 'The "options.signal" argument must be an instance of type AbortSignal.');
3083
- }
3084
- }
3085
-
3086
- function validateOperatorOptions(options) {
3087
- if (options != null) {
3088
- validateObjectArg(options, 'options');
3089
- }
3090
- validateSignalArg(options);
3091
- }
3092
-
3093
- // node's toIntegerOrInfinity (operators:298): Number coercion per the
3094
- // iterator-helpers proposal, then the range refusal.
3095
- function toIntegerOrInfinity(number) {
3096
- number = Number(number);
3097
- if (Number.isNaN(number)) {
3098
- return 0;
3099
- }
3100
- if (number < 0) {
3101
- throw errorOf('ERR_OUT_OF_RANGE',
3102
- `The value of "number" is out of range. It must be >= 0. Received ${number}`);
3103
- }
3104
- return number;
3105
- }
3106
-
3107
- // node's createAsyncIterator (readable.js:1576). The request protocol -- next
3108
- // fast path, queue behind an inFlight request, return/throw draining through
3109
- // the same pump -- is reproduced member by member; the wake is h2lean's
3110
- // 'readable' event (node's emitReadable, same coalescing) and the end verdict
3111
- // comes from the error/end/close trio standing in for
3112
- // eos(stream, { writable: false }).
3113
- function createStreamIterator(stream, options) {
3114
- let callback = noop;
3115
- let error; // undefined: active, null: ended cleanly, else: the Error
3116
- let started = false;
3117
- let completed = false;
3118
- let inFlight = false; // an asynchronous request is outstanding
3119
- let queue = null; // requests received while inFlight
3120
- let draining = false;
3121
- let detach = noop;
3122
-
3123
- function fire() {
3124
- const cb = callback;
3125
- callback = noop;
3126
- cb();
3127
- }
3128
-
3129
- function wait() {
3130
- return new Promise((resolve) => {
3131
- callback = resolve;
3132
- });
3133
- }
3134
-
3135
- function start() {
3136
- started = true;
3137
- stream.on('readable', fire);
3138
- // node's eos(stream, { writable: false }, cb), adapted: the verdict
3139
- // handlers record the FIRST verdict and wake the pump (node's once-wrapped
3140
- // callback suppresses the rest -- an 'end' followed by a destroy(err) is
3141
- // swallowed on node, measured off a live client), and the LISTENERS stay
3142
- // attached until finalize's detach branch -- the part that matters here:
3143
- // node's eos keeps its 'error' handler attached through the teardown, so a
3144
- // destroy that races a natural end does not turn into an unhandled
3145
- // 'error'. A close with neither end nor error is node's eos verdict
3146
- // ERR_STREAM_PREMATURE_CLOSE ('Premature close', read out of
3147
- // internal/errors with --expose-internals).
3148
- const settle = (err) => {
3149
- if (error !== undefined) {
3150
- return;
3151
- }
3152
- error = err;
3153
- fire();
3154
- };
3155
- const onEnd = () => {
3156
- settle(null);
3157
- };
3158
- const onClose = () => {
3159
- settle(errorOf('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'));
3160
- };
3161
- stream.on('error', settle);
3162
- stream.on('end', onEnd);
3163
- stream.on('close', onClose);
3164
- detach = () => {
3165
- stream.removeListener('readable', fire);
3166
- stream.removeListener('error', settle);
3167
- stream.removeListener('end', onEnd);
3168
- stream.removeListener('close', onClose);
3169
- };
3170
- // node's eos settles immediately (on the next tick) when the stream has
3171
- // ALREADY reached its verdict at start(): a second iterator over an ended
3172
- // stream gets `{done:true}` (measured on live node: every() after some()
3173
- // on the same stream answers true without hanging), and over a destroyed
3174
- // one gets the premature-close error.
3175
- if (stream.readableEnded === true) {
3176
- stream._tick(() => settle(null));
3177
- } else if (stream.destroyed === true) {
3178
- stream._tick(() => settle(errorOf('ERR_STREAM_PREMATURE_CLOSE', 'Premature close')));
3179
- }
3180
- }
3181
-
3182
- function finalize() {
3183
- completed = true;
3184
- // node's finalize (readable.js:1609) reads autoDestroy off the state
3185
- // object; Http2Stream fixes it false (core.js:2132), so the second
3186
- // clause reduces to `error === undefined`: only a still-active
3187
- // return()/break destroys -- node's destroyer(stream, null) on a
3188
- // not-finished stream is destroy(new AbortError()), which core.js:2516
3189
- // turns into RST CANCEL. h2lean's public destroy() derives
3190
- // INTERNAL_ERROR from any Error object (its own documented rule, task
3191
- // 17), so the iterator calls the engine with node's derived pair
3192
- // directly. Measured: break -- destroyed true, rstCode 8, aborted,
3193
- // error:ABORT_ERR, close; natural end -- destroyed stays false.
3194
- if ((error || options?.destroyOnReturn !== false) && error === undefined) {
3195
- if (!stream.destroyed) {
3196
- stream._destroy(frames.CANCEL, true, abortError());
3197
- }
3198
- } else {
3199
- stream.removeListener('readable', fire);
3200
- detach();
3201
- }
3202
- }
3203
-
3204
- function drain() {
3205
- // node's guard: requests settled synchronously call back into drain(),
3206
- // and one loop runs instead of one recursion per request.
3207
- if (draining) {
3208
- return;
3209
- }
3210
- draining = true;
3211
- try {
3212
- while (!inFlight && queue !== null && queue.length > 0) {
3213
- const req = queue.shift();
3214
- if (req.type === 'next') {
3215
- processNext(req.resolve, req.reject);
3216
- } else if (req.type === 'return') {
3217
- processReturn(req.value, req.resolve);
3218
- } else {
3219
- processThrow(req.value, req.reject);
3220
- }
3221
- }
3222
- } finally {
3223
- draining = false;
3224
- }
3225
- }
3226
-
3227
- function pump(resolve, reject) {
3228
- const chunk = stream.destroyed ? null : stream.read();
3229
- if (chunk !== null) {
3230
- inFlight = false;
3231
- resolve({ done: false, value: chunk });
3232
- if (queue !== null) {
3233
- drain();
3234
- }
3235
- } else if (error) {
3236
- inFlight = false;
3237
- finalize();
3238
- reject(error);
3239
- if (queue !== null) {
3240
- drain();
3241
- }
3242
- } else if (error === null) {
3243
- inFlight = false;
3244
- finalize();
3245
- resolve({ done: true, value: undefined });
3246
- if (queue !== null) {
3247
- drain();
3248
- }
3249
- } else {
3250
- // nothing buffered yet: wait for the next 'readable' or end verdict
3251
- // and retry, node's wakeup-promise tail.
3252
- wait().then(() => pump(resolve, reject));
3253
- }
3254
- }
3255
-
3256
- function processNext(resolve, reject) {
3257
- if (completed) {
3258
- resolve({ done: true, value: undefined });
3259
- return;
3260
- }
3261
- if (!started) {
3262
- start();
3263
- }
3264
- inFlight = true;
3265
- pump(resolve, reject);
3266
- }
3267
-
3268
- function processReturn(value, resolve) {
3269
- if (!completed) {
3270
- if (started) {
3271
- finalize();
3272
- } else {
3273
- // never started: complete without touching the stream.
3274
- completed = true;
3275
- }
3276
- }
3277
- resolve({ done: true, value });
3278
- }
3279
-
3280
- function processThrow(err, reject) {
3281
- if (completed || !started) {
3282
- completed = true;
3283
- reject(err);
3284
- return;
3285
- }
3286
- error = err;
3287
- finalize();
3288
- reject(err);
3289
- }
3290
-
3291
- const iter = {
3292
- __proto__: ASYNC_ITERATOR_PROTO,
3293
- next() {
3294
- if (!inFlight && !completed) {
3295
- if (!started) {
3296
- start();
3297
- }
3298
- const chunk = stream.destroyed ? null : stream.read();
3299
- if (chunk !== null) {
3300
- return Promise.resolve({ done: false, value: chunk });
3301
- }
3302
- if (error) {
3303
- finalize();
3304
- return Promise.reject(error);
3305
- }
3306
- if (error === null) {
3307
- finalize();
3308
- return Promise.resolve({ done: true, value: undefined });
3309
- }
3310
- inFlight = true;
3311
- return new Promise((resolve, reject) => {
3312
- wait().then(() => pump(resolve, reject));
3313
- });
3314
- }
3315
- return new Promise((resolve, reject) => {
3316
- if (inFlight) {
3317
- (queue ??= []).push({ __proto__: null, type: 'next', value: undefined, resolve, reject });
3318
- } else {
3319
- resolve({ done: true, value: undefined });
3320
- }
3321
- });
3322
- },
3323
- return(value) {
3324
- return new Promise((resolve) => {
3325
- if (inFlight) {
3326
- (queue ??= []).push({ __proto__: null, type: 'return', value, resolve, reject: null });
3327
- } else {
3328
- processReturn(value, resolve);
3329
- }
3330
- });
3331
- },
3332
- throw(err) {
3333
- return new Promise((resolve, reject) => {
3334
- if (inFlight) {
3335
- (queue ??= []).push({ __proto__: null, type: 'throw', value: err, resolve, reject });
3336
- } else {
3337
- processThrow(err, reject);
3338
- }
3339
- });
3340
- }
3341
- };
3342
- // node's streamToAsyncIterator hangs the source on the iterator object
3343
- // (readable.js:1563-1565); measured raw.stream === rd on a live node.
3344
- iter.stream = stream;
3345
- return iter;
3346
- }
3347
-
3348
- // node's operators (internal/streams/operators). Each is a plain function or
3349
- // async function mirroring the original's argument shape, so the synchronous
3350
- // validation the transform family performs (measured: map('nope') throws
3351
- // ERR_INVALID_ARG_TYPE out of the call) and the rejection the promise family
3352
- // produces land exactly where node puts them.
3353
-
3354
- function opMap(stream, fn, options) {
3355
- validateFunctionArg(fn, 'fn');
3356
- validateOperatorOptions(options);
3357
- let concurrency = 1;
3358
- if (options?.concurrency != null) {
3359
- concurrency = Math.floor(options.concurrency);
3360
- }
3361
- let highWaterMark = concurrency - 1;
3362
- if (options?.highWaterMark != null) {
3363
- highWaterMark = Math.floor(options.highWaterMark);
3364
- }
3365
- if (!Number.isInteger(concurrency) || concurrency < 1) {
3366
- throw errorOf('ERR_OUT_OF_RANGE',
3367
- `The value of "options.concurrency" is out of range. It must be >= 1. Received ${concurrency}`);
3368
- }
3369
- if (!Number.isInteger(highWaterMark) || highWaterMark < 0) {
3370
- throw errorOf('ERR_OUT_OF_RANGE',
3371
- `The value of "options.highWaterMark" is out of range. It must be >= 0. Received ${highWaterMark}`);
3372
- }
3373
- highWaterMark += concurrency;
3374
- // node builds its always-present signal with AbortSignal.any([...]) --
3375
- // any([]) is a fresh never-aborted signal, which a never-aborted
3376
- // controller's signal is byte-equivalent to for everything the operator
3377
- // reads off it.
3378
- const signal = options?.signal ?? new AbortController().signal;
3379
-
3380
- return (async function* map() {
3381
- const queue = [];
3382
- const signalOpt = { signal };
3383
- let next = null;
3384
- let resume = null;
3385
- let done = false;
3386
- let cnt = 0;
3387
-
3388
- function onCatch() {
3389
- done = true;
3390
- afterItemProcessed();
3391
- }
3392
-
3393
- function afterItemProcessed() {
3394
- cnt -= 1;
3395
- maybeResume();
3396
- }
3397
-
3398
- function maybeResume() {
3399
- if (resume && !done && cnt < concurrency && queue.length < highWaterMark) {
3400
- const r = resume;
3401
- resume = null;
3402
- r();
3403
- }
3404
- }
3405
-
3406
- async function pump() {
3407
- try {
3408
- for await (let val of stream) {
3409
- if (done) {
3410
- return;
3411
- }
3412
- if (signal.aborted) {
3413
- throw abortError();
3414
- }
3415
- try {
3416
- val = fn(val, signalOpt);
3417
- if (val === kEmpty) {
3418
- continue;
3419
- }
3420
- val = Promise.resolve(val);
3421
- } catch (err) {
3422
- val = Promise.reject(err);
3423
- }
3424
- cnt += 1;
3425
- val.then(afterItemProcessed, onCatch);
3426
- queue.push(val);
3427
- if (next) {
3428
- const n = next;
3429
- next = null;
3430
- n();
3431
- }
3432
- if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) {
3433
- await new Promise((resolve) => {
3434
- resume = resolve;
3435
- });
3436
- }
3437
- }
3438
- queue.push(kEof);
3439
- } catch (err) {
3440
- const val = Promise.reject(err);
3441
- val.then(afterItemProcessed, onCatch);
3442
- queue.push(val);
3443
- } finally {
3444
- done = true;
3445
- if (next) {
3446
- const n = next;
3447
- next = null;
3448
- n();
3449
- }
3450
- }
3451
- }
3452
-
3453
- pump();
3454
-
3455
- try {
3456
- while (true) {
3457
- while (queue.length > 0) {
3458
- const val = await queue[0];
3459
- if (val === kEof) {
3460
- return;
3461
- }
3462
- if (signal.aborted) {
3463
- throw abortError();
3464
- }
3465
- if (val !== kEmpty) {
3466
- yield val;
3467
- }
3468
- queue.shift();
3469
- maybeResume();
3470
- }
3471
- await new Promise((resolve) => {
3472
- next = resolve;
3473
- });
3474
- }
3475
- } finally {
3476
- done = true;
3477
- if (resume) {
3478
- const r = resume;
3479
- resume = null;
3480
- r();
3481
- }
3482
- }
3483
- })();
3484
- }
3485
-
3486
- function opFilter(stream, fn, options) {
3487
- validateFunctionArg(fn, 'fn');
3488
- async function filterFn(value, opt) {
3489
- if (await fn(value, opt)) {
3490
- return value;
3491
- }
3492
- return kEmpty;
3493
- }
3494
- return opMap(stream, filterFn, options);
3495
- }
3496
-
3497
- async function opForEach(stream, fn, options) {
3498
- validateFunctionArg(fn, 'fn');
3499
- async function forEachFn(value, opt) {
3500
- await fn(value, opt);
3501
- return kEmpty;
3502
- }
3503
- // node drains the mapped generator with an empty for-await body. The same
3504
- // descent is spelled out here -- an fn error propagates out of the mapped
3505
- // generator's own body, so its cleanup runs at the throw point and no
3506
- // abrupt-close return() call from this loop would add anything.
3507
- const it = opMap(stream, forEachFn, options)[Symbol.asyncIterator]();
3508
- let res = await it.next();
3509
- while (!res.done) {
3510
- res = await it.next();
3511
- }
3512
- }
3513
-
3514
- function opFlatMap(stream, fn, options) {
3515
- const values = opMap(stream, fn, options);
3516
- return (async function* flatMap() {
3517
- for await (const val of values) {
3518
- yield* val;
3519
- }
3520
- })();
3521
- }
3522
-
3523
- function opDrop(stream, number, options) {
3524
- validateOperatorOptions(options);
3525
- const limit = toIntegerOrInfinity(number);
3526
- return (async function* drop() {
3527
- if (options?.signal?.aborted) {
3528
- throw abortError();
3529
- }
3530
- let numberLeft = limit;
3531
- for await (const val of stream) {
3532
- if (options?.signal?.aborted) {
3533
- throw abortError();
3534
- }
3535
- if (numberLeft-- <= 0) {
3536
- yield val;
3537
- }
3538
- }
3539
- })();
3540
- }
3541
-
3542
- function opTake(stream, number, options) {
3543
- validateOperatorOptions(options);
3544
- const limit = toIntegerOrInfinity(number);
3545
- return (async function* take() {
3546
- if (options?.signal?.aborted) {
3547
- throw abortError();
3548
- }
3549
- let numberLeft = limit;
3550
- for await (const val of stream) {
3551
- if (options?.signal?.aborted) {
3552
- throw abortError();
3553
- }
3554
- if (numberLeft-- > 0) {
3555
- yield val;
3556
- }
3557
- // Don't get another item from iterator in case we reached the end --
3558
- // node's comment; the return() this early exit triggers on the source
3559
- // iterator is what destroys a stream taken short of its EOF.
3560
- if (numberLeft <= 0) {
3561
- return;
3562
- }
3563
- }
3564
- })();
3565
- }
3566
-
3567
- async function opSome(stream, fn, options) {
3568
- for await (const unused of opFilter(stream, fn, options)) {
3569
- return true;
3570
- }
3571
- return false;
3572
- }
3573
-
3574
- async function opEvery(stream, fn, options) {
3575
- validateFunctionArg(fn, 'fn');
3576
- // https://en.wikipedia.org/wiki/De_Morgan%27s_laws -- node's comment.
3577
- return !(await opSome(stream, async (...args) => !(await fn(...args)), options));
3578
- }
3579
-
3580
- async function opFind(stream, fn, options) {
3581
- for await (const result of opFilter(stream, fn, options)) {
3582
- return result;
3583
- }
3584
- return undefined;
3585
- }
3586
-
3587
- async function opReduce(stream, hasInitial, reducer, initialValue, options) {
3588
- validateFunctionArg(reducer, 'reducer');
3589
- validateOperatorOptions(options);
3590
- if (options?.signal?.aborted) {
3591
- const err = abortError(options.signal.reason);
3592
- stream.once('error', () => {}); // the error is already propagated
3593
- // node awaits its internal eos, which RESOLVES on the errored teardown;
3594
- // the callback form wrapped here is that promise, since the public
3595
- // callback-less `finished` refuses instead.
3596
- await new Promise((resolve) => {
3597
- // h2lean's destroy() returns nothing, unlike node's, so the stream is
3598
- // handed to eos on its own line.
3599
- stream.destroy(err);
3600
- finished(stream, resolve);
3601
- });
3602
- throw err;
3603
- }
3604
- const ac = new AbortController();
3605
- const signal = ac.signal;
3606
- if (options?.signal) {
3607
- options.signal.addEventListener('abort', () => ac.abort(), { once: true });
3608
- }
3609
- let gotAnyItemFromStream = false;
3610
- try {
3611
- for await (const value of stream) {
3612
- gotAnyItemFromStream = true;
3613
- if (options?.signal?.aborted) {
3614
- throw abortError();
3615
- }
3616
- if (!hasInitial) {
3617
- initialValue = value;
3618
- hasInitial = true;
3619
- } else {
3620
- initialValue = await reducer(initialValue, value, { signal });
3621
- }
3622
- }
3623
- if (!gotAnyItemFromStream && !hasInitial) {
3624
- // node's ReduceAwareErrMissingArgs: same code, same custom message.
3625
- throw errorOf('ERR_MISSING_ARGS', 'Reduce of an empty stream requires an initial value');
3626
- }
3627
- } finally {
3628
- ac.abort();
3629
- }
3630
- return initialValue;
3631
- }
3632
-
3633
- async function opToArray(stream, options) {
3634
- validateOperatorOptions(options);
3635
- const result = [];
3636
- for await (const val of stream) {
3637
- if (options?.signal?.aborted) {
3638
- throw abortError(options.signal.reason);
3639
- }
3640
- result.push(val);
3641
- }
3642
- return result;
3643
- }
3644
-
3645
- // The error a stream reports when an RST_STREAM ends it, on either side. node's rule is
3646
- // one line (internal/http2/core.js:2543): `if (err == null && code !== NGHTTP2_NO_ERROR &&
3647
- // code !== NGHTTP2_CANCEL) err = new ERR_HTTP2_STREAM_ERROR(nameForErrorCode[code] || code)`.
3648
- // So a graceful reset (0) and a client abort (8) are NOT errors -- measured on a live node
3649
- // client and a live node server, both report only 'aborted'/'close' for those two codes --
3650
- // and every other code names itself in the message. h2lean used to answer every code with
3651
- // 'HTTP/2 stream error' on the client and with no error at all on the server.
3652
- function streamErrorOf(code) {
3653
- if (code === frames.NO_ERROR || code === frames.CANCEL) {
3654
- return null;
3655
- }
3656
- return errorOf('ERR_HTTP2_STREAM_ERROR',
3657
- `Stream closed with error code ${frames.ERROR_NAMES[code] || code}`);
3658
- }
3659
-
3660
- module.exports = { Http2Stream, errorOf, streamErrorOf, validateRstCode, emitNT, emitCloseNT, emitDrainNT };
2144
+ module.exports = { Http2ServerStream };