forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpush.js
More file actions
760 lines (672 loc) · 21.8 KB
/
Copy pathpush.js
File metadata and controls
760 lines (672 loc) · 21.8 KB
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
'use strict';
// New Streams API - Push Stream Implementation
//
// Creates a bonded pair of writer and async iterable for push-based streaming
// with built-in backpressure.
const {
ArrayIsArray,
ArrayPrototypePush,
MathMax,
PromiseReject,
PromiseResolve,
PromiseWithResolvers,
SymbolAsyncDispose,
SymbolAsyncIterator,
SymbolDispose,
TypedArrayPrototypeGetByteLength,
} = primordials;
const {
codes: {
ERR_INVALID_ARG_TYPE,
ERR_INVALID_STATE,
},
} = require('internal/errors');
const { isError, lazyDOMException } = require('internal/util');
const {
validateAbortSignal,
validateInteger,
} = require('internal/validators');
const {
drainableProtocol,
kSyncWriteAccepted,
kSyncWriteAcceptedOnFalse,
} = require('internal/streams/iter/types');
const {
kPushDefaultHWM,
kResolvedPromise,
clampHWM,
onSignalAbort,
toUint8Array,
convertChunks,
parsePullArgs,
validateBackpressure,
} = require('internal/streams/iter/utils');
const {
pull: pullWithTransforms,
} = require('internal/streams/iter/pull');
const {
RingBuffer,
} = require('internal/streams/iter/ringbuffer');
// =============================================================================
// PushQueue - Internal Queue with Chunk-Based Backpressure
// =============================================================================
class PushQueue {
/** Buffered chunks (each slot is from one write/writev call) */
#slots = new RingBuffer();
/** Pending writes waiting for buffer space */
#pendingWrites = new RingBuffer();
/** Pending reads waiting for data */
#pendingReads = new RingBuffer();
/** Pending drains waiting for backpressure to clear */
#pendingDrains = [];
/** Writer state: 'open' | 'closing' | 'closed' | 'errored' */
#writerState = 'open';
/** Consumer state: 'active' | 'returned' | 'thrown' */
#consumerState = 'active';
/** Error that closed the stream */
#error = null;
/** Total bytes written */
#bytesWritten = 0;
/** Pending end promise (resolves when consumer drains past end sentinel) */
#pendingEnd = null;
/** Configuration */
#highWaterMark;
#backpressure;
#signal;
#abortHandler;
constructor(options = { __proto__: null }) {
const {
highWaterMark = kPushDefaultHWM,
backpressure = 'strict',
signal,
} = options;
validateInteger(highWaterMark, 'options.highWaterMark');
validateBackpressure(backpressure);
if (signal !== undefined) {
validateAbortSignal(signal, 'options.signal');
}
this.#highWaterMark = clampHWM(highWaterMark);
this.#backpressure = backpressure;
this.#signal = signal;
this.#abortHandler = undefined;
if (this.#signal) {
this.#abortHandler = () => {
this.fail(isError(this.#signal.reason) ?
this.#signal.reason :
lazyDOMException('Aborted', 'AbortError'));
};
onSignalAbort(this.#signal, this.#abortHandler);
}
}
// ===========================================================================
// Writer Methods
// ===========================================================================
/**
* Get slots available before hitting highWaterMark.
* Returns null if writer is closed/errored or consumer has terminated.
* @returns {number | null}
*/
get desiredSize() {
if (this.#writerState !== 'open' || this.#consumerState !== 'active') {
return null;
}
return MathMax(0, this.#highWaterMark - this.#slots.length);
}
/**
* Check if a sync write would be accepted.
* @returns {boolean}
*/
canWriteSync() {
if (this.#writerState !== 'open') return false;
if (this.#consumerState !== 'active') return false;
if ((this.#backpressure === 'strict' ||
this.#backpressure === 'block') &&
this.#slots.length >= this.#highWaterMark) {
return false;
}
return true;
}
/**
* Write chunks synchronously if possible.
* Returns true if write completed, false if buffer is full.
* @returns {boolean}
*/
writeSync(chunks) {
if (this.#writerState !== 'open') return false;
if (this.#consumerState !== 'active') return false;
if (this.#slots.length >= this.#highWaterMark) {
switch (this.#backpressure) {
case 'strict':
return false;
case 'block':
return false;
case 'drop-oldest':
if (this.#slots.length > 0) {
this.#slots.shift();
}
break;
case 'drop-newest':
// Discard this write, but return true
for (let i = 0; i < chunks.length; i++) {
this.#bytesWritten += TypedArrayPrototypeGetByteLength(chunks[i]);
}
return true;
}
}
this.#slots.push(chunks);
for (let i = 0; i < chunks.length; i++) {
this.#bytesWritten += TypedArrayPrototypeGetByteLength(chunks[i]);
}
this.#resolvePendingReads();
return true;
}
/**
* Write chunks asynchronously.
* If signal is provided, a write blocked on backpressure will reject
* immediately when the signal fires. The cancelled write is removed from
* pendingWrites so it does not occupy a slot. The queue itself is NOT put
* into an error state - this is per-operation cancellation, not terminal
* failure.
* @returns {Promise<void>}
*/
async writeAsync(chunks, signal) {
// Check writer state before signal (spec order: state, then signal)
if (this.#writerState === 'closed') {
throw new ERR_INVALID_STATE.TypeError('Writer is closed');
}
if (this.#writerState === 'closing') {
throw new ERR_INVALID_STATE.TypeError('Writer is closing');
}
if (this.#writerState === 'errored') {
throw this.#error;
}
if (this.#consumerState !== 'active') {
throw this.#consumerState === 'thrown' && this.#error ?
this.#error :
new ERR_INVALID_STATE.TypeError('Stream closed by consumer');
}
// Check for pre-aborted signal (after state checks per spec)
signal?.throwIfAborted();
// Try sync first
if (this.writeSync(chunks)) {
return;
}
// Buffer is full
switch (this.#backpressure) {
case 'strict':
if (this.#pendingWrites.length >= this.#highWaterMark) {
throw new ERR_INVALID_STATE.RangeError(
'Backpressure violation: too many pending writes. ' +
'Await each write() call to respect backpressure.');
}
return this.#createPendingWrite(chunks, signal);
case 'block':
return this.#createPendingWrite(chunks, signal);
default:
throw new ERR_INVALID_STATE(
'Unexpected: writeSync should have handled non-strict policy');
}
}
/**
* Create a pending write promise, optionally racing against a signal.
* If the signal fires, the entry is removed from pendingWrites and the
* promise rejects. Signal listeners are cleaned up on normal resolution.
* @returns {Promise<void>}
*/
#createPendingWrite(chunks, signal) {
const { promise, resolve, reject } = PromiseWithResolvers();
const entry = { __proto__: null, chunks, resolve, reject };
this.#pendingWrites.push(entry);
if (signal) {
const onAbort = () => {
// Remove from queue so it doesn't occupy a slot
const idx = this.#pendingWrites.indexOf(entry);
if (idx !== -1) this.#pendingWrites.removeAt(idx);
reject(signal.reason ?? lazyDOMException('Aborted', 'AbortError'));
};
// Wrap resolve/reject to clean up signal listener
entry.resolve = function() {
signal.removeEventListener('abort', onAbort);
resolve();
};
entry.reject = function(reason) {
signal.removeEventListener('abort', onAbort);
reject(reason);
};
signal.addEventListener('abort', onAbort, { __proto__: null, once: true });
}
return promise;
}
/**
* Signal end of stream. Returns total bytes written.
* @returns {number}
*/
end() {
if (this.#writerState === 'errored') {
return -2; // Signal to reject with stored error
}
if (this.#writerState === 'closing') {
return -3; // Signal to PushWriter: wait for drain to complete
}
if (this.#writerState === 'closed') {
return this.#bytesWritten; // Idempotent
}
this.#cleanup();
this.#rejectPendingWrites(
new ERR_INVALID_STATE.TypeError('Writer closed'));
this.#resolvePendingDrains(false);
// If buffer is empty, close immediately
if (this.#slots.length === 0) {
this.#writerState = 'closed';
this.#resolvePendingReads();
return this.#bytesWritten;
}
// Buffer has data: transition to closing, defer completion until drained
this.#writerState = 'closing';
return -3; // Signal to PushWriter: create deferred end promise
}
/**
* Called by the read path when the consumer has drained all data while
* the writer is in the 'closing' state. Transitions to 'closed' and
* resolves the pending end promise.
*/
endDrained() {
if (this.#writerState !== 'closing') return;
this.#writerState = 'closed';
if (this.#pendingEnd) {
this.#pendingEnd.resolve(this.#bytesWritten);
this.#pendingEnd = null;
}
}
/**
* Put queue into terminal error state.
* No-op if errored or closed (fully drained).
* If closing (draining), short-circuits the drain.
*/
fail(reason) {
if (this.#writerState === 'errored' || this.#writerState === 'closed') {
return;
}
const wasClosing = this.#writerState === 'closing';
this.#writerState = 'errored';
this.#error = reason ?? new ERR_INVALID_STATE('Failed');
this.#cleanup();
this.#rejectPendingReads(this.#error);
this.#rejectPendingDrains(this.#error);
if (wasClosing) {
// Short-circuit the graceful drain: reject the pending end promise
if (this.#pendingEnd) {
this.#pendingEnd.reject(this.#error);
this.#pendingEnd = null;
}
} else {
this.#rejectPendingWrites(this.#error);
}
}
get totalBytesWritten() {
return this.#bytesWritten;
}
get error() {
return this.#error;
}
get backpressurePolicy() {
return this.#backpressure;
}
get writerState() {
return this.#writerState;
}
get pendingEndPromise() {
return this.#pendingEnd?.promise ?? null;
}
setPendingEnd(pending) {
this.#pendingEnd = pending;
}
/**
* Force-enqueue chunks into the slots buffer, bypassing capacity checks.
* Used by PushWriter.writeSync() for 'block' policy where the data is
* accepted but false is returned as a backpressure signal.
*/
forceEnqueue(chunks) {
this.#slots.push(chunks);
for (let i = 0; i < chunks.length; i++) {
this.#bytesWritten += TypedArrayPrototypeGetByteLength(chunks[i]);
}
this.#resolvePendingReads();
}
/**
* Wait for backpressure to clear (desiredSize > 0).
* @returns {Promise<void>}
*/
waitForDrain() {
const { promise, resolve, reject } = PromiseWithResolvers();
ArrayPrototypePush(this.#pendingDrains, { __proto__: null, resolve, reject });
return promise;
}
// ===========================================================================
// Consumer Methods
// ===========================================================================
async read() {
// If there's data in the buffer, return it immediately
if (this.#slots.length > 0) {
const result = this.#drain();
this.#resolvePendingWrites();
// After draining, check if writer was closing and buffer is now empty
if (this.#writerState === 'closing' && this.#slots.length === 0) {
this.endDrained();
}
return { __proto__: null, value: result, done: false };
}
// Buffer empty and writer closing = drain complete
if (this.#writerState === 'closing') {
this.endDrained();
return { __proto__: null, value: undefined, done: true };
}
if (this.#writerState === 'closed') {
return { __proto__: null, value: undefined, done: true };
}
if (this.#writerState === 'errored' && this.#error) {
throw this.#error;
}
const { promise, resolve, reject } = PromiseWithResolvers();
this.#pendingReads.push({ __proto__: null, resolve, reject });
return promise;
}
consumerReturn() {
if (this.#consumerState !== 'active') return;
this.#consumerState = 'returned';
this.#cleanup();
this.#resolvePendingReads();
this.#rejectPendingWrites(
new ERR_INVALID_STATE.TypeError('Stream closed by consumer'));
// If closing, reject the pending end promise
if (this.#writerState === 'closing' && this.#pendingEnd) {
this.#pendingEnd.reject(
new ERR_INVALID_STATE.TypeError('Stream closed by consumer'));
this.#pendingEnd = null;
}
// Resolve pending drains with false - no more data will be consumed
this.#resolvePendingDrains(false);
}
consumerThrow(error) {
if (this.#consumerState !== 'active') return;
this.#consumerState = 'thrown';
this.#error = error;
this.#cleanup();
this.#rejectPendingReads(error);
this.#rejectPendingWrites(error);
if (this.#writerState === 'closing' && this.#pendingEnd) {
this.#pendingEnd.reject(error);
this.#pendingEnd = null;
}
// Reject pending drains - the consumer errored
this.#rejectPendingDrains(error);
}
// ===========================================================================
// Private Methods
// ===========================================================================
#drain() {
if (this.#slots.length === 1) {
return this.#slots.shift();
}
const result = [];
for (let i = 0; i < this.#slots.length; i++) {
const slot = this.#slots.get(i);
for (let j = 0; j < slot.length; j++) {
ArrayPrototypePush(result, slot[j]);
}
}
this.#slots.clear();
return result;
}
#resolvePendingReads() {
while (this.#pendingReads.length > 0) {
if (this.#slots.length > 0) {
const pending = this.#pendingReads.shift();
const result = this.#drain();
this.#resolvePendingWrites();
pending.resolve({ __proto__: null, value: result, done: false });
} else if (this.#writerState === 'closing' && this.#slots.length === 0) {
this.endDrained();
const pending = this.#pendingReads.shift();
pending.resolve({ __proto__: null, value: undefined, done: true });
} else if (this.#writerState === 'closed') {
const pending = this.#pendingReads.shift();
pending.resolve({ __proto__: null, value: undefined, done: true });
} else if (this.#writerState === 'errored' && this.#error) {
const pending = this.#pendingReads.shift();
pending.reject(this.#error);
} else if (this.#consumerState === 'returned') {
const pending = this.#pendingReads.shift();
pending.resolve({ __proto__: null, value: undefined, done: true });
} else {
break;
}
}
}
#resolvePendingWrites() {
while (this.#pendingWrites.length > 0 &&
this.#slots.length < this.#highWaterMark) {
const pending = this.#pendingWrites.shift();
this.#slots.push(pending.chunks);
for (let i = 0; i < pending.chunks.length; i++) {
this.#bytesWritten += TypedArrayPrototypeGetByteLength(pending.chunks[i]);
}
pending.resolve();
}
if (this.#slots.length < this.#highWaterMark) {
this.#resolvePendingDrains(true);
}
}
#resolvePendingDrains(canWrite) {
const drains = this.#pendingDrains;
this.#pendingDrains = [];
for (let i = 0; i < drains.length; i++) {
drains[i].resolve(canWrite);
}
}
#rejectPendingDrains(error) {
const drains = this.#pendingDrains;
this.#pendingDrains = [];
for (let i = 0; i < drains.length; i++) {
drains[i].reject(error);
}
}
#rejectPendingReads(error) {
while (this.#pendingReads.length > 0) {
this.#pendingReads.shift().reject(error);
}
}
#rejectPendingWrites(error) {
while (this.#pendingWrites.length > 0) {
this.#pendingWrites.shift().reject(error);
}
}
#cleanup() {
if (this.#signal && this.#abortHandler) {
this.#signal.removeEventListener('abort', this.#abortHandler);
this.#abortHandler = undefined;
}
}
}
// =============================================================================
// PushWriter Implementation
// =============================================================================
class PushWriter {
#queue;
#syncWriteAccepted = false;
constructor(queue) {
this.#queue = queue;
}
[kSyncWriteAccepted]() {
return this.#syncWriteAccepted;
}
[drainableProtocol]() {
const desired = this.desiredSize;
if (desired === null) return null;
if (desired > 0) return PromiseResolve(true);
return this.#queue.waitForDrain();
}
get desiredSize() {
return this.#queue.desiredSize;
}
get [kSyncWriteAcceptedOnFalse]() {
return this.#queue.backpressurePolicy === 'block';
}
write(chunk, options) {
if (!options?.signal && this.#queue.canWriteSync()) {
const bytes = toUint8Array(chunk);
this.#queue.writeSync([bytes]);
return kResolvedPromise;
}
const bytes = toUint8Array(chunk);
return this.#queue.writeAsync([bytes], options?.signal);
}
writev(chunks, options) {
if (!ArrayIsArray(chunks)) {
throw new ERR_INVALID_ARG_TYPE('chunks', 'Array', chunks);
}
if (!options?.signal && this.#queue.canWriteSync()) {
const bytes = convertChunks(chunks);
this.#queue.writeSync(bytes);
return kResolvedPromise;
}
const bytes = convertChunks(chunks);
return this.#queue.writeAsync(bytes, options?.signal);
}
writeSync(chunk) {
this.#syncWriteAccepted = false;
const bytes = toUint8Array(chunk);
const result = this.#queue.writeSync([bytes]);
if (!result && this.#queue.backpressurePolicy === 'block' &&
this.#queue.desiredSize === 0) {
// Block policy: force-enqueue and return false as backpressure signal.
// Data IS accepted; false tells caller to slow down.
this.#queue.forceEnqueue([bytes]);
this.#syncWriteAccepted = true;
return false;
}
this.#syncWriteAccepted = result;
return result;
}
writevSync(chunks) {
this.#syncWriteAccepted = false;
if (!ArrayIsArray(chunks)) {
throw new ERR_INVALID_ARG_TYPE('chunks', 'Array', chunks);
}
const bytes = convertChunks(chunks);
const result = this.#queue.writeSync(bytes);
if (!result && this.#queue.backpressurePolicy === 'block' &&
this.#queue.desiredSize === 0) {
this.#queue.forceEnqueue(bytes);
this.#syncWriteAccepted = true;
return false;
}
this.#syncWriteAccepted = result;
return result;
}
end(options) {
const result = this.#queue.end();
if (result === -2) {
// Errored: reject with stored error
return PromiseReject(this.#queue.error);
}
if (result === -3) {
// Closing: buffer has data, create deferred promise that resolves
// when consumer drains past the end sentinel
const pendingEndPromise = this.#queue.pendingEndPromise;
if (pendingEndPromise !== null) {
return pendingEndPromise;
}
const { promise, resolve, reject } = PromiseWithResolvers();
this.#queue.setPendingEnd({ __proto__: null, promise, resolve, reject });
return promise;
}
// >= 0: byte count (immediate close or idempotent)
return PromiseResolve(result);
}
endSync() {
const result = this.#queue.end();
if (result === -2) return -1; // Errored
if (result === -3) return -1; // Buffer not empty, can't wait
return result;
}
fail(reason) {
this.#queue.fail(reason);
}
[SymbolAsyncDispose]() {
const state = this.#queue.writerState;
if (state === 'closing') {
// Wait for graceful drain
return this.#queue.pendingEndPromise ?? PromiseResolve();
}
if (state === 'open') {
this.fail();
}
return PromiseResolve();
}
[SymbolDispose]() {
this.fail();
}
}
// =============================================================================
// Readable Implementation
// =============================================================================
function createReadable(queue) {
return {
__proto__: null,
[SymbolAsyncIterator]() {
return {
__proto__: null,
async next() {
return queue.read();
},
async return() {
queue.consumerReturn();
return { __proto__: null, value: undefined, done: true };
},
async throw(error) {
queue.consumerThrow(error);
return { __proto__: null, value: undefined, done: true };
},
};
},
};
}
// =============================================================================
// Stream.push() Factory
// =============================================================================
function parseArgs(args) {
const result = parsePullArgs(args);
// PushQueue constructor requires a non-undefined options object.
if (result.options === undefined) {
result.options = { __proto__: null };
}
return result;
}
/**
* Create a push stream with optional transforms.
* @param {...(Function|object)} args - Transforms, then options (optional)
* @returns {{ writer: Writer, readable: AsyncIterable<Uint8Array[]> }}
*/
function push(...args) {
const { transforms, options } = parseArgs(args);
const queue = new PushQueue(options);
const writer = new PushWriter(queue);
const rawReadable = createReadable(queue);
// Apply transforms lazily if provided
let readable;
if (transforms.length > 0) {
if (options.signal) {
readable = pullWithTransforms(
rawReadable, ...transforms, { __proto__: null, signal: options.signal });
} else {
readable = pullWithTransforms(rawReadable, ...transforms);
}
} else {
readable = rawReadable;
}
return { __proto__: null, writer, readable };
}
module.exports = {
push,
};