-
Notifications
You must be signed in to change notification settings - Fork 29
/
pipe.ts
366 lines (329 loc) · 11.8 KB
/
pipe.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import type { ReadableStreamState } from '../readable-stream';
import { IsReadableStream } from '../readable-stream';
import type { WritableStreamState } from '../writable-stream';
import { IsWritableStream, WritableStreamCloseQueuedOrInFlight } from '../writable-stream';
import type { ReadableStreamLike, WritableStreamLike } from '../helpers/stream-like';
import { IsReadableStreamLike, IsWritableStreamLike } from '../helpers/stream-like';
import assert from '../../stub/assert';
import {
newPromise,
PerformPromiseThen,
promiseRejectedWith,
promiseResolvedWith,
queueMicrotask,
setPromiseIsHandledToTrue,
transformPromiseWith,
uponFulfillment,
uponPromise
} from '../helpers/webidl';
import type { AbortSignal } from '../abort-signal';
import { isAbortSignal } from '../abort-signal';
import { DOMException } from '../../stub/dom-exception';
export function ReadableStreamPipeTo<T>(source: ReadableStreamLike<T>,
dest: WritableStreamLike<T>,
preventClose: boolean,
preventAbort: boolean,
preventCancel: boolean,
signal: AbortSignal | undefined): Promise<undefined> {
assert(IsReadableStreamLike(source));
assert(IsWritableStreamLike(dest));
assert(typeof preventClose === 'boolean');
assert(typeof preventAbort === 'boolean');
assert(typeof preventCancel === 'boolean');
assert(signal === undefined || isAbortSignal(signal));
assert(!source.locked);
assert(!dest.locked);
const reader = source.getReader();
const writer = dest.getWriter();
if (IsReadableStream(source)) {
source._disturbed = true;
}
let shuttingDown = false;
let released = false;
let sourceState: ReadableStreamState = 'readable';
let sourceStoredError: any;
let destState: WritableStreamState = 'writable';
let destStoredError: any;
let destCloseRequested = false;
// This is used to track when we initially start the pipe loop, and have initialized sourceState and destState.
let started = false;
let resolveStart: () => void;
const startPromise: Promise<void> = newPromise(resolve => {
resolveStart = resolve;
});
// This is used to keep track of the spec's requirement that we wait for ongoing reads and writes during shutdown.
let currentRead: Promise<unknown> | undefined;
let currentWrite: Promise<unknown> | undefined;
return newPromise((resolve, reject) => {
let abortAlgorithm: () => void;
if (signal !== undefined) {
abortAlgorithm = () => {
const error = new DOMException('Aborted', 'AbortError');
const actions: Array<() => Promise<void>> = [];
if (!preventAbort) {
actions.push(() => {
if (destState === 'writable') {
return writer.abort(error);
}
return promiseResolvedWith(undefined);
});
}
if (!preventCancel) {
actions.push(() => {
if (sourceState === 'readable') {
return reader.cancel(error);
}
return promiseResolvedWith(undefined);
});
}
shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);
};
if (signal.aborted) {
abortAlgorithm();
} else {
signal.addEventListener('abort', abortAlgorithm);
}
}
// Using reader and writer, read all chunks from this and write them to dest
// - Backpressure must be enforced
// - Shutdown must stop all activity
function pipeLoop() {
if (shuttingDown) {
return;
}
const loop = newPromise<void>((resolveLoop, rejectLoop) => {
function next(done: boolean) {
if (done) {
resolveLoop();
} else {
// Use `PerformPromiseThen` instead of `uponPromise` to avoid
// adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers
PerformPromiseThen(pipeStep(), next, rejectLoop);
}
}
next(false);
});
setPromiseIsHandledToTrue(loop);
}
function pipeStep(): Promise<boolean> {
if (shuttingDown) {
return promiseResolvedWith(true);
}
return PerformPromiseThen(writer.ready, () => {
const read = PerformPromiseThen(reader.read(), result => {
if (result.done) {
return true;
}
currentWrite = writer.write(result.value);
setPromiseIsHandledToTrue(currentWrite);
return false;
});
currentRead = read;
return read;
});
}
function handleSourceClose(): null {
// Closing must be propagated forward
assert(!released);
assert(!IsReadableStream(source) || source._state === 'closed');
sourceState = 'closed';
if (!preventClose) {
shutdownWithAction(() => {
if (IsWritableStream(dest)) {
destCloseRequested = WritableStreamCloseQueuedOrInFlight(dest);
destState = dest._state;
}
if (destCloseRequested || destState === 'closed') {
return promiseResolvedWith(undefined);
}
if (destState === 'errored') {
return promiseRejectedWith(destStoredError);
}
assert(destState === 'writable' || destState === 'erroring');
destCloseRequested = true;
return writer.close();
}, false, undefined, true);
} else {
shutdown();
}
return null;
}
function handleSourceError(storedError: any): null {
if (released) {
return null;
}
// Errors must be propagated forward
assert(!IsReadableStream(source) || source._state === 'errored');
sourceState = 'errored';
sourceStoredError = storedError;
if (!preventAbort) {
shutdownWithAction(() => writer.abort(storedError), true, storedError);
} else {
shutdown(true, storedError);
}
return null;
}
function handleDestClose(): null {
assert(!released);
assert(!IsWritableStream(dest) || dest._state === 'closed');
destState = 'closed';
return null;
}
function handleDestError(storedError: any): null {
if (released) {
return null;
}
// Errors must be propagated backward
assert(!IsWritableStream(dest) || dest._state === 'errored');
destState = 'errored';
destStoredError = storedError;
if (!preventCancel) {
shutdownWithAction(() => reader.cancel(storedError), true, storedError);
} else {
shutdown(true, storedError);
}
return null;
}
// If we're using our own stream implementations, synchronously inspect their state.
if (IsReadableStream(source)) {
sourceState = source._state;
sourceStoredError = source._storedError;
}
if (IsWritableStream(dest)) {
destState = dest._state;
destStoredError = dest._storedError;
destCloseRequested = WritableStreamCloseQueuedOrInFlight(dest);
}
// If we synchronously inspected the stream's state, then we can shutdown immediately.
if (IsReadableStream(source) && IsWritableStream(dest)) {
started = true;
resolveStart();
}
if (sourceState === 'errored') {
// Errors must be propagated forward
handleSourceError(sourceStoredError);
} else if (destState === 'errored') {
// Errors must be propagated backward
handleDestError(destStoredError);
} else if (sourceState === 'closed') {
// Closing must be propagated forward
handleSourceClose();
} else if (destCloseRequested || destState === 'closed') {
// Closing must be propagated backward
const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');
if (!preventCancel) {
shutdownWithAction(() => reader.cancel(destClosed), true, destClosed);
} else {
shutdown(true, destClosed);
}
}
// Detect asynchronous state transitions.
if (!shuttingDown) {
uponPromise(reader.closed, handleSourceClose, handleSourceError);
uponPromise(writer.closed, handleDestClose, handleDestError);
}
// If we synchronously inspected the stream's state, then we can start the loop immediately.
// Otherwise, we give `reader.closed` or `writer.closed` a little bit of time to settle.
if (started) {
pipeLoop();
} else {
queueMicrotask(() => {
started = true;
resolveStart();
pipeLoop();
});
}
function waitForWritesToFinish(): Promise<void> {
let oldCurrentWrite: Promise<unknown> | undefined;
return promiseResolvedWith(check());
function check(): undefined | Promise<undefined> {
// Another write may have started while we were waiting on this currentWrite,
// so we have to be sure to wait for that too.
if (oldCurrentWrite !== currentWrite) {
oldCurrentWrite = currentWrite;
return transformPromiseWith(currentWrite!, check, check);
}
return undefined;
}
}
function waitForReadsAndWritesToFinish(): Promise<void> {
let oldCurrentRead: Promise<unknown> | undefined;
let oldCurrentWrite: Promise<unknown> | undefined;
return promiseResolvedWith(check());
function check(): undefined | Promise<undefined> {
// Another read or write may have started while we were waiting on this currentRead or currentWrite,
// so we have to be sure to wait for that too.
if (oldCurrentRead !== currentRead) {
oldCurrentRead = currentRead;
return transformPromiseWith(currentRead!, check, check);
}
if (oldCurrentWrite !== currentWrite) {
oldCurrentWrite = currentWrite;
return transformPromiseWith(currentWrite!, check, check);
}
return undefined;
}
}
function shutdownWithAction(action: (() => Promise<unknown>) | undefined,
isError?: boolean,
error?: any,
waitForReads?: boolean) {
if (shuttingDown) {
return;
}
shuttingDown = true;
if (!started) {
uponFulfillment(startPromise, onStart);
} else {
onStart();
}
function onStart(): null {
if (waitForReads && (currentRead !== undefined || currentWrite !== undefined)) {
uponFulfillment(waitForReadsAndWritesToFinish(), doTheRest);
} else if (currentWrite !== undefined) {
uponFulfillment(waitForWritesToFinish(), doTheRest);
} else {
doTheRest();
}
return null;
}
function doTheRest(): null {
if (action) {
uponPromise(
action(),
() => waitForReadsAndWritesThenFinalize(isError, error),
newError => waitForReadsAndWritesThenFinalize(true, newError)
);
} else {
waitForReadsAndWritesThenFinalize(isError, error);
}
return null;
}
}
function shutdown(isError?: boolean, error?: any) {
shutdownWithAction(undefined, isError, error);
}
function waitForReadsAndWritesThenFinalize(isError?: boolean, error?: any): null {
if (currentRead !== undefined || currentWrite !== undefined) {
uponFulfillment(waitForReadsAndWritesToFinish(), () => finalize(isError, error));
} else {
finalize(isError, error);
}
return null;
}
function finalize(isError?: boolean, error?: any): null {
released = true;
writer.releaseLock();
reader.releaseLock();
if (signal !== undefined) {
signal.removeEventListener('abort', abortAlgorithm);
}
if (isError) {
reject(error);
} else {
resolve(undefined);
}
return null;
}
});
}