stream: normalize async sources without a generator in from()

from() normalized an async iterable source with an async generator
looping over it with for await, which costs several promises and an
async frame for every batch.

Replace it with an iterator written out by hand that behaves the same
way: nothing happens until the first next(), calls made while one is in
progress are queued, an error from the source ends the iteration
without closing the source, an error normalizing a value closes the
source first, return() closes the value being normalized and the source
and propagates errors from closing them, and throw() closes them
ignoring such errors. Values that are already Uint8Array[] batches or
Uint8Arrays take one promise per batch; any other value is normalized
by an async generator as before. Sync iterable sources are unchanged.

With an async generator yielding 16-byte chunks, this allocates about
440 bytes less per chunk; pipeTo() is about 28% faster and iterating
from() about 38% faster.

The results of the iterator are now IterResult objects, like those of
the other stream/iter iterators, rather than ordinary objects; one
test compared them as such. New tests cover the behavior above.

Assisted-by: OpenCode
Signed-off-by: James M Snell <jasnell@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/66504
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
This commit is contained in:
James M Snell authored and Antoine du Hamel committed 2026-11-25 18:00:49 +01:00
1 parent b56d4b89bf
commit 391ad80583
3 files changed
+409 -46

No files matched your search

+249 -45
View File
@@ -631,58 +631,262 @@ async function* normalizeAsyncValue(
}
/**
* Normalize an async streamable source, yielding batches of Uint8Array.
* @param {AsyncIterable|Iterable} source
* Normalize a value of an async source that is neither a Uint8Array nor a
* Uint8Array[] batch, yielding batches of Uint8Array. Chunks are batched,
* but whatever has been collected is yielded before waiting on async content
* (such as a nested async iterable), so data is not held back until it ends.
* @param {any} value
* @param {object} context
* @yields {Uint8Array[]}
*/
async function* normalizeAsyncSource(source, context) {
throwIfNormalizationCancelled(context);
// Prefer async iteration if available
if (isAsyncIterable(source)) {
const iterable = yieldNormalizationAbortable(source, context);
for await (const value of iterable) {
// Fast path 1: value is already a Uint8Array[] batch. Yield a batch
// within the bound directly: yield* of a sync generator from an async
// generator costs several extra promise ticks per batch.
if (isUint8ArrayBatch(value)) {
if (value.length <= FROM_BATCH_SIZE) {
if (value.length !== 0) yield value;
} else {
yield* yieldBoundedBatch(value);
}
continue;
}
// Fast path 2: value is a single Uint8Array (very common)
if (isUint8Array(value)) {
yield [value];
continue;
}
// Slow path: normalize the value. Chunks are batched, but whatever has
// been collected is yielded before waiting on async content (such as a
// nested async iterable), so data is not held back until it ends.
let batch = [];
for await (const chunk of
normalizeAsyncValue(value, true, context, true)) {
if (chunk === kFlushBatch) {
if (batch.length > 0) {
yield batch;
batch = [];
}
continue;
}
ArrayPrototypePush(batch, chunk);
if (batch.length === FROM_BATCH_SIZE) {
yield batch;
batch = [];
}
}
async function* normalizeAsyncSourceValue(value, context) {
let batch = [];
for await (const chunk of
normalizeAsyncValue(value, true, context, true)) {
if (chunk === kFlushBatch) {
if (batch.length > 0) {
yield batch;
batch = [];
}
continue;
}
ArrayPrototypePush(batch, chunk);
if (batch.length === FROM_BATCH_SIZE) {
yield batch;
batch = [];
}
return;
}
if (batch.length > 0) {
yield batch;
}
}
const kStart = 0;
const kActive = 1;
const kDone = 2;
/**
* Iterator normalizing an async iterable source into batches of Uint8Array.
*
* This is what an async generator looping over the source with for await
* would do, written out by hand: the source is read for every batch, and an
* async generator layer costs several promises and an async frame each
* time. Values that are already batches or Uint8Arrays (the common case)
* are handled with one promise per batch; any other value is normalized by
* normalizeAsyncSourceValue(). As with an async generator:
* - nothing happens until the first next();
* - calls made while one is in progress are queued;
* - an error from the source ends the iteration without closing the source,
* and an error normalizing a value closes the source first;
* - return() closes the value being normalized and the source, propagating
* errors from closing them, and throw() closes them ignoring such errors.
* @param {AsyncIterable} source
* @param {object} context
* @returns {object} An object with next(), return() and throw().
*/
function createAsyncSourceNormalizer(source, context) {
let state = kStart;
// The source iterator, from yieldNormalizationAbortable(). Its return()
// is an async function, so calling it cannot throw synchronously.
let iterator;
// The value being normalized: a sync iterator of the sub-batches of an
// oversized batch, or a normalizeAsyncSourceValue() generator.
let boundedBatches = null;
let valueBatches = null;
let busy = false;
let queue = null;
function drain() {
if (busy || queue === null) return;
const { 0: method, 1: arg, 2: resolve, 3: reject } = queue.shift();
if (queue.length === 0) queue = null;
busy = true;
PromisePrototypeThen(method(arg), resolve, reject);
}
function settled() {
busy = false;
if (queue !== null) PromisePrototypeThen(kResolvedPromise, drain);
}
function finish(result) {
settled();
return result;
}
function fail(error) {
state = kDone;
settled();
throw error;
}
function run(method, arg) {
if (busy || queue !== null) {
const { promise, resolve, reject } = PromiseWithResolvers();
queue ??= [];
ArrayPrototypePush(queue, [method, arg, resolve, reject]);
return promise;
}
busy = true;
return method(arg);
}
// Closing for a throw completion: wait, but ignore errors.
function closeQuietly(it) {
return PromisePrototypeThen(it.return(), undefined, () => {});
}
function onBodyError(error) {
// Like for await when its body throws: close the source, keep the error.
valueBatches = null;
boundedBatches = null;
state = kDone;
return PromisePrototypeThen(
closeQuietly(iterator), () => fail(error));
}
function onSourceResult(result) {
if (result.done) {
state = kDone;
return finish(new IterResult(true, undefined));
}
try {
return handleValue(result.value);
} catch (error) {
return onBodyError(error);
}
}
function handleValue(value) {
if (isUint8ArrayBatch(value)) {
if (value.length <= FROM_BATCH_SIZE) {
if (value.length === 0) return pullSource();
return finish(new IterResult(false, value));
}
boundedBatches = yieldBoundedBatch(value);
return pullValue();
}
if (isUint8Array(value)) return finish(new IterResult(false, [value]));
valueBatches = normalizeAsyncSourceValue(value, context);
return pullValue();
}
function onValueResult(result) {
if (result.done) {
valueBatches = null;
return pullSource();
}
return finish(new IterResult(false, result.value));
}
function pullSource() {
return PromisePrototypeThen(iterator.next(), onSourceResult, fail);
}
function pullValue() {
if (boundedBatches !== null) {
const result = boundedBatches.next();
if (!result.done) return finish(new IterResult(false, result.value));
boundedBatches = null;
return pullSource();
}
return PromisePrototypeThen(
valueBatches.next(), onValueResult, onBodyError);
}
function doNext() {
if (state === kDone) {
return PromiseResolve(finish(new IterResult(true, undefined)));
}
if (state === kStart) {
try {
throwIfNormalizationCancelled(context);
const iterable = yieldNormalizationAbortable(source, context);
iterator = iterable[SymbolAsyncIterator]();
} catch (error) {
state = kDone;
settled();
return PromiseReject(error);
}
state = kActive;
}
if (boundedBatches !== null || valueBatches !== null) {
return PromiseResolve(pullValue());
}
return pullSource();
}
function doReturn(value) {
const result = new IterResult(true, value);
if (state !== kActive) {
state = kDone;
return PromiseResolve(finish(result));
}
state = kDone;
boundedBatches = null;
const pending = valueBatches;
valueBatches = null;
// Close the value being normalized, then the source. If closing the
// value fails, the source is still closed and the error kept.
let closed;
if (pending === null) {
closed = iterator.return();
} else {
closed = PromisePrototypeThen(
pending.return(),
() => iterator.return(),
(error) => PromisePrototypeThen(closeQuietly(iterator), () => {
throw error;
}));
}
return PromisePrototypeThen(closed, () => finish(result), fail);
}
function doThrow(error) {
if (state !== kActive) {
state = kDone;
settled();
return PromiseReject(error);
}
state = kDone;
boundedBatches = null;
const pending = valueBatches;
valueBatches = null;
const closed = pending === null ? closeQuietly(iterator) :
PromisePrototypeThen(closeQuietly(pending), () => closeQuietly(iterator));
return PromisePrototypeThen(closed, () => fail(error));
}
return ObjectSetPrototypeOf({
next() { return run(doNext); },
return(value) { return run(doReturn, value); },
throw(error) { return run(doThrow, error); },
}, null);
}
/**
* Normalize an async streamable source, yielding batches of Uint8Array.
* @param {AsyncIterable|Iterable} source
* @param {object} context
* @returns {object} An async iterator.
*/
function normalizeAsyncSource(source, context) {
// Prefer async iteration if available.
if (isAsyncIterable(source)) {
return createAsyncSourceNormalizer(source, context);
}
return normalizeSyncSourceAsync(source, context);
}
/**
* Normalize a sync streamable source for from(), yielding batches of
* Uint8Array.
* @param {Iterable} source
* @param {object} context
* @yields {Uint8Array[]}
*/
async function* normalizeSyncSourceAsync(source, context) {
throwIfNormalizationCancelled(context);
// Fall back to sync iteration - batch sync values together with a bound.
if (isSyncIterable(source)) {
+157 -1
View File
@@ -123,7 +123,7 @@ async function testFromDoesNotHoldBackNestedAsyncIterable() {
}
const iterator = from(source())[Symbol.asyncIterator]();
assert.deepStrictEqual(await iterator.next(),
assert.deepStrictEqual({ ...await iterator.next() },
{ done: false, value: [new Uint8Array([1])] });
resolve();
const rest = [];
@@ -529,6 +529,156 @@ async function testFromFunctionWithProtocols() {
assert.throws(() => from(() => {}), { code: 'ERR_INVALID_ARG_TYPE' });
}
// from() reads async sources like an async generator looping over them with
// for await. The tests below check the parts of that behavior that are
// observable from the source: when it is read and closed.
// Creates an async iterable source of `values`, recording calls in `log`.
function createLoggedSource(log, values, { failAt = -1, returnError } = {}) {
let i = 0;
return {
[Symbol.asyncIterator]() {
log.push('iterator');
return {
async next() {
log.push(`next ${i}`);
if (i === failAt) {
i++;
throw new Error('source failed');
}
if (i >= values.length) return { done: true, value: undefined };
return { done: false, value: values[i++] };
},
async return() {
log.push('return');
if (returnError !== undefined) throw returnError;
return { done: true, value: undefined };
},
};
},
};
}
async function settle(log, label, promise) {
try {
const result = await promise;
log.push(`${label}: ${result.done ? 'done' : result.value.length}`);
} catch (error) {
log.push(`${label}: ${error.code ?? error.message}`);
}
}
async function testFromQueuesConcurrentNext() {
const log = [];
const iterator = from(createLoggedSource(log, [
Uint8Array.of(1), Uint8Array.of(2),
]))[Symbol.asyncIterator]();
const results = [iterator.next(), iterator.next(), iterator.next()];
for (let i = 0; i < results.length; i++) {
await settle(log, `result ${i}`, results[i]);
}
assert.deepStrictEqual(log, [
'iterator', 'next 0', 'next 1', 'result 0: 1', 'next 2', 'result 1: 1',
'result 2: done',
]);
}
async function testFromSplitsOversizedBatches() {
const log = [];
const batch = Array.from({ length: 300 }, () => new Uint8Array(1));
const iterator = from(createLoggedSource(log, [batch, [], [batch[0]]]))[
Symbol.asyncIterator]();
for (let i = 0; i < 5; i++) await settle(log, `result ${i}`, iterator.next());
assert.deepStrictEqual(log, [
'iterator', 'next 0', 'result 0: 128', 'result 1: 128', 'result 2: 44',
'next 1', 'next 2', 'result 3: 1', 'next 3', 'result 4: done',
]);
}
async function testFromSourceErrorDoesNotCloseSource() {
const log = [];
const iterator = from(createLoggedSource(log, [Uint8Array.of(1)], {
failAt: 1,
}))[Symbol.asyncIterator]();
for (let i = 0; i < 3; i++) await settle(log, `result ${i}`, iterator.next());
assert.deepStrictEqual(log, [
'iterator', 'next 0', 'result 0: 1', 'next 1', 'result 1: source failed',
'result 2: done',
]);
}
async function testFromNormalizationErrorClosesSource() {
// A value that cannot be normalized.
let log = [];
let iterator = from(createLoggedSource(log, [Uint8Array.of(1), 42]))[
Symbol.asyncIterator]();
for (let i = 0; i < 3; i++) await settle(log, `result ${i}`, iterator.next());
assert.deepStrictEqual(log, [
'iterator', 'next 0', 'result 0: 1', 'next 1', 'return',
'result 1: ERR_INVALID_ARG_TYPE', 'result 2: done',
]);
// A nested async iterable that fails.
async function* nested() {
yield Uint8Array.of(2);
throw new Error('nested failed');
}
log = [];
iterator = from(createLoggedSource(log, [nested()]))[Symbol.asyncIterator]();
for (let i = 0; i < 3; i++) await settle(log, `result ${i}`, iterator.next());
assert.deepStrictEqual(log, [
'iterator', 'next 0', 'result 0: 1', 'return', 'result 1: nested failed',
'result 2: done',
]);
}
async function testFromReturnAndThrowBeforeStart() {
const log = [];
let iterator = from(createLoggedSource(log, [Uint8Array.of(1)]))[
Symbol.asyncIterator]();
assert.deepStrictEqual({ ...await iterator.return('v') },
{ done: true, value: 'v' });
await settle(log, 'after return', iterator.next());
iterator = from(createLoggedSource(log, [Uint8Array.of(1)]))[
Symbol.asyncIterator]();
await settle(log, 'throw', iterator.throw(new Error('thrown')));
await settle(log, 'after throw', iterator.next());
// The source is never read.
assert.deepStrictEqual(log, [
'after return: done', 'throw: thrown', 'after throw: done',
]);
}
async function testFromReturnAndThrowCloseSource() {
const returnError = new Error('return failed');
for (const method of ['return', 'throw']) {
const log = [];
let nestedClosed = false;
async function* nested() {
try {
yield Uint8Array.of(1);
yield Uint8Array.of(2);
} finally {
nestedClosed = true;
}
}
const iterator = from(createLoggedSource(log, [nested()], {
returnError,
}))[Symbol.asyncIterator]();
await settle(log, 'result', iterator.next());
await settle(log, method, iterator[method](new Error('thrown')));
await settle(log, 'after', iterator.next());
assert.strictEqual(nestedClosed, true);
// return() propagates errors from closing the source; throw() keeps its
// own error.
assert.deepStrictEqual(log, [
'iterator', 'next 0', 'result: 1', 'return',
method === 'return' ? 'return: return failed' : 'throw: thrown',
'after: done',
]);
}
}
Promise.all([
testFromString(),
testFromAsyncGenerator(),
@@ -563,4 +713,10 @@ Promise.all([
testConsumerAbortClosesPendingNestedIterator(),
testFromCancellationHandlesCleanupRejection(),
testFromDataView(),
testFromQueuesConcurrentNext(),
testFromSplitsOversizedBatches(),
testFromSourceErrorDoesNotCloseSource(),
testFromNormalizationErrorClosesSource(),
testFromReturnAndThrowBeforeStart(),
testFromReturnAndThrowCloseSource(),
]).then(common.mustCall());
@@ -33,6 +33,9 @@ async function testAsyncIterators() {
return readable;
},
'share()': () => share(from('a')).pull(),
'from() of an async iterable': () => from((async function*() {
yield 'a';
})()),
'broadcast()': () => {
const { writer, broadcast: bc } = broadcast();
const consumer = bc.push();