Skip to content

Commit 404e671

Browse files
jasnelladuh95
authored andcommitted
stream: read stream/iter from() async sources in one reaction
from() read an async source through yieldNormalizationAbortable(), whose next() a cancellation can interrupt: for every batch it created a promise with three closures, a reaction to the source's result, and an iterator result, and the normalizer then took another reaction and another iterator result. Only pipeTo() without a signal avoided this, with kNextUncancellable. Give yieldNormalizationAbortable() a read, kRead, that calls handlers set once by the normalizer, so that it takes no closure, and handle the source's result in the same reaction. The normalizer's pending read is a promise of its own, which a cancellation rejects as before. A batch passed on unchanged keeps the iterator result of the read. For 16-byte chunks one per batch, iterating from() of an async generator is 13-20% faster and allocates about 370 bytes less per batch; piping one with a signal is 11-15% 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 1ca7ec5 commit 404e671

1 file changed

Lines changed: 136 additions & 2 deletions

File tree

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

Lines changed: 136 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,10 @@ const kNextUncancellable = Symbol('kNextUncancellable');
154154
const kReadUncancellable = Symbol('kReadUncancellable');
155155
const kToIterResult = Symbol('kToIterResult');
156156
const kReadFailed = Symbol('kReadFailed');
157+
// A read of the source that a cancellation can interrupt, for
158+
// createAsyncSourceNormalizer(): see kRead in yieldNormalizationAbortable().
159+
const kSetReadHandlers = Symbol('kSetReadHandlers');
160+
const kRead = Symbol('kRead');
157161
// The result kReadUncancellable gives once the source is done.
158162
const kDoneSourceResult = ObjectFreeze({ __proto__: null, done: true, value: undefined });
159163

@@ -516,6 +520,55 @@ function yieldNormalizationAbortable(source, context) {
516520
}
517521
}
518522

523+
// The handlers of kRead, set once by kSetReadHandlers, and whether a
524+
// kRead is pending.
525+
let onRead = null;
526+
let onReadError = null;
527+
let readPending = false;
528+
529+
// Fail a kRead, closing the source first if the normalization has
530+
// been cancelled.
531+
function failRead(error) {
532+
if (context.cancelled) {
533+
PromisePrototypeThen(closeSource(true), () => {
534+
reading = false;
535+
onReadError(error);
536+
});
537+
return;
538+
}
539+
reading = false;
540+
onReadError(error);
541+
}
542+
543+
// context.resolve while a kRead is pending.
544+
function onReadCancelled() {
545+
if (!readPending) return;
546+
readPending = false;
547+
context.resolve = null;
548+
failRead(context.reason);
549+
}
550+
551+
function onReadResult(result) {
552+
if (!readPending) return;
553+
readPending = false;
554+
if (context.resolve === onReadCancelled) context.resolve = null;
555+
let iterResult;
556+
try {
557+
iterResult = toIterResult(result);
558+
} catch (error) {
559+
failRead(error);
560+
return;
561+
}
562+
onRead(iterResult);
563+
}
564+
565+
function onReadRejected(error) {
566+
if (!readPending) return;
567+
readPending = false;
568+
if (context.resolve === onReadCancelled) context.resolve = null;
569+
failRead(error);
570+
}
571+
519572
// Reject a pending next(), closing the source first if the
520573
// normalization has been cancelled.
521574
function rejectNext(reject, error) {
@@ -604,6 +657,38 @@ function yieldNormalizationAbortable(source, context) {
604657
return PromiseResolve(next);
605658
},
606659
[kToIterResult]: onUncancellableResult,
660+
// Like next(), calling the handlers set by kSetReadHandlers instead
661+
// of settling a promise of its own: onRead with the result, or
662+
// onReadError with the error, possibly synchronously. A cancellation
663+
// calls onReadError with its reason. The handlers are the same for
664+
// every read, so that a read takes no closure, and the caller can
665+
// handle the result in the same reaction.
666+
[kSetReadHandlers](resultHandler, errorHandler) {
667+
onRead = resultHandler;
668+
onReadError = errorHandler;
669+
},
670+
[kRead]() {
671+
if (completed) {
672+
onRead(new IterResult(true, undefined));
673+
return;
674+
}
675+
if (context.cancelled) {
676+
onReadError(context.reason);
677+
return;
678+
}
679+
reading = true;
680+
let next;
681+
try {
682+
next = FunctionPrototypeCall(nextMethod, iterator);
683+
} catch (error) {
684+
failRead(error);
685+
return;
686+
}
687+
readPending = true;
688+
context.resolve = onReadCancelled;
689+
PromisePrototypeThen(PromiseResolve(next), onReadResult,
690+
onReadRejected);
691+
},
607692
[kReadFailed]() {
608693
reading = false;
609694
},
@@ -799,6 +884,11 @@ function createAsyncSourceNormalizer(source, context) {
799884
// kNextUncancellable method, for callers that never cancel the
800885
// normalization while a read is pending.
801886
let uncancellable = false;
887+
// Whether the source is read with kRead, and the settling functions of
888+
// the read's promise while it is pending.
889+
let readable = false;
890+
let resolveRead = null;
891+
let rejectRead = null;
802892
const { run, settled } = createOperationQueue();
803893

804894
function finish(result) {
@@ -832,16 +922,23 @@ function createAsyncSourceNormalizer(source, context) {
832922
return finish(new IterResult(true, undefined));
833923
}
834924
try {
835-
return handleValue(result.value);
925+
return handleValue(result.value, result);
836926
} catch (error) {
837927
return onBodyError(error);
838928
}
839929
}
840930

841-
function handleValue(value) {
931+
// `result` is the source's result for `value`. When the source is read
932+
// with kRead or kReadUncancellable, it is an IterResult of
933+
// yieldNormalizationAbortable(), passed on as it is for a batch passed on
934+
// unchanged.
935+
function handleValue(value, result) {
842936
if (isUint8ArrayBatch(value)) {
843937
if (value.length <= FROM_BATCH_SIZE) {
844938
if (value.length === 0) return pullSource();
939+
if (readable || uncancellable) {
940+
return finish(result);
941+
}
845942
return finish(new IterResult(false, value));
846943
}
847944
boundedBatches = yieldBoundedBatch(value);
@@ -877,11 +974,44 @@ function createAsyncSourceNormalizer(source, context) {
877974
return fail(error);
878975
}
879976

977+
// The kRead handlers: the result is handled in the reaction to the
978+
// source's result, and settles the read's promise.
979+
function onRead(result) {
980+
const resolve = resolveRead;
981+
const reject = rejectRead;
982+
resolveRead = rejectRead = null;
983+
let settledWith;
984+
try {
985+
settledWith = onSourceResult(result);
986+
} catch (error) {
987+
reject(error);
988+
return;
989+
}
990+
resolve(settledWith);
991+
}
992+
993+
function onReadError(error) {
994+
const reject = rejectRead;
995+
resolveRead = rejectRead = null;
996+
state = kDone;
997+
settled();
998+
reject(error);
999+
}
1000+
8801001
function pullSource() {
8811002
if (uncancellable) {
8821003
return PromisePrototypeThen(iterator[kReadUncancellable](),
8831004
onUncancellableResult, onUncancellableError);
8841005
}
1006+
if (readable) {
1007+
// One promise for the read, which a cancellation rejects, instead of
1008+
// next()'s promise and a reaction to it.
1009+
const { promise, resolve, reject } = PromiseWithResolvers();
1010+
resolveRead = resolve;
1011+
rejectRead = reject;
1012+
iterator[kRead]();
1013+
return promise;
1014+
}
8851015
return PromisePrototypeThen(iterator.next(), onSourceResult, fail);
8861016
}
8871017

@@ -905,6 +1035,10 @@ function createAsyncSourceNormalizer(source, context) {
9051035
throwIfNormalizationCancelled(context);
9061036
const iterable = yieldNormalizationAbortable(source, context);
9071037
iterator = iterable[SymbolAsyncIterator]();
1038+
if (iterator[kSetReadHandlers] !== undefined) {
1039+
iterator[kSetReadHandlers](onRead, onReadError);
1040+
readable = true;
1041+
}
9081042
} catch (error) {
9091043
state = kDone;
9101044
settled();

0 commit comments

Comments
 (0)