Skip to content

Commit 28c8740

Browse files
jasnelladuh95
authored andcommitted
stream: read stream/iter share() sync sources at once
A share() consumer that needed the next batch of the source always waited for an asynchronous read of it, also when the source was a sync iterable that from() can read synchronously, and every such read added a reaction to clear the consumer's pending read when it settled. When there is room in the buffer and no read of the source is pending, read a batch of a sync source synchronously, with from()'s kNextSyncBatch, as pipeTo() does: the consumer then gets it at once. Values that from() normalizes asynchronously are still read asynchronously. A read waiting for the source now clears itself from the consumer's pending read when it settles, without a reaction of its own; only next() calls queued behind another still add one. With two consumers of a share of a sync source, one 16-byte chunk per batch, reading is about 2.4 times faster, on par with tee() of a ReadableStream, with 60% less allocated per chunk. For an async source it is about 7% faster. Assisted-by: OpenCode Signed-off-by: James M Snell <jasnell@gmail.com> PR-URL: #66504 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
1 parent 017564e commit 28c8740

2 files changed

Lines changed: 161 additions & 33 deletions

File tree

‎lib/internal/streams/iter/share.js‎

Lines changed: 109 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ const {
3030
fromSync,
3131
isAsyncIterable,
3232
isSyncIterable,
33+
kNextSyncBatch,
3334
} = require('internal/streams/iter/from');
3435

3536
const {
@@ -78,6 +79,15 @@ const kNoShareError = Symbol('kNoShareError');
7879
const kPull = Symbol('kPull');
7980
const kSetFactorySignal = Symbol('kSetFactorySignal');
8081

82+
// Clear `pending` from the pendingNext of the consumer `state` when it
83+
// settles, unless a next() has been queued behind it.
84+
function clearPendingNext(state, pending) {
85+
const onSettled = () => {
86+
if (state.pendingNext === pending) state.pendingNext = null;
87+
};
88+
PromisePrototypeThen(pending, onSettled, onSettled);
89+
}
90+
8191
class ShareImpl {
8292
#source;
8393
#options;
@@ -160,6 +170,8 @@ class ShareImpl {
160170
waiting: false,
161171
// Created by #readAfterPull() on first use.
162172
afterPull: undefined,
173+
// The read #readAfterPull() returned, while it is pending.
174+
waitingRead: null,
163175
// The last pending next() of the consumer, if it is waiting for the
164176
// source: the next one waits for it, as next() calls of an async
165177
// generator do.
@@ -186,18 +198,19 @@ class ShareImpl {
186198
let result;
187199
try {
188200
result = self.#tryRead(state);
201+
// A sync source can be read at once, when there is room.
202+
while (result === kPull &&
203+
self.#bufferedBytes < self.#options.budget &&
204+
self.#pullSync()) {
205+
result = self.#tryRead(state);
206+
}
189207
} catch (error) {
190208
return PromiseReject(error);
191209
}
192210
if (result !== kPull) return PromiseResolve(result);
193211
return self.#readAsync(state);
194212
};
195-
const clearPending = (pending) => {
196-
const onSettled = () => {
197-
if (state.pendingNext === pending) state.pendingNext = null;
198-
};
199-
PromisePrototypeThen(pending, onSettled, onSettled);
200-
};
213+
const clearPending = (pending) => clearPendingNext(state, pending);
201214

202215
return ObjectSetPrototypeOf({
203216
next() {
@@ -212,7 +225,9 @@ class ShareImpl {
212225
}
213226
state.pendingNext = next;
214227
markPromiseAsHandled(next);
215-
clearPending(next);
228+
// A read waiting for a pull of the source clears pendingNext
229+
// itself (see #readAfterPull()).
230+
if (next !== state.waitingRead) clearPending(next);
216231
return next;
217232
},
218233

@@ -344,7 +359,9 @@ class ShareImpl {
344359
#readAsync(state) {
345360
state.waiting = true;
346361
if (this.#bufferedBytes < this.#options.budget) {
347-
return this.#readAfterPull(state);
362+
const read = this.#readAfterPull(state);
363+
state.waitingRead = read;
364+
return read;
348365
}
349366
return this.#readAsyncLoop(state);
350367
}
@@ -386,14 +403,69 @@ class ShareImpl {
386403

387404
// The common case of #readAsyncLoop(), without an async function: there
388405
// is room in the buffer, so read the source and then the consumer's batch.
406+
// When the read settles with the result afterPull() returns, it is no
407+
// longer pending: clear it from pendingNext, unless a next() has been
408+
// queued behind it, without a reaction of its own.
389409
#readAfterPull(state) {
390410
state.afterPull ??= () => {
391-
const result = this.#tryRead(state);
392-
return result !== kPull ? result : this.#readAsyncLoop(state);
411+
let result;
412+
try {
413+
result = this.#tryRead(state);
414+
} catch (error) {
415+
this.#clearWaitingRead(state);
416+
throw error;
417+
}
418+
if (result === kPull) {
419+
// Still pending: clear it when it settles.
420+
const read = state.waitingRead;
421+
state.waitingRead = null;
422+
if (state.pendingNext === read) clearPendingNext(state, read);
423+
return this.#readAsyncLoop(state);
424+
}
425+
this.#clearWaitingRead(state);
426+
return result;
393427
};
394428
return PromisePrototypeThen(this.#pullFromSource(false), state.afterPull);
395429
}
396430

431+
#clearWaitingRead(state) {
432+
if (state.pendingNext === state.waitingRead) state.pendingNext = null;
433+
state.waitingRead = null;
434+
}
435+
436+
// Read a batch of the source synchronously, if it can be read so (a sync
437+
// source normalized by from()) and no read of it is pending. Returns
438+
// whether the source was read: a batch buffered, or its end or error
439+
// recorded.
440+
#pullSync() {
441+
if (this.#pulling || this.#sourceExhausted || this.#cancelled) {
442+
return false;
443+
}
444+
try {
445+
const iterator = this.#getSourceIterator();
446+
const nextSyncBatch = iterator[kNextSyncBatch];
447+
if (nextSyncBatch === undefined) return false;
448+
const batch = FunctionPrototypeCall(nextSyncBatch, iterator);
449+
if (batch === undefined) return false;
450+
if (batch === null) {
451+
this.#sourceExhausted = true;
452+
} else {
453+
this.#bufferBatch(batch);
454+
}
455+
} catch (error) {
456+
this.#sourceError = error;
457+
this.#sourceExhausted = true;
458+
}
459+
if (this.#sourceExhausted && this.#consumers.size === 0) {
460+
this.#cleanupFactorySignal();
461+
}
462+
for (let i = 0; i < this.#pullWaiters.length; i++) {
463+
this.#pullWaiters[i]();
464+
}
465+
this.#pullWaiters = [];
466+
return true;
467+
}
468+
397469
async #waitForBufferSpace() {
398470
while (this.#bufferedBytes >= this.#options.budget) {
399471
if (this.#cancelled ||
@@ -461,29 +533,7 @@ class ShareImpl {
461533

462534
let next;
463535
try {
464-
if (!this.#sourceIterator) {
465-
if (isAsyncIterable(this.#source)) {
466-
this.#sourceIterator =
467-
this.#source[SymbolAsyncIterator]();
468-
} else if (isSyncIterable(this.#source)) {
469-
const syncIterator =
470-
this.#source[SymbolIterator]();
471-
this.#sourceIterator = ObjectSetPrototypeOf({
472-
// Its result is passed to PromiseResolve().
473-
next() {
474-
return syncIterator.next();
475-
},
476-
async return() {
477-
return syncIterator.return?.() ??
478-
new IterResult(true, undefined);
479-
},
480-
}, null);
481-
} else {
482-
throw new ERR_INVALID_ARG_TYPE(
483-
'source', ['AsyncIterable', 'Iterable'], this.#source);
484-
}
485-
}
486-
next = this.#sourceIterator.next();
536+
next = this.#getSourceIterator().next();
487537
} catch (error) {
488538
this.#onReadError(error);
489539
return promise;
@@ -493,6 +543,32 @@ class ShareImpl {
493543
return promise;
494544
}
495545

546+
#getSourceIterator() {
547+
if (!this.#sourceIterator) {
548+
if (isAsyncIterable(this.#source)) {
549+
this.#sourceIterator =
550+
this.#source[SymbolAsyncIterator]();
551+
} else if (isSyncIterable(this.#source)) {
552+
const syncIterator =
553+
this.#source[SymbolIterator]();
554+
this.#sourceIterator = ObjectSetPrototypeOf({
555+
// Its result is passed to PromiseResolve().
556+
next() {
557+
return syncIterator.next();
558+
},
559+
async return() {
560+
return syncIterator.return?.() ??
561+
new IterResult(true, undefined);
562+
},
563+
}, null);
564+
} else {
565+
throw new ERR_INVALID_ARG_TYPE(
566+
'source', ['AsyncIterable', 'Iterable'], this.#source);
567+
}
568+
}
569+
return this.#sourceIterator;
570+
}
571+
496572
// The handlers of a read of the source, created once per share. A read
497573
// ended by a cancellation is ignored.
498574
#onReadResult = (result) => {

‎test/parallel/test-stream-iter-share-async.js‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -507,6 +507,57 @@ async function testShareConsumerConcurrentNextCalls() {
507507
assert.strictEqual(dec.decode(r2.value[0]), 'second');
508508
}
509509

510+
// A sync source is read as the consumers pull, including values that are
511+
// normalized asynchronously, and its errors reach every consumer after the
512+
// data before them.
513+
async function testShareSyncSource() {
514+
const reason = new Error('sync source boom');
515+
function* source() {
516+
yield [Uint8Array.of(1)];
517+
yield Promise.resolve(Uint8Array.of(2));
518+
yield 'c';
519+
yield [Uint8Array.of(4)];
520+
throw reason;
521+
}
522+
const shared = share(source());
523+
const consumers = [shared.pull(), shared.pull()];
524+
const read = async (consumer) => {
525+
const values = [];
526+
try {
527+
for await (const batch of consumer) values.push(...batch.map((c) => c[0]));
528+
} catch (error) {
529+
values.push(error);
530+
}
531+
return values;
532+
};
533+
const results = await Promise.all(consumers.map(read));
534+
for (const values of results) {
535+
assert.deepStrictEqual(values, [1, 2, 99, 4, reason]);
536+
}
537+
538+
// Concurrent next() calls get the batches in order.
539+
function* numbers() {
540+
for (let i = 0; i < 4; i++) yield [Uint8Array.of(i)];
541+
}
542+
const it = share(numbers()).pull()[Symbol.asyncIterator]();
543+
const all = await Promise.all([it.next(), it.next(), it.next(), it.next(),
544+
it.next()]);
545+
assert.deepStrictEqual(all.map((r) => (r.done ? 'done' : r.value[0][0])),
546+
[0, 1, 2, 3, 'done']);
547+
548+
// 'strict' backpressure rejects a consumer that would exceed the budget
549+
// when another one lags.
550+
function* big() {
551+
for (let i = 0; i < 4; i++) yield [new Uint8Array(8)];
552+
}
553+
const strict = share(big(), { budget: 16 });
554+
const fast = strict.pull()[Symbol.asyncIterator]();
555+
strict.pull();
556+
await fast.next();
557+
await fast.next();
558+
await assert.rejects(fast.next(), { code: 'ERR_OUT_OF_RANGE' });
559+
}
560+
510561
// share() accepts string source directly (normalized via from())
511562
async function testShareStringSource() {
512563
const shared = share('hello-share');
@@ -516,6 +567,7 @@ async function testShareStringSource() {
516567

517568
Promise.all([
518569
testBasicShare(),
570+
testShareSyncSource(),
519571
testShareMultipleConsumers(),
520572
testShareConsumerCount(),
521573
testShareCancel(),

0 commit comments

Comments
 (0)