Skip to content

Commit d7be9e0

Browse files
jasnelladuh95
authored andcommitted
stream: apply stream/iter stateful transforms without async generators
Every stateful (generator) transform in an async pipeline added two async generators of stream/iter's own to every batch, besides the transform's: one to append the null flush signal to its source, and one to read and normalize its output. Validated transforms, such as compression, added one. Write both out by hand. The source of the transform passes reads to the pipeline with one reaction each, then yields null once, and passes return() and throw() on as yield* does. The output is read with one reaction per item, and normalized as before; outputs that are not async iterables are still read by an async generator, as for await reads them. The transform is still called on the first pull. For 16-byte chunks one per batch, iterating pull() with one stateful transform is 23-31% faster, and with three 36-45% faster; compression is unchanged. 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 6843a59 commit d7be9e0

2 files changed

Lines changed: 275 additions & 35 deletions

File tree

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

Lines changed: 216 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -972,22 +972,98 @@ function applyFusedStatelessAsyncTransforms(source, run, abort) {
972972
}
973973

974974
/**
975-
* Append a null flush signal after the source is exhausted.
976-
* @yields {Uint8Array[]}
977-
*/
978-
/**
979-
* Append a null flush signal after the source is exhausted.
980-
* @yields {Uint8Array[]}
975+
* The source of a stateful transform: what an async generator doing
976+
* `yield* source; yield null;` would yield, written out by hand, as it is
977+
* read for every batch. Reads are passed to
978+
* the source's iterator, with one reaction each; once it is done, null is
979+
* yielded once, as the flush signal. return() and throw() are passed on as
980+
* yield* does.
981+
* @param {AsyncIterable<Uint8Array[]>} source
982+
* @returns {AsyncIterator<Uint8Array[]|null>}
981983
*/
982-
async function* withFlushAsync(source) {
983-
yield* source;
984-
yield null;
984+
function createFlushSource(source) {
985+
let iterator = null;
986+
// Whether the source is done, and the flush signal yielded; then the
987+
// source is ended.
988+
let sourceDone = false;
989+
let done = false;
990+
991+
function onResult(result) {
992+
if ((typeof result !== 'object' && typeof result !== 'function') ||
993+
result === null) {
994+
done = true;
995+
throw new ERR_INVALID_RETURN_VALUE(
996+
'an object', 'iterator.next()', result);
997+
}
998+
if (result.done) {
999+
sourceDone = true;
1000+
return new IterResult(false, null);
1001+
}
1002+
return new IterResult(false, result.value);
1003+
}
1004+
1005+
function onError(error) {
1006+
done = true;
1007+
throw error;
1008+
}
1009+
1010+
return ObjectSetPrototypeOf({
1011+
next() {
1012+
if (done || sourceDone) {
1013+
done = true;
1014+
return PromiseResolve(new IterResult(true, undefined));
1015+
}
1016+
try {
1017+
iterator ??= source[SymbolAsyncIterator]();
1018+
return PromisePrototypeThen(PromiseResolve(iterator.next()),
1019+
onResult, onError);
1020+
} catch (error) {
1021+
done = true;
1022+
return PromiseReject(error);
1023+
}
1024+
},
1025+
return(value) {
1026+
const result = new IterResult(true, value);
1027+
if (done || sourceDone || iterator === null) {
1028+
done = true;
1029+
return PromiseResolve(result);
1030+
}
1031+
done = true;
1032+
return PromisePrototypeThen(closeAsyncIterator(iterator, false),
1033+
() => result);
1034+
},
1035+
throw(error) {
1036+
if (done || sourceDone || iterator === null) {
1037+
done = true;
1038+
return PromiseReject(error);
1039+
}
1040+
try {
1041+
const throwMethod = iterator.throw;
1042+
if (throwMethod === undefined || throwMethod === null) {
1043+
// As yield*: close the source, then throw a TypeError.
1044+
done = true;
1045+
return PromisePrototypeThen(closeAsyncIterator(iterator, false),
1046+
() => {
1047+
throw new ERR_INVALID_STATE.TypeError(
1048+
'The iterator does not provide ' +
1049+
'a \'throw\' method');
1050+
});
1051+
}
1052+
return PromisePrototypeThen(
1053+
PromiseResolve(FunctionPrototypeCall(throwMethod, iterator, error)),
1054+
onResult, onError);
1055+
} catch (thrown) {
1056+
done = true;
1057+
return PromiseReject(thrown);
1058+
}
1059+
},
1060+
[SymbolAsyncIterator]() { return this; },
1061+
}, null);
9851062
}
9861063

987-
async function* applyStatefulAsyncTransform(
988-
source, transform, receiver, options) {
989-
const output = FunctionPrototypeCall(
990-
transform, receiver, withFlushAsync(source), options);
1064+
// Iterate the output of a stateful transform as for await does, for outputs
1065+
// that are not async iterables: see createStatefulTransformIterator().
1066+
async function* yieldStatefulOutput(output) {
9911067
for await (const item of output) {
9921068
if (item === null) continue;
9931069
// Fast path: item is already a Uint8Array[] batch (e.g. compression transforms)
@@ -1014,24 +1090,133 @@ async function* applyStatefulAsyncTransform(
10141090
}
10151091

10161092
/**
1017-
* Fast path for validated stateful transforms (e.g. compression).
1018-
* Skips withFlushAsync (transform handles done internally) and
1019-
* skips isUint8ArrayBatch validation (transform guarantees valid output).
1020-
* @yields {Uint8Array[]}
1093+
* A stateful transform applied to `source`: what an async generator doing
1094+
* `for await (const item of output)` over the transform's output would
1095+
* yield, written out by hand, as it runs for every batch. The transform is
1096+
* called on the first next(), with createFlushSource(source), or with
1097+
* `source` itself for a validated transform (e.g. compression), whose
1098+
* output needs no normalization. An output that is not an async iterable
1099+
* is read by the async generator instead (yieldStatefulOutput()).
1100+
* @param {AsyncIterable<Uint8Array[]>} source
1101+
* @param {Function} transform
1102+
* @param {object} receiver
1103+
* @param {TransformOptions} options
1104+
* @param {PipelineAbort} abort
1105+
* @param {boolean} validated
1106+
* @returns {AsyncIterator<Uint8Array[]>}
10211107
*/
1022-
async function* applyValidatedStatefulAsyncTransform(
1023-
source, transform, receiver, options, abort) {
1024-
const output = FunctionPrototypeCall(
1025-
transform, receiver, source, options);
1026-
for await (const batch of output) {
1027-
if (batch.length > 0) {
1028-
yield batch;
1108+
function createStatefulTransformIterator(
1109+
source, transform, receiver, options, abort, validated) {
1110+
let state = kStart;
1111+
let iterator;
1112+
let nextMethod;
1113+
1114+
function pull() {
1115+
return PromisePrototypeThen(
1116+
PromiseResolve(FunctionPrototypeCall(nextMethod, iterator)),
1117+
onItem, onError);
1118+
}
1119+
1120+
function onItem(result) {
1121+
if ((typeof result !== 'object' && typeof result !== 'function') ||
1122+
result === null) {
1123+
state = kDone;
1124+
throw new ERR_INVALID_RETURN_VALUE(
1125+
'an object', 'iterator.next()', result);
1126+
}
1127+
if (result.done) {
1128+
state = kDone;
1129+
// Without the flush signal there is no extra read to give the
1130+
// pipeline a chance to see an abort.
1131+
if (validated) abort.throwIfAborted();
1132+
return new IterResult(true, undefined);
1133+
}
1134+
const item = result.value;
1135+
if (validated) {
1136+
return item.length > 0 ? new IterResult(false, item) : pull();
1137+
}
1138+
if (item === null) return pull();
1139+
if (isUint8ArrayBatch(item)) {
1140+
return item.length > 0 ? new IterResult(false, item) : pull();
1141+
}
1142+
if (isUint8Array(item)) return new IterResult(false, [item]);
1143+
// Slow path: flatten arbitrary transform yield. An error doing so
1144+
// closes the output, as for await does when its body throws.
1145+
return PromisePrototypeThen(flattenItem(item), (batch) => {
1146+
return batch.length > 0 ? new IterResult(false, batch) : pull();
1147+
}, (error) => {
1148+
state = kDone;
1149+
return PromisePrototypeThen(closeAsyncIterator(iterator, true), () => {
1150+
throw error;
1151+
});
1152+
});
1153+
}
1154+
1155+
async function flattenItem(item) {
1156+
const batch = [];
1157+
for await (const chunk of flattenTransformYieldAsync(item)) {
1158+
batch[batch.length] = chunk;
10291159
}
1160+
return batch;
10301161
}
1031-
// Check abort after the transform completes - without the
1032-
// withFlushAsync wrapper there is no extra yield to give
1033-
// the outer pipeline a chance to see the abort.
1034-
abort.throwIfAborted();
1162+
1163+
function onError(error) {
1164+
state = kDone;
1165+
throw error;
1166+
}
1167+
1168+
return ObjectSetPrototypeOf({
1169+
next() {
1170+
if (state === kDone) {
1171+
return PromiseResolve(new IterResult(true, undefined));
1172+
}
1173+
if (state === kStart) {
1174+
state = kActive;
1175+
try {
1176+
const output = FunctionPrototypeCall(
1177+
transform, receiver,
1178+
validated ? source : createFlushSource(source), options);
1179+
if (output != null &&
1180+
typeof output[SymbolAsyncIterator] === 'function') {
1181+
iterator = output[SymbolAsyncIterator]();
1182+
} else {
1183+
// Iterated as for await would: sync iterables, and errors.
1184+
iterator = yieldStatefulOutput(output);
1185+
}
1186+
nextMethod = iterator.next;
1187+
} catch (error) {
1188+
state = kDone;
1189+
return PromiseReject(error);
1190+
}
1191+
}
1192+
try {
1193+
return pull();
1194+
} catch (error) {
1195+
state = kDone;
1196+
return PromiseReject(error);
1197+
}
1198+
},
1199+
return(value) {
1200+
const result = new IterResult(true, value);
1201+
if (state !== kActive) {
1202+
state = kDone;
1203+
return PromiseResolve(result);
1204+
}
1205+
state = kDone;
1206+
return PromisePrototypeThen(closeAsyncIterator(iterator, false),
1207+
() => result);
1208+
},
1209+
throw(error) {
1210+
if (state !== kActive) {
1211+
state = kDone;
1212+
return PromiseReject(error);
1213+
}
1214+
state = kDone;
1215+
return PromisePrototypeThen(closeAsyncIterator(iterator, true),
1216+
() => { throw error; });
1217+
},
1218+
[SymbolAsyncIterator]() { return this; },
1219+
}, null);
10351220
}
10361221

10371222
/**
@@ -1131,13 +1316,9 @@ function createAsyncTransformLayers(normalized, transforms, abort) {
11311316
statelessRun = [];
11321317
}
11331318
const opts = new TransformOptions(abort);
1134-
if (transform[kValidatedTransform]) {
1135-
current = applyValidatedStatefulAsyncTransform(
1136-
current, transform.transform, transform.receiver, opts, abort);
1137-
} else {
1138-
current = applyStatefulAsyncTransform(
1139-
current, transform.transform, transform.receiver, opts);
1140-
}
1319+
current = createStatefulTransformIterator(
1320+
current, transform.transform, transform.receiver, opts, abort,
1321+
transform[kValidatedTransform] === true);
11411322
} else {
11421323
ArrayPrototypePush(statelessRun, transform);
11431324
}

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

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
const common = require('../common');
55
const assert = require('assert');
66
const {
7+
array,
78
broadcast,
89
dump,
910
from,
@@ -428,6 +429,63 @@ async function testPullSignalListenerRemoved() {
428429
await assert.rejects(iter.next(), { name: 'AbortError' });
429430
}
430431

432+
// Stateful transforms: called on the first pull, with a source that ends
433+
// with one null flush signal; their output is normalized; stopping early
434+
// closes the output and the source.
435+
async function testStatefulTransformProtocol() {
436+
const log = [];
437+
const stateful = {
438+
async *transform(source) {
439+
log.push('called');
440+
try {
441+
for await (const batch of source) {
442+
log.push(batch === null ? 'flush' : `batch ${batch[0][0]}`);
443+
if (batch === null) {
444+
yield 'end';
445+
} else {
446+
yield batch;
447+
yield batch[0];
448+
yield null;
449+
yield [];
450+
}
451+
}
452+
} finally {
453+
log.push('output closed');
454+
}
455+
},
456+
};
457+
const iterable = pull(createLoggedSource(log, [1, 2]), stateful);
458+
assert.deepStrictEqual(log, []);
459+
const chunks = await array(iterable);
460+
assert.deepStrictEqual(chunks.map((chunk) => chunk[0]), [1, 1, 2, 2, 101]);
461+
assert.deepStrictEqual(log, [
462+
'called', 'next 0', 'batch 1', 'next 1', 'batch 2', 'next 2', 'flush',
463+
'output closed',
464+
]);
465+
466+
log.length = 0;
467+
const iterator = pull(createLoggedSource(log, [1, 2, 3]),
468+
stateful)[Symbol.asyncIterator]();
469+
assert.strictEqual((await iterator.next()).value[0][0], 1);
470+
assert.strictEqual((await iterator.return()).done, true);
471+
assert.deepStrictEqual(log, [
472+
'called', 'next 0', 'batch 1', 'return', 'output closed',
473+
]);
474+
assert.strictEqual((await iterator.next()).done, true);
475+
476+
// Outputs that are sync iterables are read as for await reads them.
477+
const syncOutput = { transform: () => [[Uint8Array.of(7)], 'x'] };
478+
assert.deepStrictEqual((await array(pull(from('a'), syncOutput))).map(
479+
(chunk) => chunk[0]), [7, 120]);
480+
481+
// Errors from the transform reject the pull.
482+
const failing = {
483+
// eslint-disable-next-line require-yield
484+
async *transform() { throw new Error('stateful failed'); },
485+
};
486+
await assert.rejects(array(pull(from('a'), failing)), /stateful failed/);
487+
}
488+
431489
// Pull consumer break (return()) cleans up transform signal
432490
async function testPullConsumerBreakCleanup() {
433491
let signalAborted = false;
@@ -884,6 +942,7 @@ async function testTransformReturnClosesOutputAndSource() {
884942
testPullSignalAbortWhileTransformPending(),
885943
testPullSignalAbortWhileIdleClosesSource(),
886944
testPullSignalListenerRemoved(),
945+
testStatefulTransformProtocol(),
887946
testTransformOptionsSignalAssignable(),
888947
testTransformErrorClosesSource(),
889948
testTransformSourceErrorDoesNotCloseSource(),

0 commit comments

Comments
 (0)