h2lean 0.17.3 → 0.17.5
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/index.js +6 -6
- package/lib/Http2Stream.js +1328 -0
- package/lib/{client-session.js → client/Http2ClientSession.js} +28 -28
- package/lib/{client-stream.js → client/Http2ClientStream.js} +27 -782
- package/lib/{client.js → client/client.js} +4 -4
- package/lib/fast-timer.js +1 -1
- package/lib/headers.js +131 -25
- package/lib/hpack.js +43 -7
- package/lib/{session.js → server/Http2ServerSession.js} +101 -26
- package/lib/{stream.js → server/Http2ServerStream.js} +55 -1560
- package/lib/{compat.js → server/compat.js} +9 -9
- package/lib/{server.js → server/server.js} +9 -9
- package/package.json +1 -1
|
@@ -0,0 +1,1328 @@
|
|
|
1
|
+
// Http2Stream: the shared base of both hand-written stream classes.
|
|
2
|
+
//
|
|
3
|
+
// It carries the role-neutral surface -- the async-iteration helpers, pipe
|
|
4
|
+
// plumbing, encoding getters and the counting cork stub -- and nothing else.
|
|
5
|
+
// There is deliberately no constructor here: both subclasses keep their own
|
|
6
|
+
// field list and insertion order, so their V8 object shapes stay the ones the
|
|
7
|
+
// paired matrix measured (OPTIMIZATION.md items 41/42). The two places that do
|
|
8
|
+
// differ by role are hooks: `_createIterator()` (node's end-of-stream verdict
|
|
9
|
+
// differs between an inbound and a request stream) and `_abortError()` (the
|
|
10
|
+
// client needs an `instanceof`-able AbortError for its destroy derivation).
|
|
11
|
+
//
|
|
12
|
+
// v1 deliberately implements the parts of the contract that can be honoured
|
|
13
|
+
// honestly, and omits the ones that cannot:
|
|
14
|
+
// * the base is `stream.Stream`, not Duplex and not a bare EventEmitter. node's Http2Stream
|
|
15
|
+
// extends Duplex (internal/http2/core.js:2128), but the part of that surface real code reaches
|
|
16
|
+
// for is pipe() on the readable half, and the Duplex machinery behind it -- two state objects
|
|
17
|
+
// plus the nextTick read loop -- is what OPTIMIZATION.md item 41 measured as ~+1.4 us/req
|
|
18
|
+
// against the EventEmitter arm. h2lean therefore carries the Duplex SURFACE as methods and
|
|
19
|
+
// getters over the hand-rolled core: pipe() is not the legacy Stream.prototype.pipe but
|
|
20
|
+
// node's Readable.prototype.pipe reimplemented on this base (tracked destinations,
|
|
21
|
+
// unpipe(), the destroy-time EOF that ends and unpipes the dest -- test/pipe-parity.test.js),
|
|
22
|
+
// and read()/push()/setEncoding() are node's readable pull surface with the same
|
|
23
|
+
// member-by-member derivation (test/duplex-surface.test.js), and so is the async
|
|
24
|
+
// iteration surface -- [Symbol.asyncIterator], iterator(), the operator helpers and
|
|
25
|
+
// compose() -- ported member-by-member from node v26's createAsyncIterator,
|
|
26
|
+
// operators.js and compose.js; web streams are refused by compose() where node
|
|
27
|
+
// composes them; writev() is absent because
|
|
28
|
+
// node itself throws TypeError on it here, and cork()/uncork() and the
|
|
29
|
+
// writableCorked/writableHighWaterMark getters are present as a counting stub:
|
|
30
|
+
// node's Writable cork buffers write()/end() and defers the DATA until corked reaches 0
|
|
31
|
+
// (measured on v26.12.1: write('AAA') while corked leaves writableLength 3 and the peer
|
|
32
|
+
// receives nothing until the second uncork), while h2lean writes straight through -- its
|
|
33
|
+
// per-read socket batch already coalesces a synchronous burst, so only the cross-tick
|
|
34
|
+
// deferral differs. KNOWN DIVERGENCE, pinned in test/cork-parity.test.js.
|
|
35
|
+
// * the read side releases flow-control credit as the application takes the
|
|
36
|
+
// bytes. With no reader the peer's window stays shut, so an unread body
|
|
37
|
+
// costs the sender instead of our heap; data that arrives before anyone is
|
|
38
|
+
// listening is buffered and replayed in order, so late listeners lose
|
|
39
|
+
// nothing. pause()/resume()/isPaused() are implemented on that mechanism --
|
|
40
|
+
// there is no partial credit accounting, the side either is read or it isn't.
|
|
41
|
+
// * a delivered chunk stays readable for as long as the application holds it:
|
|
42
|
+
// it is either a view of the buffer node read off the socket, or the private
|
|
43
|
+
// buffer a frame that straddled two reads was assembled into. Neither is ever
|
|
44
|
+
// recycled underneath the application, so queueing a chunk nobody has read yet
|
|
45
|
+
// is safe and the receive path performs no copy.
|
|
46
|
+
// * write()/end() are real and respect both the stream and connection send
|
|
47
|
+
// windows, returning false when the window is exhausted. A body larger than the
|
|
48
|
+
// reference threshold is queued as a view of the caller's buffer and copied
|
|
49
|
+
// nowhere, so the caller must not write into it before the bytes have gone out --
|
|
50
|
+
// the same promise node:http2 makes.
|
|
51
|
+
// * a response the application never started is started for it: the first write()
|
|
52
|
+
// sends HEADERS{:status 200} before the DATA, as node does. An end() with no body at
|
|
53
|
+
// all is the one shape where h2lean answers (200, empty DATA/ES) and node says nothing
|
|
54
|
+
// -- measured, and recorded in AGENTS.md section 10.
|
|
55
|
+
// * a response STARTED and then destroyed in the same turn of the loop is the other:
|
|
56
|
+
// node submits the HEADERS to nghttp2 and nothing sends them before the destroy, so
|
|
57
|
+
// the teardown discards them and the peer sees only RST_STREAM. respond() here frames
|
|
58
|
+
// them into the session's staging buffer immediately and the batch leaves at the end
|
|
59
|
+
// of the read, so they reach the peer. The trigger is the turn, not the empty write:
|
|
60
|
+
// a non-empty write() flushes in the same turn on both stacks, and a destroy a
|
|
61
|
+
// setImmediate later agrees too. headersSent and rstCode are the same either way.
|
|
62
|
+
// Measured by tools/probe-zero-write.js, pinned in test/response-start.test.js, and
|
|
63
|
+
// the same outbound-batch decision as the refusal case in AGENTS.md section 10 --
|
|
64
|
+
// the staging buffer holds flat bytes with no per-stream handle to discard.
|
|
65
|
+
// * an outbound header block over the session's maxSendHeaderBlockLength is refused the
|
|
66
|
+
// way nghttp2 refuses it: 'frameError' on the stream, then a deferred close carrying
|
|
67
|
+
// FRAME_SIZE_ERROR and a session close behind it -- not a throw out of the send call.
|
|
68
|
+
// With no reader on the request half, node's own unread-request auto-close reaches the
|
|
69
|
+
// stream first and reports rstCode 0 where h2lean reports 6: the two stacks schedule
|
|
70
|
+
// the same pair in opposite orders, node's writable 'finish' before the frame pump
|
|
71
|
+
// refuses the block and h2lean's half-close after it
|
|
72
|
+
// (test/upstream/exceeds-server-trailer-size.test.js).
|
|
73
|
+
// * respondWithFD()/respondWithFile() send a file body straight from the descriptor:
|
|
74
|
+
// HEADERS are framed in the call (headersSent is true on return), then a chunked
|
|
75
|
+
// read/pump walk writes the body through write()/end() with normal backpressure, the
|
|
76
|
+
// same shape node's StreamPipe drives. statCheck (3-arg on the FD path, 2-arg on the
|
|
77
|
+
// file path) may rewrite 'content-length' in the prepared copy and may cancel by
|
|
78
|
+
// returning false; on the FD path cancelling leaves the descriptor open (the caller
|
|
79
|
+
// owns it), on the file path it is closed. Non-regular files refuse seek options and
|
|
80
|
+
// directories refuse outright (ERR_HTTP2_SEND_FILE / ERR_HTTP2_SEND_FILE_NOSEEK),
|
|
81
|
+
// as node's doSendFileFD does. Read and async errors destroy the stream with
|
|
82
|
+
// ERR_HTTP2_STREAM_ERROR(NGHTTP2_INTERNAL_ERROR) rather than throwing out of the call,
|
|
83
|
+
// matching node's buildNgHeaderString/processRespondWithFD teardown: a bad field name
|
|
84
|
+
// leaves headersSent true (node sets HEADERS_SENT before validating fields) and takes
|
|
85
|
+
// the destroy path. An array-form headers argument passes through hdr.block as-is
|
|
86
|
+
// instead of node's for..in over indices (which sends field names '0', '1', ...);
|
|
87
|
+
// the content-length statCheck injects is only applied to object-form headers.
|
|
88
|
+
// * 'finish' and writableFinished exist on the stream: 'finish' is queued on a
|
|
89
|
+
// nextTick once the writable half has ended with every octet accepted by the
|
|
90
|
+
// session (no queued DATA left), before any wantTrailers/close tick, and is never
|
|
91
|
+
// emitted for a stream destroyed before completion -- node's Writable semantics,
|
|
92
|
+
// measured on v26.12.1 (clean respondWithFD: finish after the pump completes, close
|
|
93
|
+
// with writableFinished true; abort after respondWithFD: only close, writableFinished
|
|
94
|
+
// false).
|
|
95
|
+
'use strict';
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
const fs = require('node:fs');
|
|
99
|
+
const { inspect } = require('node:util');
|
|
100
|
+
const { Stream, Writable, Readable, finished } = require('node:stream');
|
|
101
|
+
const frames = require('./frames');
|
|
102
|
+
const hdr = require('./headers');
|
|
103
|
+
|
|
104
|
+
const EMPTY = Buffer.alloc(0);
|
|
105
|
+
|
|
106
|
+
// node's Http2Stream sets no highWaterMark (internal/http2/core.js constructor passes only
|
|
107
|
+
// allowHalfOpen/decodeStrings/autoDestroy), so its writableHighWaterMark is the default
|
|
108
|
+
// Writable one -- 16384 on node 20, 65536 from 22 on. Read it off node itself once rather
|
|
109
|
+
// than hardcode a per-major constant that could drift; measured equal to a live node
|
|
110
|
+
// stream's writableHighWaterMark on v26.12.1.
|
|
111
|
+
const WRITABLE_HWM = new Writable().writableHighWaterMark;
|
|
112
|
+
|
|
113
|
+
// The same for the readable half: node's Http2Stream sets no readable highWaterMark
|
|
114
|
+
// either, so readableHighWaterMark is the Readable default -- 16384 on node 20, 65536
|
|
115
|
+
// from 22 on, measured on live server streams of all four majors and equal to
|
|
116
|
+
// `new Readable().readableHighWaterMark` on each.
|
|
117
|
+
const READABLE_HWM = new Readable().readableHighWaterMark;
|
|
118
|
+
|
|
119
|
+
// process.nextTick(fn, args) instead of an arrow closure per event: the arrow
|
|
120
|
+
// allocated a new function object for every request, and in the compat layer
|
|
121
|
+
// that showed up as GC time.
|
|
122
|
+
function emitNT(target, name, arg) {
|
|
123
|
+
if (arg === undefined) {
|
|
124
|
+
target.emit(name);
|
|
125
|
+
} else {
|
|
126
|
+
target.emit(name, arg);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// One-arg emitters for the per-request deliveries: the batched tick route of
|
|
131
|
+
// lib/fast-tick.js carries (fn, arg) pairs, so these replace the
|
|
132
|
+
// `emitNT(target, 'close' | 'drain')` calls the hot paths used, without
|
|
133
|
+
// paying a closure per event (the reason emitNT exists, item 41).
|
|
134
|
+
function emitCloseNT(target) {
|
|
135
|
+
target.emit('close');
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function emitDrainNT(target) {
|
|
139
|
+
target.emit('drain');
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function emitErrorCloseNT(target, err) {
|
|
143
|
+
target._errorEmitted = true;
|
|
144
|
+
target._streamErrored = err;
|
|
145
|
+
target.emit('error', err);
|
|
146
|
+
target.emit('close');
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// The 'error' of the write-after-end shape: emitted on a stream that closes by itself
|
|
150
|
+
// a moment later, so 'close' is NOT this helper's job -- but the Duplex getters read the
|
|
151
|
+
// same two slots, and node's errorOrDestroy fills state.errored BEFORE the event, not at
|
|
152
|
+
// the emit (destroy.js checkError). Same moment here: the nextTick that carries the
|
|
153
|
+
// event is the nextTick that ran the flag set in emitErrorCloseNT anyway.
|
|
154
|
+
function emitErrorOnlyNT(target, err) {
|
|
155
|
+
target._errorEmitted = true;
|
|
156
|
+
if (target._streamErrored === undefined) {
|
|
157
|
+
target._streamErrored = err;
|
|
158
|
+
}
|
|
159
|
+
target.emit('error', err);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// 'end' with the Duplex bookkeeping: readableEnded/buffer-free readable read node's
|
|
163
|
+
// endEmitted bit, and the bit flips at the delivery, not at the schedule.
|
|
164
|
+
function emitEndNT(target) {
|
|
165
|
+
if (target._eofEmitted === true) {
|
|
166
|
+
return; // the 'end' of a Duplex is once-only; the drain paths can re-arm it
|
|
167
|
+
}
|
|
168
|
+
target._eofEmitted = true;
|
|
169
|
+
target.emit('end');
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// node's onStreamTrailers (internal/http2/core.js), the callback nghttp2 runs when the
|
|
173
|
+
// writable half of a stream that asked for trailers finishes. Two parts of it are easy
|
|
174
|
+
// to lose: `trailersReady` is set before the destroyed/closed check (so a stream that is
|
|
175
|
+
// already gone is still marked ready), and when nothing is listening for the event node
|
|
176
|
+
// does not leave the deferred END_STREAM outstanding -- it sends an empty trailer block
|
|
177
|
+
// itself and closes. An empty block is not a header section on the wire: it is the withheld
|
|
178
|
+
// END_STREAM on a zero-length DATA, see sendTrailers() below. Without that last part a
|
|
179
|
+
// `respond({waitForTrailers:true})` followed by `end()` with no 'wantTrailers' handler hangs
|
|
180
|
+
// the stream forever, which is exactly what upstream's
|
|
181
|
+
// test-http2-no-wanttrailers-listener.js tests.
|
|
182
|
+
//
|
|
183
|
+
// h2lean's compat layer is not a subscriber (see emit() below), so `false` from emit()
|
|
184
|
+
// does not by itself mean nobody answered: the compat handler calls sendTrailers() from
|
|
185
|
+
// inside the dispatch, and the sentTrailers check is what sees that it did.
|
|
186
|
+
function wantTrailersNT(stream) {
|
|
187
|
+
stream._trailersReady = true;
|
|
188
|
+
if (stream._destroyed || stream.closed) {
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (!stream.emit('wantTrailers') && !stream.sentTrailers) {
|
|
192
|
+
stream.sendTrailers({});
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// The tick body of _scheduleFinish, a named function rather than a closure: it runs
|
|
197
|
+
// once per finished stream, and a per-response allocation on the compat finish path
|
|
198
|
+
// was measured into the regression item 44 closes.
|
|
199
|
+
// Not _destroyed here: a stream whose both halves close in the same turn the
|
|
200
|
+
// writable ends flips ST_CLOSED synchronously (_closeNow) while the close EVENTS
|
|
201
|
+
// are deferred -- and node's order for that shape is 'finish' before 'close',
|
|
202
|
+
// with writableFinished true at the close (measured). The only cancel is a
|
|
203
|
+
// writable that never drained: octets still parked on window credit.
|
|
204
|
+
function finishNT(stream) {
|
|
205
|
+
stream._finishQueued = false;
|
|
206
|
+
if (stream._writableFinished || stream._queued !== null) {
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
stream._writableFinished = true;
|
|
210
|
+
stream.emit('finish');
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// 'end' and 'close' for a stream whose two halves finished in the same turn.
|
|
214
|
+
// They were already going to run in the same tick drain, so folding them into
|
|
215
|
+
// one callback only removes one TickObject per request.
|
|
216
|
+
function emitEndCloseNT(target) {
|
|
217
|
+
if (target._finishFuse) {
|
|
218
|
+
// the finish work rides here, ahead of every state this tick flips: the separate
|
|
219
|
+
// tick it replaces ran in the same drain, directly before this callback, when the
|
|
220
|
+
// session reference and _closeDelivered were still what end() left them.
|
|
221
|
+
target._finishFuse = false;
|
|
222
|
+
finishNT(target);
|
|
223
|
+
}
|
|
224
|
+
target._closeDelivered = true;
|
|
225
|
+
// node clears the stream's session reference in _destroy, before any of the close
|
|
226
|
+
// events go out (internal/http2/core.js:2546) -- see _closeNow for why the drop waits
|
|
227
|
+
// for this tick here.
|
|
228
|
+
target.session = undefined;
|
|
229
|
+
if (target._eofEmitted !== true) {
|
|
230
|
+
target._eofEmitted = true;
|
|
231
|
+
target.emit('end');
|
|
232
|
+
}
|
|
233
|
+
target.emit('close');
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// The plain-close half of the same pair: 'close' for a stream whose both halves finished
|
|
237
|
+
// in one turn, with no 'end' owed. Marks the node-equivalent close moment -- see
|
|
238
|
+
// _closeDelivered above.
|
|
239
|
+
function emitCloseDeliveredNT(target) {
|
|
240
|
+
if (target._finishFuse) {
|
|
241
|
+
target._finishFuse = false;
|
|
242
|
+
finishNT(target);
|
|
243
|
+
}
|
|
244
|
+
target._closeDelivered = true;
|
|
245
|
+
target.session = undefined;
|
|
246
|
+
target.emit('close');
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// The scheduled half of the unread-request auto-close -- see _maybeAutoClose
|
|
250
|
+
// below for the rule and its measurement. The unread request half reports 'end'
|
|
251
|
+
// here, before the 'close' _destroy schedules behind it: node's trace for the
|
|
252
|
+
// shape does the same (test/event-order.test.js, scenario eof-body) -- the
|
|
253
|
+
// readable side is finished by the close, never having been read.
|
|
254
|
+
function autoCloseNT(stream) {
|
|
255
|
+
if (stream._destroyed) {
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
stream._tick(emitEndNT, stream);
|
|
259
|
+
stream._destroy(NO_ERROR, true);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// node's onFileUnpipe closes an owned descriptor without caring about the error; the
|
|
263
|
+
// same empty callback goes to every fs.close the file paths issue.
|
|
264
|
+
function noopClose() {}
|
|
265
|
+
|
|
266
|
+
// The read chunk of the file pump. node's StreamPipe sizes its reads internally; the
|
|
267
|
+
// boundaries are not wire-visible here (each read feeds write(), which frames DATA by
|
|
268
|
+
// maxFrameSize and the flow-control windows either way), so a plain 64 KiB read is used.
|
|
269
|
+
const FILE_CHUNK = 65536;
|
|
270
|
+
|
|
271
|
+
// node tests `fd instanceof fsPromisesInternal.FileHandle`, but node:fs/promises does
|
|
272
|
+
// not export the class (it lives behind --expose-internals), so a real handle is
|
|
273
|
+
// recognised by its constructor name and the numeric fd member: an fs.promises.open()
|
|
274
|
+
// instance passes, a plain { fd } object does not. A subclass or a same-named replica
|
|
275
|
+
// passes too, which is the same leniency node's instanceof shows to subclasses.
|
|
276
|
+
const isFileHandle = (v) =>
|
|
277
|
+
typeof v === 'object' && v !== null && typeof v.fd === 'number' &&
|
|
278
|
+
typeof v.close === 'function' && v.constructor != null &&
|
|
279
|
+
v.constructor.name === 'FileHandle';
|
|
280
|
+
|
|
281
|
+
// node's ERR_INVALID_ARG_TYPE received-tail (lib/internal/errors.js), measured against
|
|
282
|
+
// a live v26.12.1 respondWithFD: a named function renders `function ${name}` -- with
|
|
283
|
+
// the trailing space an anonymous one keeps --, instances name their constructor,
|
|
284
|
+
// primitives their typeof with the inspected value, null/undefined stand alone.
|
|
285
|
+
function receivedArgType(v) {
|
|
286
|
+
switch (typeof v) {
|
|
287
|
+
case 'function':
|
|
288
|
+
return `function ${v.name}`;
|
|
289
|
+
case 'object':
|
|
290
|
+
if (v === null) {
|
|
291
|
+
return 'null';
|
|
292
|
+
}
|
|
293
|
+
return v.constructor != null
|
|
294
|
+
? `an instance of ${v.constructor.name}` : 'an object with null prototype';
|
|
295
|
+
case 'undefined':
|
|
296
|
+
return 'undefined';
|
|
297
|
+
case 'string':
|
|
298
|
+
return `type string (${inspect(v)})`;
|
|
299
|
+
case 'symbol':
|
|
300
|
+
return `type symbol (${String(v)})`;
|
|
301
|
+
default:
|
|
302
|
+
return `type ${typeof v} (${inspect(v)})`;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// The two TypeError shapes the argument guards raise, measured on the same binary:
|
|
307
|
+
// 'The "fd" argument must be of type number or an instance of FileHandle. Received ...'
|
|
308
|
+
// and `The property 'options.offset' is invalid. Received ${inspect(v)}`.
|
|
309
|
+
function argTypeError(msg, v) {
|
|
310
|
+
const err = new TypeError(`${msg} Received ${receivedArgType(v)}`);
|
|
311
|
+
err.code = 'ERR_INVALID_ARG_TYPE';
|
|
312
|
+
return err;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function propertyValueError(name, v) {
|
|
316
|
+
const err = new TypeError(
|
|
317
|
+
`The property 'options.${name}' is invalid. Received ${inspect(v)}`);
|
|
318
|
+
err.code = 'ERR_INVALID_ARG_VALUE';
|
|
319
|
+
return err;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// node's options guard (assertIsObject plus the explicit checks of respondWithFD,
|
|
323
|
+
// internal/http2/core.js): an undefined options is an empty one, null and primitives
|
|
324
|
+
// are refused, and -- measured -- an array is refused for options (unlike the headers
|
|
325
|
+
// argument). offset/length/statCheck keep node's `!== undefined` tests, so a null
|
|
326
|
+
// offset is refused exactly the way a string one is.
|
|
327
|
+
function fdOptions(options) {
|
|
328
|
+
if (options !== undefined &&
|
|
329
|
+
(options === null || typeof options !== 'object' || Array.isArray(options))) {
|
|
330
|
+
throw argTypeError('The "options" argument must be of type object.', options);
|
|
331
|
+
}
|
|
332
|
+
const opts = options === undefined ? {} : { ...options };
|
|
333
|
+
if (opts.offset !== undefined && typeof opts.offset !== 'number') {
|
|
334
|
+
throw propertyValueError('offset', opts.offset);
|
|
335
|
+
}
|
|
336
|
+
if (opts.length !== undefined && typeof opts.length !== 'number') {
|
|
337
|
+
throw propertyValueError('length', opts.length);
|
|
338
|
+
}
|
|
339
|
+
if (opts.statCheck !== undefined && typeof opts.statCheck !== 'function') {
|
|
340
|
+
throw propertyValueError('statCheck', opts.statCheck);
|
|
341
|
+
}
|
|
342
|
+
return opts;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// node's prepareResponseHeadersObject (internal/http2/core.js): a null-prototype copy
|
|
346
|
+
// of the caller's object with ':status' coerced in, so a statCheck that rewrites
|
|
347
|
+
// 'content-length' lands on the copy -- which is also what sentHeaders reports,
|
|
348
|
+
// exactly where node's kSentHeaders has it. The generated date is left to hdr.block,
|
|
349
|
+
// whose sendDate rule is the one prepare applies too. Status validation happens here,
|
|
350
|
+
// before the payload-forbidden check -- measured: ':status': 700 throws
|
|
351
|
+
// ERR_HTTP2_STATUS_INVALID out of the call, and ':status': '700' is coerced to 700
|
|
352
|
+
// first. The array form passes through untouched (hdr.block handles pairs natively);
|
|
353
|
+
// node's for..in over an array copies the index keys into the copy and sends field
|
|
354
|
+
// names '0', '1', ... instead -- the junk shape the header comment documents.
|
|
355
|
+
function prepareResponseHeadersObject(headersParam) {
|
|
356
|
+
if (headersParam !== undefined &&
|
|
357
|
+
(headersParam === null || typeof headersParam !== 'object')) {
|
|
358
|
+
throw argTypeError('The "headers" argument must be an instance of Array or Object.',
|
|
359
|
+
headersParam);
|
|
360
|
+
}
|
|
361
|
+
if (Array.isArray(headersParam)) {
|
|
362
|
+
return { headers: headersParam, statusCode: 0, isArray: true };
|
|
363
|
+
}
|
|
364
|
+
const copy = { __proto__: null };
|
|
365
|
+
let statusCode;
|
|
366
|
+
// node guards the copy on oldHeaders !== null && !== undefined (core.js): a missing
|
|
367
|
+
// headers argument is a valid response -- respondWithFD(fd) with no fields -- and an
|
|
368
|
+
// unguarded Object.keys would turn it into a session-killing TypeError
|
|
369
|
+
if (headersParam !== undefined && headersParam !== null) {
|
|
370
|
+
const keys = Object.keys(headersParam);
|
|
371
|
+
for (let i = 0; i < keys.length; i++) {
|
|
372
|
+
const key = keys[i];
|
|
373
|
+
copy[key] = headersParam[key];
|
|
374
|
+
if (key === ':status') {
|
|
375
|
+
statusCode = copy[key];
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
copy[hdr.KSensitiveHeaders] = headersParam[hdr.KSensitiveHeaders];
|
|
379
|
+
}
|
|
380
|
+
statusCode = copy[':status'] = (statusCode | 0) || 200;
|
|
381
|
+
if (statusCode < 200 || statusCode > 599) {
|
|
382
|
+
throw errorOf('ERR_HTTP2_STATUS_INVALID', `Invalid status code: ${statusCode}`);
|
|
383
|
+
}
|
|
384
|
+
const neverIndex = copy[hdr.KSensitiveHeaders];
|
|
385
|
+
if (neverIndex !== undefined && !Array.isArray(neverIndex)) {
|
|
386
|
+
const err = new TypeError(
|
|
387
|
+
`The property 'headers[http2.neverIndex]' is invalid. Received ${inspect(neverIndex)}`);
|
|
388
|
+
err.code = 'ERR_INVALID_ARG_VALUE';
|
|
389
|
+
throw err;
|
|
390
|
+
}
|
|
391
|
+
return { headers: copy, statusCode, isArray: false };
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
const { NO_ERROR } = frames;
|
|
395
|
+
class Http2Stream extends Stream {
|
|
396
|
+
|
|
397
|
+
get readableDidRead() {
|
|
398
|
+
return this._dataRead === true;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
get readableFlowing() {
|
|
402
|
+
return this._flowing === undefined ? null : this._flowing;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
get readableHighWaterMark() {
|
|
406
|
+
return READABLE_HWM;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
get readableObjectMode() {
|
|
410
|
+
return false;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
get writableObjectMode() {
|
|
414
|
+
return false;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
get bufferSize() {
|
|
418
|
+
return this.writableLength;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
cork() {
|
|
422
|
+
this._corked++;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
uncork() {
|
|
426
|
+
if (this._corked > 0) {
|
|
427
|
+
this._corked--;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
get writableCorked() {
|
|
432
|
+
return this._corked;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
get writableHighWaterMark() {
|
|
436
|
+
return WRITABLE_HWM;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
setDefaultEncoding(encoding) {
|
|
440
|
+
if (typeof encoding === 'string') {
|
|
441
|
+
encoding = encoding.toLowerCase();
|
|
442
|
+
}
|
|
443
|
+
if (!Buffer.isEncoding(encoding)) {
|
|
444
|
+
const err = new TypeError(`Unknown encoding: ${encoding}`);
|
|
445
|
+
err.code = 'ERR_UNKNOWN_ENCODING';
|
|
446
|
+
throw err;
|
|
447
|
+
}
|
|
448
|
+
this._defaultEnc = encoding;
|
|
449
|
+
return this;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
unpipe(dest) {
|
|
453
|
+
const pipes = this._pipes;
|
|
454
|
+
if (pipes === null || pipes.length === 0) {
|
|
455
|
+
return this;
|
|
456
|
+
}
|
|
457
|
+
if (!dest) {
|
|
458
|
+
const dests = pipes;
|
|
459
|
+
this._pipes = [];
|
|
460
|
+
this.pause();
|
|
461
|
+
for (let i = 0; i < dests.length; i++) {
|
|
462
|
+
dests[i].emit('unpipe', this, { hasUnpiped: false });
|
|
463
|
+
}
|
|
464
|
+
return this;
|
|
465
|
+
}
|
|
466
|
+
const index = pipes.indexOf(dest);
|
|
467
|
+
if (index === -1) {
|
|
468
|
+
return this;
|
|
469
|
+
}
|
|
470
|
+
pipes.splice(index, 1);
|
|
471
|
+
if (pipes.length === 0) {
|
|
472
|
+
this.pause();
|
|
473
|
+
}
|
|
474
|
+
dest.emit('unpipe', this, { hasUnpiped: false });
|
|
475
|
+
return this;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
[Symbol.asyncIterator]() {
|
|
479
|
+
return this._createIterator(undefined);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
iterator(options) {
|
|
483
|
+
if (options !== undefined) {
|
|
484
|
+
validateObjectArg(options, 'options');
|
|
485
|
+
}
|
|
486
|
+
return this._createIterator(options);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
map(fn, options) {
|
|
490
|
+
return Readable.from(opMap(this, fn, options));
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
filter(fn, options) {
|
|
494
|
+
return Readable.from(opFilter(this, fn, options));
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
flatMap(fn, options) {
|
|
498
|
+
return Readable.from(opFlatMap(this, fn, options));
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
drop(number, options) {
|
|
502
|
+
return Readable.from(opDrop(this, number, options));
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
take(number, options) {
|
|
506
|
+
return Readable.from(opTake(this, number, options));
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
reduce(reducer, initialValue, options) {
|
|
510
|
+
// node's reduce tests `arguments.length > 1` inside the operator to tell
|
|
511
|
+
// "no initial value" from "initial value undefined"; the arity has to be
|
|
512
|
+
// read at the call, which is here.
|
|
513
|
+
return opReduce(this, arguments.length > 1, reducer, initialValue, options);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
forEach(fn, options) {
|
|
517
|
+
return opForEach(this, fn, options);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
toArray(options) {
|
|
521
|
+
return opToArray(this, options);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
some(fn, options) {
|
|
525
|
+
return opSome(this, fn, options);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
every(fn, options) {
|
|
529
|
+
return opEvery(this, fn, options);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
find(fn, options) {
|
|
533
|
+
return opFind(this, fn, options);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
wrap(stream) {
|
|
537
|
+
let paused = false;
|
|
538
|
+
stream.on('data', (chunk) => {
|
|
539
|
+
if (!this.push(chunk) && stream.pause) {
|
|
540
|
+
paused = true;
|
|
541
|
+
stream.pause();
|
|
542
|
+
}
|
|
543
|
+
});
|
|
544
|
+
stream.on('end', () => {
|
|
545
|
+
this.push(null);
|
|
546
|
+
});
|
|
547
|
+
stream.on('error', (err) => {
|
|
548
|
+
if (!this.destroyed) {
|
|
549
|
+
this.destroy(err);
|
|
550
|
+
}
|
|
551
|
+
});
|
|
552
|
+
stream.on('close', () => {
|
|
553
|
+
if (!this.destroyed) {
|
|
554
|
+
this.destroy();
|
|
555
|
+
}
|
|
556
|
+
});
|
|
557
|
+
stream.on('destroy', () => {
|
|
558
|
+
if (!this.destroyed) {
|
|
559
|
+
this.destroy();
|
|
560
|
+
}
|
|
561
|
+
});
|
|
562
|
+
this._read = () => {
|
|
563
|
+
if (paused && stream.resume) {
|
|
564
|
+
paused = false;
|
|
565
|
+
stream.resume();
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
const streamKeys = Object.keys(stream);
|
|
569
|
+
for (let j = 0; j < streamKeys.length; j++) {
|
|
570
|
+
const i = streamKeys[j];
|
|
571
|
+
if (this[i] === undefined && typeof stream[i] === 'function') {
|
|
572
|
+
this[i] = stream[i].bind(stream);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
return this;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
setTimeout(ms, cb) {
|
|
579
|
+
this.session.setTimeout(ms, cb);
|
|
580
|
+
return this;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
function errorOf(code, msg) {
|
|
587
|
+
const err = new Error(msg);
|
|
588
|
+
err.code = code;
|
|
589
|
+
return err;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// node's Http2Stream.close validates its code with validateInteger(code, 'code', 0,
|
|
593
|
+
// kMaxInt) and the callback with validateFunction (internal/http2/core.js:2474,
|
|
594
|
+
// kMaxInt = 2^32 - 1 at core.js:239). The messages are internal/validators', read
|
|
595
|
+
// out of it in the same session: a non-number is ERR_INVALID_ARG_TYPE, a
|
|
596
|
+
// non-integer or an out-of-range integer is ERR_OUT_OF_RANGE.
|
|
597
|
+
// The Received-tail is determineSpecificType (internal/errors.js), ported from the
|
|
598
|
+
// bundled source and measured through Http2Stream.close on a live v26.12.1 client:
|
|
599
|
+
// strings quote with '' and flip to JSON.stringify when the value itself carries a
|
|
600
|
+
// quote, both truncated at 28 octets to 25 plus '...'; -0/NaN/Infinity are named;
|
|
601
|
+
// an object reports `an instance of ${constructor.name}` only when that name is a
|
|
602
|
+
// non-empty string, else the inspect fallback at depth -1; `function ${name}` keeps
|
|
603
|
+
// the trailing space for an anonymous function; the generic tail inspects, it does
|
|
604
|
+
// not String().
|
|
605
|
+
function specType(v) {
|
|
606
|
+
if (v === null) {
|
|
607
|
+
return 'null';
|
|
608
|
+
}
|
|
609
|
+
if (v === undefined) {
|
|
610
|
+
return 'undefined';
|
|
611
|
+
}
|
|
612
|
+
const t = typeof v;
|
|
613
|
+
if (t === 'string') {
|
|
614
|
+
if (v.length > 28) {
|
|
615
|
+
v = `${v.slice(0, 25)}...`;
|
|
616
|
+
}
|
|
617
|
+
return v.indexOf("'") === -1 ? `type string ('${v}')`
|
|
618
|
+
: `type string (${JSON.stringify(v)})`;
|
|
619
|
+
}
|
|
620
|
+
if (t === 'number') {
|
|
621
|
+
if (v === 0) {
|
|
622
|
+
return 1 / v === -Infinity ? 'type number (-0)' : 'type number (0)';
|
|
623
|
+
}
|
|
624
|
+
if (v !== v) {
|
|
625
|
+
return 'type number (NaN)';
|
|
626
|
+
}
|
|
627
|
+
if (v === Infinity) {
|
|
628
|
+
return 'type number (Infinity)';
|
|
629
|
+
}
|
|
630
|
+
if (v === -Infinity) {
|
|
631
|
+
return 'type number (-Infinity)';
|
|
632
|
+
}
|
|
633
|
+
return `type number (${v})`;
|
|
634
|
+
}
|
|
635
|
+
if (t === 'boolean') {
|
|
636
|
+
return v ? 'type boolean (true)' : 'type boolean (false)';
|
|
637
|
+
}
|
|
638
|
+
if (t === 'bigint') {
|
|
639
|
+
return `type bigint (${v}n)`;
|
|
640
|
+
}
|
|
641
|
+
if (t === 'symbol') {
|
|
642
|
+
return `type symbol (${String(v)})`;
|
|
643
|
+
}
|
|
644
|
+
if (t === 'function') {
|
|
645
|
+
return `function ${v.name}`;
|
|
646
|
+
}
|
|
647
|
+
if (t === 'object') {
|
|
648
|
+
// `constructor` may be user-controlled: node reads it once and only trusts a
|
|
649
|
+
// non-empty string name (internal/errors.js).
|
|
650
|
+
const name = v.constructor?.name;
|
|
651
|
+
if (typeof name === 'string' && name !== '') {
|
|
652
|
+
return `an instance of ${name}`;
|
|
653
|
+
}
|
|
654
|
+
return inspect(v, { depth: -1 });
|
|
655
|
+
}
|
|
656
|
+
let shown = inspect(v, { colors: false });
|
|
657
|
+
if (shown.length > 28) {
|
|
658
|
+
shown = `${shown.slice(0, 25)}...`;
|
|
659
|
+
}
|
|
660
|
+
return `type ${t} (${shown})`;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// node's Http2Stream.close (core.js:2474) validates its code through
|
|
664
|
+
// validateInteger(code, 'code', 0, kMaxInt) -- kMaxInt is 2^32-1 (core.js:239) -- and
|
|
665
|
+
// its callback through validateFunction; the three verdicts and their exact texts are
|
|
666
|
+
// measured on a live v26.12.1 client: a non-number code is ERR_INVALID_ARG_TYPE
|
|
667
|
+
// ("must be of type number"), a non-integer number is ERR_OUT_OF_RANGE ("It must be an
|
|
668
|
+
// integer"), and a code outside [0, 2^32-1] is ERR_OUT_OF_RANGE ("It must be >= 0 &&
|
|
669
|
+
// <= 4294967295"). The callback's own message names "callback" and follows the same
|
|
670
|
+
// determineSpecificType shapes (measured: string, null, number).
|
|
671
|
+
function validateRstCode(code, callback) {
|
|
672
|
+
if (typeof code !== 'number') {
|
|
673
|
+
throw errorOf('ERR_INVALID_ARG_TYPE',
|
|
674
|
+
`The "code" argument must be of type number. Received ${specType(code)}`);
|
|
675
|
+
}
|
|
676
|
+
if (!Number.isInteger(code)) {
|
|
677
|
+
throw errorOf('ERR_OUT_OF_RANGE',
|
|
678
|
+
`The value of "code" is out of range. It must be an integer. Received ${code}`);
|
|
679
|
+
}
|
|
680
|
+
if (code < 0 || code > 4294967295) {
|
|
681
|
+
throw errorOf('ERR_OUT_OF_RANGE',
|
|
682
|
+
`The value of "code" is out of range. It must be >= 0 && <= 4294967295. Received ${code}`);
|
|
683
|
+
}
|
|
684
|
+
if (callback !== undefined && typeof callback !== 'function') {
|
|
685
|
+
throw errorOf('ERR_INVALID_ARG_TYPE',
|
|
686
|
+
`The "callback" argument must be of type function. Received ${specType(callback)}`);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// --- the async-iteration machinery ----------------------------------------------
|
|
691
|
+
// Everything below reproduces node's internal/streams/readable.js:1552-1805
|
|
692
|
+
// (streamToAsyncIterator/createAsyncIterator) and internal/streams/operators,
|
|
693
|
+
// read from the binary in the same session as the measurements cited at the
|
|
694
|
+
// methods. Two simplifications are honest, not inventions: (a) the iterator
|
|
695
|
+
// never meets a thenable chunk -- push() validates its argument, so the queue
|
|
696
|
+
// holds only Buffer/string/null and node's `chunk?.then` unwrapping and the
|
|
697
|
+
// two-error AggregateError race it guards cannot occur (measured: an errored
|
|
698
|
+
// iteration rejects with the bare error); (b) the FixedQueue node parks
|
|
699
|
+
// queued requests in is an array here -- queue depth is a behaviour of the
|
|
700
|
+
// consumer, not of the protocol.
|
|
701
|
+
|
|
702
|
+
const kEmpty = Symbol('kEmpty');
|
|
703
|
+
const kEof = Symbol('kEof');
|
|
704
|
+
// %AsyncIteratorPrototype% in V8: the function's .prototype is an INSTANCE of
|
|
705
|
+
// the (shared) async-generator prototype, so the intrinsic with
|
|
706
|
+
// [Symbol.asyncIterator]/[Symbol.asyncDispose] and no own methods sits TWO
|
|
707
|
+
// levels up. Verified identity with the proto of a live node v26 iterator
|
|
708
|
+
// object; the single getPrototypeOf lands on the generator prototype instead.
|
|
709
|
+
// Node's own iterator is NOT this shape on every major: 22 and 24 hand back a
|
|
710
|
+
// real async-generator instance, whose proto has no own keys at all. The
|
|
711
|
+
// intrinsic is the only anchor stable across majors, and the behaviour that
|
|
712
|
+
// depends on it ([Symbol.asyncIterator] resolving through the chain,
|
|
713
|
+
// self-identical) is verified per major; exact proto identity is unportable.
|
|
714
|
+
const ASYNC_ITERATOR_PROTO =
|
|
715
|
+
Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}.prototype));
|
|
716
|
+
|
|
717
|
+
function noop() {}
|
|
718
|
+
|
|
719
|
+
// node's internal AbortError as the stream machinery constructs it (measured
|
|
720
|
+
// on a live node break: name 'AbortError', code 'ABORT_ERR'). core.js:2516
|
|
721
|
+
// maps it onto RST CANCEL(8) inside _destroy.
|
|
722
|
+
function abortError(cause) {
|
|
723
|
+
const err = new Error('The operation was aborted',
|
|
724
|
+
cause === undefined ? undefined : { cause });
|
|
725
|
+
err.name = 'AbortError';
|
|
726
|
+
err.code = 'ABORT_ERR';
|
|
727
|
+
return err;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
function validateObjectArg(value, name) {
|
|
731
|
+
if (value === null || typeof value !== 'object') {
|
|
732
|
+
throw errorOf('ERR_INVALID_ARG_TYPE',
|
|
733
|
+
`The "${name}" argument must be of type object. Received ${inspect(value)}`);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
function validateFunctionArg(value, name) {
|
|
738
|
+
if (typeof value !== 'function') {
|
|
739
|
+
throw errorOf('ERR_INVALID_ARG_TYPE',
|
|
740
|
+
`The "${name}" argument must be of type function. Received ${inspect(value)}`);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
// node's pair in every operator: validateObject(options) then
|
|
745
|
+
// validateAbortSignal(options.signal).
|
|
746
|
+
function validateSignalArg(options) {
|
|
747
|
+
if (options != null && options.signal != null && !(options.signal instanceof AbortSignal)) {
|
|
748
|
+
throw errorOf('ERR_INVALID_ARG_TYPE',
|
|
749
|
+
'The "options.signal" argument must be an instance of type AbortSignal.');
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
function validateOperatorOptions(options) {
|
|
754
|
+
if (options != null) {
|
|
755
|
+
validateObjectArg(options, 'options');
|
|
756
|
+
}
|
|
757
|
+
validateSignalArg(options);
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// node's toIntegerOrInfinity (operators:298): Number coercion per the
|
|
761
|
+
// iterator-helpers proposal, then the range refusal.
|
|
762
|
+
function toIntegerOrInfinity(number) {
|
|
763
|
+
number = Number(number);
|
|
764
|
+
if (Number.isNaN(number)) {
|
|
765
|
+
return 0;
|
|
766
|
+
}
|
|
767
|
+
if (number < 0) {
|
|
768
|
+
throw errorOf('ERR_OUT_OF_RANGE',
|
|
769
|
+
`The value of "number" is out of range. It must be >= 0. Received ${number}`);
|
|
770
|
+
}
|
|
771
|
+
return number;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
// node's createAsyncIterator (readable.js:1576). The request protocol -- next
|
|
775
|
+
// fast path, queue behind an inFlight request, return/throw draining through
|
|
776
|
+
// the same pump -- is reproduced member by member; the wake is h2lean's
|
|
777
|
+
// 'readable' event (node's emitReadable, same coalescing) and the end verdict
|
|
778
|
+
// comes from the error/end/close trio standing in for
|
|
779
|
+
// eos(stream, { writable: false }).
|
|
780
|
+
function createStreamIterator(stream, options) {
|
|
781
|
+
let callback = noop;
|
|
782
|
+
let error; // undefined: active, null: ended cleanly, else: the Error
|
|
783
|
+
let started = false;
|
|
784
|
+
let completed = false;
|
|
785
|
+
let inFlight = false; // an asynchronous request is outstanding
|
|
786
|
+
let queue = null; // requests received while inFlight
|
|
787
|
+
let draining = false;
|
|
788
|
+
let detach = noop;
|
|
789
|
+
|
|
790
|
+
function fire() {
|
|
791
|
+
const cb = callback;
|
|
792
|
+
callback = noop;
|
|
793
|
+
cb();
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
function wait() {
|
|
797
|
+
return new Promise((resolve) => {
|
|
798
|
+
callback = resolve;
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
function start() {
|
|
803
|
+
started = true;
|
|
804
|
+
stream.on('readable', fire);
|
|
805
|
+
// node's eos(stream, { writable: false }, cb), adapted: the verdict
|
|
806
|
+
// handlers record the FIRST verdict and wake the pump (node's once-wrapped
|
|
807
|
+
// callback suppresses the rest -- an 'end' followed by a destroy(err) is
|
|
808
|
+
// swallowed on node, measured off a live client), and the LISTENERS stay
|
|
809
|
+
// attached until finalize's detach branch -- the part that matters here:
|
|
810
|
+
// node's eos keeps its 'error' handler attached through the teardown, so a
|
|
811
|
+
// destroy that races a natural end does not turn into an unhandled
|
|
812
|
+
// 'error'. A close with neither end nor error is node's eos verdict
|
|
813
|
+
// ERR_STREAM_PREMATURE_CLOSE ('Premature close', read out of
|
|
814
|
+
// internal/errors with --expose-internals).
|
|
815
|
+
const settle = (err) => {
|
|
816
|
+
if (error !== undefined) {
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
819
|
+
error = err;
|
|
820
|
+
fire();
|
|
821
|
+
};
|
|
822
|
+
const onEnd = () => {
|
|
823
|
+
settle(null);
|
|
824
|
+
};
|
|
825
|
+
const onClose = () => {
|
|
826
|
+
settle(errorOf('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'));
|
|
827
|
+
};
|
|
828
|
+
stream.on('error', settle);
|
|
829
|
+
stream.on('end', onEnd);
|
|
830
|
+
stream.on('close', onClose);
|
|
831
|
+
detach = () => {
|
|
832
|
+
stream.removeListener('readable', fire);
|
|
833
|
+
stream.removeListener('error', settle);
|
|
834
|
+
stream.removeListener('end', onEnd);
|
|
835
|
+
stream.removeListener('close', onClose);
|
|
836
|
+
};
|
|
837
|
+
// node's eos settles immediately (on the next tick) when the stream has
|
|
838
|
+
// ALREADY reached its verdict at start(): a second iterator over an ended
|
|
839
|
+
// stream gets `{done:true}` (measured on live node: every() after some()
|
|
840
|
+
// on the same stream answers true without hanging), and over a destroyed
|
|
841
|
+
// one gets the premature-close error.
|
|
842
|
+
if (stream.readableEnded === true) {
|
|
843
|
+
stream._tick(() => settle(null));
|
|
844
|
+
} else if (stream.destroyed === true) {
|
|
845
|
+
stream._tick(() => settle(errorOf('ERR_STREAM_PREMATURE_CLOSE', 'Premature close')));
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
function finalize() {
|
|
850
|
+
completed = true;
|
|
851
|
+
// node's finalize (readable.js:1609) reads autoDestroy off the state
|
|
852
|
+
// object; Http2Stream fixes it false (core.js:2132), so the second
|
|
853
|
+
// clause reduces to `error === undefined`: only a still-active
|
|
854
|
+
// return()/break destroys -- node's destroyer(stream, null) on a
|
|
855
|
+
// not-finished stream is destroy(new AbortError()), which core.js:2516
|
|
856
|
+
// turns into RST CANCEL. h2lean's public destroy() derives
|
|
857
|
+
// INTERNAL_ERROR from any Error object (its own documented rule, task
|
|
858
|
+
// 17), so the iterator calls the engine with node's derived pair
|
|
859
|
+
// directly. Measured: break -- destroyed true, rstCode 8, aborted,
|
|
860
|
+
// error:ABORT_ERR, close; natural end -- destroyed stays false.
|
|
861
|
+
if ((error || options?.destroyOnReturn !== false) && error === undefined) {
|
|
862
|
+
if (!stream.destroyed) {
|
|
863
|
+
stream._destroy(frames.CANCEL, true, abortError());
|
|
864
|
+
}
|
|
865
|
+
} else {
|
|
866
|
+
stream.removeListener('readable', fire);
|
|
867
|
+
detach();
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
function drain() {
|
|
872
|
+
// node's guard: requests settled synchronously call back into drain(),
|
|
873
|
+
// and one loop runs instead of one recursion per request.
|
|
874
|
+
if (draining) {
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
877
|
+
draining = true;
|
|
878
|
+
try {
|
|
879
|
+
while (!inFlight && queue !== null && queue.length > 0) {
|
|
880
|
+
const req = queue.shift();
|
|
881
|
+
if (req.type === 'next') {
|
|
882
|
+
processNext(req.resolve, req.reject);
|
|
883
|
+
} else if (req.type === 'return') {
|
|
884
|
+
processReturn(req.value, req.resolve);
|
|
885
|
+
} else {
|
|
886
|
+
processThrow(req.value, req.reject);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
} finally {
|
|
890
|
+
draining = false;
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
function pump(resolve, reject) {
|
|
895
|
+
const chunk = stream.destroyed ? null : stream.read();
|
|
896
|
+
if (chunk !== null) {
|
|
897
|
+
inFlight = false;
|
|
898
|
+
resolve({ done: false, value: chunk });
|
|
899
|
+
if (queue !== null) {
|
|
900
|
+
drain();
|
|
901
|
+
}
|
|
902
|
+
} else if (error) {
|
|
903
|
+
inFlight = false;
|
|
904
|
+
finalize();
|
|
905
|
+
reject(error);
|
|
906
|
+
if (queue !== null) {
|
|
907
|
+
drain();
|
|
908
|
+
}
|
|
909
|
+
} else if (error === null) {
|
|
910
|
+
inFlight = false;
|
|
911
|
+
finalize();
|
|
912
|
+
resolve({ done: true, value: undefined });
|
|
913
|
+
if (queue !== null) {
|
|
914
|
+
drain();
|
|
915
|
+
}
|
|
916
|
+
} else {
|
|
917
|
+
// nothing buffered yet: wait for the next 'readable' or end verdict
|
|
918
|
+
// and retry, node's wakeup-promise tail.
|
|
919
|
+
wait().then(() => pump(resolve, reject));
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
function processNext(resolve, reject) {
|
|
924
|
+
if (completed) {
|
|
925
|
+
resolve({ done: true, value: undefined });
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
if (!started) {
|
|
929
|
+
start();
|
|
930
|
+
}
|
|
931
|
+
inFlight = true;
|
|
932
|
+
pump(resolve, reject);
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
function processReturn(value, resolve) {
|
|
936
|
+
if (!completed) {
|
|
937
|
+
if (started) {
|
|
938
|
+
finalize();
|
|
939
|
+
} else {
|
|
940
|
+
// never started: complete without touching the stream.
|
|
941
|
+
completed = true;
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
resolve({ done: true, value });
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
function processThrow(err, reject) {
|
|
948
|
+
if (completed || !started) {
|
|
949
|
+
completed = true;
|
|
950
|
+
reject(err);
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
953
|
+
error = err;
|
|
954
|
+
finalize();
|
|
955
|
+
reject(err);
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
const iter = {
|
|
959
|
+
__proto__: ASYNC_ITERATOR_PROTO,
|
|
960
|
+
next() {
|
|
961
|
+
if (!inFlight && !completed) {
|
|
962
|
+
if (!started) {
|
|
963
|
+
start();
|
|
964
|
+
}
|
|
965
|
+
const chunk = stream.destroyed ? null : stream.read();
|
|
966
|
+
if (chunk !== null) {
|
|
967
|
+
return Promise.resolve({ done: false, value: chunk });
|
|
968
|
+
}
|
|
969
|
+
if (error) {
|
|
970
|
+
finalize();
|
|
971
|
+
return Promise.reject(error);
|
|
972
|
+
}
|
|
973
|
+
if (error === null) {
|
|
974
|
+
finalize();
|
|
975
|
+
return Promise.resolve({ done: true, value: undefined });
|
|
976
|
+
}
|
|
977
|
+
inFlight = true;
|
|
978
|
+
return new Promise((resolve, reject) => {
|
|
979
|
+
wait().then(() => pump(resolve, reject));
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
return new Promise((resolve, reject) => {
|
|
983
|
+
if (inFlight) {
|
|
984
|
+
(queue ??= []).push({ __proto__: null, type: 'next', value: undefined, resolve, reject });
|
|
985
|
+
} else {
|
|
986
|
+
resolve({ done: true, value: undefined });
|
|
987
|
+
}
|
|
988
|
+
});
|
|
989
|
+
},
|
|
990
|
+
return(value) {
|
|
991
|
+
return new Promise((resolve) => {
|
|
992
|
+
if (inFlight) {
|
|
993
|
+
(queue ??= []).push({ __proto__: null, type: 'return', value, resolve, reject: null });
|
|
994
|
+
} else {
|
|
995
|
+
processReturn(value, resolve);
|
|
996
|
+
}
|
|
997
|
+
});
|
|
998
|
+
},
|
|
999
|
+
throw(err) {
|
|
1000
|
+
return new Promise((resolve, reject) => {
|
|
1001
|
+
if (inFlight) {
|
|
1002
|
+
(queue ??= []).push({ __proto__: null, type: 'throw', value: err, resolve, reject });
|
|
1003
|
+
} else {
|
|
1004
|
+
processThrow(err, reject);
|
|
1005
|
+
}
|
|
1006
|
+
});
|
|
1007
|
+
}
|
|
1008
|
+
};
|
|
1009
|
+
// node's streamToAsyncIterator hangs the source on the iterator object
|
|
1010
|
+
// (readable.js:1563-1565); measured raw.stream === rd on a live node.
|
|
1011
|
+
iter.stream = stream;
|
|
1012
|
+
return iter;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
// node's operators (internal/streams/operators). Each is a plain function or
|
|
1016
|
+
// async function mirroring the original's argument shape, so the synchronous
|
|
1017
|
+
// validation the transform family performs (measured: map('nope') throws
|
|
1018
|
+
// ERR_INVALID_ARG_TYPE out of the call) and the rejection the promise family
|
|
1019
|
+
// produces land exactly where node puts them.
|
|
1020
|
+
|
|
1021
|
+
function opMap(stream, fn, options) {
|
|
1022
|
+
validateFunctionArg(fn, 'fn');
|
|
1023
|
+
validateOperatorOptions(options);
|
|
1024
|
+
let concurrency = 1;
|
|
1025
|
+
if (options?.concurrency != null) {
|
|
1026
|
+
concurrency = Math.floor(options.concurrency);
|
|
1027
|
+
}
|
|
1028
|
+
let highWaterMark = concurrency - 1;
|
|
1029
|
+
if (options?.highWaterMark != null) {
|
|
1030
|
+
highWaterMark = Math.floor(options.highWaterMark);
|
|
1031
|
+
}
|
|
1032
|
+
if (!Number.isInteger(concurrency) || concurrency < 1) {
|
|
1033
|
+
throw errorOf('ERR_OUT_OF_RANGE',
|
|
1034
|
+
`The value of "options.concurrency" is out of range. It must be >= 1. Received ${concurrency}`);
|
|
1035
|
+
}
|
|
1036
|
+
if (!Number.isInteger(highWaterMark) || highWaterMark < 0) {
|
|
1037
|
+
throw errorOf('ERR_OUT_OF_RANGE',
|
|
1038
|
+
`The value of "options.highWaterMark" is out of range. It must be >= 0. Received ${highWaterMark}`);
|
|
1039
|
+
}
|
|
1040
|
+
highWaterMark += concurrency;
|
|
1041
|
+
// node builds its always-present signal with AbortSignal.any([...]) --
|
|
1042
|
+
// any([]) is a fresh never-aborted signal, which a never-aborted
|
|
1043
|
+
// controller's signal is byte-equivalent to for everything the operator
|
|
1044
|
+
// reads off it.
|
|
1045
|
+
const signal = options?.signal ?? new AbortController().signal;
|
|
1046
|
+
|
|
1047
|
+
return (async function* map() {
|
|
1048
|
+
const queue = [];
|
|
1049
|
+
const signalOpt = { signal };
|
|
1050
|
+
let next = null;
|
|
1051
|
+
let resume = null;
|
|
1052
|
+
let done = false;
|
|
1053
|
+
let cnt = 0;
|
|
1054
|
+
|
|
1055
|
+
function onCatch() {
|
|
1056
|
+
done = true;
|
|
1057
|
+
afterItemProcessed();
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
function afterItemProcessed() {
|
|
1061
|
+
cnt -= 1;
|
|
1062
|
+
maybeResume();
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
function maybeResume() {
|
|
1066
|
+
if (resume && !done && cnt < concurrency && queue.length < highWaterMark) {
|
|
1067
|
+
const r = resume;
|
|
1068
|
+
resume = null;
|
|
1069
|
+
r();
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
async function pump() {
|
|
1074
|
+
try {
|
|
1075
|
+
for await (let val of stream) {
|
|
1076
|
+
if (done) {
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
if (signal.aborted) {
|
|
1080
|
+
throw stream._abortError();
|
|
1081
|
+
}
|
|
1082
|
+
try {
|
|
1083
|
+
val = fn(val, signalOpt);
|
|
1084
|
+
if (val === kEmpty) {
|
|
1085
|
+
continue;
|
|
1086
|
+
}
|
|
1087
|
+
val = Promise.resolve(val);
|
|
1088
|
+
} catch (err) {
|
|
1089
|
+
val = Promise.reject(err);
|
|
1090
|
+
}
|
|
1091
|
+
cnt += 1;
|
|
1092
|
+
val.then(afterItemProcessed, onCatch);
|
|
1093
|
+
queue.push(val);
|
|
1094
|
+
if (next) {
|
|
1095
|
+
const n = next;
|
|
1096
|
+
next = null;
|
|
1097
|
+
n();
|
|
1098
|
+
}
|
|
1099
|
+
if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) {
|
|
1100
|
+
await new Promise((resolve) => {
|
|
1101
|
+
resume = resolve;
|
|
1102
|
+
});
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
queue.push(kEof);
|
|
1106
|
+
} catch (err) {
|
|
1107
|
+
const val = Promise.reject(err);
|
|
1108
|
+
val.then(afterItemProcessed, onCatch);
|
|
1109
|
+
queue.push(val);
|
|
1110
|
+
} finally {
|
|
1111
|
+
done = true;
|
|
1112
|
+
if (next) {
|
|
1113
|
+
const n = next;
|
|
1114
|
+
next = null;
|
|
1115
|
+
n();
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
pump();
|
|
1121
|
+
|
|
1122
|
+
try {
|
|
1123
|
+
while (true) {
|
|
1124
|
+
while (queue.length > 0) {
|
|
1125
|
+
const val = await queue[0];
|
|
1126
|
+
if (val === kEof) {
|
|
1127
|
+
return;
|
|
1128
|
+
}
|
|
1129
|
+
if (signal.aborted) {
|
|
1130
|
+
throw stream._abortError();
|
|
1131
|
+
}
|
|
1132
|
+
if (val !== kEmpty) {
|
|
1133
|
+
yield val;
|
|
1134
|
+
}
|
|
1135
|
+
queue.shift();
|
|
1136
|
+
maybeResume();
|
|
1137
|
+
}
|
|
1138
|
+
await new Promise((resolve) => {
|
|
1139
|
+
next = resolve;
|
|
1140
|
+
});
|
|
1141
|
+
}
|
|
1142
|
+
} finally {
|
|
1143
|
+
done = true;
|
|
1144
|
+
if (resume) {
|
|
1145
|
+
const r = resume;
|
|
1146
|
+
resume = null;
|
|
1147
|
+
r();
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
})();
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
function opFilter(stream, fn, options) {
|
|
1154
|
+
validateFunctionArg(fn, 'fn');
|
|
1155
|
+
async function filterFn(value, opt) {
|
|
1156
|
+
if (await fn(value, opt)) {
|
|
1157
|
+
return value;
|
|
1158
|
+
}
|
|
1159
|
+
return kEmpty;
|
|
1160
|
+
}
|
|
1161
|
+
return opMap(stream, filterFn, options);
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
async function opForEach(stream, fn, options) {
|
|
1165
|
+
validateFunctionArg(fn, 'fn');
|
|
1166
|
+
async function forEachFn(value, opt) {
|
|
1167
|
+
await fn(value, opt);
|
|
1168
|
+
return kEmpty;
|
|
1169
|
+
}
|
|
1170
|
+
// node drains the mapped generator with an empty for-await body. The same
|
|
1171
|
+
// descent is spelled out here -- an fn error propagates out of the mapped
|
|
1172
|
+
// generator's own body, so its cleanup runs at the throw point and no
|
|
1173
|
+
// abrupt-close return() call from this loop would add anything.
|
|
1174
|
+
const it = opMap(stream, forEachFn, options)[Symbol.asyncIterator]();
|
|
1175
|
+
let res = await it.next();
|
|
1176
|
+
while (!res.done) {
|
|
1177
|
+
res = await it.next();
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
function opFlatMap(stream, fn, options) {
|
|
1182
|
+
const values = opMap(stream, fn, options);
|
|
1183
|
+
return (async function* flatMap() {
|
|
1184
|
+
for await (const val of values) {
|
|
1185
|
+
yield* val;
|
|
1186
|
+
}
|
|
1187
|
+
})();
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
function opDrop(stream, number, options) {
|
|
1191
|
+
validateOperatorOptions(options);
|
|
1192
|
+
const limit = toIntegerOrInfinity(number);
|
|
1193
|
+
return (async function* drop() {
|
|
1194
|
+
if (options?.signal?.aborted) {
|
|
1195
|
+
throw stream._abortError();
|
|
1196
|
+
}
|
|
1197
|
+
let numberLeft = limit;
|
|
1198
|
+
for await (const val of stream) {
|
|
1199
|
+
if (options?.signal?.aborted) {
|
|
1200
|
+
throw stream._abortError();
|
|
1201
|
+
}
|
|
1202
|
+
if (numberLeft-- <= 0) {
|
|
1203
|
+
yield val;
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
})();
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
function opTake(stream, number, options) {
|
|
1210
|
+
validateOperatorOptions(options);
|
|
1211
|
+
const limit = toIntegerOrInfinity(number);
|
|
1212
|
+
return (async function* take() {
|
|
1213
|
+
if (options?.signal?.aborted) {
|
|
1214
|
+
throw stream._abortError();
|
|
1215
|
+
}
|
|
1216
|
+
let numberLeft = limit;
|
|
1217
|
+
for await (const val of stream) {
|
|
1218
|
+
if (options?.signal?.aborted) {
|
|
1219
|
+
throw stream._abortError();
|
|
1220
|
+
}
|
|
1221
|
+
if (numberLeft-- > 0) {
|
|
1222
|
+
yield val;
|
|
1223
|
+
}
|
|
1224
|
+
// Don't get another item from iterator in case we reached the end --
|
|
1225
|
+
// node's comment; the return() this early exit triggers on the source
|
|
1226
|
+
// iterator is what destroys a stream taken short of its EOF.
|
|
1227
|
+
if (numberLeft <= 0) {
|
|
1228
|
+
return;
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
})();
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
async function opSome(stream, fn, options) {
|
|
1235
|
+
for await (const unused of opFilter(stream, fn, options)) {
|
|
1236
|
+
return true;
|
|
1237
|
+
}
|
|
1238
|
+
return false;
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
async function opEvery(stream, fn, options) {
|
|
1242
|
+
validateFunctionArg(fn, 'fn');
|
|
1243
|
+
// https://en.wikipedia.org/wiki/De_Morgan%27s_laws -- node's comment.
|
|
1244
|
+
return !(await opSome(stream, async (...args) => !(await fn(...args)), options));
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
async function opFind(stream, fn, options) {
|
|
1248
|
+
for await (const result of opFilter(stream, fn, options)) {
|
|
1249
|
+
return result;
|
|
1250
|
+
}
|
|
1251
|
+
return undefined;
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
async function opReduce(stream, hasInitial, reducer, initialValue, options) {
|
|
1255
|
+
validateFunctionArg(reducer, 'reducer');
|
|
1256
|
+
validateOperatorOptions(options);
|
|
1257
|
+
if (options?.signal?.aborted) {
|
|
1258
|
+
const err = abortError(options.signal.reason);
|
|
1259
|
+
stream.once('error', () => {}); // the error is already propagated
|
|
1260
|
+
// node awaits its internal eos, which RESOLVES on the errored teardown;
|
|
1261
|
+
// the callback form wrapped here is that promise, since the public
|
|
1262
|
+
// callback-less `finished` refuses instead.
|
|
1263
|
+
await new Promise((resolve) => {
|
|
1264
|
+
// h2lean's destroy() returns nothing, unlike node's, so the stream is
|
|
1265
|
+
// handed to eos on its own line.
|
|
1266
|
+
stream.destroy(err);
|
|
1267
|
+
finished(stream, resolve);
|
|
1268
|
+
});
|
|
1269
|
+
throw err;
|
|
1270
|
+
}
|
|
1271
|
+
const ac = new AbortController();
|
|
1272
|
+
const signal = ac.signal;
|
|
1273
|
+
if (options?.signal) {
|
|
1274
|
+
options.signal.addEventListener('abort', () => ac.abort(), { once: true });
|
|
1275
|
+
}
|
|
1276
|
+
let gotAnyItemFromStream = false;
|
|
1277
|
+
try {
|
|
1278
|
+
for await (const value of stream) {
|
|
1279
|
+
gotAnyItemFromStream = true;
|
|
1280
|
+
if (options?.signal?.aborted) {
|
|
1281
|
+
throw abortError();
|
|
1282
|
+
}
|
|
1283
|
+
if (!hasInitial) {
|
|
1284
|
+
initialValue = value;
|
|
1285
|
+
hasInitial = true;
|
|
1286
|
+
} else {
|
|
1287
|
+
initialValue = await reducer(initialValue, value, { signal });
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
if (!gotAnyItemFromStream && !hasInitial) {
|
|
1291
|
+
// node's ReduceAwareErrMissingArgs: same code, same custom message.
|
|
1292
|
+
throw errorOf('ERR_MISSING_ARGS', 'Reduce of an empty stream requires an initial value');
|
|
1293
|
+
}
|
|
1294
|
+
} finally {
|
|
1295
|
+
ac.abort();
|
|
1296
|
+
}
|
|
1297
|
+
return initialValue;
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
async function opToArray(stream, options) {
|
|
1301
|
+
validateOperatorOptions(options);
|
|
1302
|
+
const result = [];
|
|
1303
|
+
for await (const val of stream) {
|
|
1304
|
+
if (options?.signal?.aborted) {
|
|
1305
|
+
throw abortError(options.signal.reason);
|
|
1306
|
+
}
|
|
1307
|
+
result.push(val);
|
|
1308
|
+
}
|
|
1309
|
+
return result;
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
// The error a stream reports when an RST_STREAM ends it, on either side. node's rule is
|
|
1313
|
+
// one line (internal/http2/core.js:2543): `if (err == null && code !== NGHTTP2_NO_ERROR &&
|
|
1314
|
+
// code !== NGHTTP2_CANCEL) err = new ERR_HTTP2_STREAM_ERROR(nameForErrorCode[code] || code)`.
|
|
1315
|
+
// So a graceful reset (0) and a client abort (8) are NOT errors -- measured on a live node
|
|
1316
|
+
// client and a live node server, both report only 'aborted'/'close' for those two codes --
|
|
1317
|
+
// and every other code names itself in the message. h2lean used to answer every code with
|
|
1318
|
+
// 'HTTP/2 stream error' on the client and with no error at all on the server.
|
|
1319
|
+
function streamErrorOf(code) {
|
|
1320
|
+
if (code === frames.NO_ERROR || code === frames.CANCEL) {
|
|
1321
|
+
return null;
|
|
1322
|
+
}
|
|
1323
|
+
return errorOf('ERR_HTTP2_STREAM_ERROR',
|
|
1324
|
+
`Stream closed with error code ${frames.ERROR_NAMES[code] || code}`);
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
|
|
1328
|
+
module.exports = { Http2Stream, fs, frames, hdr, EMPTY, WRITABLE_HWM, READABLE_HWM, emitNT, emitCloseNT, emitDrainNT, emitErrorCloseNT, emitErrorOnlyNT, emitEndNT, wantTrailersNT, finishNT, emitEndCloseNT, emitCloseDeliveredNT, autoCloseNT, noopClose, FILE_CHUNK, isFileHandle, receivedArgType, argTypeError, propertyValueError, fdOptions, prepareResponseHeadersObject, errorOf, specType, validateRstCode, kEmpty, kEof, ASYNC_ITERATOR_PROTO, noop, abortError, validateObjectArg, validateFunctionArg, validateSignalArg, validateOperatorOptions, toIntegerOrInfinity, createStreamIterator, opMap, opFilter, opFlatMap, opDrop, opTake, streamErrorOf };
|