-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathshare.ts
More file actions
756 lines (658 loc) · 21.8 KB
/
Copy pathshare.ts
File metadata and controls
756 lines (658 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
/**
* Share - Pull-model multi-consumer streaming
*
* Shares a single source among multiple consumers with explicit buffering.
* Complements broadcast (push model) with a pull model.
*/
import {
type Share as ShareInterface,
type SyncShare as SyncShareInterface,
type ShareOptions,
type ShareSyncOptions,
type Transform,
type SyncTransform,
type PullOptions,
type Streamable,
type SyncStreamable,
type Shareable,
type SyncShareable,
shareProtocol,
shareSyncProtocol,
} from './types.js';
import { isAsyncIterable, isSyncIterable } from './from.js';
import { pull as pullWithTransforms, pullSync as pullSyncWithTransforms } from './pull.js';
import { parsePullArgs } from './utils.js';
import { RingBuffer } from './ringbuffer.js';
// =============================================================================
// Consumer State
// =============================================================================
interface AsyncConsumerState {
/** Position in buffer (index of next chunk to read) */
cursor: number;
/** Resolve function for pending read */
resolve: ((value: IteratorResult<Uint8Array[]>) => void) | null;
/** Reject function for pending read */
reject: ((error: Error) => void) | null;
/** Whether consumer has been detached */
detached: boolean;
}
interface SyncConsumerState {
/** Position in buffer (index of next chunk to read) */
cursor: number;
/** Whether consumer has been detached */
detached: boolean;
}
// =============================================================================
// Async Share Implementation
// =============================================================================
class ShareImpl implements ShareInterface {
private buffer = new RingBuffer<Uint8Array[]>();
private bufferStart = 0;
private consumers: Set<AsyncConsumerState> = new Set();
private sourceIterator: AsyncIterator<Uint8Array[]> | null = null;
private sourceExhausted = false;
private sourceError: Error | null = null;
private cancelled = false;
private pulling = false;
private pullWaiters: (() => void)[] = [];
constructor(
private source: AsyncIterable<Uint8Array[]> | Iterable<Uint8Array[]>,
private options: Required<ShareOptions>
) {
// Initialize source iterator lazily
}
get consumerCount(): number {
return this.consumers.size;
}
get bufferSize(): number {
return this.buffer.length;
}
/**
* Create a new consumer that pulls from the shared source.
* Optionally apply transforms to the consumer's data.
*/
pull(...args: (Transform | PullOptions)[]): AsyncIterable<Uint8Array[]> {
const { transforms, options } = parsePullArgs<Transform, PullOptions>(args);
// Create raw consumer
const rawConsumer = this.createRawConsumer();
// If transforms provided, wrap with pull() pipeline
if (transforms.length > 0) {
if (options) {
return pullWithTransforms(rawConsumer, ...transforms, options);
}
return pullWithTransforms(rawConsumer, ...transforms);
}
return rawConsumer;
}
/**
* Create a raw consumer iterable (internal helper).
*/
private createRawConsumer(): AsyncIterable<Uint8Array[]> {
const state: AsyncConsumerState = {
cursor: this.bufferStart, // Start from beginning of available buffer
resolve: null,
reject: null,
detached: false,
};
this.consumers.add(state);
const self = this;
return {
[Symbol.asyncIterator]() {
return {
async next(): Promise<IteratorResult<Uint8Array[]>> {
// Check for error first (even if detached, propagate the error)
if (self.sourceError) {
state.detached = true;
self.consumers.delete(state);
throw self.sourceError;
}
if (state.detached) {
return { done: true, value: undefined };
}
if (self.cancelled) {
state.detached = true;
self.consumers.delete(state);
return { done: true, value: undefined };
}
// Check if data is available in buffer
const bufferIndex = state.cursor - self.bufferStart;
if (bufferIndex < self.buffer.length) {
const chunk = self.buffer.get(bufferIndex);
state.cursor++;
self.tryTrimBuffer();
return { done: false, value: chunk };
}
// Check if source is exhausted
if (self.sourceExhausted) {
state.detached = true;
self.consumers.delete(state);
return { done: true, value: undefined };
}
// Need to pull from source - but check buffer limit first
const canPull = await self.waitForBufferSpace(state);
if (!canPull) {
// Cancelled while waiting
state.detached = true;
self.consumers.delete(state);
if (self.sourceError) throw self.sourceError;
return { done: true, value: undefined };
}
// Pull from source
await self.pullFromSource();
// Check again
if (self.sourceError) {
state.detached = true;
self.consumers.delete(state);
throw self.sourceError;
}
const newBufferIndex = state.cursor - self.bufferStart;
if (newBufferIndex < self.buffer.length) {
const chunk = self.buffer.get(newBufferIndex);
state.cursor++;
self.tryTrimBuffer();
return { done: false, value: chunk };
}
if (self.sourceExhausted) {
state.detached = true;
self.consumers.delete(state);
return { done: true, value: undefined };
}
// Shouldn't get here
return { done: true, value: undefined };
},
async return(): Promise<IteratorResult<Uint8Array[]>> {
state.detached = true;
state.resolve = null;
state.reject = null;
self.consumers.delete(state);
self.tryTrimBuffer();
return { done: true, value: undefined };
},
async throw(_error?: Error): Promise<IteratorResult<Uint8Array[]>> {
state.detached = true;
state.resolve = null;
state.reject = null;
self.consumers.delete(state);
self.tryTrimBuffer();
return { done: true, value: undefined };
},
};
},
};
}
/**
* Cancel all consumers and close source.
*/
cancel(reason?: Error): void {
if (this.cancelled) return;
this.cancelled = true;
if (reason) {
this.sourceError = reason;
}
// Close source iterator if open
if (this.sourceIterator?.return) {
this.sourceIterator.return().catch(() => {});
}
// Notify all waiting consumers
for (const consumer of this.consumers) {
if (consumer.resolve) {
if (reason) {
consumer.reject?.(reason);
} else {
consumer.resolve({ done: true, value: undefined });
}
consumer.resolve = null;
consumer.reject = null;
}
consumer.detached = true;
}
this.consumers.clear();
// Wake up any pull waiters
for (const waiter of this.pullWaiters) {
waiter();
}
this.pullWaiters = [];
}
[Symbol.dispose](): void {
this.cancel();
}
// ==========================================================================
// Internal Methods
// ==========================================================================
/**
* Wait for buffer space based on backpressure policy.
* Returns false if cancelled while waiting, or throws if strict policy.
*/
private async waitForBufferSpace(_state: AsyncConsumerState): Promise<boolean> {
while (this.buffer.length >= this.options.highWaterMark) {
if (this.cancelled || this.sourceError || this.sourceExhausted) {
return !this.cancelled;
}
switch (this.options.backpressure) {
case 'strict':
// Reject - buffer limit exceeded
throw new RangeError(
`Share buffer limit of ${this.options.highWaterMark} exceeded`
);
case 'block':
// Wait for slow consumers to catch up
await new Promise<void>((resolve) => {
this.pullWaiters.push(resolve);
});
break;
case 'drop-oldest':
// Drop oldest and advance cursors
this.buffer.shift();
this.bufferStart++;
for (const consumer of this.consumers) {
if (consumer.cursor < this.bufferStart) {
consumer.cursor = this.bufferStart;
}
}
return true;
case 'drop-newest':
// Don't pull, just return what we have
return true;
}
}
return true;
}
/**
* Pull next chunk from source into buffer.
* Returns a promise that resolves when the pull completes (or immediately if already pulling).
*/
private pullFromSource(): Promise<void> {
if (this.sourceExhausted || this.cancelled) {
return Promise.resolve();
}
// If already pulling, wait for that pull to complete
if (this.pulling) {
return new Promise<void>((resolve) => {
this.pullWaiters.push(resolve);
});
}
this.pulling = true;
return (async () => {
try {
// Initialize iterator if needed
if (!this.sourceIterator) {
if (isAsyncIterable(this.source)) {
this.sourceIterator = this.source[Symbol.asyncIterator]();
} else if (isSyncIterable(this.source)) {
// Wrap sync iterator
const syncIterator = (this.source as Iterable<Uint8Array[]>)[Symbol.iterator]();
this.sourceIterator = {
async next() {
return syncIterator.next();
},
async return() {
return syncIterator.return?.() ?? { done: true, value: undefined };
},
};
} else {
throw new TypeError('Source must be iterable');
}
}
const result = await this.sourceIterator.next();
if (result.done) {
this.sourceExhausted = true;
} else {
this.buffer.push(result.value);
}
} catch (error) {
this.sourceError = error instanceof Error ? error : new Error(String(error));
this.sourceExhausted = true;
} finally {
this.pulling = false;
// Wake up waiters so they can check the buffer
for (const waiter of this.pullWaiters) {
waiter();
}
this.pullWaiters = [];
}
})();
}
/**
* Get the slowest consumer's cursor position.
*/
private getMinCursor(): number {
let min = Infinity;
for (const consumer of this.consumers) {
if (consumer.cursor < min) {
min = consumer.cursor;
}
}
return min === Infinity ? this.bufferStart + this.buffer.length : min;
}
/**
* Trim buffer from front if all consumers have advanced.
*/
private tryTrimBuffer(): void {
const minCursor = this.getMinCursor();
const trimCount = minCursor - this.bufferStart;
if (trimCount > 0) {
this.buffer.trimFront(trimCount);
this.bufferStart = minCursor;
// Wake up any waiting pullers
for (const waiter of this.pullWaiters) {
waiter();
}
this.pullWaiters = [];
}
}
}
// =============================================================================
// Sync Share Implementation
// =============================================================================
class SyncShareImpl implements SyncShareInterface {
private buffer = new RingBuffer<Uint8Array[]>();
private bufferStart = 0;
private consumers: Set<SyncConsumerState> = new Set();
private sourceIterator: Iterator<Uint8Array[]> | null = null;
private sourceExhausted = false;
private sourceError: Error | null = null;
private cancelled = false;
constructor(
private source: Iterable<Uint8Array[]>,
private options: Required<ShareSyncOptions>
) {}
get consumerCount(): number {
return this.consumers.size;
}
get bufferSize(): number {
return this.buffer.length;
}
/**
* Create a new consumer that pulls from the shared source.
* Optionally apply transforms to the consumer's data.
*/
pull(...transforms: SyncTransform[]): Iterable<Uint8Array[]> {
// Create raw consumer
const rawConsumer = this.createRawConsumer();
// If transforms provided, wrap with pullSync() pipeline
if (transforms.length > 0) {
return pullSyncWithTransforms(rawConsumer, ...transforms);
}
return rawConsumer;
}
/**
* Create a raw consumer iterable (internal helper).
*/
private createRawConsumer(): Iterable<Uint8Array[]> {
const state: SyncConsumerState = {
cursor: this.bufferStart,
detached: false,
};
this.consumers.add(state);
const self = this;
return {
[Symbol.iterator]() {
return {
next(): IteratorResult<Uint8Array[]> {
if (state.detached) {
return { done: true, value: undefined };
}
if (self.sourceError) {
state.detached = true;
self.consumers.delete(state);
throw self.sourceError;
}
if (self.cancelled) {
state.detached = true;
self.consumers.delete(state);
return { done: true, value: undefined };
}
// Check if data is available in buffer
const bufferIndex = state.cursor - self.bufferStart;
if (bufferIndex < self.buffer.length) {
const chunk = self.buffer.get(bufferIndex);
state.cursor++;
self.tryTrimBuffer();
return { done: false, value: chunk };
}
// Check if source is exhausted
if (self.sourceExhausted) {
state.detached = true;
self.consumers.delete(state);
return { done: true, value: undefined };
}
// Need to pull from source - check buffer limit
if (self.buffer.length >= self.options.highWaterMark) {
switch (self.options.backpressure) {
case 'strict':
throw new RangeError(
`Share buffer limit of ${self.options.highWaterMark} exceeded`
);
case 'block':
// In sync context, we can't block - throw an error
throw new RangeError(
`Share buffer limit of ${self.options.highWaterMark} exceeded (blocking not available in sync context)`
);
case 'drop-oldest':
self.buffer.shift();
self.bufferStart++;
for (const consumer of self.consumers) {
if (consumer.cursor < self.bufferStart) {
consumer.cursor = self.bufferStart;
}
}
break;
case 'drop-newest':
// Return done - can't pull more
state.detached = true;
self.consumers.delete(state);
return { done: true, value: undefined };
}
}
// Pull from source
self.pullFromSource();
// Check again
if (self.sourceError) {
state.detached = true;
self.consumers.delete(state);
throw self.sourceError;
}
const newBufferIndex = state.cursor - self.bufferStart;
if (newBufferIndex < self.buffer.length) {
const chunk = self.buffer.get(newBufferIndex);
state.cursor++;
self.tryTrimBuffer();
return { done: false, value: chunk };
}
if (self.sourceExhausted) {
state.detached = true;
self.consumers.delete(state);
return { done: true, value: undefined };
}
return { done: true, value: undefined };
},
return(): IteratorResult<Uint8Array[]> {
state.detached = true;
self.consumers.delete(state);
self.tryTrimBuffer();
return { done: true, value: undefined };
},
throw(_error?: Error): IteratorResult<Uint8Array[]> {
state.detached = true;
self.consumers.delete(state);
self.tryTrimBuffer();
return { done: true, value: undefined };
},
};
},
};
}
/**
* Cancel all consumers and close source.
*/
cancel(reason?: Error): void {
if (this.cancelled) return;
this.cancelled = true;
if (reason) {
this.sourceError = reason;
}
// Close source iterator if open
if (this.sourceIterator?.return) {
this.sourceIterator.return();
}
for (const consumer of this.consumers) {
consumer.detached = true;
}
this.consumers.clear();
}
[Symbol.dispose](): void {
this.cancel();
}
// ==========================================================================
// Internal Methods
// ==========================================================================
/**
* Pull next chunk from source into buffer.
*/
private pullFromSource(): void {
if (this.sourceExhausted || this.cancelled) return;
try {
// Initialize iterator if needed
if (!this.sourceIterator) {
this.sourceIterator = this.source[Symbol.iterator]();
}
const result = this.sourceIterator.next();
if (result.done) {
this.sourceExhausted = true;
} else {
this.buffer.push(result.value);
}
} catch (error) {
this.sourceError = error instanceof Error ? error : new Error(String(error));
this.sourceExhausted = true;
}
}
/**
* Get the slowest consumer's cursor position.
*/
private getMinCursor(): number {
let min = Infinity;
for (const consumer of this.consumers) {
if (consumer.cursor < min) {
min = consumer.cursor;
}
}
return min === Infinity ? this.bufferStart + this.buffer.length : min;
}
/**
* Trim buffer from front if all consumers have advanced.
*/
private tryTrimBuffer(): void {
const minCursor = this.getMinCursor();
const trimCount = minCursor - this.bufferStart;
if (trimCount > 0) {
this.buffer.trimFront(trimCount);
this.bufferStart = minCursor;
}
}
}
// =============================================================================
// Public API
// =============================================================================
/**
* Create a shared source for pull-model multi-consumer streaming.
*
* @param source - The source to share
* @param options - Buffer limit and backpressure policy
* @returns Share instance
*/
export function share(
source: AsyncIterable<Uint8Array[]> | Iterable<Uint8Array[]>,
options?: ShareOptions
): ShareInterface {
const opts: Required<ShareOptions> = {
highWaterMark: Math.max(1, options?.highWaterMark ?? 16),
backpressure: options?.backpressure ?? 'strict',
signal: options?.signal as AbortSignal,
};
const shareImpl = new ShareImpl(source, opts);
// Handle abort signal - cancel without error (clean shutdown)
if (opts.signal) {
if (opts.signal.aborted) {
shareImpl.cancel();
} else {
opts.signal.addEventListener('abort', () => {
shareImpl.cancel();
}, { once: true });
}
}
return shareImpl;
}
/**
* Create a sync shared source for pull-model multi-consumer streaming.
*
* @param source - The sync source to share
* @param options - Buffer limit and backpressure policy
* @returns SyncShare instance
*/
export function shareSync(
source: Iterable<Uint8Array[]>,
options?: ShareSyncOptions
): SyncShareInterface {
const opts: Required<ShareSyncOptions> = {
highWaterMark: Math.max(1, options?.highWaterMark ?? 16),
backpressure: options?.backpressure ?? 'strict',
};
return new SyncShareImpl(source, opts);
}
/**
* Check if value implements Shareable protocol.
*/
function isShareable(value: unknown): value is Shareable {
return (
value !== null &&
typeof value === 'object' &&
shareProtocol in value &&
typeof (value as Shareable)[shareProtocol] === 'function'
);
}
/**
* Check if value implements SyncShareable protocol.
*/
function isSyncShareable(value: unknown): value is SyncShareable {
return (
value !== null &&
typeof value === 'object' &&
shareSyncProtocol in value &&
typeof (value as SyncShareable)[shareSyncProtocol] === 'function'
);
}
/**
* Namespace for Share.from() static method.
*/
export const Share = {
/**
* Get or create a Share from a Shareable or Streamable.
*/
from(input: Shareable | Streamable, options?: ShareOptions): ShareInterface {
if (isShareable(input)) {
return input[shareProtocol](options);
}
if (isAsyncIterable(input) || isSyncIterable(input)) {
return share(input as AsyncIterable<Uint8Array[]> | Iterable<Uint8Array[]>, options);
}
throw new TypeError('Input must be Shareable or Streamable');
},
};
/**
* Namespace for SyncShare.fromSync() static method.
*/
export const SyncShare = {
/**
* Get or create a SyncShare from a SyncShareable or SyncStreamable.
*/
fromSync(input: SyncShareable | SyncStreamable, options?: ShareSyncOptions): SyncShareInterface {
if (isSyncShareable(input)) {
return input[shareSyncProtocol](options);
}
if (isSyncIterable(input)) {
return shareSync(input as Iterable<Uint8Array[]>, options);
}
throw new TypeError('Input must be SyncShareable or SyncStreamable');
},
};