h2lean 0.8.1 → 0.10.0
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/client-session.js +120 -45
- package/lib/headers.js +7 -7
- package/lib/hpack.js +15 -0
- package/lib/server.js +27 -7
- package/lib/session.js +114 -8
- package/lib/stream.js +2500 -129
- package/package.json +1 -1
package/lib/stream.js
CHANGED
|
@@ -6,19 +6,23 @@
|
|
|
6
6
|
// extends Duplex (internal/http2/core.js:2128), but the part of that surface real code reaches
|
|
7
7
|
// for is pipe() on the readable half, and the Duplex machinery behind it -- two state objects
|
|
8
8
|
// plus the nextTick read loop -- is what OPTIMIZATION.md item 41 measured as ~+1.4 us/req
|
|
9
|
-
// against the EventEmitter arm.
|
|
10
|
-
//
|
|
11
|
-
//
|
|
9
|
+
// against the EventEmitter arm. h2lean therefore carries the Duplex SURFACE as methods and
|
|
10
|
+
// getters over the hand-rolled core: pipe() is not the legacy Stream.prototype.pipe but
|
|
11
|
+
// node's Readable.prototype.pipe reimplemented on this base (tracked destinations,
|
|
12
|
+
// unpipe(), the destroy-time EOF that ends and unpipes the dest -- test/pipe-parity.test.js),
|
|
13
|
+
// and read()/push()/setEncoding() are node's readable pull surface with the same
|
|
14
|
+
// member-by-member derivation (test/duplex-surface.test.js), and so is the async
|
|
15
|
+
// iteration surface -- [Symbol.asyncIterator], iterator(), the operator helpers and
|
|
16
|
+
// compose() -- ported member-by-member from node v26's createAsyncIterator,
|
|
17
|
+
// operators.js and compose.js; web streams are refused by compose() where node
|
|
18
|
+
// composes them; writev() is absent because
|
|
19
|
+
// node itself throws TypeError on it here, and cork()/uncork() and the
|
|
20
|
+
// writableCorked/writableHighWaterMark getters are present as a counting stub:
|
|
12
21
|
// node's Writable cork buffers write()/end() and defers the DATA until corked reaches 0
|
|
13
22
|
// (measured on v26.12.1: write('AAA') while corked leaves writableLength 3 and the peer
|
|
14
23
|
// receives nothing until the second uncork), while h2lean writes straight through -- its
|
|
15
24
|
// per-read socket batch already coalesces a synchronous burst, so only the cross-tick
|
|
16
|
-
// deferral differs. KNOWN DIVERGENCE, pinned in test/cork-parity.test.js.
|
|
17
|
-
// Duplex surface -- unpipe(), read(), writev() and the readable/writable/writableLength
|
|
18
|
-
// state getters -- is still absent (AGENTS.md section 10). The one behavioural difference the
|
|
19
|
-
// bare base leaves is pipe teardown: legacy Stream.prototype.pipe ends the dest only on the
|
|
20
|
-
// source 'end', so a stream destroyed mid-pipe leaves the dest without the 'finish'/'unpipe'
|
|
21
|
-
// node's Duplex pipe emits. Measured and pinned in test/pipe-parity.test.js.
|
|
25
|
+
// deferral differs. KNOWN DIVERGENCE, pinned in test/cork-parity.test.js.
|
|
22
26
|
// * the read side releases flow-control credit as the application takes the
|
|
23
27
|
// bytes. With no reader the peer's window stays shut, so an unread body
|
|
24
28
|
// costs the sender instead of our heap; data that arrives before anyone is
|
|
@@ -57,10 +61,36 @@
|
|
|
57
61
|
// the same pair in opposite orders, node's writable 'finish' before the frame pump
|
|
58
62
|
// refuses the block and h2lean's half-close after it
|
|
59
63
|
// (test/upstream/exceeds-server-trailer-size.test.js).
|
|
64
|
+
// * respondWithFD()/respondWithFile() send a file body straight from the descriptor:
|
|
65
|
+
// HEADERS are framed in the call (headersSent is true on return), then a chunked
|
|
66
|
+
// read/pump walk writes the body through write()/end() with normal backpressure, the
|
|
67
|
+
// same shape node's StreamPipe drives. statCheck (3-arg on the FD path, 2-arg on the
|
|
68
|
+
// file path) may rewrite 'content-length' in the prepared copy and may cancel by
|
|
69
|
+
// returning false; on the FD path cancelling leaves the descriptor open (the caller
|
|
70
|
+
// owns it), on the file path it is closed. Non-regular files refuse seek options and
|
|
71
|
+
// directories refuse outright (ERR_HTTP2_SEND_FILE / ERR_HTTP2_SEND_FILE_NOSEEK),
|
|
72
|
+
// as node's doSendFileFD does. Read and async errors destroy the stream with
|
|
73
|
+
// ERR_HTTP2_STREAM_ERROR(NGHTTP2_INTERNAL_ERROR) rather than throwing out of the call,
|
|
74
|
+
// matching node's buildNgHeaderString/processRespondWithFD teardown: a bad field name
|
|
75
|
+
// leaves headersSent true (node sets HEADERS_SENT before validating fields) and takes
|
|
76
|
+
// the destroy path. An array-form headers argument passes through hdr.block as-is
|
|
77
|
+
// instead of node's for..in over indices (which sends field names '0', '1', ...);
|
|
78
|
+
// the content-length statCheck injects is only applied to object-form headers.
|
|
79
|
+
// * 'finish' and writableFinished exist on the stream: 'finish' is queued on a
|
|
80
|
+
// nextTick once the writable half has ended with every octet accepted by the
|
|
81
|
+
// session (no queued DATA left), before any wantTrailers/close tick, and is never
|
|
82
|
+
// emitted for a stream destroyed before completion -- node's Writable semantics,
|
|
83
|
+
// measured on v26.12.1 (clean respondWithFD: finish after the pump completes, close
|
|
84
|
+
// with writableFinished true; abort after respondWithFD: only close, writableFinished
|
|
85
|
+
// false).
|
|
60
86
|
'use strict';
|
|
61
87
|
|
|
62
|
-
const
|
|
88
|
+
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');
|
|
63
92
|
const { deprecate } = require('node:util');
|
|
93
|
+
const { StringDecoder } = require('node:string_decoder');
|
|
64
94
|
const frames = require('./frames');
|
|
65
95
|
const hdr = require('./headers');
|
|
66
96
|
|
|
@@ -73,6 +103,12 @@ const EMPTY = Buffer.alloc(0);
|
|
|
73
103
|
// stream's writableHighWaterMark on v26.12.1.
|
|
74
104
|
const WRITABLE_HWM = new Writable().writableHighWaterMark;
|
|
75
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
|
+
|
|
76
112
|
// process.nextTick(fn, args) instead of an arrow closure per event: the arrow
|
|
77
113
|
// allocated a new function object for every request, and in the compat layer
|
|
78
114
|
// that showed up as GC time.
|
|
@@ -85,10 +121,35 @@ function emitNT(target, name, arg) {
|
|
|
85
121
|
}
|
|
86
122
|
|
|
87
123
|
function emitErrorCloseNT(target, err) {
|
|
124
|
+
target._errorEmitted = true;
|
|
125
|
+
target._streamErrored = err;
|
|
88
126
|
target.emit('error', err);
|
|
89
127
|
target.emit('close');
|
|
90
128
|
}
|
|
91
129
|
|
|
130
|
+
// The 'error' of the write-after-end shape: emitted on a stream that closes by itself
|
|
131
|
+
// a moment later, so 'close' is NOT this helper's job -- but the Duplex getters read the
|
|
132
|
+
// same two slots, and node's errorOrDestroy fills state.errored BEFORE the event, not at
|
|
133
|
+
// the emit (destroy.js checkError). Same moment here: the nextTick that carries the
|
|
134
|
+
// event is the nextTick that ran the flag set in emitErrorCloseNT anyway.
|
|
135
|
+
function emitErrorOnlyNT(target, err) {
|
|
136
|
+
target._errorEmitted = true;
|
|
137
|
+
if (target._streamErrored === undefined) {
|
|
138
|
+
target._streamErrored = err;
|
|
139
|
+
}
|
|
140
|
+
target.emit('error', err);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// 'end' with the Duplex bookkeeping: readableEnded/buffer-free readable read node's
|
|
144
|
+
// endEmitted bit, and the bit flips at the delivery, not at the schedule.
|
|
145
|
+
function emitEndNT(target) {
|
|
146
|
+
if (target._eofEmitted === true) {
|
|
147
|
+
return; // the 'end' of a Duplex is once-only; the drain paths can re-arm it
|
|
148
|
+
}
|
|
149
|
+
target._eofEmitted = true;
|
|
150
|
+
target.emit('end');
|
|
151
|
+
}
|
|
152
|
+
|
|
92
153
|
// node's onStreamTrailers (internal/http2/core.js), the callback nghttp2 runs when the
|
|
93
154
|
// writable half of a stream that asked for trailers finishes. Two parts of it are easy
|
|
94
155
|
// to lose: `trailersReady` is set before the destroyed/closed check (so a stream that is
|
|
@@ -117,7 +178,24 @@ function wantTrailersNT(stream) {
|
|
|
117
178
|
// They were already going to run in the same tick drain, so folding them into
|
|
118
179
|
// one callback only removes one TickObject per request.
|
|
119
180
|
function emitEndCloseNT(target) {
|
|
120
|
-
target.
|
|
181
|
+
target._closeDelivered = true;
|
|
182
|
+
// node clears the stream's session reference in _destroy, before any of the close
|
|
183
|
+
// events go out (internal/http2/core.js:2546) -- see _closeNow for why the drop waits
|
|
184
|
+
// for this tick here.
|
|
185
|
+
target.session = undefined;
|
|
186
|
+
if (target._eofEmitted !== true) {
|
|
187
|
+
target._eofEmitted = true;
|
|
188
|
+
target.emit('end');
|
|
189
|
+
}
|
|
190
|
+
target.emit('close');
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// The plain-close half of the same pair: 'close' for a stream whose both halves finished
|
|
194
|
+
// in one turn, with no 'end' owed. Marks the node-equivalent close moment -- see
|
|
195
|
+
// _closeDelivered above.
|
|
196
|
+
function emitCloseDeliveredNT(target) {
|
|
197
|
+
target._closeDelivered = true;
|
|
198
|
+
target.session = undefined;
|
|
121
199
|
target.emit('close');
|
|
122
200
|
}
|
|
123
201
|
|
|
@@ -130,10 +208,142 @@ function autoCloseNT(stream) {
|
|
|
130
208
|
if (stream._destroyed) {
|
|
131
209
|
return;
|
|
132
210
|
}
|
|
133
|
-
process.nextTick(
|
|
211
|
+
process.nextTick(emitEndNT, stream);
|
|
134
212
|
stream._destroy(NO_ERROR, undefined, true);
|
|
135
213
|
}
|
|
136
214
|
|
|
215
|
+
// node's onFileUnpipe closes an owned descriptor without caring about the error; the
|
|
216
|
+
// same empty callback goes to every fs.close the file paths issue.
|
|
217
|
+
function noopClose() {}
|
|
218
|
+
|
|
219
|
+
// The read chunk of the file pump. node's StreamPipe sizes its reads internally; the
|
|
220
|
+
// boundaries are not wire-visible here (each read feeds write(), which frames DATA by
|
|
221
|
+
// maxFrameSize and the flow-control windows either way), so a plain 64 KiB read is used.
|
|
222
|
+
const FILE_CHUNK = 65536;
|
|
223
|
+
|
|
224
|
+
// node tests `fd instanceof fsPromisesInternal.FileHandle`, but node:fs/promises does
|
|
225
|
+
// not export the class (it lives behind --expose-internals), so a real handle is
|
|
226
|
+
// recognised by its constructor name and the numeric fd member: an fs.promises.open()
|
|
227
|
+
// instance passes, a plain { fd } object does not. A subclass or a same-named replica
|
|
228
|
+
// passes too, which is the same leniency node's instanceof shows to subclasses.
|
|
229
|
+
const isFileHandle = (v) =>
|
|
230
|
+
typeof v === 'object' && v !== null && typeof v.fd === 'number' &&
|
|
231
|
+
typeof v.close === 'function' && v.constructor != null &&
|
|
232
|
+
v.constructor.name === 'FileHandle';
|
|
233
|
+
|
|
234
|
+
// node's ERR_INVALID_ARG_TYPE received-tail (lib/internal/errors.js), measured against
|
|
235
|
+
// a live v26.12.1 respondWithFD: a named function renders `function ${name}` -- with
|
|
236
|
+
// the trailing space an anonymous one keeps --, instances name their constructor,
|
|
237
|
+
// primitives their typeof with the inspected value, null/undefined stand alone.
|
|
238
|
+
function receivedArgType(v) {
|
|
239
|
+
switch (typeof v) {
|
|
240
|
+
case 'function':
|
|
241
|
+
return `function ${v.name}`;
|
|
242
|
+
case 'object':
|
|
243
|
+
if (v === null) {
|
|
244
|
+
return 'null';
|
|
245
|
+
}
|
|
246
|
+
return v.constructor != null
|
|
247
|
+
? `an instance of ${v.constructor.name}` : 'an object with null prototype';
|
|
248
|
+
case 'undefined':
|
|
249
|
+
return 'undefined';
|
|
250
|
+
case 'string':
|
|
251
|
+
return `type string (${inspect(v)})`;
|
|
252
|
+
case 'symbol':
|
|
253
|
+
return `type symbol (${String(v)})`;
|
|
254
|
+
default:
|
|
255
|
+
return `type ${typeof v} (${inspect(v)})`;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// The two TypeError shapes the argument guards raise, measured on the same binary:
|
|
260
|
+
// 'The "fd" argument must be of type number or an instance of FileHandle. Received ...'
|
|
261
|
+
// and `The property 'options.offset' is invalid. Received ${inspect(v)}`.
|
|
262
|
+
function argTypeError(msg, v) {
|
|
263
|
+
const err = new TypeError(`${msg} Received ${receivedArgType(v)}`);
|
|
264
|
+
err.code = 'ERR_INVALID_ARG_TYPE';
|
|
265
|
+
return err;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function propertyValueError(name, v) {
|
|
269
|
+
const err = new TypeError(
|
|
270
|
+
`The property 'options.${name}' is invalid. Received ${inspect(v)}`);
|
|
271
|
+
err.code = 'ERR_INVALID_ARG_VALUE';
|
|
272
|
+
return err;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// node's options guard (assertIsObject plus the explicit checks of respondWithFD,
|
|
276
|
+
// internal/http2/core.js): an undefined options is an empty one, null and primitives
|
|
277
|
+
// are refused, and -- measured -- an array is refused for options (unlike the headers
|
|
278
|
+
// argument). offset/length/statCheck keep node's `!== undefined` tests, so a null
|
|
279
|
+
// offset is refused exactly the way a string one is.
|
|
280
|
+
function fdOptions(options) {
|
|
281
|
+
if (options !== undefined &&
|
|
282
|
+
(options === null || typeof options !== 'object' || Array.isArray(options))) {
|
|
283
|
+
throw argTypeError('The "options" argument must be of type object.', options);
|
|
284
|
+
}
|
|
285
|
+
const opts = options === undefined ? {} : { ...options };
|
|
286
|
+
if (opts.offset !== undefined && typeof opts.offset !== 'number') {
|
|
287
|
+
throw propertyValueError('offset', opts.offset);
|
|
288
|
+
}
|
|
289
|
+
if (opts.length !== undefined && typeof opts.length !== 'number') {
|
|
290
|
+
throw propertyValueError('length', opts.length);
|
|
291
|
+
}
|
|
292
|
+
if (opts.statCheck !== undefined && typeof opts.statCheck !== 'function') {
|
|
293
|
+
throw propertyValueError('statCheck', opts.statCheck);
|
|
294
|
+
}
|
|
295
|
+
return opts;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// node's prepareResponseHeadersObject (internal/http2/core.js): a null-prototype copy
|
|
299
|
+
// of the caller's object with ':status' coerced in, so a statCheck that rewrites
|
|
300
|
+
// 'content-length' lands on the copy -- which is also what sentHeaders reports,
|
|
301
|
+
// exactly where node's kSentHeaders has it. The generated date is left to hdr.block,
|
|
302
|
+
// whose sendDate rule is the one prepare applies too. Status validation happens here,
|
|
303
|
+
// before the payload-forbidden check -- measured: ':status': 700 throws
|
|
304
|
+
// ERR_HTTP2_STATUS_INVALID out of the call, and ':status': '700' is coerced to 700
|
|
305
|
+
// first. The array form passes through untouched (hdr.block handles pairs natively);
|
|
306
|
+
// node's for..in over an array copies the index keys into the copy and sends field
|
|
307
|
+
// names '0', '1', ... instead -- the junk shape the header comment documents.
|
|
308
|
+
function prepareResponseHeadersObject(headersParam) {
|
|
309
|
+
if (headersParam !== undefined &&
|
|
310
|
+
(headersParam === null || typeof headersParam !== 'object')) {
|
|
311
|
+
throw argTypeError('The "headers" argument must be an instance of Array or Object.',
|
|
312
|
+
headersParam);
|
|
313
|
+
}
|
|
314
|
+
if (Array.isArray(headersParam)) {
|
|
315
|
+
return { headers: headersParam, statusCode: 0, isArray: true };
|
|
316
|
+
}
|
|
317
|
+
const copy = { __proto__: null };
|
|
318
|
+
let statusCode;
|
|
319
|
+
// node guards the copy on oldHeaders !== null && !== undefined (core.js): a missing
|
|
320
|
+
// headers argument is a valid response -- respondWithFD(fd) with no fields -- and an
|
|
321
|
+
// unguarded Object.keys would turn it into a session-killing TypeError
|
|
322
|
+
if (headersParam !== undefined && headersParam !== null) {
|
|
323
|
+
const keys = Object.keys(headersParam);
|
|
324
|
+
for (let i = 0; i < keys.length; i++) {
|
|
325
|
+
const key = keys[i];
|
|
326
|
+
copy[key] = headersParam[key];
|
|
327
|
+
if (key === ':status') {
|
|
328
|
+
statusCode = copy[key];
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
copy[hdr.KSensitiveHeaders] = headersParam[hdr.KSensitiveHeaders];
|
|
332
|
+
}
|
|
333
|
+
statusCode = copy[':status'] = (statusCode | 0) || 200;
|
|
334
|
+
if (statusCode < 200 || statusCode > 599) {
|
|
335
|
+
throw errorOf('ERR_HTTP2_STATUS_INVALID', `Invalid status code: ${statusCode}`);
|
|
336
|
+
}
|
|
337
|
+
const neverIndex = copy[hdr.KSensitiveHeaders];
|
|
338
|
+
if (neverIndex !== undefined && !Array.isArray(neverIndex)) {
|
|
339
|
+
const err = new TypeError(
|
|
340
|
+
`The property 'headers[http2.neverIndex]' is invalid. Received ${inspect(neverIndex)}`);
|
|
341
|
+
err.code = 'ERR_INVALID_ARG_VALUE';
|
|
342
|
+
throw err;
|
|
343
|
+
}
|
|
344
|
+
return { headers: copy, statusCode, isArray: false };
|
|
345
|
+
}
|
|
346
|
+
|
|
137
347
|
const {
|
|
138
348
|
ST_OPEN, ST_HALF_CLOSED_LOCAL, ST_HALF_CLOSED_REMOTE, ST_CLOSED, NO_ERROR, PROTOCOL_ERROR,
|
|
139
349
|
INTERNAL_ERROR
|
|
@@ -174,11 +384,19 @@ class Http2Stream extends Stream {
|
|
|
174
384
|
this._bodyLen = 0; // ...octets of body actually received
|
|
175
385
|
this._queued = null; // Buffers waiting on window credit
|
|
176
386
|
this._pending = null; // inbound chunks nobody has read yet
|
|
387
|
+
this._pipes = null; // destinations of pipe(), node's state.pipes
|
|
388
|
+
this._awaitDrain = null; // ...a dest whose false write still parks the flow
|
|
177
389
|
this._endPending = false; // END_STREAM arrived with no reader
|
|
178
390
|
this._consumeState = 0; // 0 no reader, 1 delivering, 2 reader is full
|
|
179
391
|
this._endQueued = false;
|
|
180
392
|
this._corked = 0; // Writable cork count -- a stub, not a write buffer (see cork()/uncork())
|
|
181
393
|
this._gracefulClose = false; // both halves closed on their own terms (_closeNow)
|
|
394
|
+
// node's closed/destroyed flip only when nghttp2 has actually closed the stream -- for
|
|
395
|
+
// a local end() that is when the send loop has carried the END_STREAM out, a tick after
|
|
396
|
+
// the call. h2lean flips its state inside the call (see _closeNow), so the flag marks
|
|
397
|
+
// the node-equivalent moment: the graceful close's event delivery. pushAllowed reads
|
|
398
|
+
// it to keep the same-turn window node keeps open.
|
|
399
|
+
this._closeDelivered = false;
|
|
182
400
|
this._waitForTrailers = false;
|
|
183
401
|
// node's `state.trailersReady` (internal/http2/core.js onStreamTrailers): the
|
|
184
402
|
// permission to call sendTrailers(), granted by the 'wantTrailers' callback and
|
|
@@ -199,6 +417,22 @@ class Http2Stream extends Stream {
|
|
|
199
417
|
// The compat layer's handler for this stream's events, or null when the
|
|
200
418
|
// application uses the stream API. See emit() below.
|
|
201
419
|
this._compatDispatch = null;
|
|
420
|
+
// node's `_writableState.ending`: the writable side has been told to end, whether
|
|
421
|
+
// or not the last octet has been accepted yet. It is what decides 'aborted' in
|
|
422
|
+
// node's closeStream (`if (!ending) emit('aborted')`), and the file paths set it
|
|
423
|
+
// EARLY -- node's processRespondWithFD calls self.end() before the pump starts --
|
|
424
|
+
// which is why a respondWithFD interrupted by a destroy reports no 'aborted'
|
|
425
|
+
// (measured: only 'close' with writableFinished false). _state.localClose does not
|
|
426
|
+
// cover that: it stays 0 until the pump reaches EOF.
|
|
427
|
+
this._ending = false;
|
|
428
|
+
// The writable-side finish state. 'finish' reports that every octet the
|
|
429
|
+
// application handed to this stream (body writes or a file pump) has been
|
|
430
|
+
// accepted by the session; writableFinished reads the flag set right
|
|
431
|
+
// before the event. Both stay false for a stream destroyed before
|
|
432
|
+
// completion (measured on v26.12.1: an abort after respondWithFD reports
|
|
433
|
+
// 'close' with writableFinished false and no 'finish').
|
|
434
|
+
this._writableFinished = false;
|
|
435
|
+
this._finishQueued = false;
|
|
202
436
|
}
|
|
203
437
|
|
|
204
438
|
get destroyed() {
|
|
@@ -231,6 +465,164 @@ class Http2Stream extends Stream {
|
|
|
231
465
|
return this._sentView;
|
|
232
466
|
}
|
|
233
467
|
|
|
468
|
+
// --- the Duplex state surface ------------------------------------------------
|
|
469
|
+
//
|
|
470
|
+
// Measured member-by-member off a live node server stream and read out of node's own
|
|
471
|
+
// internals (internal/streams/readable.js, internal/streams/writable.js, core.js
|
|
472
|
+
// bufferSize/headRequest; tools/probe-duplex-surface.js is the transcript, and
|
|
473
|
+
// test/duplex-surface.test.js pins the table). Every getter is computed from state this
|
|
474
|
+
// file already keeps, plus five lazily-set booleans (_eofEmitted, _errorEmitted,
|
|
475
|
+
// _dataRead, _flowing, _needDrain) written at the event/decision points below --
|
|
476
|
+
// no constructor additions, nothing allocated unless an application reads the member.
|
|
477
|
+
//
|
|
478
|
+
// The one deliberate divergence: writableLength/writableBuffer/bufferSize report the
|
|
479
|
+
// octets THIS stream still parks on window credit. node counts the bytes sitting in the
|
|
480
|
+
// JS Writable buffer before nghttp2 takes them (writableLength) PLUS the ones nghttp2
|
|
481
|
+
// holds (core.js bufferSize = writeQueueSize + writableLength, which double-counts a
|
|
482
|
+
// stalled write: measured 4096 queued reads 4096 and 8192); h2lean accepts a write into
|
|
483
|
+
// the session's staging buffer inside the call, so there is no JS-side buffer to show.
|
|
484
|
+
// Same write-through decision as the cork stub (header above, test/cork-parity.test.js).
|
|
485
|
+
|
|
486
|
+
// node: `!r.destroyed && !r.errorEmitted && !r.endEmitted` -- readable-side, not
|
|
487
|
+
// half-open-ness: a stream that has emitted 'end' reads false with both halves alive.
|
|
488
|
+
get readable() {
|
|
489
|
+
return !this._destroyed && this._errorEmitted !== true && this._eofEmitted !== true;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// node's readableDidRead is the dataEmitted bit (readable.js:1857): true once any
|
|
493
|
+
// delivery of octets happened -- through a 'data' event OR a successful read(), because
|
|
494
|
+
// node's read() itself emits 'data' on every chunk it hands back (readable.js read()
|
|
495
|
+
// tail, measured: three reads delivered three data events to a listener attached for
|
|
496
|
+
// the second one).
|
|
497
|
+
get readableDidRead() {
|
|
498
|
+
return this._dataRead === true;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// endEmitted, not "the peer's END arrived": false until THIS stream has emitted 'end'.
|
|
502
|
+
get readableEnded() {
|
|
503
|
+
return this._eofEmitted === true;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// node's tri-state (readable.js:1901): null until anything ever touches the readable
|
|
507
|
+
// side, true while it flows, false while paused. Measured boundaries: attaching a
|
|
508
|
+
// 'readable' listener reads false, a 'data' listener or resume() reads true, pause()
|
|
509
|
+
// reads false again, and a destroyed stream reads false. The compat path never sets it
|
|
510
|
+
// -- node's compat reads the stream through a 'readable' subscription, so a getter read
|
|
511
|
+
// on a compat stream reports false there; h2lean's compat dispatch does not subscribe
|
|
512
|
+
// (AGENTS.md 5), so an untouched compat-mode stream reads null. Written-up divergence,
|
|
513
|
+
// invisible unless an application mixes the two APIs.
|
|
514
|
+
get readableFlowing() {
|
|
515
|
+
return this._flowing === undefined ? null : this._flowing;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// node: `readable !== false && (destroyed || errored) && !endEmitted`.
|
|
519
|
+
get readableAborted() {
|
|
520
|
+
return (this._destroyed || this._streamErrored !== undefined) &&
|
|
521
|
+
this._eofEmitted !== true;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
get readableEncoding() {
|
|
525
|
+
return this._encoding === undefined ? null : this._encoding;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
get readableHighWaterMark() {
|
|
529
|
+
return READABLE_HWM;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
get readableObjectMode() {
|
|
533
|
+
return false;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
get readableLength() {
|
|
537
|
+
const pending = this._pending;
|
|
538
|
+
if (pending === null) {
|
|
539
|
+
return 0;
|
|
540
|
+
}
|
|
541
|
+
let n = 0;
|
|
542
|
+
for (let i = 0; i < pending.length; i++) {
|
|
543
|
+
const c = pending[i];
|
|
544
|
+
n += c.length === undefined ? c.data.length : c.length;
|
|
545
|
+
}
|
|
546
|
+
return n;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
get readableBuffer() {
|
|
550
|
+
// node returns the buffer list itself; h2lean hands out a copy -- the live array would
|
|
551
|
+
// let the caller splice chunks out from under the replay queue. Pushed entries are
|
|
552
|
+
// reported as the buffers they hold, which is what node's list shows.
|
|
553
|
+
const pending = this._pending;
|
|
554
|
+
if (pending === null) {
|
|
555
|
+
return [];
|
|
556
|
+
}
|
|
557
|
+
const out = new Array(pending.length);
|
|
558
|
+
for (let i = 0; i < pending.length; i++) {
|
|
559
|
+
const c = pending[i];
|
|
560
|
+
out[i] = c.length === undefined ? c.data : c;
|
|
561
|
+
}
|
|
562
|
+
return out;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// node: `(kEnding | kEnded | kDestroyed | kErrored) === 0`.
|
|
566
|
+
get writable() {
|
|
567
|
+
return !this._destroyed && !this._ending && this._streamErrored === undefined;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// node's kEnding bit. A plain destroy() ends the writable inside closeStream
|
|
571
|
+
// (`if (!ending) stream.end()`, core.js:2088) -- h2lean reports that without touching
|
|
572
|
+
// _ending (which carries the 'aborted' decision); a destroy WITH an error does not set
|
|
573
|
+
// it, because node's end() skips kEnding on an errored writable (writable.js:876) --
|
|
574
|
+
// measured: the push-after-EOF snapshot reads writableEnded false with writable false.
|
|
575
|
+
get writableEnded() {
|
|
576
|
+
return this._ending || (this._destroyed && this._streamErrored === undefined);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
get writableObjectMode() {
|
|
580
|
+
return false;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
get writableLength() {
|
|
584
|
+
const queued = this._queued;
|
|
585
|
+
if (queued === null) {
|
|
586
|
+
return 0;
|
|
587
|
+
}
|
|
588
|
+
let n = 0;
|
|
589
|
+
for (let i = 0; i < queued.length; i++) {
|
|
590
|
+
n += queued[i].length;
|
|
591
|
+
}
|
|
592
|
+
return n;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
get writableBuffer() {
|
|
596
|
+
return this._queued === null ? [] : this._queued.slice();
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// node: `kNeedDrain` set and neither destroyed nor ending. h2lean flips the flag from
|
|
600
|
+
// the write()/end() accept verdict -- false when the window still takes bytes, true
|
|
601
|
+
// when the send queue parked them -- and the session clears it as the queue drains.
|
|
602
|
+
get writableNeedDrain() {
|
|
603
|
+
return this._needDrain === true && !this._destroyed && !this._ending;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// core.js:2215: `writeQueueSize + writableLength`. The nghttp2 queue this file has no
|
|
607
|
+
// equivalent for (write-through, header above), so the second term is the whole number.
|
|
608
|
+
get bufferSize() {
|
|
609
|
+
return this.writableLength;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// node keeps one `errored` per half; the public getter is the READABLE one
|
|
613
|
+
// (readable.js:1939). It holds the Error an 'error' is delivering, set when destroy
|
|
614
|
+
// runs with an error (destroy.js checkError), not when the event fires.
|
|
615
|
+
get errored() {
|
|
616
|
+
return this._streamErrored === undefined ? null : this._streamErrored;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// core.js: `!!(flags & STREAM_FLAGS_HEAD_REQUEST)`, set at stream creation from the
|
|
620
|
+
// request line. Same fact in h2lean, read where respond() tests it already: the flag
|
|
621
|
+
// source is the request map, so there is no state to keep out of sync.
|
|
622
|
+
get headRequest() {
|
|
623
|
+
return this._requestHeaders !== undefined && this._requestHeaders[':method'] === 'HEAD';
|
|
624
|
+
}
|
|
625
|
+
|
|
234
626
|
respond(headers, options) {
|
|
235
627
|
// node guards the stream's life first (internal/http2/core.js respond():
|
|
236
628
|
// `if (this.destroyed || this.closed) throw new ERR_HTTP2_INVALID_STREAM()`),
|
|
@@ -265,8 +657,10 @@ class Http2Stream extends Stream {
|
|
|
265
657
|
// off. Measured against a live node server: respond({':status':200}) carries a date,
|
|
266
658
|
// respond({':status':204}) and 304 do too, and sendDate:false removes it.
|
|
267
659
|
const sendDate = opts.sendDate == null ? true : !!opts.sendDate;
|
|
268
|
-
|
|
269
|
-
|
|
660
|
+
// node reads the never-indexed names only off the headers object's sensitiveHeaders
|
|
661
|
+
// symbol (buildNgHeaderString reads arrayOrMap[kSensitiveHeaders],
|
|
662
|
+
// internal/http2/util.js) -- there is no options.sensitiveHeaders for node to ignore.
|
|
663
|
+
const block = hdr.block(headers, { sendDate }, this.session);
|
|
270
664
|
// Read the encoder's result slots before anything else can build a block: they are
|
|
271
665
|
// what `sentHeaders` reports, so they have to be this response's, not a later one's.
|
|
272
666
|
this._sentSrc = headers;
|
|
@@ -296,11 +690,293 @@ class Http2Stream extends Stream {
|
|
|
296
690
|
// So the outstanding request for trailers is dropped instead of answered after the
|
|
297
691
|
// stream is closed, and 'wantTrailers' is not emitted for a stream that cannot send.
|
|
298
692
|
this._waitForTrailers = false;
|
|
693
|
+
this._ending = true;
|
|
299
694
|
this._endLocalSide();
|
|
300
695
|
}
|
|
301
696
|
return this;
|
|
302
697
|
}
|
|
303
698
|
|
|
699
|
+
// --- file responses (respondWithFD / respondWithFile) ---
|
|
700
|
+
//
|
|
701
|
+
// The step order below is node's respondWithFD (internal/http2/core.js), each guard
|
|
702
|
+
// measured against a live v26.12.1: stream guards, the options copy and its
|
|
703
|
+
// offset/length/statCheck checks, the waitForTrailers flag (before the fd is
|
|
704
|
+
// validated -- an invalid fd with waitForTrailers set still marks the stream for
|
|
705
|
+
// trailers), the fd argument itself, ownsFd = false, the prepared header copy, and
|
|
706
|
+
// the payload-forbidden statuses (204/205/304 and a HEAD request). respondWithFile
|
|
707
|
+
// is the same list with fs.open in front, ownsFd = true, and its own
|
|
708
|
+
// non-regular-file rules.
|
|
709
|
+
//
|
|
710
|
+
// A FileHandle instance is accepted wherever node accepts one; `this.ownsFd` is set
|
|
711
|
+
// unconditionally on each path -- node does the same, so an application that pre-set
|
|
712
|
+
// stream.ownsFd before respondWithFD has it clobbered there.
|
|
713
|
+
|
|
714
|
+
respondWithFD(fd, headers, options) {
|
|
715
|
+
if (this._destroyed || this.closed) {
|
|
716
|
+
throw errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed');
|
|
717
|
+
}
|
|
718
|
+
if (this.headersSent) {
|
|
719
|
+
throw errorOf('ERR_HTTP2_HEADERS_SENT', 'Response has already been initiated.');
|
|
720
|
+
}
|
|
721
|
+
const opts = fdOptions(options);
|
|
722
|
+
if (opts.waitForTrailers) {
|
|
723
|
+
this._waitForTrailers = true;
|
|
724
|
+
}
|
|
725
|
+
if (isFileHandle(fd)) {
|
|
726
|
+
fd = fd.fd;
|
|
727
|
+
} else if (typeof fd !== 'number') {
|
|
728
|
+
throw argTypeError(
|
|
729
|
+
'The "fd" argument must be of type number or an instance of FileHandle.', fd);
|
|
730
|
+
}
|
|
731
|
+
this.ownsFd = false;
|
|
732
|
+
const sendDate = opts.sendDate == null ? true : !!opts.sendDate;
|
|
733
|
+
const { headers: prepared, statusCode } = prepareResponseHeadersObject(headers);
|
|
734
|
+
const head =
|
|
735
|
+
this._requestHeaders !== undefined && this._requestHeaders[':method'] === 'HEAD';
|
|
736
|
+
if (statusCode === 204 || statusCode === 205 || statusCode === 304 || head) {
|
|
737
|
+
throw errorOf('ERR_HTTP2_PAYLOAD_FORBIDDEN',
|
|
738
|
+
`Responses with ${statusCode} status must not have a payload`);
|
|
739
|
+
}
|
|
740
|
+
if (opts.statCheck !== undefined) {
|
|
741
|
+
// node's doSendFD: the statCheck sees (stat, headers-copy, statOptions) with
|
|
742
|
+
// statOptions defaulted to { offset: 0, length: -1 } -- on this path node never
|
|
743
|
+
// injects 'content-length' and never checks that the fd is a regular file; both
|
|
744
|
+
// are the application's job through the statCheck callback (which is exactly
|
|
745
|
+
// what upstream's test-http2-respond-file-fd-range.js does). Returning false
|
|
746
|
+
// cancels without touching the descriptor: on this path the application owns it.
|
|
747
|
+
fs.fstat(fd, (err, stat) => {
|
|
748
|
+
if (err) {
|
|
749
|
+
this.destroy(err);
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
if (this._destroyed || this.closed) {
|
|
753
|
+
this.destroy(errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed'));
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
const statOptions = {
|
|
757
|
+
offset: opts.offset !== undefined ? opts.offset : 0,
|
|
758
|
+
length: opts.length !== undefined ? opts.length : -1
|
|
759
|
+
};
|
|
760
|
+
if (opts.statCheck.call(this, stat, prepared, statOptions) === false ||
|
|
761
|
+
this.headersSent) {
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
this._processRespondWithFD(fd, prepared, statOptions.offset | 0,
|
|
765
|
+
statOptions.length | 0, sendDate);
|
|
766
|
+
});
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
this._processRespondWithFD(fd, prepared, opts.offset, opts.length, sendDate);
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
respondWithFile(path, headers, options) {
|
|
773
|
+
if (this._destroyed || this.closed) {
|
|
774
|
+
throw errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed');
|
|
775
|
+
}
|
|
776
|
+
if (this.headersSent) {
|
|
777
|
+
throw errorOf('ERR_HTTP2_HEADERS_SENT', 'Response has already been initiated.');
|
|
778
|
+
}
|
|
779
|
+
const opts = fdOptions(options);
|
|
780
|
+
if (opts.waitForTrailers) {
|
|
781
|
+
this._waitForTrailers = true;
|
|
782
|
+
}
|
|
783
|
+
this.ownsFd = true;
|
|
784
|
+
const sendDate = opts.sendDate == null ? true : !!opts.sendDate;
|
|
785
|
+
const { headers: prepared, statusCode, isArray } =
|
|
786
|
+
prepareResponseHeadersObject(headers);
|
|
787
|
+
const head =
|
|
788
|
+
this._requestHeaders !== undefined && this._requestHeaders[':method'] === 'HEAD';
|
|
789
|
+
if (statusCode === 204 || statusCode === 205 || statusCode === 304 || head) {
|
|
790
|
+
throw errorOf('ERR_HTTP2_PAYLOAD_FORBIDDEN',
|
|
791
|
+
`Responses with ${statusCode} status must not have a payload`);
|
|
792
|
+
}
|
|
793
|
+
fs.open(path, 'r', (err, fd) => {
|
|
794
|
+
const onError = typeof opts.onError === 'function' ? opts.onError : null;
|
|
795
|
+
if (err) {
|
|
796
|
+
if (onError) {
|
|
797
|
+
onError(err);
|
|
798
|
+
} else {
|
|
799
|
+
this.destroy(err);
|
|
800
|
+
}
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
if (this._destroyed || this.closed) {
|
|
804
|
+
fs.close(fd, noopClose);
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
fs.fstat(fd, (err2, stat) => {
|
|
808
|
+
if (err2) {
|
|
809
|
+
fs.close(fd, noopClose);
|
|
810
|
+
if (onError) {
|
|
811
|
+
onError(err2);
|
|
812
|
+
} else {
|
|
813
|
+
this.destroy(err2);
|
|
814
|
+
}
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
// node's doSendFileFD: for a non-regular file, any seek option at all (or a
|
|
818
|
+
// directory) is refused -- with the descriptor closed either way, and the
|
|
819
|
+
// error routed through options.onError when the application gave one. A
|
|
820
|
+
// non-regular file that survives the check gets node's unseekable sentinel
|
|
821
|
+
// (-1, -1) in the copy; note node's `!== undefined || > 0` pair, kept as
|
|
822
|
+
// measured.
|
|
823
|
+
if (!stat.isFile()) {
|
|
824
|
+
const isDirectory = stat.isDirectory();
|
|
825
|
+
if ((opts.offset !== undefined || opts.offset > 0) ||
|
|
826
|
+
(opts.length !== undefined || opts.length >= 0) || isDirectory) {
|
|
827
|
+
fs.close(fd, noopClose);
|
|
828
|
+
const e = isDirectory
|
|
829
|
+
? errorOf('ERR_HTTP2_SEND_FILE', 'Directories cannot be sent')
|
|
830
|
+
: errorOf('ERR_HTTP2_SEND_FILE_NOSEEK',
|
|
831
|
+
'Offset or length can only be specified for regular files');
|
|
832
|
+
if (onError) {
|
|
833
|
+
onError(e);
|
|
834
|
+
} else {
|
|
835
|
+
this.destroy(e);
|
|
836
|
+
}
|
|
837
|
+
return;
|
|
838
|
+
}
|
|
839
|
+
opts.offset = -1;
|
|
840
|
+
opts.length = -1;
|
|
841
|
+
}
|
|
842
|
+
if (this._destroyed || this.closed) {
|
|
843
|
+
fs.close(fd, noopClose);
|
|
844
|
+
this.destroy(errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed'));
|
|
845
|
+
return;
|
|
846
|
+
}
|
|
847
|
+
const statOptions = {
|
|
848
|
+
offset: opts.offset !== undefined ? opts.offset : 0,
|
|
849
|
+
length: opts.length !== undefined ? opts.length : -1
|
|
850
|
+
};
|
|
851
|
+
if ((typeof opts.statCheck === 'function' &&
|
|
852
|
+
opts.statCheck.call(this, stat, prepared) === false) || this.headersSent) {
|
|
853
|
+
// on this path the stack owns the descriptor: a cancelled statCheck closes it
|
|
854
|
+
fs.close(fd, noopClose);
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
857
|
+
if (stat.isFile()) {
|
|
858
|
+
statOptions.length = statOptions.length < 0
|
|
859
|
+
? stat.size - (+statOptions.offset)
|
|
860
|
+
: Math.min(stat.size - (+statOptions.offset), statOptions.length);
|
|
861
|
+
if (!isArray) {
|
|
862
|
+
prepared['content-length'] = statOptions.length;
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
// node passes options.offset (post-mutation), not statOptions.offset
|
|
866
|
+
this._processRespondWithFD(fd, prepared, opts.offset | 0,
|
|
867
|
+
statOptions.length | 0, sendDate);
|
|
868
|
+
});
|
|
869
|
+
});
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
// node's processRespondWithFD: the HEADERS_SENT flag goes up BEFORE the fields are
|
|
873
|
+
// validated, so a bad field name leaves headersSent true and takes the destroy path
|
|
874
|
+
// below -- measured, the call does not throw. node also calls self.end() here --
|
|
875
|
+
// the writable is "ending" from this turn on, which is why an interrupted file
|
|
876
|
+
// pipe reports no 'aborted' -- while the END_STREAM itself waits for the pump's
|
|
877
|
+
// EOF. The prepared copy is what sentHeaders reports (node's kSentHeaders = the
|
|
878
|
+
// copy), and the encoding error and a refused block both leave the descriptor
|
|
879
|
+
// with its owner.
|
|
880
|
+
_processRespondWithFD(fd, prepared, offset, length, sendDate) {
|
|
881
|
+
this.headersSent = true;
|
|
882
|
+
this.pending = false;
|
|
883
|
+
this._ending = true;
|
|
884
|
+
let block;
|
|
885
|
+
try {
|
|
886
|
+
block = hdr.block(prepared, { sendDate }, this.session);
|
|
887
|
+
} catch (err) {
|
|
888
|
+
if (this.ownsFd) {
|
|
889
|
+
fs.close(fd, noopClose);
|
|
890
|
+
}
|
|
891
|
+
this.destroy(err);
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
this._sentSrc = prepared;
|
|
895
|
+
this._sentStatus = hdr.sent.status;
|
|
896
|
+
this._sentDate = hdr.sent.date;
|
|
897
|
+
const bound = hdr.sent.bound;
|
|
898
|
+
if (this._blockRefused || this.session.sendHeaders(this.id, block, false, bound)) {
|
|
899
|
+
this._blockRefused = true;
|
|
900
|
+
// node has already called self.end() by this point (processRespondWithFD ends
|
|
901
|
+
// the writable before the wire write), so the half-close happens even here.
|
|
902
|
+
this._endLocalSide();
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
this._startFilePipe(fd, offset, length);
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
// node's startFilePipe: read the descriptor in chunks and hand each to the writable
|
|
909
|
+
// side, end at EOF, honour the write path's backpressure; teardown closes an owned
|
|
910
|
+
// descriptor (node's onFileUnpipe), and a read error other than EOF raises
|
|
911
|
+
// NGHTTP2_INTERNAL_ERROR on the stream -- the client then reports
|
|
912
|
+
// ERR_HTTP2_STREAM_ERROR with that rstCode, the shape upstream's
|
|
913
|
+
// test-http2-respond-file-fd-invalid.js pins. The reads go through write()/end(),
|
|
914
|
+
// so credit, the outbound batch and the session hold behave exactly as for a body
|
|
915
|
+
// written by hand.
|
|
916
|
+
_startFilePipe(fd, offset, length) {
|
|
917
|
+
const pump = {
|
|
918
|
+
remaining: length === undefined || length < 0 ? Infinity : length,
|
|
919
|
+
position: offset === undefined || offset < 0 ? -1 : offset,
|
|
920
|
+
stopped: false
|
|
921
|
+
};
|
|
922
|
+
this.once('close', () => {
|
|
923
|
+
pump.stopped = true;
|
|
924
|
+
if (this.ownsFd) {
|
|
925
|
+
fs.close(fd, noopClose);
|
|
926
|
+
}
|
|
927
|
+
});
|
|
928
|
+
const step = () => {
|
|
929
|
+
if (pump.stopped || this._destroyed) {
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
const want = Math.min(FILE_CHUNK, pump.remaining);
|
|
933
|
+
const buf = Buffer.allocUnsafe(want);
|
|
934
|
+
const pos = pump.position < 0 ? null : pump.position;
|
|
935
|
+
fs.read(fd, buf, 0, want, pos, (err, n) => {
|
|
936
|
+
if (pump.stopped || this._destroyed) {
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
if (err && err.code !== 'EOF') {
|
|
940
|
+
this.destroy(streamErrorOf(frames.INTERNAL_ERROR));
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
if (n === 0) {
|
|
944
|
+
this._pumpEnd();
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
947
|
+
pump.remaining -= n;
|
|
948
|
+
if (pump.position >= 0) {
|
|
949
|
+
pump.position += n;
|
|
950
|
+
}
|
|
951
|
+
const view = n === want ? buf : buf.subarray(0, n);
|
|
952
|
+
if (this.write(view)) {
|
|
953
|
+
if (pump.remaining > 0) {
|
|
954
|
+
step();
|
|
955
|
+
} else {
|
|
956
|
+
this._pumpEnd();
|
|
957
|
+
}
|
|
958
|
+
} else {
|
|
959
|
+
this.once('drain', step);
|
|
960
|
+
}
|
|
961
|
+
});
|
|
962
|
+
};
|
|
963
|
+
step();
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
// The file pump's EOF. node's pump never runs Writable.end: StreamPipe writes into
|
|
967
|
+
// the nghttp2 handle directly (core.js startFilePipe), the writable side was closed
|
|
968
|
+
// in processRespondWithFD (`self._final = null; self.end()`) and the application's
|
|
969
|
+
// end() is the no-op Writable.end() is on an ended stream. h2lean's pump shares the
|
|
970
|
+
// application's write()/sendData path, so its EOF mirrors end()'s body without the
|
|
971
|
+
// ended-guard, and the same waitForTrailers split applies.
|
|
972
|
+
_pumpEnd() {
|
|
973
|
+
const oweTrailers = this._waitForTrailers;
|
|
974
|
+
this.session.sendData(this, EMPTY, !oweTrailers);
|
|
975
|
+
if (oweTrailers) {
|
|
976
|
+
this._endLocalSide();
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
|
|
304
980
|
write(chunk, encoding, cb) {
|
|
305
981
|
if (typeof encoding === 'function') {
|
|
306
982
|
cb = encoding; encoding = undefined;
|
|
@@ -335,12 +1011,19 @@ class Http2Stream extends Stream {
|
|
|
335
1011
|
// the event is owed here instead. A reset or a session destroy is not
|
|
336
1012
|
// this shape -- there node's errorOrDestroy is a no-op and no 'error'
|
|
337
1013
|
// goes out (the session-destroy case of test/upstream-push.test.js).
|
|
338
|
-
process.nextTick(
|
|
1014
|
+
process.nextTick(emitErrorOnlyNT, this, err);
|
|
339
1015
|
}
|
|
340
1016
|
return false;
|
|
341
1017
|
}
|
|
342
|
-
|
|
1018
|
+
// node's encodeString: an encoding-less write(string) uses the writable
|
|
1019
|
+
// default, which setDefaultEncoding is the way to change (writable.js:465).
|
|
1020
|
+
const buf = typeof chunk === 'string'
|
|
1021
|
+
? Buffer.from(chunk, encoding || this._defaultEnc || 'utf8') : chunk;
|
|
343
1022
|
const canContinue = this.session.sendData(this, buf, false);
|
|
1023
|
+
// writableNeedDrain is node's needDrain bit: set when a write left the buffer
|
|
1024
|
+
// over the highWaterMark, cleared when the buffer drops back under it (the
|
|
1025
|
+
// session's drain path). It reports the credit stall, nothing else.
|
|
1026
|
+
this._needDrain = !canContinue;
|
|
344
1027
|
if (cb) {
|
|
345
1028
|
process.nextTick(cb);
|
|
346
1029
|
}
|
|
@@ -353,17 +1036,25 @@ class Http2Stream extends Stream {
|
|
|
353
1036
|
} else if (typeof encoding === 'function') {
|
|
354
1037
|
cb = encoding; encoding = null;
|
|
355
1038
|
}
|
|
356
|
-
if (this._endQueued || this._state.localClose === 1) {
|
|
1039
|
+
if (this._endQueued || this._ending || this._state.localClose === 1) {
|
|
357
1040
|
// node: Writable.end() on an ended writable is a no-op that still answers
|
|
358
1041
|
// the callback (internal/streams/writable.js end() -> writableEnded checks;
|
|
359
1042
|
// measured v26.12.1: respond() on a HEAD request ends the writable itself,
|
|
360
1043
|
// and the application's end() after it neither errors nor destroys).
|
|
361
|
-
//
|
|
1044
|
+
// The same state is what respondWithFD leaves: node's processRespondWithFD
|
|
1045
|
+
// closes the writable before the pump starts (`self._final = null; self.end()`,
|
|
1046
|
+
// core.js), so the application's end() after it is the no-op and the pump's
|
|
1047
|
+
// EOF goes out through the pipe, not through end(). h2lean's pump reaches for
|
|
1048
|
+
// _pumpEnd() for exactly that reason; write() after end IS the error -- see
|
|
1049
|
+
// write() above.
|
|
362
1050
|
if (cb) {
|
|
363
1051
|
process.nextTick(cb);
|
|
364
1052
|
}
|
|
365
1053
|
return this;
|
|
366
1054
|
}
|
|
1055
|
+
// node's Writable.end flips _writableState.ending here, before anything is sent
|
|
1056
|
+
// -- even when the body is still parked on window credit. 'aborted' reads it.
|
|
1057
|
+
this._ending = true;
|
|
367
1058
|
if (!this.headersSent) {
|
|
368
1059
|
// A body takes the auto-respond of write() above; an empty end() is where h2lean and node
|
|
369
1060
|
// part company, and the split is written down in AGENTS.md section 10: node puts NOTHING on
|
|
@@ -424,6 +1115,10 @@ class Http2Stream extends Stream {
|
|
|
424
1115
|
return WRITABLE_HWM;
|
|
425
1116
|
}
|
|
426
1117
|
|
|
1118
|
+
get writableFinished() {
|
|
1119
|
+
return this._writableFinished;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
427
1122
|
sendTrailers(trailers) {
|
|
428
1123
|
// node's three guards, in node's order, and all three as synchronous throws --
|
|
429
1124
|
// not emitted errors (internal/http2/core.js Http2Stream.sendTrailers). Measured
|
|
@@ -443,7 +1138,7 @@ class Http2Stream extends Stream {
|
|
|
443
1138
|
throw errorOf('ERR_HTTP2_TRAILERS_NOT_READY',
|
|
444
1139
|
'Trailing headers cannot be sent until after the wantTrailers event is emitted');
|
|
445
1140
|
}
|
|
446
|
-
const block = hdr.block(trailers,
|
|
1141
|
+
const block = hdr.block(trailers, { trailer: true }, this.session);
|
|
447
1142
|
const bound = hdr.sent.bound;
|
|
448
1143
|
// node records a null-prototype copy, not the caller's map (`ObjectAssign({
|
|
449
1144
|
// __proto__: null }, headers)`, internal/http2/core.js sendTrailers -- the shared
|
|
@@ -508,7 +1203,7 @@ class Http2Stream extends Stream {
|
|
|
508
1203
|
}
|
|
509
1204
|
// `{ info: true }` is node's separate rule for these blocks: :status must be 100..199
|
|
510
1205
|
// (101 has its own error), there is no default status and no generated date.
|
|
511
|
-
const block = hdr.block(headers,
|
|
1206
|
+
const block = hdr.block(headers, { info: true }, this.session);
|
|
512
1207
|
const bound = hdr.sent.bound;
|
|
513
1208
|
this.sentInfoHeaders.push(headers);
|
|
514
1209
|
this.session.sendHeaders(this.id, block, false, bound);
|
|
@@ -531,8 +1226,19 @@ class Http2Stream extends Stream {
|
|
|
531
1226
|
// the server may push. Measured on v26.12.1: a client with settings:{enablePush:false}
|
|
532
1227
|
// makes pushAllowed false and pushStream throw ERR_HTTP2_PUSH_DISABLED synchronously.
|
|
533
1228
|
get pushAllowed() {
|
|
534
|
-
|
|
535
|
-
|
|
1229
|
+
// node's ServerHttp2Stream.pushAllowed (core.js) reads the same terms, but node's
|
|
1230
|
+
// stream reaches `closed` only when nghttp2 has actually closed it -- for a local
|
|
1231
|
+
// end() that is the send-loop turn after the call, so a pushStream in the same turn
|
|
1232
|
+
// still sees a live stream (upstream's respond({})/end()/pushStream() shape,
|
|
1233
|
+
// test/upstream/respond-file-push.test.js). h2lean frames END_STREAM inside the call
|
|
1234
|
+
// and flips closed/destroyed there, a tick earlier than node, so a graceful close
|
|
1235
|
+
// whose event has not been delivered yet still counts as open. A peer reset has no
|
|
1236
|
+
// such window: node's nghttp2 closes that stream inside the read batch.
|
|
1237
|
+
if (this._destroyed) {
|
|
1238
|
+
return this._gracefulClose && !this._closeDelivered;
|
|
1239
|
+
}
|
|
1240
|
+
return !this.closed && !this.session.closed && !this.session.destroyed
|
|
1241
|
+
&& !!this.session.remoteSettings.enablePush;
|
|
536
1242
|
}
|
|
537
1243
|
|
|
538
1244
|
// node: ServerHttp2Stream.pushStream (internal/http2/core.js:2971).
|
|
@@ -604,7 +1310,9 @@ class Http2Stream extends Stream {
|
|
|
604
1310
|
|
|
605
1311
|
// Validation errors are synchronous in node (buildNgHeaderString throws before
|
|
606
1312
|
// the frame is submitted). The id was already reserved; it stays consumed.
|
|
607
|
-
|
|
1313
|
+
// Like respond(), the never-indexed names come only off the headers object's
|
|
1314
|
+
// sensitiveHeaders symbol -- node's pushStream has no options.sensitiveHeaders.
|
|
1315
|
+
const block = hdr.pushBlock(h, this.session);
|
|
608
1316
|
const refused = this.session.sendPushPromise(this.id, promisedId, block, hdr.sent.bound);
|
|
609
1317
|
|
|
610
1318
|
// Create the pushed stream and register it. The readable side is pre-ended:
|
|
@@ -643,106 +1351,1023 @@ class Http2Stream extends Stream {
|
|
|
643
1351
|
// so the sender is the one that waits, and whatever arrives in the meantime is
|
|
644
1352
|
// buffered and replayed on resume(). Returns this, like the Duplex does.
|
|
645
1353
|
pause() {
|
|
1354
|
+
this._flowing = false;
|
|
646
1355
|
this._pauseConsuming();
|
|
647
1356
|
return this;
|
|
648
1357
|
}
|
|
649
1358
|
|
|
650
1359
|
resume() {
|
|
651
|
-
this.
|
|
1360
|
+
this._flowing = true;
|
|
1361
|
+
this._scheduleResume();
|
|
652
1362
|
return this;
|
|
653
1363
|
}
|
|
654
1364
|
|
|
1365
|
+
// node's resume() flips the flowing bit synchronously but the delivery itself
|
|
1366
|
+
// runs on the kResumeScheduled next tick, and an attaching 'data' listener only
|
|
1367
|
+
// calls resume when the stream is neither explicitly paused nor in pull mode --
|
|
1368
|
+
// the 'readable' attach has set kHasFlowing, and measured: a 'data' attach
|
|
1369
|
+
// inside a pull handler leaves the buffer for read() untouched.
|
|
1370
|
+
_scheduleResume() {
|
|
1371
|
+
if (this._resumeScheduled === true || this._flowing === false ||
|
|
1372
|
+
this._destroyed) {
|
|
1373
|
+
return;
|
|
1374
|
+
}
|
|
1375
|
+
this._resumeScheduled = true;
|
|
1376
|
+
process.nextTick(() => {
|
|
1377
|
+
this._resumeScheduled = false;
|
|
1378
|
+
if (this._destroyed || this._flowing === false) {
|
|
1379
|
+
return;
|
|
1380
|
+
}
|
|
1381
|
+
this._startConsuming();
|
|
1382
|
+
});
|
|
1383
|
+
}
|
|
1384
|
+
|
|
655
1385
|
isPaused() {
|
|
656
1386
|
return this._consumeState === 2;
|
|
657
1387
|
}
|
|
658
1388
|
|
|
659
|
-
//
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
1389
|
+
// --- the readable pull surface: read() and push() -----------------------------
|
|
1390
|
+
//
|
|
1391
|
+
// A mini-Readable over the existing `_pending` queue, reproduced member by
|
|
1392
|
+
// member from internal/streams/readable.js (v26) and pinned against a live
|
|
1393
|
+
// node by tools/probe-duplex-surface.js: an arrival emits 'readable' and
|
|
1394
|
+
// nothing else until the application pulls; read() with no argument returns
|
|
1395
|
+
// the whole first chunk, read(n) merges across chunks and hands the
|
|
1396
|
+
// remainder back, an ask past the buffered end returns what the queue can
|
|
1397
|
+
// cover (nothing at all before the EOF is known), every data-returning read
|
|
1398
|
+
// flips dataRead and emits 'data', and a read past the end of an empty,
|
|
1399
|
+
// EOF-known queue schedules the end-of-stream. push() after the EOF errors
|
|
1400
|
+
// with ERR_STREAM_PUSH_AFTER_EOF through 'error', push() on a destroyed
|
|
1401
|
+
// stream is a silent false, push(null) always returns false. The queue holds
|
|
1402
|
+
// two entry kinds: a bare Buffer is octets off the socket (credit-owed), a
|
|
1403
|
+
// `{ data }` wrapper is octets the application pushed (never credited — they
|
|
1404
|
+
// never came off the wire, and crediting them would let a peer send bytes we
|
|
1405
|
+
// never advertised).
|
|
1406
|
+
//
|
|
1407
|
+
// The EOF becomes known to node when the END_STREAM is processed in the read
|
|
1408
|
+
// callback — measured by stack (stream_base_commons:236 -> Readable.push ->
|
|
1409
|
+
// onEofChunk): that push(null) emits 'readable' synchronously from
|
|
1410
|
+
// onEofChunk's non-sync branch, and onStreamClose pushes it again for the
|
|
1411
|
+
// paths that end without a final frame (reset, teardown). h2lean knows the
|
|
1412
|
+
// EOF at the same frame and parks it in `_endPending` when no reader is
|
|
1413
|
+
// watching, which matches the visible sequences (data, end, close, and the
|
|
1414
|
+
// measured-identical push-after-EOF matrix) with the parked EOF standing in
|
|
1415
|
+
// for the buffered one.
|
|
664
1416
|
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
if (this._state.remoteClose === 1) {
|
|
673
|
-
return;
|
|
1417
|
+
read(n) {
|
|
1418
|
+
// node's argument normalisation, kept exact: no argument is NaN and means
|
|
1419
|
+
// the whole first chunk; a non-integer goes through parseInt.
|
|
1420
|
+
if (n === undefined) {
|
|
1421
|
+
n = NaN;
|
|
1422
|
+
} else if (!Number.isInteger(n)) {
|
|
1423
|
+
n = Number.parseInt(n, 10);
|
|
674
1424
|
}
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
// message ends. Measured on node (h2spec http2/8.1.2.6): RST_STREAM(PROTOCOL_ERROR) and the
|
|
678
|
-
// application is told ERR_HTTP2_STREAM_ERROR -- the short body is one request's failure, not
|
|
679
|
-
// the session's, which is the same split nghttp2 makes and the reason the two directions of
|
|
680
|
-
// the same lie get two different codes.
|
|
681
|
-
if (this._expLen >= 0 && this._bodyLen < this._expLen) {
|
|
682
|
-
this.session._streamError(this, PROTOCOL_ERROR, `content-length ${this._expLen} with only ` +
|
|
683
|
-
`${this._bodyLen} octets received`);
|
|
684
|
-
return;
|
|
1425
|
+
if (this._destroyed) {
|
|
1426
|
+
return null;
|
|
685
1427
|
}
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
// STREAM_FLAGS_HAS_TRAILERS set is not shut down early
|
|
699
|
-
// (internal/http2/core.js, `Trailers are pending, so the writable side cannot be
|
|
700
|
-
// shut down early`). Measured: a compat response that ends with no body against an
|
|
701
|
-
// unread request put HEADERS then a zero-length DATA/END_STREAM on node's wire, with
|
|
702
|
-
// the stream close after both; ending here sent the HEADERS only and the client
|
|
703
|
-
// waited for an answer that never came.
|
|
704
|
-
this._closeNow();
|
|
705
|
-
process.nextTick(emitEndCloseNT, this);
|
|
706
|
-
return;
|
|
1428
|
+
const pending = this._pending;
|
|
1429
|
+
let avail = 0;
|
|
1430
|
+
let firstLen = 0;
|
|
1431
|
+
if (pending !== null) {
|
|
1432
|
+
for (let i = 0; i < pending.length; i++) {
|
|
1433
|
+
const c = pending[i];
|
|
1434
|
+
const l = c.length === undefined ? c.data.length : c.length;
|
|
1435
|
+
avail += l;
|
|
1436
|
+
if (i === 0) {
|
|
1437
|
+
firstLen = l;
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
707
1440
|
}
|
|
708
|
-
|
|
709
|
-
|
|
1441
|
+
// howMuchToRead, byte mode (readable.js:678): the NaN fast path is the
|
|
1442
|
+
// first chunk's length; more-than-buffered is only satisfiable past the
|
|
1443
|
+
// EOF, where the whole remainder comes back instead.
|
|
1444
|
+
const eofKnown = this._eofSeen === true || this._endPending === true;
|
|
1445
|
+
let want;
|
|
1446
|
+
if (n <= 0 || (avail === 0 && eofKnown)) {
|
|
1447
|
+
want = 0;
|
|
1448
|
+
} else if (Number.isNaN(n)) {
|
|
1449
|
+
// node's decoder branch of howMuchToRead (readable.js:684): the
|
|
1450
|
+
// one-chunk-at-a-time fast path belongs to flowing mode -- in pull mode
|
|
1451
|
+
// an argumentless read returns the WHOLE buffered character count,
|
|
1452
|
+
// because the queue now holds strings, not buffers.
|
|
1453
|
+
want = this._decoder === undefined ? firstLen
|
|
1454
|
+
: (this._flowing === true && avail !== 0) ? firstLen : avail;
|
|
1455
|
+
} else if (n <= avail) {
|
|
1456
|
+
want = n;
|
|
1457
|
+
} else {
|
|
1458
|
+
want = eofKnown ? avail : 0;
|
|
1459
|
+
}
|
|
1460
|
+
let ret = null;
|
|
1461
|
+
if (want > 0) {
|
|
1462
|
+
ret = this._takeQueued(want);
|
|
1463
|
+
}
|
|
1464
|
+
if (this._pending === null || this._pending.length === 0) {
|
|
1465
|
+
// the tail of node's read(): asking past what the queue holds — node
|
|
1466
|
+
// compares the asked amount with what howMuchToRead allowed (nOrig !== n),
|
|
1467
|
+
// which the argumentless NaN form always is — with the EOF known and
|
|
1468
|
+
// nothing left is what schedules the end-of-stream: endReadable.
|
|
1469
|
+
if (n !== want && eofKnown) {
|
|
1470
|
+
this._scheduleEOF();
|
|
1471
|
+
} else if (!eofKnown && typeof this._read === 'function') {
|
|
1472
|
+
// node fires maybeReadMore after a consumption drops the buffer below
|
|
1473
|
+
// the mark, and that is where _read gets called -- the only thing in
|
|
1474
|
+
// h2lean that installs an _read is the legacy wrap(), whose paused
|
|
1475
|
+
// source needs exactly this nudge to continue; the empty-and-not-EOF
|
|
1476
|
+
// condition is where node's own call lands for a pull consumer.
|
|
1477
|
+
this._read();
|
|
1478
|
+
}
|
|
710
1479
|
}
|
|
711
|
-
if (
|
|
712
|
-
//
|
|
713
|
-
//
|
|
714
|
-
|
|
715
|
-
|
|
1480
|
+
if (ret !== null && this._errorEmitted !== true && this._closeDelivered !== true) {
|
|
1481
|
+
// node's read() hands the chunk to the consumer as a 'data' event too —
|
|
1482
|
+
// measured: three reads delivered three data events to a listener
|
|
1483
|
+
// attached for the second one. dataEmitted flips with the emission.
|
|
1484
|
+
this._dataRead = true;
|
|
1485
|
+
this.emit('data', ret);
|
|
716
1486
|
}
|
|
717
|
-
|
|
1487
|
+
return ret;
|
|
718
1488
|
}
|
|
719
1489
|
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
1490
|
+
// Pull `n` octets off the queue: the exact-first-chunk case returns the buffer
|
|
1491
|
+
// view itself (no copy, the AGENTS.md 5 rule that a chunk the app holds is
|
|
1492
|
+
// never recycled); a read that splits or merges allocates one buffer and
|
|
1493
|
+
// re-queues the remainder with the origin it had. Credit goes out for the
|
|
1494
|
+
// wire octets handed over, in one call, only for them.
|
|
1495
|
+
_takeQueued(n) {
|
|
1496
|
+
const pending = this._pending;
|
|
1497
|
+
const first = pending[0];
|
|
1498
|
+
const firstLen = first.length === undefined ? first.data.length : first.length;
|
|
1499
|
+
if (firstLen === n) {
|
|
1500
|
+
pending.shift();
|
|
1501
|
+
if (pending.length === 0) {
|
|
1502
|
+
this._pending = null;
|
|
1503
|
+
}
|
|
1504
|
+
if (first.length !== undefined) {
|
|
1505
|
+
this._release(n);
|
|
1506
|
+
return first;
|
|
1507
|
+
}
|
|
1508
|
+
if (first.bytes !== undefined) {
|
|
1509
|
+
this._release(first.bytes);
|
|
1510
|
+
}
|
|
1511
|
+
return first.data;
|
|
1512
|
+
}
|
|
1513
|
+
if (first.length === undefined && typeof first.data === 'string') {
|
|
1514
|
+
// node's fromList decoder branch (readable.js:2060): string entries
|
|
1515
|
+
// concatenate toward the asked length and a split lands on character
|
|
1516
|
+
// boundaries. The wire octets an entry stands for are credited per slice
|
|
1517
|
+
// by the slice's own length in the encoding -- the queue is homogeneous
|
|
1518
|
+
// once an encoding is set (setEncoding merged what stood there, every
|
|
1519
|
+
// later arrival is decoded at the door), so a string entry is the only
|
|
1520
|
+
// kind this loop sees.
|
|
1521
|
+
let ret = '';
|
|
1522
|
+
let need = n;
|
|
1523
|
+
let j = 0;
|
|
1524
|
+
while (need > 0) {
|
|
1525
|
+
const e = pending[j];
|
|
1526
|
+
const s = e.data;
|
|
1527
|
+
if (need > s.length) {
|
|
1528
|
+
ret += s;
|
|
1529
|
+
need -= s.length;
|
|
1530
|
+
if (e.bytes !== undefined) {
|
|
1531
|
+
this._release(e.bytes);
|
|
1532
|
+
}
|
|
1533
|
+
j++;
|
|
1534
|
+
} else {
|
|
1535
|
+
if (need === s.length) {
|
|
1536
|
+
ret += s;
|
|
1537
|
+
if (e.bytes !== undefined) {
|
|
1538
|
+
this._release(e.bytes);
|
|
1539
|
+
}
|
|
1540
|
+
j++;
|
|
1541
|
+
} else {
|
|
1542
|
+
const head = s.slice(0, need);
|
|
1543
|
+
ret += head;
|
|
1544
|
+
if (e.bytes !== undefined) {
|
|
1545
|
+
const owed = Math.min(Buffer.byteLength(head, this._encoding), e.bytes);
|
|
1546
|
+
this._release(owed);
|
|
1547
|
+
e.bytes -= owed;
|
|
1548
|
+
}
|
|
1549
|
+
e.data = s.slice(need);
|
|
1550
|
+
}
|
|
1551
|
+
need = 0;
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
if (j > 0) {
|
|
1555
|
+
pending.splice(0, j);
|
|
1556
|
+
}
|
|
1557
|
+
if (pending.length === 0) {
|
|
1558
|
+
this._pending = null;
|
|
1559
|
+
}
|
|
1560
|
+
return ret;
|
|
1561
|
+
}
|
|
1562
|
+
const out = Buffer.allocUnsafe(n);
|
|
1563
|
+
let off = 0;
|
|
1564
|
+
let i = 0;
|
|
1565
|
+
let wire = 0;
|
|
1566
|
+
while (off < n) {
|
|
1567
|
+
const c = pending[i];
|
|
1568
|
+
const buf = c.length === undefined ? c.data : c;
|
|
1569
|
+
const take = buf.length <= n - off ? buf.length : n - off;
|
|
1570
|
+
buf.copy(out, off, 0, take);
|
|
1571
|
+
off += take;
|
|
1572
|
+
if (c.length !== undefined) {
|
|
1573
|
+
wire += take;
|
|
1574
|
+
}
|
|
1575
|
+
if (take === buf.length) {
|
|
1576
|
+
i++;
|
|
1577
|
+
} else {
|
|
1578
|
+
pending[i] = c.length === undefined ? { data: buf.subarray(take) } : buf.subarray(take);
|
|
1579
|
+
}
|
|
731
1580
|
}
|
|
732
|
-
if (
|
|
733
|
-
|
|
1581
|
+
if (i > 0) {
|
|
1582
|
+
pending.splice(0, i);
|
|
734
1583
|
}
|
|
735
|
-
if (
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
1584
|
+
if (pending.length === 0) {
|
|
1585
|
+
this._pending = null;
|
|
1586
|
+
}
|
|
1587
|
+
if (wire !== 0) {
|
|
1588
|
+
this._release(wire);
|
|
1589
|
+
}
|
|
1590
|
+
return out;
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
// node's Writable-side sibling call: push queued readable data with NO wire
|
|
1594
|
+
// accounting — the octets did not come off the socket, so _release must never
|
|
1595
|
+
// see them (a credit for them would advertise window the peer never spent).
|
|
1596
|
+
push(chunk, encoding) {
|
|
1597
|
+
if (chunk === null) {
|
|
1598
|
+
// push(null) is the EOF into the readable queue: it never returns true and
|
|
1599
|
+
// is silent when the EOF is already owed (node's onEofChunk early return).
|
|
1600
|
+
if (!this._eofSeen && !this._endPending && this._eofEmitted !== true) {
|
|
1601
|
+
this._eofSeen = true;
|
|
1602
|
+
this._endPending = true;
|
|
1603
|
+
this._flushDecoder();
|
|
1604
|
+
if (this._pending === null || this._pending.length === 0) {
|
|
1605
|
+
if (this._isConsuming()) {
|
|
1606
|
+
this._endPending = false;
|
|
1607
|
+
this._scheduleEOF();
|
|
1608
|
+
} else if (this.listenerCount('readable') > 0) {
|
|
1609
|
+
// node's onEofChunk sync branch, same mechanism as the wire EOF in
|
|
1610
|
+
// _remoteEnded: the pull consumer is woken synchronously, and the
|
|
1611
|
+
// 'end' waits for a read() (or a resume) that reaches the EOF.
|
|
1612
|
+
this.emit('readable');
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
740
1615
|
}
|
|
741
|
-
return;
|
|
1616
|
+
return false;
|
|
742
1617
|
}
|
|
743
|
-
if (
|
|
744
|
-
|
|
745
|
-
|
|
1618
|
+
if (chunk === undefined) {
|
|
1619
|
+
// node's byte-mode chain lets undefined fall past the type error into the
|
|
1620
|
+
// empty-chunk branch: no queueing, no event, the canPushMore return only.
|
|
1621
|
+
return this._canPushMore();
|
|
1622
|
+
}
|
|
1623
|
+
// node's readableAddChunkPushByteMode order is load-bearing: convert,
|
|
1624
|
+
// then the empty-chunk branch, and only after it the after-EOF error and
|
|
1625
|
+
// the destroyed silence -- an empty chunk after EOF returns canPushMore,
|
|
1626
|
+
// it does not error.
|
|
1627
|
+
let buf = chunk;
|
|
1628
|
+
let enc = encoding;
|
|
1629
|
+
if (typeof buf === 'string') {
|
|
1630
|
+
if (enc === undefined || enc === '') {
|
|
1631
|
+
enc = 'utf8'; // the readable side's defaultEncoding; setDefaultEncoding is the WRITABLE's
|
|
1632
|
+
}
|
|
1633
|
+
if (this._encoding !== enc) {
|
|
1634
|
+
buf = Buffer.from(buf, enc);
|
|
1635
|
+
enc = '';
|
|
1636
|
+
}
|
|
1637
|
+
} else if (buf instanceof Buffer) {
|
|
1638
|
+
enc = '';
|
|
1639
|
+
} else if (ArrayBuffer.isView(buf)) {
|
|
1640
|
+
buf = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1641
|
+
enc = '';
|
|
1642
|
+
} else {
|
|
1643
|
+
this.destroy(errorOf('ERR_INVALID_ARG_TYPE',
|
|
1644
|
+
'The "chunk" argument must be of type string or an instance of Buffer, ArrayBufferView, or DataView'));
|
|
1645
|
+
return false;
|
|
1646
|
+
}
|
|
1647
|
+
if (buf.length === 0) {
|
|
1648
|
+
return this._canPushMore();
|
|
1649
|
+
}
|
|
1650
|
+
if (this._eofSeen === true || this._eofEmitted === true) {
|
|
1651
|
+
const err = errorOf('ERR_STREAM_PUSH_AFTER_EOF', 'push() after EOF');
|
|
1652
|
+
if (!this._destroyed) {
|
|
1653
|
+
// node's errorOrDestroy destroys the stream through its autoDestroy, so
|
|
1654
|
+
// this arrives as 'error' then 'close' on the next ticks — the same
|
|
1655
|
+
// route the write-after-end shape takes in write() above.
|
|
1656
|
+
this.destroy(err);
|
|
1657
|
+
}
|
|
1658
|
+
return false;
|
|
1659
|
+
}
|
|
1660
|
+
if (this._destroyed || this._errorEmitted === true) {
|
|
1661
|
+
return false; // node: kDestroyed|kErrored is the silent false
|
|
1662
|
+
}
|
|
1663
|
+
if (this._decoder !== undefined && !enc) {
|
|
1664
|
+
// decode at the door, node's kDecoder branch: the queue holds characters
|
|
1665
|
+
// from here on. A chunk the decoder swallowed whole (a split multi-byte
|
|
1666
|
+
// sequence) queues nothing and wakes nothing -- canPushMore only.
|
|
1667
|
+
const str = this._decoder.write(buf);
|
|
1668
|
+
if (str.length === 0) {
|
|
1669
|
+
return this._canPushMore();
|
|
1670
|
+
}
|
|
1671
|
+
buf = str;
|
|
1672
|
+
}
|
|
1673
|
+
if (this._pending === null) {
|
|
1674
|
+
this._pending = [];
|
|
1675
|
+
}
|
|
1676
|
+
this._pending.push({ data: buf });
|
|
1677
|
+
this._scheduleReadable();
|
|
1678
|
+
return this._canPushMore();
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
// node's canPushMore: below the watermark, or nothing buffered, and never
|
|
1682
|
+
// past the EOF the readable queue has received.
|
|
1683
|
+
_canPushMore() {
|
|
1684
|
+
if (this._eofSeen === true) {
|
|
1685
|
+
return false;
|
|
1686
|
+
}
|
|
1687
|
+
const n = this.readableLength;
|
|
1688
|
+
return n < READABLE_HWM || n === 0;
|
|
1689
|
+
}
|
|
1690
|
+
|
|
1691
|
+
// node's Readable.prototype.setEncoding (readable.js:631), member by member:
|
|
1692
|
+
// a FRESH StringDecoder replaces whatever was set before (an unknown name
|
|
1693
|
+
// throws ERR_UNKNOWN_ENCODING synchronously out of the StringDecoder
|
|
1694
|
+
// constructor; `null` and `undefined` decode as utf8, and the getter reports
|
|
1695
|
+
// what the decoder normalised, not what the caller passed), the octets
|
|
1696
|
+
// already queued are decoded through it and merged into ONE string entry, and
|
|
1697
|
+
// if the EOF is already known the decoder's flush rides along. From here the
|
|
1698
|
+
// queue holds strings and `readableLength` counts characters -- node's
|
|
1699
|
+
// state.length does the same once a decoder exists, which is why the
|
|
1700
|
+
// watermark arithmetic in _canPushMore needs no special case. The wire
|
|
1701
|
+
// octets the merged string stands for stay credited as a bundle on its
|
|
1702
|
+
// consumption (the `bytes` field), so a setEncoding between DATA frames
|
|
1703
|
+
// cannot leak or invent window.
|
|
1704
|
+
setEncoding(enc) {
|
|
1705
|
+
const decoder = new StringDecoder(enc);
|
|
1706
|
+
this._decoder = decoder;
|
|
1707
|
+
this._encoding = decoder.encoding;
|
|
1708
|
+
const pending = this._pending;
|
|
1709
|
+
if (pending !== null) {
|
|
1710
|
+
let content = '';
|
|
1711
|
+
// octets the old decoder still held: they were never delivered and were
|
|
1712
|
+
// never credited; the merged entry inherits the debt.
|
|
1713
|
+
let wire = this._decHeld === undefined ? 0 : this._decHeld;
|
|
1714
|
+
this._decHeld = undefined;
|
|
1715
|
+
for (let i = 0; i < pending.length; i++) {
|
|
1716
|
+
const c = pending[i];
|
|
1717
|
+
if (c.length !== undefined) {
|
|
1718
|
+
content += decoder.write(c);
|
|
1719
|
+
wire += c.length;
|
|
1720
|
+
} else {
|
|
1721
|
+
content += decoder.write(c.data);
|
|
1722
|
+
if (c.bytes !== undefined) {
|
|
1723
|
+
wire += c.bytes;
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
if (this._eofSeen === true || this._endPending === true) {
|
|
1728
|
+
content += decoder.end();
|
|
1729
|
+
}
|
|
1730
|
+
pending.length = 0;
|
|
1731
|
+
this._pending = null;
|
|
1732
|
+
if (content !== '') {
|
|
1733
|
+
this._pending = [{ data: content, bytes: wire }];
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1736
|
+
return this;
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1739
|
+
// node's Writable.prototype.setDefaultEncoding (writable.js:537): the name is
|
|
1740
|
+
// lower-cased first because node::ParseEncoding requires it, an unknown one
|
|
1741
|
+
// throws ERR_UNKNOWN_ENCODING synchronously, and the call returns the stream.
|
|
1742
|
+
// It is the WRITABLE half's default -- what an encoding-less write(string)
|
|
1743
|
+
// encodes with; the readable side keeps its own 'utf8'.
|
|
1744
|
+
setDefaultEncoding(encoding) {
|
|
1745
|
+
if (typeof encoding === 'string') {
|
|
1746
|
+
encoding = encoding.toLowerCase();
|
|
1747
|
+
}
|
|
1748
|
+
if (!Buffer.isEncoding(encoding)) {
|
|
1749
|
+
const err = new TypeError(`Unknown encoding: ${encoding}`);
|
|
1750
|
+
err.code = 'ERR_UNKNOWN_ENCODING';
|
|
1751
|
+
throw err;
|
|
1752
|
+
}
|
|
1753
|
+
this._defaultEnc = encoding;
|
|
1754
|
+
return this;
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
// The EOF flush of the readable decoder -- node's onEofChunk head
|
|
1758
|
+
// (readable.js:849): the tail a split multi-byte sequence left in the decoder
|
|
1759
|
+
// becomes one last queue entry before the end machinery runs, carrying the
|
|
1760
|
+
// octets held there as its credit.
|
|
1761
|
+
_flushDecoder() {
|
|
1762
|
+
if (this._decoder === undefined) {
|
|
1763
|
+
return;
|
|
1764
|
+
}
|
|
1765
|
+
const tail = this._decoder.end();
|
|
1766
|
+
if (tail.length !== 0) {
|
|
1767
|
+
if (this._pending === null) {
|
|
1768
|
+
this._pending = [];
|
|
1769
|
+
}
|
|
1770
|
+
const bytes = this._decHeld === undefined ? 0 : this._decHeld;
|
|
1771
|
+
this._decHeld = undefined;
|
|
1772
|
+
this._pending.push({ data: tail, bytes });
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
|
|
1776
|
+
// node's Readable.prototype.pipe (internal/streams/readable.js:978), not the
|
|
1777
|
+
// legacy Stream.prototype.pipe the bare base would supply: the tracked
|
|
1778
|
+
// destination list, the unpipe() surface, and the teardown that makes a
|
|
1779
|
+
// destroyed or finished source end and unpipe its destinations -- measured
|
|
1780
|
+
// on a live node the sink of a stream destroyed mid-pipe reports
|
|
1781
|
+
// pipe,finish,unpipe,close where the legacy base stops at pipe,close
|
|
1782
|
+
// (test/pipe-parity.test.js). The await-drain bookkeeping is node's
|
|
1783
|
+
// single-dest fast value promoted to a Set for the second destination.
|
|
1784
|
+
pipe(dest, options) {
|
|
1785
|
+
const src = this;
|
|
1786
|
+
if (src._pipes === null) {
|
|
1787
|
+
src._pipes = [];
|
|
1788
|
+
}
|
|
1789
|
+
src._pipes.push(dest);
|
|
1790
|
+
|
|
1791
|
+
const doEnd = (!options || options.end !== false) &&
|
|
1792
|
+
dest !== process.stdout && dest !== process.stderr;
|
|
1793
|
+
const endFn = doEnd ? onend : unpipe;
|
|
1794
|
+
if (src._eofEmitted === true) {
|
|
1795
|
+
process.nextTick(endFn);
|
|
1796
|
+
} else {
|
|
1797
|
+
src.once('end', endFn);
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
dest.on('unpipe', onunpipe);
|
|
1801
|
+
function onunpipe(readable, unpipeInfo) {
|
|
1802
|
+
if (readable === src) {
|
|
1803
|
+
if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
|
|
1804
|
+
unpipeInfo.hasUnpiped = true;
|
|
1805
|
+
cleanup();
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
function onend() {
|
|
1811
|
+
dest.end();
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
let ondrain;
|
|
1815
|
+
let cleanedUp = false;
|
|
1816
|
+
function cleanup() {
|
|
1817
|
+
dest.removeListener('close', onclose);
|
|
1818
|
+
dest.removeListener('finish', onfinish);
|
|
1819
|
+
if (ondrain) {
|
|
1820
|
+
dest.removeListener('drain', ondrain);
|
|
1821
|
+
}
|
|
1822
|
+
dest.removeListener('error', onerror);
|
|
1823
|
+
dest.removeListener('unpipe', onunpipe);
|
|
1824
|
+
src.removeListener('end', onend);
|
|
1825
|
+
src.removeListener('end', unpipe);
|
|
1826
|
+
src.removeListener('data', ondata);
|
|
1827
|
+
cleanedUp = true;
|
|
1828
|
+
// a dest that errored or closed while the source waited on its drain
|
|
1829
|
+
// must not leave the flow parked for a writer that is gone
|
|
1830
|
+
if (ondrain && src._awaitDrain !== null) {
|
|
1831
|
+
ondrain();
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
function pause() {
|
|
1836
|
+
if (!cleanedUp) {
|
|
1837
|
+
if (src._pipes.length === 1 && src._pipes[0] === dest) {
|
|
1838
|
+
src._awaitDrain = dest;
|
|
1839
|
+
} else if (src._pipes.includes(dest)) {
|
|
1840
|
+
if (!(src._awaitDrain instanceof Set)) {
|
|
1841
|
+
src._awaitDrain = new Set(src._awaitDrain === null ? [] : [src._awaitDrain]);
|
|
1842
|
+
}
|
|
1843
|
+
src._awaitDrain.add(dest);
|
|
1844
|
+
}
|
|
1845
|
+
src.pause();
|
|
1846
|
+
}
|
|
1847
|
+
if (!ondrain) {
|
|
1848
|
+
ondrain = pipeOnDrain;
|
|
1849
|
+
dest.on('drain', ondrain);
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1853
|
+
function pipeOnDrain() {
|
|
1854
|
+
const a = src._awaitDrain;
|
|
1855
|
+
if (a === dest) {
|
|
1856
|
+
src._awaitDrain = null;
|
|
1857
|
+
} else if (a instanceof Set) {
|
|
1858
|
+
a.delete(dest);
|
|
1859
|
+
}
|
|
1860
|
+
const still = src._awaitDrain;
|
|
1861
|
+
if ((still === null || still.size === 0) && src.listenerCount('data') > 0) {
|
|
1862
|
+
src.resume();
|
|
1863
|
+
}
|
|
1864
|
+
}
|
|
1865
|
+
|
|
1866
|
+
src.on('data', ondata);
|
|
1867
|
+
function ondata(chunk) {
|
|
1868
|
+
try {
|
|
1869
|
+
if (dest.write(chunk) === false) {
|
|
1870
|
+
pause();
|
|
1871
|
+
}
|
|
1872
|
+
} catch (error) {
|
|
1873
|
+
dest.destroy(error);
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
// If the dest has an error, then stop piping into it. However, don't
|
|
1878
|
+
// suppress the throwing behavior for this (node's comment, verbatim rule).
|
|
1879
|
+
function onerror(er) {
|
|
1880
|
+
unpipe();
|
|
1881
|
+
dest.removeListener('error', onerror);
|
|
1882
|
+
if (dest.listenerCount('error') === 0) {
|
|
1883
|
+
const s = dest._writableState || dest._readableState;
|
|
1884
|
+
if (s && !s.errorEmitted) {
|
|
1885
|
+
dest.destroy(er);
|
|
1886
|
+
} else {
|
|
1887
|
+
dest.emit('error', er);
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
dest.prependListener('error', onerror);
|
|
1892
|
+
|
|
1893
|
+
// Both close and finish should trigger unpipe, but only once.
|
|
1894
|
+
function onclose() {
|
|
1895
|
+
dest.removeListener('finish', onfinish);
|
|
1896
|
+
unpipe();
|
|
1897
|
+
}
|
|
1898
|
+
dest.once('close', onclose);
|
|
1899
|
+
function onfinish() {
|
|
1900
|
+
dest.removeListener('close', onclose);
|
|
1901
|
+
unpipe();
|
|
1902
|
+
}
|
|
1903
|
+
dest.once('finish', onfinish);
|
|
1904
|
+
|
|
1905
|
+
function unpipe() {
|
|
1906
|
+
src.unpipe(dest);
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
dest.emit('pipe', src);
|
|
1910
|
+
|
|
1911
|
+
if (dest.writableNeedDrain === true) {
|
|
1912
|
+
pause();
|
|
1913
|
+
} else if (src._flowing !== true) {
|
|
1914
|
+
src.resume();
|
|
1915
|
+
}
|
|
1916
|
+
return dest;
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
// node's Readable.prototype.unpipe (readable.js:1180): no argument removes
|
|
1920
|
+
// every destination and stops the flow; one argument removes that
|
|
1921
|
+
// destination if it is piped to, and the call is its own 'unpipe' event
|
|
1922
|
+
// onto the dest with the hasUnpiped record the pipe closure cleans up on.
|
|
1923
|
+
unpipe(dest) {
|
|
1924
|
+
const pipes = this._pipes;
|
|
1925
|
+
if (pipes === null || pipes.length === 0) {
|
|
1926
|
+
return this;
|
|
1927
|
+
}
|
|
1928
|
+
if (!dest) {
|
|
1929
|
+
const dests = pipes;
|
|
1930
|
+
this._pipes = [];
|
|
1931
|
+
this.pause();
|
|
1932
|
+
for (let i = 0; i < dests.length; i++) {
|
|
1933
|
+
dests[i].emit('unpipe', this, { hasUnpiped: false });
|
|
1934
|
+
}
|
|
1935
|
+
return this;
|
|
1936
|
+
}
|
|
1937
|
+
const index = pipes.indexOf(dest);
|
|
1938
|
+
if (index === -1) {
|
|
1939
|
+
return this;
|
|
1940
|
+
}
|
|
1941
|
+
pipes.splice(index, 1);
|
|
1942
|
+
if (pipes.length === 0) {
|
|
1943
|
+
this.pause();
|
|
1944
|
+
}
|
|
1945
|
+
dest.emit('unpipe', this, { hasUnpiped: false });
|
|
1946
|
+
return this;
|
|
1947
|
+
}
|
|
1948
|
+
|
|
1949
|
+
// --- the async-iteration surface -------------------------------------------
|
|
1950
|
+
// node's readable-iteration protocol (internal/streams/readable.js:1552-1805)
|
|
1951
|
+
// and the fourteen helpers the public `stream` module bolts onto the same
|
|
1952
|
+
// prototype (stream.js:72-103, wrapping internal/streams/operators): the
|
|
1953
|
+
// transform family returns `Readable.from(generator)` -- measured on a live
|
|
1954
|
+
// node server stream: `map(fn)` yields an objectMode Readable -- and the
|
|
1955
|
+
// promise family returns the operation's promise. The iterator itself is a
|
|
1956
|
+
// pull machine over read(); break over for-await destroys through the
|
|
1957
|
+
// iterator's return() (AbortError into _destroy, RST CANCEL(8), events
|
|
1958
|
+
// aborted, error:ABORT_ERR, close), while a natural end leaves the stream
|
|
1959
|
+
// alive -- node reaches finalize() in both cases, but Http2Stream sets
|
|
1960
|
+
// autoDestroy false (core.js:2132), so only the still-active return()
|
|
1961
|
+
// branch satisfies finalize's second clause (measured: destroyed false,
|
|
1962
|
+
// readableEnded true after a clean loop; destroyed true, rstCode 8 after
|
|
1963
|
+
// break, both read inside the same handler turn).
|
|
1964
|
+
[Symbol.asyncIterator]() {
|
|
1965
|
+
return createStreamIterator(this, undefined);
|
|
1966
|
+
}
|
|
1967
|
+
|
|
1968
|
+
iterator(options) {
|
|
1969
|
+
if (options !== undefined) {
|
|
1970
|
+
validateObjectArg(options, 'options');
|
|
1971
|
+
}
|
|
1972
|
+
return createStreamIterator(this, options);
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1975
|
+
map(fn, options) {
|
|
1976
|
+
return Readable.from(opMap(this, fn, options));
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
filter(fn, options) {
|
|
1980
|
+
return Readable.from(opFilter(this, fn, options));
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
flatMap(fn, options) {
|
|
1984
|
+
return Readable.from(opFlatMap(this, fn, options));
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
drop(number, options) {
|
|
1988
|
+
return Readable.from(opDrop(this, number, options));
|
|
1989
|
+
}
|
|
1990
|
+
|
|
1991
|
+
take(number, options) {
|
|
1992
|
+
return Readable.from(opTake(this, number, options));
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
reduce(reducer, initialValue, options) {
|
|
1996
|
+
// node's reduce tests `arguments.length > 1` inside the operator to tell
|
|
1997
|
+
// "no initial value" from "initial value undefined"; the arity has to be
|
|
1998
|
+
// read at the call, which is here.
|
|
1999
|
+
return opReduce(this, arguments.length > 1, reducer, initialValue, options);
|
|
2000
|
+
}
|
|
2001
|
+
|
|
2002
|
+
forEach(fn, options) {
|
|
2003
|
+
return opForEach(this, fn, options);
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
toArray(options) {
|
|
2007
|
+
return opToArray(this, options);
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
some(fn, options) {
|
|
2011
|
+
return opSome(this, fn, options);
|
|
2012
|
+
}
|
|
2013
|
+
|
|
2014
|
+
every(fn, options) {
|
|
2015
|
+
return opEvery(this, fn, options);
|
|
2016
|
+
}
|
|
2017
|
+
|
|
2018
|
+
find(fn, options) {
|
|
2019
|
+
return opFind(this, fn, options);
|
|
2020
|
+
}
|
|
2021
|
+
|
|
2022
|
+
// node's Readable.prototype.compose (readable.js:1810 plus
|
|
2023
|
+
// internal/streams/compose.js, the Node-stream branch): the composed Duplex
|
|
2024
|
+
// writes into this and reads out of the chain behind it. h2lean drives the
|
|
2025
|
+
// two-stream chain with its own pipe() -- the port of Readable.prototype.pipe
|
|
2026
|
+
// above -- where node uses internal/streams/pipeline; for the prototype
|
|
2027
|
+
// method's single argument those are the same chain (src 'end' -> dest.end(),
|
|
2028
|
+
// src error -> dest teardown), and the rest is node's wiring verbatim:
|
|
2029
|
+
// d._write into head with the drain callback, d._final = head.end(),
|
|
2030
|
+
// tail 'data'/'end' into d.push, teardown destroying the tail. Web streams
|
|
2031
|
+
// (TransformStream and friends) are refused here where node composes them --
|
|
2032
|
+
// KNOWN DIVERGENCE, stated in the header of this file's difference list.
|
|
2033
|
+
compose(stream, options) {
|
|
2034
|
+
if (options != null) {
|
|
2035
|
+
validateObjectArg(options, 'options');
|
|
2036
|
+
}
|
|
2037
|
+
validateSignalArg(options);
|
|
2038
|
+
const tail = typeof stream === 'function' ? Duplex.from(stream) : stream;
|
|
2039
|
+
if (tail === null || typeof tail !== 'object' ||
|
|
2040
|
+
typeof tail.pipe !== 'function' || typeof tail.write !== 'function') {
|
|
2041
|
+
// node's internal compose SKIPS non-streams in its own loop (the
|
|
2042
|
+
// "TODO: add checks for non streams" branch) and the refusal actually
|
|
2043
|
+
// comes from pipeline's `body` validation -- measured code:
|
|
2044
|
+
// ERR_INVALID_ARG_TYPE, not ERR_INVALID_ARG_VALUE.
|
|
2045
|
+
throw errorOf('ERR_INVALID_ARG_TYPE',
|
|
2046
|
+
'The "body" argument must be of type function or an instance of Stream. ' +
|
|
2047
|
+
`Received type ${typeof stream} (${inspect(stream)}).`);
|
|
2048
|
+
}
|
|
2049
|
+
let ondrain = null;
|
|
2050
|
+
let onfinish = null;
|
|
2051
|
+
let onclose = undefined;
|
|
2052
|
+
const src = this;
|
|
2053
|
+
const d = new Duplex({
|
|
2054
|
+
writableObjectMode: !!src.writableObjectMode,
|
|
2055
|
+
readableObjectMode: !!tail.readableObjectMode,
|
|
2056
|
+
writable: true,
|
|
2057
|
+
readable: true
|
|
2058
|
+
});
|
|
2059
|
+
|
|
2060
|
+
function onfinished(err) {
|
|
2061
|
+
const cb = onclose;
|
|
2062
|
+
onclose = null;
|
|
2063
|
+
if (cb) {
|
|
2064
|
+
cb(err);
|
|
2065
|
+
} else if (err) {
|
|
2066
|
+
d.destroy(err);
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
// the writable half, node's d._write/d._final over head = this.
|
|
2071
|
+
d._write = function (chunk, encoding, callback) {
|
|
2072
|
+
if (src.write(chunk, encoding)) {
|
|
2073
|
+
callback();
|
|
2074
|
+
} else {
|
|
2075
|
+
ondrain = callback;
|
|
2076
|
+
}
|
|
2077
|
+
};
|
|
2078
|
+
d._final = function (callback) {
|
|
2079
|
+
src.end();
|
|
2080
|
+
onfinish = callback;
|
|
2081
|
+
};
|
|
2082
|
+
src.on('drain', () => {
|
|
2083
|
+
if (ondrain) {
|
|
2084
|
+
const cb = ondrain;
|
|
2085
|
+
ondrain = null;
|
|
2086
|
+
cb();
|
|
2087
|
+
}
|
|
2088
|
+
});
|
|
2089
|
+
|
|
2090
|
+
// node's pipeline([head, tail], onfinished): the chain is this pipe, and
|
|
2091
|
+
// any chain error reaches onfinished the way the pipeline callback takes
|
|
2092
|
+
// it (the pipe's own dest-side teardown is already node's behaviour).
|
|
2093
|
+
src.pipe(tail);
|
|
2094
|
+
src.on('error', onfinished);
|
|
2095
|
+
tail.on('error', onfinished);
|
|
2096
|
+
|
|
2097
|
+
// node's eos(toRead, cb) that releases d._final's callback.
|
|
2098
|
+
finished(tail, () => {
|
|
2099
|
+
if (onfinish) {
|
|
2100
|
+
const cb = onfinish;
|
|
2101
|
+
onfinish = null;
|
|
2102
|
+
cb();
|
|
2103
|
+
}
|
|
2104
|
+
});
|
|
2105
|
+
|
|
2106
|
+
// the readable half, node's tail 'data'/'end' push.
|
|
2107
|
+
d._read = function () {
|
|
2108
|
+
tail.resume();
|
|
2109
|
+
};
|
|
2110
|
+
tail.on('data', (chunk) => {
|
|
2111
|
+
if (!d.push(chunk)) {
|
|
2112
|
+
tail.pause();
|
|
2113
|
+
}
|
|
2114
|
+
});
|
|
2115
|
+
tail.on('end', () => {
|
|
2116
|
+
d.push(null);
|
|
2117
|
+
});
|
|
2118
|
+
|
|
2119
|
+
d._destroy = function (err, callback) {
|
|
2120
|
+
if (!err && onclose !== null) {
|
|
2121
|
+
err = abortError();
|
|
2122
|
+
}
|
|
2123
|
+
ondrain = null;
|
|
2124
|
+
onfinish = null;
|
|
2125
|
+
destroyStream(tail, err);
|
|
2126
|
+
if (onclose === null) {
|
|
2127
|
+
callback(err);
|
|
2128
|
+
} else {
|
|
2129
|
+
onclose = callback;
|
|
2130
|
+
}
|
|
2131
|
+
};
|
|
2132
|
+
|
|
2133
|
+
if (options && options.signal) {
|
|
2134
|
+
addAbortSignal(options.signal, d);
|
|
2135
|
+
}
|
|
2136
|
+
return d;
|
|
2137
|
+
}
|
|
2138
|
+
|
|
2139
|
+
// node's legacy Readable.prototype.wrap (readable.js:1503) -- the "ugly
|
|
2140
|
+
// unfortunate mess of history" that turns any event source into readable
|
|
2141
|
+
// data on this stream. It is honest machinery here because push() is node's
|
|
2142
|
+
// (task 39) and the pull-side resume hook fires where node's maybeReadMore
|
|
2143
|
+
// would call _read.
|
|
2144
|
+
wrap(stream) {
|
|
2145
|
+
let paused = false;
|
|
2146
|
+
stream.on('data', (chunk) => {
|
|
2147
|
+
if (!this.push(chunk) && stream.pause) {
|
|
2148
|
+
paused = true;
|
|
2149
|
+
stream.pause();
|
|
2150
|
+
}
|
|
2151
|
+
});
|
|
2152
|
+
stream.on('end', () => {
|
|
2153
|
+
this.push(null);
|
|
2154
|
+
});
|
|
2155
|
+
stream.on('error', (err) => {
|
|
2156
|
+
if (!this.destroyed) {
|
|
2157
|
+
this.destroy(err);
|
|
2158
|
+
}
|
|
2159
|
+
});
|
|
2160
|
+
stream.on('close', () => {
|
|
2161
|
+
if (!this.destroyed) {
|
|
2162
|
+
this.destroy();
|
|
2163
|
+
}
|
|
2164
|
+
});
|
|
2165
|
+
stream.on('destroy', () => {
|
|
2166
|
+
if (!this.destroyed) {
|
|
2167
|
+
this.destroy();
|
|
2168
|
+
}
|
|
2169
|
+
});
|
|
2170
|
+
this._read = () => {
|
|
2171
|
+
if (paused && stream.resume) {
|
|
2172
|
+
paused = false;
|
|
2173
|
+
stream.resume();
|
|
2174
|
+
}
|
|
2175
|
+
};
|
|
2176
|
+
const streamKeys = Object.keys(stream);
|
|
2177
|
+
for (let j = 0; j < streamKeys.length; j++) {
|
|
2178
|
+
const i = streamKeys[j];
|
|
2179
|
+
if (this[i] === undefined && typeof stream[i] === 'function') {
|
|
2180
|
+
this[i] = stream[i].bind(stream);
|
|
2181
|
+
}
|
|
2182
|
+
}
|
|
2183
|
+
return this;
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
// The pull model's arrival event: node's readable-mode consumer is woken by
|
|
2187
|
+
// 'readable', never by the bytes themselves. Coalescing is node's
|
|
2188
|
+
// needReadable/emitReadable pair — one event per un-observed stretch, so two
|
|
2189
|
+
// DATA frames in one read batch produce one event (measured: readablePasses 2
|
|
2190
|
+
// for three reads over one arrival).
|
|
2191
|
+
_scheduleReadable() {
|
|
2192
|
+
if (this._readableScheduled === true || this.listenerCount('readable') === 0) {
|
|
2193
|
+
return;
|
|
2194
|
+
}
|
|
2195
|
+
this._readableScheduled = true;
|
|
2196
|
+
process.nextTick(() => {
|
|
2197
|
+
this._readableScheduled = false;
|
|
2198
|
+
if (this._destroyed || this._flowing === true ||
|
|
2199
|
+
this.listenerCount('readable') === 0) {
|
|
2200
|
+
return;
|
|
2201
|
+
}
|
|
2202
|
+
// nothing to report if the queue drained between the schedule and the tick
|
|
2203
|
+
// (node's read() clears needReadable the same way)
|
|
2204
|
+
if (this._pending === null && !this._endPending && this._eofSeen !== true) {
|
|
2205
|
+
return;
|
|
2206
|
+
}
|
|
2207
|
+
this.emit('readable');
|
|
2208
|
+
});
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2211
|
+
// The end-of-stream schedule — node's endReadable: the 'end' never overtakes
|
|
2212
|
+
// buffered octets, and one schedule is enough (the kEndScheduled bit).
|
|
2213
|
+
_scheduleEOF() {
|
|
2214
|
+
if (this._eofEmitted === true || this._eofScheduled === true) {
|
|
2215
|
+
return;
|
|
2216
|
+
}
|
|
2217
|
+
this._eofScheduled = true;
|
|
2218
|
+
process.nextTick(() => {
|
|
2219
|
+
this._eofScheduled = false;
|
|
2220
|
+
if (this._destroyed || this._eofEmitted === true) {
|
|
2221
|
+
return;
|
|
2222
|
+
}
|
|
2223
|
+
if (this._pending !== null && this._pending.length > 0) {
|
|
2224
|
+
// a push landed between the trigger and the tick: the EOF is owed to the
|
|
2225
|
+
// drain again (node's endReadableNT re-checks state.length === 0 and
|
|
2226
|
+
// simply skips the emission here)
|
|
2227
|
+
this._endPending = true;
|
|
2228
|
+
return;
|
|
2229
|
+
}
|
|
2230
|
+
this._endPending = false;
|
|
2231
|
+
emitEndNT(this);
|
|
2232
|
+
});
|
|
2233
|
+
}
|
|
2234
|
+
|
|
2235
|
+
// node maps a per-stream timeout onto the connection's idle timeout.
|
|
2236
|
+
setTimeout(ms, cb) {
|
|
2237
|
+
this.session.setTimeout(ms, cb);
|
|
2238
|
+
return this;
|
|
2239
|
+
}
|
|
2240
|
+
|
|
2241
|
+
// --- internals used by the session ------------------------------------------
|
|
2242
|
+
// Both halves have to converge: a handler that answers synchronously inside
|
|
2243
|
+
// the 'stream' emit closes the local side BEFORE the peer's END_STREAM is
|
|
2244
|
+
// reported, and vice versa. Whichever call sees both halves closed is the one
|
|
2245
|
+
// that removes the stream from the session -- without it every request leaks
|
|
2246
|
+
// an Http2Stream (and _liveStreams never falls, so close() never finishes).
|
|
2247
|
+
_remoteEnded() {
|
|
2248
|
+
if (this._state.remoteClose === 1) {
|
|
2249
|
+
return;
|
|
2250
|
+
}
|
|
2251
|
+
// The other half of the content-length promise: too many octets is caught as they arrive
|
|
2252
|
+
// (session _onDataFrame, a connection error), too few can only be seen here, where the
|
|
2253
|
+
// message ends. Measured on node (h2spec http2/8.1.2.6): RST_STREAM(PROTOCOL_ERROR) and the
|
|
2254
|
+
// application is told ERR_HTTP2_STREAM_ERROR -- the short body is one request's failure, not
|
|
2255
|
+
// the session's, which is the same split nghttp2 makes and the reason the two directions of
|
|
2256
|
+
// the same lie get two different codes.
|
|
2257
|
+
if (this._expLen >= 0 && this._bodyLen < this._expLen) {
|
|
2258
|
+
this.session._streamError(this, PROTOCOL_ERROR, `content-length ${this._expLen} with only ` +
|
|
2259
|
+
`${this._bodyLen} octets received`);
|
|
2260
|
+
return;
|
|
2261
|
+
}
|
|
2262
|
+
this._state.remoteClose = 1;
|
|
2263
|
+
this.endAfterHeaders = true;
|
|
2264
|
+
// node's onEofChunk runs when the END_STREAM is processed, and with a
|
|
2265
|
+
// decoder set it flushes the split sequence held there into the queue
|
|
2266
|
+
// BEFORE any of the end machinery below -- the tail octets are owed to the
|
|
2267
|
+
// reader that arrives later, exactly like the bytes before them.
|
|
2268
|
+
this._flushDecoder();
|
|
2269
|
+
// the readable side is done: 'end' after the last 'data', like a Readable.
|
|
2270
|
+
// No auto-destroy: the application still has to answer. node keeps the
|
|
2271
|
+
// writable side of an unanswered request open as well.
|
|
2272
|
+
if (this._state.localClose === 1 && !this._waitForTrailers) {
|
|
2273
|
+
// The local half is only *finished* once END_STREAM left on the wire. A stream that
|
|
2274
|
+
// still owes a trailer block owes that END_STREAM too -- the body DATA was framed
|
|
2275
|
+
// without it (sendTrailers() puts the close on the trailer block, or on an empty DATA
|
|
2276
|
+
// when the block has no fields) -- so closing here would leave the response
|
|
2277
|
+
// unanswered for the peer and drop the owed frame. node's rule is the same and lives
|
|
2278
|
+
// in the writable shutdown, not in the read path: a stream with
|
|
2279
|
+
// STREAM_FLAGS_HAS_TRAILERS set is not shut down early
|
|
2280
|
+
// (internal/http2/core.js, `Trailers are pending, so the writable side cannot be
|
|
2281
|
+
// shut down early`). Measured: a compat response that ends with no body against an
|
|
2282
|
+
// unread request put HEADERS then a zero-length DATA/END_STREAM on node's wire, with
|
|
2283
|
+
// the stream close after both; ending here sent the HEADERS only and the client
|
|
2284
|
+
// waited for an answer that never came.
|
|
2285
|
+
this._closeNow();
|
|
2286
|
+
process.nextTick(emitEndCloseNT, this);
|
|
2287
|
+
return;
|
|
2288
|
+
}
|
|
2289
|
+
if (this._state.state === ST_OPEN) {
|
|
2290
|
+
this._state.state = ST_HALF_CLOSED_REMOTE;
|
|
2291
|
+
}
|
|
2292
|
+
if (!this._isConsuming()) {
|
|
2293
|
+
// Nothing has read the buffered bytes yet, so 'end' must not overtake them:
|
|
2294
|
+
// a reader that attaches later is owed the whole sequence, EOF included.
|
|
2295
|
+
this._endPending = true;
|
|
2296
|
+
// node's onEofChunk, measured stack (emitReadable_ <- onEofChunk <- the
|
|
2297
|
+
// stream_base read callback at END_STREAM): the EOF push emits 'readable'
|
|
2298
|
+
// SYNCHRONOUSLY inside the frame batch, not on a tick — the merge arm sees
|
|
2299
|
+
// the second 'readable' fire in the ES callback itself while the arrival
|
|
2300
|
+
// tick still runs its own. With no pull listener the sync emit is the
|
|
2301
|
+
// no-op node's listener-less emit performs, and the parked EOF waits for
|
|
2302
|
+
// the reader exactly as before.
|
|
2303
|
+
if (this.listenerCount('readable') > 0) {
|
|
2304
|
+
this.emit('readable');
|
|
2305
|
+
}
|
|
2306
|
+
return;
|
|
2307
|
+
}
|
|
2308
|
+
process.nextTick(emitEndNT, this);
|
|
2309
|
+
}
|
|
2310
|
+
|
|
2311
|
+
// The writable-side 'finish' -- node's Writable fires it once every write has been
|
|
2312
|
+
// accepted by the stream machinery and the writable half has ended; a destroy in
|
|
2313
|
+
// the same turn as the end() cancels it (upstream's test-http2-respond-with-fd-finish.js
|
|
2314
|
+
// pins both shapes: finish, then close with writableFinished true on a clean send;
|
|
2315
|
+
// close with writableFinished false and no 'finish' on an abort). The tick is also
|
|
2316
|
+
// what keeps the event behind 'wantTrailers' -- measured on v26.12.1, 'finish'
|
|
2317
|
+
// precedes 'wantTrailers' on the trailers shape. A body still queued on window
|
|
2318
|
+
// credit re-runs _endLocalSide when the queue drains (session._release), which is
|
|
2319
|
+
// where the second scheduling comes from.
|
|
2320
|
+
_scheduleFinish() {
|
|
2321
|
+
if (this._writableFinished || this._finishQueued) {
|
|
2322
|
+
return;
|
|
2323
|
+
}
|
|
2324
|
+
this._finishQueued = true;
|
|
2325
|
+
process.nextTick(() => {
|
|
2326
|
+
this._finishQueued = false;
|
|
2327
|
+
// not _destroyed here: a stream whose both halves close in the same turn the
|
|
2328
|
+
// writable ends flips ST_CLOSED synchronously (_closeNow) while the close EVENTS
|
|
2329
|
+
// are deferred -- and node's order for that shape is 'finish' before 'close',
|
|
2330
|
+
// with writableFinished true at the close (measured). The only cancel is a
|
|
2331
|
+
// writable that never drained: octets still parked on window credit.
|
|
2332
|
+
if (this._writableFinished || this._queued !== null) {
|
|
2333
|
+
return;
|
|
2334
|
+
}
|
|
2335
|
+
this._writableFinished = true;
|
|
2336
|
+
this.emit('finish');
|
|
2337
|
+
});
|
|
2338
|
+
}
|
|
2339
|
+
|
|
2340
|
+
_endLocalSide() {
|
|
2341
|
+
const first = this._state.localClose !== 1;
|
|
2342
|
+
this._state.localClose = 1;
|
|
2343
|
+
this._endQueued = false;
|
|
2344
|
+
if (this._blockRefused) {
|
|
2345
|
+
// The half-close is the application's, and node records it whether or not the
|
|
2346
|
+
// octets went out (`_writableState.ending` is what decides 'aborted'). The close
|
|
2347
|
+
// machinery below must not run: it would finish the stream with NO_ERROR here,
|
|
2348
|
+
// synchronously, ahead of the deferred FRAME_SIZE_ERROR close node's onFrameError
|
|
2349
|
+
// schedules -- measured, node reports rstCode 6 for this shape and h2lean reported 0.
|
|
2350
|
+
return;
|
|
2351
|
+
}
|
|
2352
|
+
if (this._queued === null) {
|
|
2353
|
+
// every octet handed over has been accepted by the session: node's condition
|
|
2354
|
+
// for the writable 'finish'
|
|
2355
|
+
this._scheduleFinish();
|
|
2356
|
+
}
|
|
2357
|
+
if (this._state.state === ST_OPEN) {
|
|
2358
|
+
this._state.state = ST_HALF_CLOSED_LOCAL;
|
|
2359
|
+
}
|
|
2360
|
+
if (this._waitForTrailers) {
|
|
2361
|
+
// one shot: a later end() must not ask for trailers a second time. The flag
|
|
2362
|
+
// itself stays set, because sendTrailers() is only allowed while it is set.
|
|
2363
|
+
if (first) {
|
|
2364
|
+
process.nextTick(wantTrailersNT, this);
|
|
2365
|
+
}
|
|
2366
|
+
return;
|
|
2367
|
+
}
|
|
2368
|
+
if (this._state.remoteClose === 1) {
|
|
2369
|
+
this._closeIfBothDone();
|
|
2370
|
+
} else {
|
|
746
2371
|
// the response is over and the peer's half is not: this is the shape node
|
|
747
2372
|
// closes for the application (see _maybeAutoClose). A stream the peer has
|
|
748
2373
|
// already ended takes the graceful close above, which is also what node's
|
|
@@ -770,7 +2395,8 @@ class Http2Stream extends Stream {
|
|
|
770
2395
|
// touched the request, and node stops there too.
|
|
771
2396
|
_maybeAutoClose() {
|
|
772
2397
|
if (this._destroyed || !this.headersSent || this._waitForTrailers ||
|
|
773
|
-
this._consumeState !== 0
|
|
2398
|
+
this._consumeState !== 0 || this._flowing === false ||
|
|
2399
|
+
this._dataRead === true) {
|
|
774
2400
|
return;
|
|
775
2401
|
}
|
|
776
2402
|
// node's own deferral: the RST goes out a turn after the response, and the
|
|
@@ -791,12 +2417,12 @@ class Http2Stream extends Stream {
|
|
|
791
2417
|
// in _endPending for a reader that never appeared, and the local close below was the last
|
|
792
2418
|
// event the stream ever produced. Measured against node on exactly that shape: it emits
|
|
793
2419
|
// stream.end then stream.close (test/event-order.test.js, scenario eof).
|
|
794
|
-
if (this._endPending) {
|
|
2420
|
+
if (this._endPending || this._eofSeen === true) {
|
|
795
2421
|
this._endPending = false;
|
|
796
2422
|
process.nextTick(emitEndCloseNT, this);
|
|
797
2423
|
return;
|
|
798
2424
|
}
|
|
799
|
-
process.nextTick(
|
|
2425
|
+
process.nextTick(emitCloseDeliveredNT, this);
|
|
800
2426
|
}
|
|
801
2427
|
|
|
802
2428
|
_closeNow() {
|
|
@@ -805,9 +2431,13 @@ class Http2Stream extends Stream {
|
|
|
805
2431
|
this._gracefulClose = true;
|
|
806
2432
|
this._pending = null;
|
|
807
2433
|
this.session._dropStream(this, false);
|
|
808
|
-
// node drops the session reference
|
|
809
|
-
//
|
|
810
|
-
this.
|
|
2434
|
+
// node drops the stream's session reference in _destroy (internal/http2/core.js:2546,
|
|
2435
|
+
// `this[kSession] = undefined`) -- which for node runs only when nghttp2 closes the
|
|
2436
|
+
// stream, a tick after the end() that queued this close. The drop therefore moves to
|
|
2437
|
+
// the close-delivery tick (emitEndCloseNT/emitCloseDeliveredNT), keeping the
|
|
2438
|
+
// same-turn window live for pushStream exactly as node's window is. The _destroy path
|
|
2439
|
+
// (a peer reset) keeps its own synchronous drop -- node's nghttp2 closes that stream
|
|
2440
|
+
// inside the read batch.
|
|
811
2441
|
}
|
|
812
2442
|
|
|
813
2443
|
_destroy(code, reason, sendRst, err) {
|
|
@@ -815,14 +2445,28 @@ class Http2Stream extends Stream {
|
|
|
815
2445
|
return;
|
|
816
2446
|
}
|
|
817
2447
|
this._destroyed = true;
|
|
2448
|
+
// node's destroy does not touch state.flowing — the readableFlowing getter keeps
|
|
2449
|
+
// reporting the last resume()/pause()/listener verdict even after the destroy
|
|
2450
|
+
// (measured: snapError inside the 'error' handler reads flowing true post-resume),
|
|
2451
|
+
// and every consumer here gates on _destroyed first.
|
|
2452
|
+
// node's destroy() runs checkError BEFORE the destroyed bit and before the
|
|
2453
|
+
// nextTick that emits: state.errored is already set in the same turn the
|
|
2454
|
+
// destroy happens (destroy.js checkError), so a getter read right after
|
|
2455
|
+
// destroy(err) sees it — the deferred emitErrorCloseNT only carries the event.
|
|
2456
|
+
if (err) {
|
|
2457
|
+
this._streamErrored = err;
|
|
2458
|
+
}
|
|
818
2459
|
this.rstCode = code;
|
|
819
|
-
// node's rule for 'aborted' is about the
|
|
820
|
-
//
|
|
821
|
-
//
|
|
822
|
-
// server: a peer that resets a stream whose
|
|
823
|
-
// whose
|
|
824
|
-
//
|
|
825
|
-
|
|
2460
|
+
// node's rule for 'aborted' is about the WRITABLE side: "if the writable side of
|
|
2461
|
+
// the Http2Stream is still open, emit the 'aborted' event" -- closeStream's
|
|
2462
|
+
// `const { ending } = stream._writableState; if (!ending) ...`. The same shapes
|
|
2463
|
+
// measured against a live node server: a peer that resets a stream whose response
|
|
2464
|
+
// never started and whose end() never ran reports 'aborted'; a stream whose
|
|
2465
|
+
// writable ended -- by end(), by a file pump (node's processRespondWithFD calls
|
|
2466
|
+
// self.end() before the pump) -- does not, even when the octets are still in
|
|
2467
|
+
// flight. _ending is the portable reading of `ending`; _state.localClose would
|
|
2468
|
+
// answer the file paths wrong.
|
|
2469
|
+
const responseOpen = !this._ending;
|
|
826
2470
|
this._state.localClose = 1;
|
|
827
2471
|
this._state.state = ST_CLOSED;
|
|
828
2472
|
if (sendRst && this.session._open) {
|
|
@@ -844,6 +2488,24 @@ class Http2Stream extends Stream {
|
|
|
844
2488
|
this.session = undefined;
|
|
845
2489
|
if (err) {
|
|
846
2490
|
process.nextTick(emitErrorCloseNT, this, err);
|
|
2491
|
+
} else if (this._isConsuming() &&
|
|
2492
|
+
(this._endPending || code === NO_ERROR || code === frames.CANCEL)) {
|
|
2493
|
+
// node's _destroy (internal/http2/core.js:2527) calls `this.push(null)`
|
|
2494
|
+
// unconditionally, but the EOF it pushes only reaches the readable when the
|
|
2495
|
+
// destroy was not an error: core.js:2541 turns every other code into
|
|
2496
|
+
// ERR_HTTP2_STREAM_ERROR first, and an errored destroy reports error+close
|
|
2497
|
+
// with no 'end' at all (measured on the over-long content-length refusal:
|
|
2498
|
+
// aborted, error, close). So the owed EOF goes out for exactly the codes
|
|
2499
|
+
// streamErrorOf does not name -- a plain destroy() and an abort (CANCEL) --
|
|
2500
|
+
// plus the parked-END_STREAM case this branch has always replayed. Measured
|
|
2501
|
+
// shapes: respond + close(8), request ended on its HEADERS -- aborted, end,
|
|
2502
|
+
// close; and a stream destroyed mid-pipe with no END_STREAM ever sent --
|
|
2503
|
+
// again aborted, end, close, which is what ends and unpipes the dest
|
|
2504
|
+
// (test/pipe-parity.test.js). Without it the deferred resume of an attached
|
|
2505
|
+
// reader is cancelled by the destroy bit and the owed 'end' never goes out
|
|
2506
|
+
// (test/event-order.test.js, scenario reset).
|
|
2507
|
+
this._endPending = false;
|
|
2508
|
+
process.nextTick(emitEndCloseNT, this);
|
|
847
2509
|
} else {
|
|
848
2510
|
process.nextTick(emitNT, this, 'close');
|
|
849
2511
|
}
|
|
@@ -875,36 +2537,78 @@ class Http2Stream extends Stream {
|
|
|
875
2537
|
}
|
|
876
2538
|
|
|
877
2539
|
// --- inbound flow control ----------------------------------------------------
|
|
878
|
-
// Attaching a reader is how the application says "send me the body":
|
|
879
|
-
//
|
|
880
|
-
//
|
|
881
|
-
//
|
|
2540
|
+
// Attaching a reader is how the application says "send me the body": whatever
|
|
2541
|
+
// arrived before it did is replayed -- on the next tick, like node's
|
|
2542
|
+
// kResumeScheduled resume_, not inside the on() call (measured: a read() in the
|
|
2543
|
+
// same turn as the attach still sees the buffer). once()/addListener are
|
|
2544
|
+
// covered by the listenerCount() check at delivery time.
|
|
882
2545
|
on(name, fn) {
|
|
2546
|
+
const firstReader = (name === 'data' || name === 'readable') &&
|
|
2547
|
+
this.listenerCount(name) === 0;
|
|
883
2548
|
const r = super.on(name, fn);
|
|
884
|
-
if (name === 'data'
|
|
885
|
-
|
|
2549
|
+
if (name === 'data') {
|
|
2550
|
+
if (firstReader) {
|
|
2551
|
+
this._readerFlow(name);
|
|
2552
|
+
}
|
|
2553
|
+
this._scheduleResume();
|
|
2554
|
+
} else if (name === 'readable') {
|
|
2555
|
+
if (firstReader) {
|
|
2556
|
+
this._readerFlow(name);
|
|
2557
|
+
}
|
|
2558
|
+
this._scheduleReadable();
|
|
886
2559
|
}
|
|
887
2560
|
return r;
|
|
888
2561
|
}
|
|
889
2562
|
|
|
890
2563
|
once(name, fn) {
|
|
2564
|
+
const firstReader = (name === 'data' || name === 'readable') &&
|
|
2565
|
+
this.listenerCount(name) === 0;
|
|
891
2566
|
const r = super.once(name, fn);
|
|
892
|
-
if (name === 'data'
|
|
893
|
-
|
|
2567
|
+
if (name === 'data') {
|
|
2568
|
+
if (firstReader) {
|
|
2569
|
+
this._readerFlow(name);
|
|
2570
|
+
}
|
|
2571
|
+
this._scheduleResume();
|
|
2572
|
+
} else if (name === 'readable') {
|
|
2573
|
+
if (firstReader) {
|
|
2574
|
+
this._readerFlow(name);
|
|
2575
|
+
}
|
|
2576
|
+
this._scheduleReadable();
|
|
894
2577
|
}
|
|
895
2578
|
return r;
|
|
896
2579
|
}
|
|
897
2580
|
|
|
2581
|
+
// node's Readable.prototype.on: attaching 'data' resumes, unless the stream was
|
|
2582
|
+
// explicitly paused; attaching 'readable' takes the stream out of flowing mode
|
|
2583
|
+
// even after resume() (measured: resume() then on('readable') reads false).
|
|
2584
|
+
// Both rules show up on the readableFlowing getter only — the replay that
|
|
2585
|
+
// actually moves the bytes stayed where it was.
|
|
2586
|
+
_readerFlow(name) {
|
|
2587
|
+
if (name === 'data') {
|
|
2588
|
+
if (this._flowing !== false) {
|
|
2589
|
+
this._flowing = true;
|
|
2590
|
+
}
|
|
2591
|
+
} else if (this._eofEmitted !== true) {
|
|
2592
|
+
this._flowing = false;
|
|
2593
|
+
}
|
|
2594
|
+
}
|
|
2595
|
+
|
|
898
2596
|
// Credit goes back when the application takes the bytes, so a body nobody
|
|
899
2597
|
// reads closes the sender's window instead of growing our heap. The buffer of
|
|
900
2598
|
// unread chunks cannot exceed the window we advertised, because the peer is
|
|
901
2599
|
// not allowed to send more than that without a credit we never gave.
|
|
2600
|
+
// A 'readable' listener is NOT consuming: the pull model buffers and waits
|
|
2601
|
+
// for read(), which is where that credit comes back (node's readable mode
|
|
2602
|
+
// releases nothing until the app pulls). A 'data' listener is not consuming
|
|
2603
|
+
// either while the stream sits in pull or paused mode (_flowing === false) --
|
|
2604
|
+
// node's kHasFlowing rule measured in the merge arm: the chunks stay in the
|
|
2605
|
+
// buffer for read() and only read()'s own data emission delivers them.
|
|
902
2606
|
_isConsuming() {
|
|
903
2607
|
if (this._consumeState === 2) {
|
|
904
2608
|
return false;
|
|
905
2609
|
} // the reader asked us to stop
|
|
906
|
-
return this._consumeState === 1 ||
|
|
907
|
-
this.listenerCount('
|
|
2610
|
+
return this._consumeState === 1 ||
|
|
2611
|
+
(this._flowing !== false && this.listenerCount('data') > 0);
|
|
908
2612
|
}
|
|
909
2613
|
|
|
910
2614
|
// Called when a reader shows up: replay what was buffered, in order, and let
|
|
@@ -915,14 +2619,25 @@ class Http2Stream extends Stream {
|
|
|
915
2619
|
if (pending !== null) {
|
|
916
2620
|
this._pending = null;
|
|
917
2621
|
for (let i = 0; i < pending.length; i++) {
|
|
918
|
-
const
|
|
919
|
-
this.
|
|
920
|
-
|
|
2622
|
+
const c = pending[i];
|
|
2623
|
+
this._dataRead = true;
|
|
2624
|
+
if (c.length === undefined) {
|
|
2625
|
+
// a pushed or decoded chunk: delivered, and it owes no credit for
|
|
2626
|
+
// itself -- but a string entry that stands for wire octets carries
|
|
2627
|
+
// their count and pays it here
|
|
2628
|
+
if (c.bytes !== undefined) {
|
|
2629
|
+
this._release(c.bytes);
|
|
2630
|
+
}
|
|
2631
|
+
this.emit('data', c.data);
|
|
2632
|
+
} else {
|
|
2633
|
+
this._release(c.length);
|
|
2634
|
+
this.emit('data', c);
|
|
2635
|
+
}
|
|
921
2636
|
}
|
|
922
2637
|
}
|
|
923
|
-
if (this._endPending && !this._destroyed) {
|
|
2638
|
+
if ((this._endPending || this._eofSeen === true) && !this._destroyed) {
|
|
924
2639
|
this._endPending = false;
|
|
925
|
-
|
|
2640
|
+
this._scheduleEOF();
|
|
926
2641
|
}
|
|
927
2642
|
}
|
|
928
2643
|
|
|
@@ -944,17 +2659,53 @@ class Http2Stream extends Stream {
|
|
|
944
2659
|
return;
|
|
945
2660
|
} // an empty DATA frame carries no payload
|
|
946
2661
|
this._recvUsed += n;
|
|
947
|
-
if (this.
|
|
2662
|
+
if (this._decoder !== undefined) {
|
|
2663
|
+
// arrival decodes at the door, node's push path with a decoder set: the
|
|
2664
|
+
// queue holds characters from here on. A chunk the decoder swallowed
|
|
2665
|
+
// whole (split multi-byte sequence) produces no entry and no event --
|
|
2666
|
+
// node's `chunk.length === 0` return -- and its octets are held against
|
|
2667
|
+
// the credit of the entry that finally comes out.
|
|
2668
|
+
let held = 0;
|
|
2669
|
+
if (this._decHeld !== undefined) {
|
|
2670
|
+
held = this._decHeld;
|
|
2671
|
+
this._decHeld = undefined;
|
|
2672
|
+
}
|
|
2673
|
+
const str = this._decoder.write(buf);
|
|
2674
|
+
if (str.length === 0) {
|
|
2675
|
+
this._decHeld = n + held;
|
|
2676
|
+
return;
|
|
2677
|
+
}
|
|
2678
|
+
if (this._isConsuming() && this._pending === null) {
|
|
2679
|
+
this._dataRead = true;
|
|
2680
|
+
this._release(n + held);
|
|
2681
|
+
this.emit('data', str);
|
|
2682
|
+
return;
|
|
2683
|
+
}
|
|
2684
|
+
if (this._pending === null) {
|
|
2685
|
+
this._pending = [];
|
|
2686
|
+
}
|
|
2687
|
+
this._pending.push({ data: str, bytes: n + held });
|
|
2688
|
+
this._scheduleReadable();
|
|
2689
|
+
return;
|
|
2690
|
+
}
|
|
2691
|
+
if (this._isConsuming() && this._pending === null) {
|
|
2692
|
+
this._dataRead = true;
|
|
948
2693
|
this._release(n);
|
|
949
2694
|
this.emit('data', buf);
|
|
950
2695
|
return;
|
|
951
2696
|
}
|
|
952
2697
|
// the chunk is either a view of a socket read or a buffer built for this frame
|
|
953
|
-
// alone; both outlive the tick, so it can simply be queued
|
|
2698
|
+
// alone; both outlive the tick, so it can simply be queued. A consuming reader
|
|
2699
|
+
// with a queue still standing lands here too: resume()'s delivery is scheduled,
|
|
2700
|
+
// not synchronous (node's resume_ tick), and arriving bytes must not overtake
|
|
2701
|
+
// the buffered ones.
|
|
954
2702
|
if (this._pending === null) {
|
|
955
2703
|
this._pending = [];
|
|
956
2704
|
}
|
|
957
2705
|
this._pending.push(buf);
|
|
2706
|
+
// readable-mode arrival: the pull consumer learns about it through
|
|
2707
|
+
// 'readable', not through the bytes (node's needReadable/emitReadable).
|
|
2708
|
+
this._scheduleReadable();
|
|
958
2709
|
}
|
|
959
2710
|
}
|
|
960
2711
|
|
|
@@ -972,6 +2723,626 @@ function errorOf(code, msg) {
|
|
|
972
2723
|
return err;
|
|
973
2724
|
}
|
|
974
2725
|
|
|
2726
|
+
// --- the async-iteration machinery ----------------------------------------------
|
|
2727
|
+
// Everything below reproduces node's internal/streams/readable.js:1552-1805
|
|
2728
|
+
// (streamToAsyncIterator/createAsyncIterator) and internal/streams/operators,
|
|
2729
|
+
// read from the binary in the same session as the measurements cited at the
|
|
2730
|
+
// methods. Two simplifications are honest, not inventions: (a) the iterator
|
|
2731
|
+
// never meets a thenable chunk -- push() validates its argument, so the queue
|
|
2732
|
+
// holds only Buffer/string/null and node's `chunk?.then` unwrapping and the
|
|
2733
|
+
// two-error AggregateError race it guards cannot occur (measured: an errored
|
|
2734
|
+
// iteration rejects with the bare error); (b) the FixedQueue node parks
|
|
2735
|
+
// queued requests in is an array here -- queue depth is a behaviour of the
|
|
2736
|
+
// consumer, not of the protocol.
|
|
2737
|
+
|
|
2738
|
+
const kEmpty = Symbol('kEmpty');
|
|
2739
|
+
const kEof = Symbol('kEof');
|
|
2740
|
+
// %AsyncIteratorPrototype% in V8: the function's .prototype is an INSTANCE of
|
|
2741
|
+
// the (shared) async-generator prototype, so the intrinsic with
|
|
2742
|
+
// [Symbol.asyncIterator]/[Symbol.asyncDispose] and no own methods sits TWO
|
|
2743
|
+
// levels up. Verified identity with the proto of a live node v26 iterator
|
|
2744
|
+
// object; the single getPrototypeOf lands on the generator prototype instead.
|
|
2745
|
+
// Node's own iterator is NOT this shape on every major: 22 and 24 hand back a
|
|
2746
|
+
// real async-generator instance, whose proto has no own keys at all. The
|
|
2747
|
+
// intrinsic is the only anchor stable across majors, and the behaviour that
|
|
2748
|
+
// depends on it ([Symbol.asyncIterator] resolving through the chain,
|
|
2749
|
+
// self-identical) is verified per major; exact proto identity is unportable.
|
|
2750
|
+
const ASYNC_ITERATOR_PROTO =
|
|
2751
|
+
Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}.prototype));
|
|
2752
|
+
|
|
2753
|
+
function noop() {}
|
|
2754
|
+
|
|
2755
|
+
// node's internal AbortError as the stream machinery constructs it (measured
|
|
2756
|
+
// on a live node break: name 'AbortError', code 'ABORT_ERR'). core.js:2516
|
|
2757
|
+
// maps it onto RST CANCEL(8) inside _destroy.
|
|
2758
|
+
function abortError(cause) {
|
|
2759
|
+
const err = new Error('The operation was aborted',
|
|
2760
|
+
cause === undefined ? undefined : { cause });
|
|
2761
|
+
err.name = 'AbortError';
|
|
2762
|
+
err.code = 'ABORT_ERR';
|
|
2763
|
+
return err;
|
|
2764
|
+
}
|
|
2765
|
+
|
|
2766
|
+
function validateObjectArg(value, name) {
|
|
2767
|
+
if (value === null || typeof value !== 'object') {
|
|
2768
|
+
throw errorOf('ERR_INVALID_ARG_TYPE',
|
|
2769
|
+
`The "${name}" argument must be of type object. Received ${inspect(value)}`);
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
|
|
2773
|
+
function validateFunctionArg(value, name) {
|
|
2774
|
+
if (typeof value !== 'function') {
|
|
2775
|
+
throw errorOf('ERR_INVALID_ARG_TYPE',
|
|
2776
|
+
`The "${name}" argument must be of type function. Received ${inspect(value)}`);
|
|
2777
|
+
}
|
|
2778
|
+
}
|
|
2779
|
+
|
|
2780
|
+
// node's pair in every operator: validateObject(options) then
|
|
2781
|
+
// validateAbortSignal(options.signal).
|
|
2782
|
+
function validateSignalArg(options) {
|
|
2783
|
+
if (options != null && options.signal != null && !(options.signal instanceof AbortSignal)) {
|
|
2784
|
+
throw errorOf('ERR_INVALID_ARG_TYPE',
|
|
2785
|
+
'The "options.signal" argument must be an instance of type AbortSignal.');
|
|
2786
|
+
}
|
|
2787
|
+
}
|
|
2788
|
+
|
|
2789
|
+
function validateOperatorOptions(options) {
|
|
2790
|
+
if (options != null) {
|
|
2791
|
+
validateObjectArg(options, 'options');
|
|
2792
|
+
}
|
|
2793
|
+
validateSignalArg(options);
|
|
2794
|
+
}
|
|
2795
|
+
|
|
2796
|
+
// node's toIntegerOrInfinity (operators:298): Number coercion per the
|
|
2797
|
+
// iterator-helpers proposal, then the range refusal.
|
|
2798
|
+
function toIntegerOrInfinity(number) {
|
|
2799
|
+
number = Number(number);
|
|
2800
|
+
if (Number.isNaN(number)) {
|
|
2801
|
+
return 0;
|
|
2802
|
+
}
|
|
2803
|
+
if (number < 0) {
|
|
2804
|
+
throw errorOf('ERR_OUT_OF_RANGE',
|
|
2805
|
+
`The value of "number" is out of range. It must be >= 0. Received ${number}`);
|
|
2806
|
+
}
|
|
2807
|
+
return number;
|
|
2808
|
+
}
|
|
2809
|
+
|
|
2810
|
+
// node's createAsyncIterator (readable.js:1576). The request protocol -- next
|
|
2811
|
+
// fast path, queue behind an inFlight request, return/throw draining through
|
|
2812
|
+
// the same pump -- is reproduced member by member; the wake is h2lean's
|
|
2813
|
+
// 'readable' event (node's emitReadable, same coalescing) and the end verdict
|
|
2814
|
+
// comes from the error/end/close trio standing in for
|
|
2815
|
+
// eos(stream, { writable: false }).
|
|
2816
|
+
function createStreamIterator(stream, options) {
|
|
2817
|
+
let callback = noop;
|
|
2818
|
+
let error; // undefined: active, null: ended cleanly, else: the Error
|
|
2819
|
+
let started = false;
|
|
2820
|
+
let completed = false;
|
|
2821
|
+
let inFlight = false; // an asynchronous request is outstanding
|
|
2822
|
+
let queue = null; // requests received while inFlight
|
|
2823
|
+
let draining = false;
|
|
2824
|
+
let detach = noop;
|
|
2825
|
+
|
|
2826
|
+
function fire() {
|
|
2827
|
+
const cb = callback;
|
|
2828
|
+
callback = noop;
|
|
2829
|
+
cb();
|
|
2830
|
+
}
|
|
2831
|
+
|
|
2832
|
+
function wait() {
|
|
2833
|
+
return new Promise((resolve) => {
|
|
2834
|
+
callback = resolve;
|
|
2835
|
+
});
|
|
2836
|
+
}
|
|
2837
|
+
|
|
2838
|
+
function start() {
|
|
2839
|
+
started = true;
|
|
2840
|
+
stream.on('readable', fire);
|
|
2841
|
+
let settled = false;
|
|
2842
|
+
const settle = (err) => {
|
|
2843
|
+
if (settled) {
|
|
2844
|
+
return;
|
|
2845
|
+
}
|
|
2846
|
+
settled = true;
|
|
2847
|
+
detach();
|
|
2848
|
+
error = err;
|
|
2849
|
+
fire();
|
|
2850
|
+
};
|
|
2851
|
+
const onEnd = () => {
|
|
2852
|
+
settle(null);
|
|
2853
|
+
};
|
|
2854
|
+
// a close with neither end nor error is node's eos verdict
|
|
2855
|
+
// ERR_STREAM_PREMATURE_CLOSE ('Premature close', read out of
|
|
2856
|
+
// internal/errors with --expose-internals).
|
|
2857
|
+
const onClose = () => {
|
|
2858
|
+
settle(errorOf('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'));
|
|
2859
|
+
};
|
|
2860
|
+
stream.on('error', settle);
|
|
2861
|
+
stream.on('end', onEnd);
|
|
2862
|
+
stream.on('close', onClose);
|
|
2863
|
+
detach = () => {
|
|
2864
|
+
stream.removeListener('readable', fire);
|
|
2865
|
+
stream.removeListener('error', settle);
|
|
2866
|
+
stream.removeListener('end', onEnd);
|
|
2867
|
+
stream.removeListener('close', onClose);
|
|
2868
|
+
};
|
|
2869
|
+
// node's start() hooks eos, not raw 'end'/'close', and an eos on a
|
|
2870
|
+
// stream that has ALREADY settled calls back on the next tick: a second
|
|
2871
|
+
// iterator over an ended stream gets `{done:true}` (measured on live
|
|
2872
|
+
// node: every() after some() on the same stream answers true without
|
|
2873
|
+
// hanging), and over a destroyed one gets the premature-close error.
|
|
2874
|
+
// The one-shot trio below can never fire again, so this is where that
|
|
2875
|
+
// verdict is reproduced.
|
|
2876
|
+
if (stream.readableEnded === true) {
|
|
2877
|
+
process.nextTick(() => settle(null));
|
|
2878
|
+
} else if (stream.destroyed === true) {
|
|
2879
|
+
process.nextTick(() => settle(errorOf('ERR_STREAM_PREMATURE_CLOSE', 'Premature close')));
|
|
2880
|
+
}
|
|
2881
|
+
}
|
|
2882
|
+
|
|
2883
|
+
function finalize() {
|
|
2884
|
+
completed = true;
|
|
2885
|
+
// node's finalize (readable.js:1609) reads autoDestroy off the state
|
|
2886
|
+
// object; Http2Stream fixes it false (core.js:2132), so the second
|
|
2887
|
+
// clause reduces to `error === undefined`: only a still-active
|
|
2888
|
+
// return()/break destroys -- node's destroyer(stream, null) on a
|
|
2889
|
+
// not-finished stream is destroy(new AbortError()), which core.js:2516
|
|
2890
|
+
// turns into RST CANCEL. h2lean's public destroy() derives
|
|
2891
|
+
// INTERNAL_ERROR from any Error object (its own documented rule, task
|
|
2892
|
+
// 17), so the iterator calls the engine with node's derived pair
|
|
2893
|
+
// directly. Measured: break -- destroyed true, rstCode 8, aborted,
|
|
2894
|
+
// error:ABORT_ERR, close; natural end -- destroyed stays false.
|
|
2895
|
+
if ((error || options?.destroyOnReturn !== false) && error === undefined) {
|
|
2896
|
+
if (!stream.destroyed) {
|
|
2897
|
+
stream._destroy(frames.CANCEL, undefined, true, abortError());
|
|
2898
|
+
}
|
|
2899
|
+
} else {
|
|
2900
|
+
stream.removeListener('readable', fire);
|
|
2901
|
+
detach();
|
|
2902
|
+
}
|
|
2903
|
+
}
|
|
2904
|
+
|
|
2905
|
+
function drain() {
|
|
2906
|
+
// node's guard: requests settled synchronously call back into drain(),
|
|
2907
|
+
// and one loop runs instead of one recursion per request.
|
|
2908
|
+
if (draining) {
|
|
2909
|
+
return;
|
|
2910
|
+
}
|
|
2911
|
+
draining = true;
|
|
2912
|
+
try {
|
|
2913
|
+
while (!inFlight && queue !== null && queue.length > 0) {
|
|
2914
|
+
const req = queue.shift();
|
|
2915
|
+
if (req.type === 'next') {
|
|
2916
|
+
processNext(req.resolve, req.reject);
|
|
2917
|
+
} else if (req.type === 'return') {
|
|
2918
|
+
processReturn(req.value, req.resolve);
|
|
2919
|
+
} else {
|
|
2920
|
+
processThrow(req.value, req.reject);
|
|
2921
|
+
}
|
|
2922
|
+
}
|
|
2923
|
+
} finally {
|
|
2924
|
+
draining = false;
|
|
2925
|
+
}
|
|
2926
|
+
}
|
|
2927
|
+
|
|
2928
|
+
function pump(resolve, reject) {
|
|
2929
|
+
const chunk = stream.destroyed ? null : stream.read();
|
|
2930
|
+
if (chunk !== null) {
|
|
2931
|
+
inFlight = false;
|
|
2932
|
+
resolve({ done: false, value: chunk });
|
|
2933
|
+
if (queue !== null) {
|
|
2934
|
+
drain();
|
|
2935
|
+
}
|
|
2936
|
+
} else if (error) {
|
|
2937
|
+
inFlight = false;
|
|
2938
|
+
finalize();
|
|
2939
|
+
reject(error);
|
|
2940
|
+
if (queue !== null) {
|
|
2941
|
+
drain();
|
|
2942
|
+
}
|
|
2943
|
+
} else if (error === null) {
|
|
2944
|
+
inFlight = false;
|
|
2945
|
+
finalize();
|
|
2946
|
+
resolve({ done: true, value: undefined });
|
|
2947
|
+
if (queue !== null) {
|
|
2948
|
+
drain();
|
|
2949
|
+
}
|
|
2950
|
+
} else {
|
|
2951
|
+
// nothing buffered yet: wait for the next 'readable' or end verdict
|
|
2952
|
+
// and retry, node's wakeup-promise tail.
|
|
2953
|
+
wait().then(() => pump(resolve, reject));
|
|
2954
|
+
}
|
|
2955
|
+
}
|
|
2956
|
+
|
|
2957
|
+
function processNext(resolve, reject) {
|
|
2958
|
+
if (completed) {
|
|
2959
|
+
resolve({ done: true, value: undefined });
|
|
2960
|
+
return;
|
|
2961
|
+
}
|
|
2962
|
+
if (!started) {
|
|
2963
|
+
start();
|
|
2964
|
+
}
|
|
2965
|
+
inFlight = true;
|
|
2966
|
+
pump(resolve, reject);
|
|
2967
|
+
}
|
|
2968
|
+
|
|
2969
|
+
function processReturn(value, resolve) {
|
|
2970
|
+
if (!completed) {
|
|
2971
|
+
if (started) {
|
|
2972
|
+
finalize();
|
|
2973
|
+
} else {
|
|
2974
|
+
// never started: complete without touching the stream.
|
|
2975
|
+
completed = true;
|
|
2976
|
+
}
|
|
2977
|
+
}
|
|
2978
|
+
resolve({ done: true, value });
|
|
2979
|
+
}
|
|
2980
|
+
|
|
2981
|
+
function processThrow(err, reject) {
|
|
2982
|
+
if (completed || !started) {
|
|
2983
|
+
completed = true;
|
|
2984
|
+
reject(err);
|
|
2985
|
+
return;
|
|
2986
|
+
}
|
|
2987
|
+
error = err;
|
|
2988
|
+
finalize();
|
|
2989
|
+
reject(err);
|
|
2990
|
+
}
|
|
2991
|
+
|
|
2992
|
+
const iter = {
|
|
2993
|
+
__proto__: ASYNC_ITERATOR_PROTO,
|
|
2994
|
+
next() {
|
|
2995
|
+
if (!inFlight && !completed) {
|
|
2996
|
+
if (!started) {
|
|
2997
|
+
start();
|
|
2998
|
+
}
|
|
2999
|
+
const chunk = stream.destroyed ? null : stream.read();
|
|
3000
|
+
if (chunk !== null) {
|
|
3001
|
+
return Promise.resolve({ done: false, value: chunk });
|
|
3002
|
+
}
|
|
3003
|
+
if (error) {
|
|
3004
|
+
finalize();
|
|
3005
|
+
return Promise.reject(error);
|
|
3006
|
+
}
|
|
3007
|
+
if (error === null) {
|
|
3008
|
+
finalize();
|
|
3009
|
+
return Promise.resolve({ done: true, value: undefined });
|
|
3010
|
+
}
|
|
3011
|
+
inFlight = true;
|
|
3012
|
+
return new Promise((resolve, reject) => {
|
|
3013
|
+
wait().then(() => pump(resolve, reject));
|
|
3014
|
+
});
|
|
3015
|
+
}
|
|
3016
|
+
return new Promise((resolve, reject) => {
|
|
3017
|
+
if (inFlight) {
|
|
3018
|
+
(queue ??= []).push({ __proto__: null, type: 'next', value: undefined, resolve, reject });
|
|
3019
|
+
} else {
|
|
3020
|
+
resolve({ done: true, value: undefined });
|
|
3021
|
+
}
|
|
3022
|
+
});
|
|
3023
|
+
},
|
|
3024
|
+
return(value) {
|
|
3025
|
+
return new Promise((resolve) => {
|
|
3026
|
+
if (inFlight) {
|
|
3027
|
+
(queue ??= []).push({ __proto__: null, type: 'return', value, resolve, reject: null });
|
|
3028
|
+
} else {
|
|
3029
|
+
processReturn(value, resolve);
|
|
3030
|
+
}
|
|
3031
|
+
});
|
|
3032
|
+
},
|
|
3033
|
+
throw(err) {
|
|
3034
|
+
return new Promise((resolve, reject) => {
|
|
3035
|
+
if (inFlight) {
|
|
3036
|
+
(queue ??= []).push({ __proto__: null, type: 'throw', value: err, resolve, reject });
|
|
3037
|
+
} else {
|
|
3038
|
+
processThrow(err, reject);
|
|
3039
|
+
}
|
|
3040
|
+
});
|
|
3041
|
+
}
|
|
3042
|
+
};
|
|
3043
|
+
// node's streamToAsyncIterator hangs the source on the iterator object
|
|
3044
|
+
// (readable.js:1563-1565); measured raw.stream === rd on a live node.
|
|
3045
|
+
iter.stream = stream;
|
|
3046
|
+
return iter;
|
|
3047
|
+
}
|
|
3048
|
+
|
|
3049
|
+
// node's operators (internal/streams/operators). Each is a plain function or
|
|
3050
|
+
// async function mirroring the original's argument shape, so the synchronous
|
|
3051
|
+
// validation the transform family performs (measured: map('nope') throws
|
|
3052
|
+
// ERR_INVALID_ARG_TYPE out of the call) and the rejection the promise family
|
|
3053
|
+
// produces land exactly where node puts them.
|
|
3054
|
+
|
|
3055
|
+
function opMap(stream, fn, options) {
|
|
3056
|
+
validateFunctionArg(fn, 'fn');
|
|
3057
|
+
validateOperatorOptions(options);
|
|
3058
|
+
let concurrency = 1;
|
|
3059
|
+
if (options?.concurrency != null) {
|
|
3060
|
+
concurrency = Math.floor(options.concurrency);
|
|
3061
|
+
}
|
|
3062
|
+
let highWaterMark = concurrency - 1;
|
|
3063
|
+
if (options?.highWaterMark != null) {
|
|
3064
|
+
highWaterMark = Math.floor(options.highWaterMark);
|
|
3065
|
+
}
|
|
3066
|
+
if (!Number.isInteger(concurrency) || concurrency < 1) {
|
|
3067
|
+
throw errorOf('ERR_OUT_OF_RANGE',
|
|
3068
|
+
`The value of "options.concurrency" is out of range. It must be >= 1. Received ${concurrency}`);
|
|
3069
|
+
}
|
|
3070
|
+
if (!Number.isInteger(highWaterMark) || highWaterMark < 0) {
|
|
3071
|
+
throw errorOf('ERR_OUT_OF_RANGE',
|
|
3072
|
+
`The value of "options.highWaterMark" is out of range. It must be >= 0. Received ${highWaterMark}`);
|
|
3073
|
+
}
|
|
3074
|
+
highWaterMark += concurrency;
|
|
3075
|
+
// node builds its always-present signal with AbortSignal.any([...]) --
|
|
3076
|
+
// any([]) is a fresh never-aborted signal, which a never-aborted
|
|
3077
|
+
// controller's signal is byte-equivalent to for everything the operator
|
|
3078
|
+
// reads off it.
|
|
3079
|
+
const signal = options?.signal ?? new AbortController().signal;
|
|
3080
|
+
|
|
3081
|
+
return (async function* map() {
|
|
3082
|
+
const queue = [];
|
|
3083
|
+
const signalOpt = { signal };
|
|
3084
|
+
let next = null;
|
|
3085
|
+
let resume = null;
|
|
3086
|
+
let done = false;
|
|
3087
|
+
let cnt = 0;
|
|
3088
|
+
|
|
3089
|
+
function onCatch() {
|
|
3090
|
+
done = true;
|
|
3091
|
+
afterItemProcessed();
|
|
3092
|
+
}
|
|
3093
|
+
|
|
3094
|
+
function afterItemProcessed() {
|
|
3095
|
+
cnt -= 1;
|
|
3096
|
+
maybeResume();
|
|
3097
|
+
}
|
|
3098
|
+
|
|
3099
|
+
function maybeResume() {
|
|
3100
|
+
if (resume && !done && cnt < concurrency && queue.length < highWaterMark) {
|
|
3101
|
+
const r = resume;
|
|
3102
|
+
resume = null;
|
|
3103
|
+
r();
|
|
3104
|
+
}
|
|
3105
|
+
}
|
|
3106
|
+
|
|
3107
|
+
async function pump() {
|
|
3108
|
+
try {
|
|
3109
|
+
for await (let val of stream) {
|
|
3110
|
+
if (done) {
|
|
3111
|
+
return;
|
|
3112
|
+
}
|
|
3113
|
+
if (signal.aborted) {
|
|
3114
|
+
throw abortError();
|
|
3115
|
+
}
|
|
3116
|
+
try {
|
|
3117
|
+
val = fn(val, signalOpt);
|
|
3118
|
+
if (val === kEmpty) {
|
|
3119
|
+
continue;
|
|
3120
|
+
}
|
|
3121
|
+
val = Promise.resolve(val);
|
|
3122
|
+
} catch (err) {
|
|
3123
|
+
val = Promise.reject(err);
|
|
3124
|
+
}
|
|
3125
|
+
cnt += 1;
|
|
3126
|
+
val.then(afterItemProcessed, onCatch);
|
|
3127
|
+
queue.push(val);
|
|
3128
|
+
if (next) {
|
|
3129
|
+
const n = next;
|
|
3130
|
+
next = null;
|
|
3131
|
+
n();
|
|
3132
|
+
}
|
|
3133
|
+
if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) {
|
|
3134
|
+
await new Promise((resolve) => {
|
|
3135
|
+
resume = resolve;
|
|
3136
|
+
});
|
|
3137
|
+
}
|
|
3138
|
+
}
|
|
3139
|
+
queue.push(kEof);
|
|
3140
|
+
} catch (err) {
|
|
3141
|
+
const val = Promise.reject(err);
|
|
3142
|
+
val.then(afterItemProcessed, onCatch);
|
|
3143
|
+
queue.push(val);
|
|
3144
|
+
} finally {
|
|
3145
|
+
done = true;
|
|
3146
|
+
if (next) {
|
|
3147
|
+
const n = next;
|
|
3148
|
+
next = null;
|
|
3149
|
+
n();
|
|
3150
|
+
}
|
|
3151
|
+
}
|
|
3152
|
+
}
|
|
3153
|
+
|
|
3154
|
+
pump();
|
|
3155
|
+
|
|
3156
|
+
try {
|
|
3157
|
+
while (true) {
|
|
3158
|
+
while (queue.length > 0) {
|
|
3159
|
+
const val = await queue[0];
|
|
3160
|
+
if (val === kEof) {
|
|
3161
|
+
return;
|
|
3162
|
+
}
|
|
3163
|
+
if (signal.aborted) {
|
|
3164
|
+
throw abortError();
|
|
3165
|
+
}
|
|
3166
|
+
if (val !== kEmpty) {
|
|
3167
|
+
yield val;
|
|
3168
|
+
}
|
|
3169
|
+
queue.shift();
|
|
3170
|
+
maybeResume();
|
|
3171
|
+
}
|
|
3172
|
+
await new Promise((resolve) => {
|
|
3173
|
+
next = resolve;
|
|
3174
|
+
});
|
|
3175
|
+
}
|
|
3176
|
+
} finally {
|
|
3177
|
+
done = true;
|
|
3178
|
+
if (resume) {
|
|
3179
|
+
const r = resume;
|
|
3180
|
+
resume = null;
|
|
3181
|
+
r();
|
|
3182
|
+
}
|
|
3183
|
+
}
|
|
3184
|
+
})();
|
|
3185
|
+
}
|
|
3186
|
+
|
|
3187
|
+
function opFilter(stream, fn, options) {
|
|
3188
|
+
validateFunctionArg(fn, 'fn');
|
|
3189
|
+
async function filterFn(value, opt) {
|
|
3190
|
+
if (await fn(value, opt)) {
|
|
3191
|
+
return value;
|
|
3192
|
+
}
|
|
3193
|
+
return kEmpty;
|
|
3194
|
+
}
|
|
3195
|
+
return opMap(stream, filterFn, options);
|
|
3196
|
+
}
|
|
3197
|
+
|
|
3198
|
+
async function opForEach(stream, fn, options) {
|
|
3199
|
+
validateFunctionArg(fn, 'fn');
|
|
3200
|
+
async function forEachFn(value, opt) {
|
|
3201
|
+
await fn(value, opt);
|
|
3202
|
+
return kEmpty;
|
|
3203
|
+
}
|
|
3204
|
+
// node drains the mapped generator with an empty for-await body. The same
|
|
3205
|
+
// descent is spelled out here -- an fn error propagates out of the mapped
|
|
3206
|
+
// generator's own body, so its cleanup runs at the throw point and no
|
|
3207
|
+
// abrupt-close return() call from this loop would add anything.
|
|
3208
|
+
const it = opMap(stream, forEachFn, options)[Symbol.asyncIterator]();
|
|
3209
|
+
let res = await it.next();
|
|
3210
|
+
while (!res.done) {
|
|
3211
|
+
res = await it.next();
|
|
3212
|
+
}
|
|
3213
|
+
}
|
|
3214
|
+
|
|
3215
|
+
function opFlatMap(stream, fn, options) {
|
|
3216
|
+
const values = opMap(stream, fn, options);
|
|
3217
|
+
return (async function* flatMap() {
|
|
3218
|
+
for await (const val of values) {
|
|
3219
|
+
yield* val;
|
|
3220
|
+
}
|
|
3221
|
+
})();
|
|
3222
|
+
}
|
|
3223
|
+
|
|
3224
|
+
function opDrop(stream, number, options) {
|
|
3225
|
+
validateOperatorOptions(options);
|
|
3226
|
+
const limit = toIntegerOrInfinity(number);
|
|
3227
|
+
return (async function* drop() {
|
|
3228
|
+
if (options?.signal?.aborted) {
|
|
3229
|
+
throw abortError();
|
|
3230
|
+
}
|
|
3231
|
+
let numberLeft = limit;
|
|
3232
|
+
for await (const val of stream) {
|
|
3233
|
+
if (options?.signal?.aborted) {
|
|
3234
|
+
throw abortError();
|
|
3235
|
+
}
|
|
3236
|
+
if (numberLeft-- <= 0) {
|
|
3237
|
+
yield val;
|
|
3238
|
+
}
|
|
3239
|
+
}
|
|
3240
|
+
})();
|
|
3241
|
+
}
|
|
3242
|
+
|
|
3243
|
+
function opTake(stream, number, options) {
|
|
3244
|
+
validateOperatorOptions(options);
|
|
3245
|
+
const limit = toIntegerOrInfinity(number);
|
|
3246
|
+
return (async function* take() {
|
|
3247
|
+
if (options?.signal?.aborted) {
|
|
3248
|
+
throw abortError();
|
|
3249
|
+
}
|
|
3250
|
+
let numberLeft = limit;
|
|
3251
|
+
for await (const val of stream) {
|
|
3252
|
+
if (options?.signal?.aborted) {
|
|
3253
|
+
throw abortError();
|
|
3254
|
+
}
|
|
3255
|
+
if (numberLeft-- > 0) {
|
|
3256
|
+
yield val;
|
|
3257
|
+
}
|
|
3258
|
+
// Don't get another item from iterator in case we reached the end --
|
|
3259
|
+
// node's comment; the return() this early exit triggers on the source
|
|
3260
|
+
// iterator is what destroys a stream taken short of its EOF.
|
|
3261
|
+
if (numberLeft <= 0) {
|
|
3262
|
+
return;
|
|
3263
|
+
}
|
|
3264
|
+
}
|
|
3265
|
+
})();
|
|
3266
|
+
}
|
|
3267
|
+
|
|
3268
|
+
async function opSome(stream, fn, options) {
|
|
3269
|
+
for await (const unused of opFilter(stream, fn, options)) {
|
|
3270
|
+
return true;
|
|
3271
|
+
}
|
|
3272
|
+
return false;
|
|
3273
|
+
}
|
|
3274
|
+
|
|
3275
|
+
async function opEvery(stream, fn, options) {
|
|
3276
|
+
validateFunctionArg(fn, 'fn');
|
|
3277
|
+
// https://en.wikipedia.org/wiki/De_Morgan%27s_laws -- node's comment.
|
|
3278
|
+
return !(await opSome(stream, async (...args) => !(await fn(...args)), options));
|
|
3279
|
+
}
|
|
3280
|
+
|
|
3281
|
+
async function opFind(stream, fn, options) {
|
|
3282
|
+
for await (const result of opFilter(stream, fn, options)) {
|
|
3283
|
+
return result;
|
|
3284
|
+
}
|
|
3285
|
+
return undefined;
|
|
3286
|
+
}
|
|
3287
|
+
|
|
3288
|
+
async function opReduce(stream, hasInitial, reducer, initialValue, options) {
|
|
3289
|
+
validateFunctionArg(reducer, 'reducer');
|
|
3290
|
+
validateOperatorOptions(options);
|
|
3291
|
+
if (options?.signal?.aborted) {
|
|
3292
|
+
const err = abortError(options.signal.reason);
|
|
3293
|
+
stream.once('error', () => {}); // the error is already propagated
|
|
3294
|
+
// node awaits its internal eos, which RESOLVES on the errored teardown;
|
|
3295
|
+
// the callback form wrapped here is that promise, since the public
|
|
3296
|
+
// callback-less `finished` refuses instead.
|
|
3297
|
+
await new Promise((resolve) => {
|
|
3298
|
+
// h2lean's destroy() returns nothing, unlike node's, so the stream is
|
|
3299
|
+
// handed to eos on its own line.
|
|
3300
|
+
stream.destroy(err);
|
|
3301
|
+
finished(stream, resolve);
|
|
3302
|
+
});
|
|
3303
|
+
throw err;
|
|
3304
|
+
}
|
|
3305
|
+
const ac = new AbortController();
|
|
3306
|
+
const signal = ac.signal;
|
|
3307
|
+
if (options?.signal) {
|
|
3308
|
+
options.signal.addEventListener('abort', () => ac.abort(), { once: true });
|
|
3309
|
+
}
|
|
3310
|
+
let gotAnyItemFromStream = false;
|
|
3311
|
+
try {
|
|
3312
|
+
for await (const value of stream) {
|
|
3313
|
+
gotAnyItemFromStream = true;
|
|
3314
|
+
if (options?.signal?.aborted) {
|
|
3315
|
+
throw abortError();
|
|
3316
|
+
}
|
|
3317
|
+
if (!hasInitial) {
|
|
3318
|
+
initialValue = value;
|
|
3319
|
+
hasInitial = true;
|
|
3320
|
+
} else {
|
|
3321
|
+
initialValue = await reducer(initialValue, value, { signal });
|
|
3322
|
+
}
|
|
3323
|
+
}
|
|
3324
|
+
if (!gotAnyItemFromStream && !hasInitial) {
|
|
3325
|
+
// node's ReduceAwareErrMissingArgs: same code, same custom message.
|
|
3326
|
+
throw errorOf('ERR_MISSING_ARGS', 'Reduce of an empty stream requires an initial value');
|
|
3327
|
+
}
|
|
3328
|
+
} finally {
|
|
3329
|
+
ac.abort();
|
|
3330
|
+
}
|
|
3331
|
+
return initialValue;
|
|
3332
|
+
}
|
|
3333
|
+
|
|
3334
|
+
async function opToArray(stream, options) {
|
|
3335
|
+
validateOperatorOptions(options);
|
|
3336
|
+
const result = [];
|
|
3337
|
+
for await (const val of stream) {
|
|
3338
|
+
if (options?.signal?.aborted) {
|
|
3339
|
+
throw abortError(options.signal.reason);
|
|
3340
|
+
}
|
|
3341
|
+
result.push(val);
|
|
3342
|
+
}
|
|
3343
|
+
return result;
|
|
3344
|
+
}
|
|
3345
|
+
|
|
975
3346
|
// The error a stream reports when an RST_STREAM ends it, on either side. node's rule is
|
|
976
3347
|
// one line (internal/http2/core.js:2543): `if (err == null && code !== NGHTTP2_NO_ERROR &&
|
|
977
3348
|
// code !== NGHTTP2_CANCEL) err = new ERR_HTTP2_STREAM_ERROR(nameForErrorCode[code] || code)`.
|