h2lean 0.8.1 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/stream.js CHANGED
@@ -57,8 +57,32 @@
57
57
  // the same pair in opposite orders, node's writable 'finish' before the frame pump
58
58
  // refuses the block and h2lean's half-close after it
59
59
  // (test/upstream/exceeds-server-trailer-size.test.js).
60
+ // * respondWithFD()/respondWithFile() send a file body straight from the descriptor:
61
+ // HEADERS are framed in the call (headersSent is true on return), then a chunked
62
+ // read/pump walk writes the body through write()/end() with normal backpressure, the
63
+ // same shape node's StreamPipe drives. statCheck (3-arg on the FD path, 2-arg on the
64
+ // file path) may rewrite 'content-length' in the prepared copy and may cancel by
65
+ // returning false; on the FD path cancelling leaves the descriptor open (the caller
66
+ // owns it), on the file path it is closed. Non-regular files refuse seek options and
67
+ // directories refuse outright (ERR_HTTP2_SEND_FILE / ERR_HTTP2_SEND_FILE_NOSEEK),
68
+ // as node's doSendFileFD does. Read and async errors destroy the stream with
69
+ // ERR_HTTP2_STREAM_ERROR(NGHTTP2_INTERNAL_ERROR) rather than throwing out of the call,
70
+ // matching node's buildNgHeaderString/processRespondWithFD teardown: a bad field name
71
+ // leaves headersSent true (node sets HEADERS_SENT before validating fields) and takes
72
+ // the destroy path. An array-form headers argument passes through hdr.block as-is
73
+ // instead of node's for..in over indices (which sends field names '0', '1', ...);
74
+ // the content-length statCheck injects is only applied to object-form headers.
75
+ // * 'finish' and writableFinished exist on the stream: 'finish' is queued on a
76
+ // nextTick once the writable half has ended with every octet accepted by the
77
+ // session (no queued DATA left), before any wantTrailers/close tick, and is never
78
+ // emitted for a stream destroyed before completion -- node's Writable semantics,
79
+ // measured on v26.12.1 (clean respondWithFD: finish after the pump completes, close
80
+ // with writableFinished true; abort after respondWithFD: only close, writableFinished
81
+ // false).
60
82
  'use strict';
61
83
 
84
+ const fs = require('node:fs');
85
+ const { inspect } = require('node:util');
62
86
  const { Stream, Writable } = require('node:stream');
63
87
  const { deprecate } = require('node:util');
64
88
  const frames = require('./frames');
@@ -117,10 +141,24 @@ function wantTrailersNT(stream) {
117
141
  // They were already going to run in the same tick drain, so folding them into
118
142
  // one callback only removes one TickObject per request.
119
143
  function emitEndCloseNT(target) {
144
+ target._closeDelivered = true;
145
+ // node clears the stream's session reference in _destroy, before any of the close
146
+ // events go out (internal/http2/core.js:2546) -- see _closeNow for why the drop waits
147
+ // for this tick here.
148
+ target.session = undefined;
120
149
  target.emit('end');
121
150
  target.emit('close');
122
151
  }
123
152
 
153
+ // The plain-close half of the same pair: 'close' for a stream whose both halves finished
154
+ // in one turn, with no 'end' owed. Marks the node-equivalent close moment -- see
155
+ // _closeDelivered above.
156
+ function emitCloseDeliveredNT(target) {
157
+ target._closeDelivered = true;
158
+ target.session = undefined;
159
+ target.emit('close');
160
+ }
161
+
124
162
  // The scheduled half of the unread-request auto-close -- see _maybeAutoClose
125
163
  // below for the rule and its measurement. The unread request half reports 'end'
126
164
  // here, before the 'close' _destroy schedules behind it: node's trace for the
@@ -134,6 +172,138 @@ function autoCloseNT(stream) {
134
172
  stream._destroy(NO_ERROR, undefined, true);
135
173
  }
136
174
 
175
+ // node's onFileUnpipe closes an owned descriptor without caring about the error; the
176
+ // same empty callback goes to every fs.close the file paths issue.
177
+ function noopClose() {}
178
+
179
+ // The read chunk of the file pump. node's StreamPipe sizes its reads internally; the
180
+ // boundaries are not wire-visible here (each read feeds write(), which frames DATA by
181
+ // maxFrameSize and the flow-control windows either way), so a plain 64 KiB read is used.
182
+ const FILE_CHUNK = 65536;
183
+
184
+ // node tests `fd instanceof fsPromisesInternal.FileHandle`, but node:fs/promises does
185
+ // not export the class (it lives behind --expose-internals), so a real handle is
186
+ // recognised by its constructor name and the numeric fd member: an fs.promises.open()
187
+ // instance passes, a plain { fd } object does not. A subclass or a same-named replica
188
+ // passes too, which is the same leniency node's instanceof shows to subclasses.
189
+ const isFileHandle = (v) =>
190
+ typeof v === 'object' && v !== null && typeof v.fd === 'number' &&
191
+ typeof v.close === 'function' && v.constructor != null &&
192
+ v.constructor.name === 'FileHandle';
193
+
194
+ // node's ERR_INVALID_ARG_TYPE received-tail (lib/internal/errors.js), measured against
195
+ // a live v26.12.1 respondWithFD: a named function renders `function ${name}` -- with
196
+ // the trailing space an anonymous one keeps --, instances name their constructor,
197
+ // primitives their typeof with the inspected value, null/undefined stand alone.
198
+ function receivedArgType(v) {
199
+ switch (typeof v) {
200
+ case 'function':
201
+ return `function ${v.name}`;
202
+ case 'object':
203
+ if (v === null) {
204
+ return 'null';
205
+ }
206
+ return v.constructor != null
207
+ ? `an instance of ${v.constructor.name}` : 'an object with null prototype';
208
+ case 'undefined':
209
+ return 'undefined';
210
+ case 'string':
211
+ return `type string (${inspect(v)})`;
212
+ case 'symbol':
213
+ return `type symbol (${String(v)})`;
214
+ default:
215
+ return `type ${typeof v} (${inspect(v)})`;
216
+ }
217
+ }
218
+
219
+ // The two TypeError shapes the argument guards raise, measured on the same binary:
220
+ // 'The "fd" argument must be of type number or an instance of FileHandle. Received ...'
221
+ // and `The property 'options.offset' is invalid. Received ${inspect(v)}`.
222
+ function argTypeError(msg, v) {
223
+ const err = new TypeError(`${msg} Received ${receivedArgType(v)}`);
224
+ err.code = 'ERR_INVALID_ARG_TYPE';
225
+ return err;
226
+ }
227
+
228
+ function propertyValueError(name, v) {
229
+ const err = new TypeError(
230
+ `The property 'options.${name}' is invalid. Received ${inspect(v)}`);
231
+ err.code = 'ERR_INVALID_ARG_VALUE';
232
+ return err;
233
+ }
234
+
235
+ // node's options guard (assertIsObject plus the explicit checks of respondWithFD,
236
+ // internal/http2/core.js): an undefined options is an empty one, null and primitives
237
+ // are refused, and -- measured -- an array is refused for options (unlike the headers
238
+ // argument). offset/length/statCheck keep node's `!== undefined` tests, so a null
239
+ // offset is refused exactly the way a string one is.
240
+ function fdOptions(options) {
241
+ if (options !== undefined &&
242
+ (options === null || typeof options !== 'object' || Array.isArray(options))) {
243
+ throw argTypeError('The "options" argument must be of type object.', options);
244
+ }
245
+ const opts = options === undefined ? {} : { ...options };
246
+ if (opts.offset !== undefined && typeof opts.offset !== 'number') {
247
+ throw propertyValueError('offset', opts.offset);
248
+ }
249
+ if (opts.length !== undefined && typeof opts.length !== 'number') {
250
+ throw propertyValueError('length', opts.length);
251
+ }
252
+ if (opts.statCheck !== undefined && typeof opts.statCheck !== 'function') {
253
+ throw propertyValueError('statCheck', opts.statCheck);
254
+ }
255
+ return opts;
256
+ }
257
+
258
+ // node's prepareResponseHeadersObject (internal/http2/core.js): a null-prototype copy
259
+ // of the caller's object with ':status' coerced in, so a statCheck that rewrites
260
+ // 'content-length' lands on the copy -- which is also what sentHeaders reports,
261
+ // exactly where node's kSentHeaders has it. The generated date is left to hdr.block,
262
+ // whose sendDate rule is the one prepare applies too. Status validation happens here,
263
+ // before the payload-forbidden check -- measured: ':status': 700 throws
264
+ // ERR_HTTP2_STATUS_INVALID out of the call, and ':status': '700' is coerced to 700
265
+ // first. The array form passes through untouched (hdr.block handles pairs natively);
266
+ // node's for..in over an array copies the index keys into the copy and sends field
267
+ // names '0', '1', ... instead -- the junk shape the header comment documents.
268
+ function prepareResponseHeadersObject(headersParam) {
269
+ if (headersParam !== undefined &&
270
+ (headersParam === null || typeof headersParam !== 'object')) {
271
+ throw argTypeError('The "headers" argument must be an instance of Array or Object.',
272
+ headersParam);
273
+ }
274
+ if (Array.isArray(headersParam)) {
275
+ return { headers: headersParam, statusCode: 0, isArray: true };
276
+ }
277
+ const copy = { __proto__: null };
278
+ let statusCode;
279
+ // node guards the copy on oldHeaders !== null && !== undefined (core.js): a missing
280
+ // headers argument is a valid response -- respondWithFD(fd) with no fields -- and an
281
+ // unguarded Object.keys would turn it into a session-killing TypeError
282
+ if (headersParam !== undefined && headersParam !== null) {
283
+ const keys = Object.keys(headersParam);
284
+ for (let i = 0; i < keys.length; i++) {
285
+ const key = keys[i];
286
+ copy[key] = headersParam[key];
287
+ if (key === ':status') {
288
+ statusCode = copy[key];
289
+ }
290
+ }
291
+ copy[hdr.KSensitiveHeaders] = headersParam[hdr.KSensitiveHeaders];
292
+ }
293
+ statusCode = copy[':status'] = (statusCode | 0) || 200;
294
+ if (statusCode < 200 || statusCode > 599) {
295
+ throw errorOf('ERR_HTTP2_STATUS_INVALID', `Invalid status code: ${statusCode}`);
296
+ }
297
+ const neverIndex = copy[hdr.KSensitiveHeaders];
298
+ if (neverIndex !== undefined && !Array.isArray(neverIndex)) {
299
+ const err = new TypeError(
300
+ `The property 'headers[http2.neverIndex]' is invalid. Received ${inspect(neverIndex)}`);
301
+ err.code = 'ERR_INVALID_ARG_VALUE';
302
+ throw err;
303
+ }
304
+ return { headers: copy, statusCode, isArray: false };
305
+ }
306
+
137
307
  const {
138
308
  ST_OPEN, ST_HALF_CLOSED_LOCAL, ST_HALF_CLOSED_REMOTE, ST_CLOSED, NO_ERROR, PROTOCOL_ERROR,
139
309
  INTERNAL_ERROR
@@ -179,6 +349,12 @@ class Http2Stream extends Stream {
179
349
  this._endQueued = false;
180
350
  this._corked = 0; // Writable cork count -- a stub, not a write buffer (see cork()/uncork())
181
351
  this._gracefulClose = false; // both halves closed on their own terms (_closeNow)
352
+ // node's closed/destroyed flip only when nghttp2 has actually closed the stream -- for
353
+ // a local end() that is when the send loop has carried the END_STREAM out, a tick after
354
+ // the call. h2lean flips its state inside the call (see _closeNow), so the flag marks
355
+ // the node-equivalent moment: the graceful close's event delivery. pushAllowed reads
356
+ // it to keep the same-turn window node keeps open.
357
+ this._closeDelivered = false;
182
358
  this._waitForTrailers = false;
183
359
  // node's `state.trailersReady` (internal/http2/core.js onStreamTrailers): the
184
360
  // permission to call sendTrailers(), granted by the 'wantTrailers' callback and
@@ -199,6 +375,22 @@ class Http2Stream extends Stream {
199
375
  // The compat layer's handler for this stream's events, or null when the
200
376
  // application uses the stream API. See emit() below.
201
377
  this._compatDispatch = null;
378
+ // node's `_writableState.ending`: the writable side has been told to end, whether
379
+ // or not the last octet has been accepted yet. It is what decides 'aborted' in
380
+ // node's closeStream (`if (!ending) emit('aborted')`), and the file paths set it
381
+ // EARLY -- node's processRespondWithFD calls self.end() before the pump starts --
382
+ // which is why a respondWithFD interrupted by a destroy reports no 'aborted'
383
+ // (measured: only 'close' with writableFinished false). _state.localClose does not
384
+ // cover that: it stays 0 until the pump reaches EOF.
385
+ this._ending = false;
386
+ // The writable-side finish state. 'finish' reports that every octet the
387
+ // application handed to this stream (body writes or a file pump) has been
388
+ // accepted by the session; writableFinished reads the flag set right
389
+ // before the event. Both stay false for a stream destroyed before
390
+ // completion (measured on v26.12.1: an abort after respondWithFD reports
391
+ // 'close' with writableFinished false and no 'finish').
392
+ this._writableFinished = false;
393
+ this._finishQueued = false;
202
394
  }
203
395
 
204
396
  get destroyed() {
@@ -265,8 +457,10 @@ class Http2Stream extends Stream {
265
457
  // off. Measured against a live node server: respond({':status':200}) carries a date,
266
458
  // respond({':status':204}) and 304 do too, and sendDate:false removes it.
267
459
  const sendDate = opts.sendDate == null ? true : !!opts.sendDate;
268
- const block = hdr.block(headers, opts.sensitiveHeaders,
269
- { sendDate }, this.session);
460
+ // node reads the never-indexed names only off the headers object's sensitiveHeaders
461
+ // symbol (buildNgHeaderString reads arrayOrMap[kSensitiveHeaders],
462
+ // internal/http2/util.js) -- there is no options.sensitiveHeaders for node to ignore.
463
+ const block = hdr.block(headers, { sendDate }, this.session);
270
464
  // Read the encoder's result slots before anything else can build a block: they are
271
465
  // what `sentHeaders` reports, so they have to be this response's, not a later one's.
272
466
  this._sentSrc = headers;
@@ -296,11 +490,293 @@ class Http2Stream extends Stream {
296
490
  // So the outstanding request for trailers is dropped instead of answered after the
297
491
  // stream is closed, and 'wantTrailers' is not emitted for a stream that cannot send.
298
492
  this._waitForTrailers = false;
493
+ this._ending = true;
299
494
  this._endLocalSide();
300
495
  }
301
496
  return this;
302
497
  }
303
498
 
499
+ // --- file responses (respondWithFD / respondWithFile) ---
500
+ //
501
+ // The step order below is node's respondWithFD (internal/http2/core.js), each guard
502
+ // measured against a live v26.12.1: stream guards, the options copy and its
503
+ // offset/length/statCheck checks, the waitForTrailers flag (before the fd is
504
+ // validated -- an invalid fd with waitForTrailers set still marks the stream for
505
+ // trailers), the fd argument itself, ownsFd = false, the prepared header copy, and
506
+ // the payload-forbidden statuses (204/205/304 and a HEAD request). respondWithFile
507
+ // is the same list with fs.open in front, ownsFd = true, and its own
508
+ // non-regular-file rules.
509
+ //
510
+ // A FileHandle instance is accepted wherever node accepts one; `this.ownsFd` is set
511
+ // unconditionally on each path -- node does the same, so an application that pre-set
512
+ // stream.ownsFd before respondWithFD has it clobbered there.
513
+
514
+ respondWithFD(fd, headers, options) {
515
+ if (this._destroyed || this.closed) {
516
+ throw errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed');
517
+ }
518
+ if (this.headersSent) {
519
+ throw errorOf('ERR_HTTP2_HEADERS_SENT', 'Response has already been initiated.');
520
+ }
521
+ const opts = fdOptions(options);
522
+ if (opts.waitForTrailers) {
523
+ this._waitForTrailers = true;
524
+ }
525
+ if (isFileHandle(fd)) {
526
+ fd = fd.fd;
527
+ } else if (typeof fd !== 'number') {
528
+ throw argTypeError(
529
+ 'The "fd" argument must be of type number or an instance of FileHandle.', fd);
530
+ }
531
+ this.ownsFd = false;
532
+ const sendDate = opts.sendDate == null ? true : !!opts.sendDate;
533
+ const { headers: prepared, statusCode } = prepareResponseHeadersObject(headers);
534
+ const head =
535
+ this._requestHeaders !== undefined && this._requestHeaders[':method'] === 'HEAD';
536
+ if (statusCode === 204 || statusCode === 205 || statusCode === 304 || head) {
537
+ throw errorOf('ERR_HTTP2_PAYLOAD_FORBIDDEN',
538
+ `Responses with ${statusCode} status must not have a payload`);
539
+ }
540
+ if (opts.statCheck !== undefined) {
541
+ // node's doSendFD: the statCheck sees (stat, headers-copy, statOptions) with
542
+ // statOptions defaulted to { offset: 0, length: -1 } -- on this path node never
543
+ // injects 'content-length' and never checks that the fd is a regular file; both
544
+ // are the application's job through the statCheck callback (which is exactly
545
+ // what upstream's test-http2-respond-file-fd-range.js does). Returning false
546
+ // cancels without touching the descriptor: on this path the application owns it.
547
+ fs.fstat(fd, (err, stat) => {
548
+ if (err) {
549
+ this.destroy(err);
550
+ return;
551
+ }
552
+ if (this._destroyed || this.closed) {
553
+ this.destroy(errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed'));
554
+ return;
555
+ }
556
+ const statOptions = {
557
+ offset: opts.offset !== undefined ? opts.offset : 0,
558
+ length: opts.length !== undefined ? opts.length : -1
559
+ };
560
+ if (opts.statCheck.call(this, stat, prepared, statOptions) === false ||
561
+ this.headersSent) {
562
+ return;
563
+ }
564
+ this._processRespondWithFD(fd, prepared, statOptions.offset | 0,
565
+ statOptions.length | 0, sendDate);
566
+ });
567
+ return;
568
+ }
569
+ this._processRespondWithFD(fd, prepared, opts.offset, opts.length, sendDate);
570
+ }
571
+
572
+ respondWithFile(path, headers, options) {
573
+ if (this._destroyed || this.closed) {
574
+ throw errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed');
575
+ }
576
+ if (this.headersSent) {
577
+ throw errorOf('ERR_HTTP2_HEADERS_SENT', 'Response has already been initiated.');
578
+ }
579
+ const opts = fdOptions(options);
580
+ if (opts.waitForTrailers) {
581
+ this._waitForTrailers = true;
582
+ }
583
+ this.ownsFd = true;
584
+ const sendDate = opts.sendDate == null ? true : !!opts.sendDate;
585
+ const { headers: prepared, statusCode, isArray } =
586
+ prepareResponseHeadersObject(headers);
587
+ const head =
588
+ this._requestHeaders !== undefined && this._requestHeaders[':method'] === 'HEAD';
589
+ if (statusCode === 204 || statusCode === 205 || statusCode === 304 || head) {
590
+ throw errorOf('ERR_HTTP2_PAYLOAD_FORBIDDEN',
591
+ `Responses with ${statusCode} status must not have a payload`);
592
+ }
593
+ fs.open(path, 'r', (err, fd) => {
594
+ const onError = typeof opts.onError === 'function' ? opts.onError : null;
595
+ if (err) {
596
+ if (onError) {
597
+ onError(err);
598
+ } else {
599
+ this.destroy(err);
600
+ }
601
+ return;
602
+ }
603
+ if (this._destroyed || this.closed) {
604
+ fs.close(fd, noopClose);
605
+ return;
606
+ }
607
+ fs.fstat(fd, (err2, stat) => {
608
+ if (err2) {
609
+ fs.close(fd, noopClose);
610
+ if (onError) {
611
+ onError(err2);
612
+ } else {
613
+ this.destroy(err2);
614
+ }
615
+ return;
616
+ }
617
+ // node's doSendFileFD: for a non-regular file, any seek option at all (or a
618
+ // directory) is refused -- with the descriptor closed either way, and the
619
+ // error routed through options.onError when the application gave one. A
620
+ // non-regular file that survives the check gets node's unseekable sentinel
621
+ // (-1, -1) in the copy; note node's `!== undefined || > 0` pair, kept as
622
+ // measured.
623
+ if (!stat.isFile()) {
624
+ const isDirectory = stat.isDirectory();
625
+ if ((opts.offset !== undefined || opts.offset > 0) ||
626
+ (opts.length !== undefined || opts.length >= 0) || isDirectory) {
627
+ fs.close(fd, noopClose);
628
+ const e = isDirectory
629
+ ? errorOf('ERR_HTTP2_SEND_FILE', 'Directories cannot be sent')
630
+ : errorOf('ERR_HTTP2_SEND_FILE_NOSEEK',
631
+ 'Offset or length can only be specified for regular files');
632
+ if (onError) {
633
+ onError(e);
634
+ } else {
635
+ this.destroy(e);
636
+ }
637
+ return;
638
+ }
639
+ opts.offset = -1;
640
+ opts.length = -1;
641
+ }
642
+ if (this._destroyed || this.closed) {
643
+ fs.close(fd, noopClose);
644
+ this.destroy(errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed'));
645
+ return;
646
+ }
647
+ const statOptions = {
648
+ offset: opts.offset !== undefined ? opts.offset : 0,
649
+ length: opts.length !== undefined ? opts.length : -1
650
+ };
651
+ if ((typeof opts.statCheck === 'function' &&
652
+ opts.statCheck.call(this, stat, prepared) === false) || this.headersSent) {
653
+ // on this path the stack owns the descriptor: a cancelled statCheck closes it
654
+ fs.close(fd, noopClose);
655
+ return;
656
+ }
657
+ if (stat.isFile()) {
658
+ statOptions.length = statOptions.length < 0
659
+ ? stat.size - (+statOptions.offset)
660
+ : Math.min(stat.size - (+statOptions.offset), statOptions.length);
661
+ if (!isArray) {
662
+ prepared['content-length'] = statOptions.length;
663
+ }
664
+ }
665
+ // node passes options.offset (post-mutation), not statOptions.offset
666
+ this._processRespondWithFD(fd, prepared, opts.offset | 0,
667
+ statOptions.length | 0, sendDate);
668
+ });
669
+ });
670
+ }
671
+
672
+ // node's processRespondWithFD: the HEADERS_SENT flag goes up BEFORE the fields are
673
+ // validated, so a bad field name leaves headersSent true and takes the destroy path
674
+ // below -- measured, the call does not throw. node also calls self.end() here --
675
+ // the writable is "ending" from this turn on, which is why an interrupted file
676
+ // pipe reports no 'aborted' -- while the END_STREAM itself waits for the pump's
677
+ // EOF. The prepared copy is what sentHeaders reports (node's kSentHeaders = the
678
+ // copy), and the encoding error and a refused block both leave the descriptor
679
+ // with its owner.
680
+ _processRespondWithFD(fd, prepared, offset, length, sendDate) {
681
+ this.headersSent = true;
682
+ this.pending = false;
683
+ this._ending = true;
684
+ let block;
685
+ try {
686
+ block = hdr.block(prepared, { sendDate }, this.session);
687
+ } catch (err) {
688
+ if (this.ownsFd) {
689
+ fs.close(fd, noopClose);
690
+ }
691
+ this.destroy(err);
692
+ return;
693
+ }
694
+ this._sentSrc = prepared;
695
+ this._sentStatus = hdr.sent.status;
696
+ this._sentDate = hdr.sent.date;
697
+ const bound = hdr.sent.bound;
698
+ if (this._blockRefused || this.session.sendHeaders(this.id, block, false, bound)) {
699
+ this._blockRefused = true;
700
+ // node has already called self.end() by this point (processRespondWithFD ends
701
+ // the writable before the wire write), so the half-close happens even here.
702
+ this._endLocalSide();
703
+ return;
704
+ }
705
+ this._startFilePipe(fd, offset, length);
706
+ }
707
+
708
+ // node's startFilePipe: read the descriptor in chunks and hand each to the writable
709
+ // side, end at EOF, honour the write path's backpressure; teardown closes an owned
710
+ // descriptor (node's onFileUnpipe), and a read error other than EOF raises
711
+ // NGHTTP2_INTERNAL_ERROR on the stream -- the client then reports
712
+ // ERR_HTTP2_STREAM_ERROR with that rstCode, the shape upstream's
713
+ // test-http2-respond-file-fd-invalid.js pins. The reads go through write()/end(),
714
+ // so credit, the outbound batch and the session hold behave exactly as for a body
715
+ // written by hand.
716
+ _startFilePipe(fd, offset, length) {
717
+ const pump = {
718
+ remaining: length === undefined || length < 0 ? Infinity : length,
719
+ position: offset === undefined || offset < 0 ? -1 : offset,
720
+ stopped: false
721
+ };
722
+ this.once('close', () => {
723
+ pump.stopped = true;
724
+ if (this.ownsFd) {
725
+ fs.close(fd, noopClose);
726
+ }
727
+ });
728
+ const step = () => {
729
+ if (pump.stopped || this._destroyed) {
730
+ return;
731
+ }
732
+ const want = Math.min(FILE_CHUNK, pump.remaining);
733
+ const buf = Buffer.allocUnsafe(want);
734
+ const pos = pump.position < 0 ? null : pump.position;
735
+ fs.read(fd, buf, 0, want, pos, (err, n) => {
736
+ if (pump.stopped || this._destroyed) {
737
+ return;
738
+ }
739
+ if (err && err.code !== 'EOF') {
740
+ this.destroy(streamErrorOf(frames.INTERNAL_ERROR));
741
+ return;
742
+ }
743
+ if (n === 0) {
744
+ this._pumpEnd();
745
+ return;
746
+ }
747
+ pump.remaining -= n;
748
+ if (pump.position >= 0) {
749
+ pump.position += n;
750
+ }
751
+ const view = n === want ? buf : buf.subarray(0, n);
752
+ if (this.write(view)) {
753
+ if (pump.remaining > 0) {
754
+ step();
755
+ } else {
756
+ this._pumpEnd();
757
+ }
758
+ } else {
759
+ this.once('drain', step);
760
+ }
761
+ });
762
+ };
763
+ step();
764
+ }
765
+
766
+ // The file pump's EOF. node's pump never runs Writable.end: StreamPipe writes into
767
+ // the nghttp2 handle directly (core.js startFilePipe), the writable side was closed
768
+ // in processRespondWithFD (`self._final = null; self.end()`) and the application's
769
+ // end() is the no-op Writable.end() is on an ended stream. h2lean's pump shares the
770
+ // application's write()/sendData path, so its EOF mirrors end()'s body without the
771
+ // ended-guard, and the same waitForTrailers split applies.
772
+ _pumpEnd() {
773
+ const oweTrailers = this._waitForTrailers;
774
+ this.session.sendData(this, EMPTY, !oweTrailers);
775
+ if (oweTrailers) {
776
+ this._endLocalSide();
777
+ }
778
+ }
779
+
304
780
  write(chunk, encoding, cb) {
305
781
  if (typeof encoding === 'function') {
306
782
  cb = encoding; encoding = undefined;
@@ -353,17 +829,25 @@ class Http2Stream extends Stream {
353
829
  } else if (typeof encoding === 'function') {
354
830
  cb = encoding; encoding = null;
355
831
  }
356
- if (this._endQueued || this._state.localClose === 1) {
832
+ if (this._endQueued || this._ending || this._state.localClose === 1) {
357
833
  // node: Writable.end() on an ended writable is a no-op that still answers
358
834
  // the callback (internal/streams/writable.js end() -> writableEnded checks;
359
835
  // measured v26.12.1: respond() on a HEAD request ends the writable itself,
360
836
  // and the application's end() after it neither errors nor destroys).
361
- // write() after end IS the error -- see write() above.
837
+ // The same state is what respondWithFD leaves: node's processRespondWithFD
838
+ // closes the writable before the pump starts (`self._final = null; self.end()`,
839
+ // core.js), so the application's end() after it is the no-op and the pump's
840
+ // EOF goes out through the pipe, not through end(). h2lean's pump reaches for
841
+ // _pumpEnd() for exactly that reason; write() after end IS the error -- see
842
+ // write() above.
362
843
  if (cb) {
363
844
  process.nextTick(cb);
364
845
  }
365
846
  return this;
366
847
  }
848
+ // node's Writable.end flips _writableState.ending here, before anything is sent
849
+ // -- even when the body is still parked on window credit. 'aborted' reads it.
850
+ this._ending = true;
367
851
  if (!this.headersSent) {
368
852
  // A body takes the auto-respond of write() above; an empty end() is where h2lean and node
369
853
  // part company, and the split is written down in AGENTS.md section 10: node puts NOTHING on
@@ -424,6 +908,10 @@ class Http2Stream extends Stream {
424
908
  return WRITABLE_HWM;
425
909
  }
426
910
 
911
+ get writableFinished() {
912
+ return this._writableFinished;
913
+ }
914
+
427
915
  sendTrailers(trailers) {
428
916
  // node's three guards, in node's order, and all three as synchronous throws --
429
917
  // not emitted errors (internal/http2/core.js Http2Stream.sendTrailers). Measured
@@ -443,7 +931,7 @@ class Http2Stream extends Stream {
443
931
  throw errorOf('ERR_HTTP2_TRAILERS_NOT_READY',
444
932
  'Trailing headers cannot be sent until after the wantTrailers event is emitted');
445
933
  }
446
- const block = hdr.block(trailers, undefined, { trailer: true }, this.session);
934
+ const block = hdr.block(trailers, { trailer: true }, this.session);
447
935
  const bound = hdr.sent.bound;
448
936
  // node records a null-prototype copy, not the caller's map (`ObjectAssign({
449
937
  // __proto__: null }, headers)`, internal/http2/core.js sendTrailers -- the shared
@@ -508,7 +996,7 @@ class Http2Stream extends Stream {
508
996
  }
509
997
  // `{ info: true }` is node's separate rule for these blocks: :status must be 100..199
510
998
  // (101 has its own error), there is no default status and no generated date.
511
- const block = hdr.block(headers, undefined, { info: true }, this.session);
999
+ const block = hdr.block(headers, { info: true }, this.session);
512
1000
  const bound = hdr.sent.bound;
513
1001
  this.sentInfoHeaders.push(headers);
514
1002
  this.session.sendHeaders(this.id, block, false, bound);
@@ -531,8 +1019,19 @@ class Http2Stream extends Stream {
531
1019
  // the server may push. Measured on v26.12.1: a client with settings:{enablePush:false}
532
1020
  // makes pushAllowed false and pushStream throw ERR_HTTP2_PUSH_DISABLED synchronously.
533
1021
  get pushAllowed() {
534
- return !this._destroyed && !this.closed && !this.session.closed
535
- && !this.session.destroyed && !!this.session.remoteSettings.enablePush;
1022
+ // node's ServerHttp2Stream.pushAllowed (core.js) reads the same terms, but node's
1023
+ // stream reaches `closed` only when nghttp2 has actually closed it -- for a local
1024
+ // end() that is the send-loop turn after the call, so a pushStream in the same turn
1025
+ // still sees a live stream (upstream's respond({})/end()/pushStream() shape,
1026
+ // test/upstream/respond-file-push.test.js). h2lean frames END_STREAM inside the call
1027
+ // and flips closed/destroyed there, a tick earlier than node, so a graceful close
1028
+ // whose event has not been delivered yet still counts as open. A peer reset has no
1029
+ // such window: node's nghttp2 closes that stream inside the read batch.
1030
+ if (this._destroyed) {
1031
+ return this._gracefulClose && !this._closeDelivered;
1032
+ }
1033
+ return !this.closed && !this.session.closed && !this.session.destroyed
1034
+ && !!this.session.remoteSettings.enablePush;
536
1035
  }
537
1036
 
538
1037
  // node: ServerHttp2Stream.pushStream (internal/http2/core.js:2971).
@@ -604,7 +1103,9 @@ class Http2Stream extends Stream {
604
1103
 
605
1104
  // Validation errors are synchronous in node (buildNgHeaderString throws before
606
1105
  // the frame is submitted). The id was already reserved; it stays consumed.
607
- const block = hdr.pushBlock(h, options.sensitiveHeaders, this.session);
1106
+ // Like respond(), the never-indexed names come only off the headers object's
1107
+ // sensitiveHeaders symbol -- node's pushStream has no options.sensitiveHeaders.
1108
+ const block = hdr.pushBlock(h, this.session);
608
1109
  const refused = this.session.sendPushPromise(this.id, promisedId, block, hdr.sent.bound);
609
1110
 
610
1111
  // Create the pushed stream and register it. The readable side is pre-ended:
@@ -717,6 +1218,35 @@ class Http2Stream extends Stream {
717
1218
  process.nextTick(emitNT, this, 'end');
718
1219
  }
719
1220
 
1221
+ // The writable-side 'finish' -- node's Writable fires it once every write has been
1222
+ // accepted by the stream machinery and the writable half has ended; a destroy in
1223
+ // the same turn as the end() cancels it (upstream's test-http2-respond-with-fd-finish.js
1224
+ // pins both shapes: finish, then close with writableFinished true on a clean send;
1225
+ // close with writableFinished false and no 'finish' on an abort). The tick is also
1226
+ // what keeps the event behind 'wantTrailers' -- measured on v26.12.1, 'finish'
1227
+ // precedes 'wantTrailers' on the trailers shape. A body still queued on window
1228
+ // credit re-runs _endLocalSide when the queue drains (session._release), which is
1229
+ // where the second scheduling comes from.
1230
+ _scheduleFinish() {
1231
+ if (this._writableFinished || this._finishQueued) {
1232
+ return;
1233
+ }
1234
+ this._finishQueued = true;
1235
+ process.nextTick(() => {
1236
+ this._finishQueued = false;
1237
+ // not _destroyed here: a stream whose both halves close in the same turn the
1238
+ // writable ends flips ST_CLOSED synchronously (_closeNow) while the close EVENTS
1239
+ // are deferred -- and node's order for that shape is 'finish' before 'close',
1240
+ // with writableFinished true at the close (measured). The only cancel is a
1241
+ // writable that never drained: octets still parked on window credit.
1242
+ if (this._writableFinished || this._queued !== null) {
1243
+ return;
1244
+ }
1245
+ this._writableFinished = true;
1246
+ this.emit('finish');
1247
+ });
1248
+ }
1249
+
720
1250
  _endLocalSide() {
721
1251
  const first = this._state.localClose !== 1;
722
1252
  this._state.localClose = 1;
@@ -729,6 +1259,11 @@ class Http2Stream extends Stream {
729
1259
  // schedules -- measured, node reports rstCode 6 for this shape and h2lean reported 0.
730
1260
  return;
731
1261
  }
1262
+ if (this._queued === null) {
1263
+ // every octet handed over has been accepted by the session: node's condition
1264
+ // for the writable 'finish'
1265
+ this._scheduleFinish();
1266
+ }
732
1267
  if (this._state.state === ST_OPEN) {
733
1268
  this._state.state = ST_HALF_CLOSED_LOCAL;
734
1269
  }
@@ -796,7 +1331,7 @@ class Http2Stream extends Stream {
796
1331
  process.nextTick(emitEndCloseNT, this);
797
1332
  return;
798
1333
  }
799
- process.nextTick(emitNT, this, 'close');
1334
+ process.nextTick(emitCloseDeliveredNT, this);
800
1335
  }
801
1336
 
802
1337
  _closeNow() {
@@ -805,9 +1340,13 @@ class Http2Stream extends Stream {
805
1340
  this._gracefulClose = true;
806
1341
  this._pending = null;
807
1342
  this.session._dropStream(this, false);
808
- // node drops the session reference when the stream dies
809
- // (Http2Stream._destroy: `this[kSession] = undefined`, internal/http2/core.js:2546).
810
- this.session = undefined;
1343
+ // node drops the stream's session reference in _destroy (internal/http2/core.js:2546,
1344
+ // `this[kSession] = undefined`) -- which for node runs only when nghttp2 closes the
1345
+ // stream, a tick after the end() that queued this close. The drop therefore moves to
1346
+ // the close-delivery tick (emitEndCloseNT/emitCloseDeliveredNT), keeping the
1347
+ // same-turn window live for pushStream exactly as node's window is. The _destroy path
1348
+ // (a peer reset) keeps its own synchronous drop -- node's nghttp2 closes that stream
1349
+ // inside the read batch.
811
1350
  }
812
1351
 
813
1352
  _destroy(code, reason, sendRst, err) {
@@ -816,13 +1355,16 @@ class Http2Stream extends Stream {
816
1355
  }
817
1356
  this._destroyed = true;
818
1357
  this.rstCode = code;
819
- // node's rule for 'aborted' is about the RESPONSE, not about the request:
820
- // "if the writable side of the Http2Stream is still open, emit the 'aborted'
821
- // event" (internal/http2/core.js, closeStream). Measured against a live node
822
- // server: a peer that resets a stream whose request has already ended but
823
- // whose response never started does report 'aborted', and a peer that resets
824
- // a stream whose response was ended does not.
825
- const responseOpen = this._state.localClose !== 1;
1358
+ // node's rule for 'aborted' is about the WRITABLE side: "if the writable side of
1359
+ // the Http2Stream is still open, emit the 'aborted' event" -- closeStream's
1360
+ // `const { ending } = stream._writableState; if (!ending) ...`. The same shapes
1361
+ // measured against a live node server: a peer that resets a stream whose response
1362
+ // never started and whose end() never ran reports 'aborted'; a stream whose
1363
+ // writable ended -- by end(), by a file pump (node's processRespondWithFD calls
1364
+ // self.end() before the pump) -- does not, even when the octets are still in
1365
+ // flight. _ending is the portable reading of `ending`; _state.localClose would
1366
+ // answer the file paths wrong.
1367
+ const responseOpen = !this._ending;
826
1368
  this._state.localClose = 1;
827
1369
  this._state.state = ST_CLOSED;
828
1370
  if (sendRst && this.session._open) {