diff --git a/lib/internal/streams/iter/from.js b/lib/internal/streams/iter/from.js index d7716352d07..54b3db2a2f6 100644 --- a/lib/internal/streams/iter/from.js +++ b/lib/internal/streams/iter/from.js @@ -10,11 +10,13 @@ const { ArrayIsArray, ArrayPrototypeEvery, ArrayPrototypePush, + ArrayPrototypeShift, ArrayPrototypeSlice, DataViewPrototypeGetBuffer, DataViewPrototypeGetByteLength, DataViewPrototypeGetByteOffset, FunctionPrototypeCall, + ObjectFreeze, ObjectSetPrototypeOf, PromisePrototypeThen, PromiseReject, @@ -637,12 +639,15 @@ async function* normalizeAsyncValue( * (such as a nested async iterable), so data is not held back until it ends. * @param {any} value * @param {object} context + * @param {boolean} [allowNestedAsync] Whether nested async iterables and + * toAsyncStreamable are allowed (they are not in sync sources). * @yields {Uint8Array[]} */ -async function* normalizeAsyncSourceValue(value, context) { +async function* normalizeAsyncSourceValue(value, context, + allowNestedAsync = true) { let batch = []; for await (const chunk of - normalizeAsyncValue(value, true, context, true)) { + normalizeAsyncValue(value, allowNestedAsync, context, true)) { if (chunk === kFlushBatch) { if (batch.length > 0) { yield batch; @@ -665,6 +670,52 @@ const kStart = 0; const kActive = 1; const kDone = 2; +/** + * Serializes the operations of a hand-written async iterator the way an + * async generator queues its requests: an operation started while another + * is in progress waits until it has settled. + * @returns {{ run: Function, settled: Function, release: Function }} + */ +function createOperationQueue() { + let busy = false; + let queue = null; + + function drain() { + if (busy || queue === null) return; + const { 0: method, 1: arg, 2: resolve, 3: reject } = + ArrayPrototypeShift(queue); + if (queue.length === 0) queue = null; + busy = true; + PromisePrototypeThen(method(arg), resolve, reject); + } + + return { + __proto__: null, + // Run `method(arg)`, which returns a promise and must call settled() + // once its result is known, now or after the operations before it. + 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); + }, + settled() { + busy = false; + if (queue !== null) PromisePrototypeThen(kResolvedPromise, drain); + }, + // Like settled(), but start the next queued operation now, as an async + // generator does once the await of a yield or return completes. + release() { + busy = false; + drain(); + }, + }; +} + /** * Iterator normalizing an async iterable source into batches of Uint8Array. * @@ -693,21 +744,7 @@ function createAsyncSourceNormalizer(source, context) { // 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); - } + const { run, settled } = createOperationQueue(); function finish(result) { settled(); @@ -720,17 +757,6 @@ function createAsyncSourceNormalizer(source, context) { 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, () => {}); @@ -875,86 +901,221 @@ function normalizeAsyncSource(source, context) { if (isAsyncIterable(source)) { return createAsyncSourceNormalizer(source, context); } - return normalizeSyncSourceAsync(source, context); + return createSyncSourceNormalizer(source, context); } +// A value of a sync source that is not a Uint8Array or a Uint8Array[] +// batch, yielded by readSyncSource() to be normalized asynchronously. +function SyncSourceValue(value) { + this.value = value; +} +SyncSourceValue.prototype = ObjectFreeze({ __proto__: null }); + /** - * Normalize a sync streamable source for from(), yielding batches of - * Uint8Array. + * Read a sync iterable source for from(): yields Uint8Array[] batches, + * collecting single Uint8Arrays into batches of up to FROM_BATCH_SIZE + * chunks, and a SyncSourceValue for any other value, after the chunks + * collected before it. * @param {Iterable} source * @param {object} context - * @yields {Uint8Array[]} + * @yields {Uint8Array[]|SyncSourceValue} */ -async function* normalizeSyncSourceAsync(source, context) { +function* readSyncSource(source, context) { throwIfNormalizationCancelled(context); - - // Fall back to sync iteration - batch sync values together with a bound. - if (isSyncIterable(source)) { - let batch = []; - - for (const value of source) { - throwIfNormalizationCancelled(context); - // Fast path 1: value is already a Uint8Array[] batch - if (isUint8ArrayBatch(value)) { - // Flush any accumulated batch first - if (batch.length > 0) { - yield batch; - batch = []; - } - 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)) { - ArrayPrototypePush(batch, value); - if (batch.length === FROM_BATCH_SIZE) { - yield batch; - batch = []; - } - continue; - } - // Slow path: normalize the value - must flush and yield individually + if (!isSyncIterable(source)) { + throw new ERR_INVALID_ARG_TYPE( + 'source', ['Iterable', 'AsyncIterable'], source); + } + let batch = []; + for (const value of source) { + throwIfNormalizationCancelled(context); + // Fast path 1: value is already a Uint8Array[] batch + if (isUint8ArrayBatch(value)) { + // Flush any accumulated batch first if (batch.length > 0) { yield batch; batch = []; } - let asyncBatch = []; - for await (const chunk of - normalizeAsyncValue(value, false, context, true)) { - if (chunk === kFlushBatch) { - if (asyncBatch.length > 0) { - yield asyncBatch; - asyncBatch = []; - } - continue; - } - ArrayPrototypePush(asyncBatch, chunk); - if (asyncBatch.length === FROM_BATCH_SIZE) { - yield asyncBatch; - asyncBatch = []; - } - } - if (asyncBatch.length > 0) { - yield asyncBatch; + if (value.length <= FROM_BATCH_SIZE) { + if (value.length !== 0) yield value; + } else { + yield* yieldBoundedBatch(value); } + continue; } - - // Yield any remaining batched values + // Fast path 2: value is a single Uint8Array (very common) + if (isUint8Array(value)) { + ArrayPrototypePush(batch, value); + if (batch.length === FROM_BATCH_SIZE) { + yield batch; + batch = []; + } + continue; + } + // Slow path: flush, then have the value normalized if (batch.length > 0) { yield batch; + batch = []; } - return; + yield new SyncSourceValue(value); + } + // Yield any remaining batched values + if (batch.length > 0) { + yield batch; + } +} + +/** + * Iterator normalizing a sync iterable source for from() into batches of + * Uint8Array, without an async generator layer for every batch (see + * createAsyncSourceNormalizer()). + * + * The source is read by the sync generator readSyncSource(), so for...of + * reads and closes it, and this iterator only adds the asynchronous + * normalization of values that need it. Operations on the generator mirror + * those on the async generator this replaces: return() and throw() are + * passed to it, after closing the value being normalized, and an error + * normalizing a value is thrown into it, so that for...of closes the source + * as for an error in the loop body. + * @param {Iterable} source + * @param {object} context + * @returns {object} An object with next(), return() and throw(). + */ +function createSyncSourceNormalizer(source, context) { + const reader = readSyncSource(source, context); + let done = false; + // A normalizeAsyncSourceValue() generator for the value being normalized. + let valueBatches = null; + const { run, settled, release } = createOperationQueue(); + + // Results are often produced synchronously. An async generator stays busy + // until the tick after a yield or return (both await their operand), so + // that a next(), return() or throw() made synchronously after this one is + // queued behind it; do the same. + function finish(result) { + PromisePrototypeThen(kResolvedPromise, release); + return result; } - throw new ERR_INVALID_ARG_TYPE( - 'source', - ['Iterable', 'AsyncIterable'], - source, - ); + function fail(error) { + done = true; + settled(); + throw error; + } + + // Throw `error` into the reader, closing the source as for...of does when + // its body throws: errors from closing it are ignored. + function throwIntoReader(error) { + try { + reader.throw(error); + } catch { + // The reader rethrows `error`. + } + } + + function onValueResult(result) { + if (result.done) { + valueBatches = null; + return produce(); + } + return finish(new IterResult(false, result.value)); + } + + function onValueError(error) { + valueBatches = null; + throwIntoReader(error); + return fail(error); + } + + // Produce the next result: an IterResult, or a promise for one when a + // value is normalized asynchronously. Throws, after settling, on error. + function produce() { + if (valueBatches !== null) { + return PromisePrototypeThen( + valueBatches.next(), onValueResult, onValueError); + } + let result; + try { + result = reader.next(); + } catch (error) { + return fail(error); + } + if (result.done) { + done = true; + return finish(new IterResult(true, undefined)); + } + const value = result.value; + if (ArrayIsArray(value)) return finish(new IterResult(false, value)); + valueBatches = normalizeAsyncSourceValue(value.value, context, false); + return PromisePrototypeThen( + valueBatches.next(), onValueResult, onValueError); + } + + function doNext() { + if (done) return PromiseResolve(finish(new IterResult(true, undefined))); + try { + return PromiseResolve(produce()); + } catch (error) { + return PromiseReject(error); + } + } + + function doReturn(value) { + const result = new IterResult(true, value); + if (done) return PromiseResolve(finish(result)); + done = true; + const pending = valueBatches; + valueBatches = null; + if (pending === null) { + try { + reader.return(); + } catch (error) { + settled(); + return PromiseReject(error); + } + return PromiseResolve(finish(result)); + } + // Close the value being normalized, then the source. If closing the + // value fails, the source is still closed and the error kept. + return PromisePrototypeThen(pending.return(), () => { + try { + reader.return(); + } catch (error) { + return fail(error); + } + return finish(result); + }, (error) => { + throwIntoReader(error); + return fail(error); + }); + } + + function doThrow(error) { + if (done) { + settled(); + return PromiseReject(error); + } + done = true; + const pending = valueBatches; + valueBatches = null; + if (pending === null) { + throwIntoReader(error); + settled(); + return PromiseReject(error); + } + return PromisePrototypeThen( + PromisePrototypeThen(pending.return(), undefined, () => {}), + () => { + throwIntoReader(error); + return fail(error); + }); + } + + return ObjectSetPrototypeOf({ + next() { return run(doNext); }, + return(value) { return run(doReturn, value); }, + throw(error) { return run(doThrow, error); }, + }, null); } async function* normalizeAsyncStreamableResult(result, context) { diff --git a/test/parallel/test-stream-iter-from-async.js b/test/parallel/test-stream-iter-from-async.js index 66a921549d7..356f07353d7 100644 --- a/test/parallel/test-stream-iter-from-async.js +++ b/test/parallel/test-stream-iter-from-async.js @@ -564,7 +564,9 @@ async function settle(log, label, promise) { const result = await promise; log.push(`${label}: ${result.done ? 'done' : result.value.length}`); } catch (error) { - log.push(`${label}: ${error.code ?? error.message}`); + const reason = error.name === 'AbortError' ? error.name : + error.code ?? error.message; + log.push(`${label}: ${reason}`); } } @@ -679,6 +681,126 @@ async function testFromReturnAndThrowCloseSource() { } } +// Creates a sync iterable source of `values`, recording calls in `log`. +function createLoggedSyncSource(log, values, { failAt = -1, returnError } = {}) { + let i = 0; + return { + [Symbol.iterator]() { + log.push('iterator'); + return { + 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++] }; + }, + return() { + log.push('return'); + if (returnError !== undefined) throw returnError; + return { done: true, value: undefined }; + }, + }; + }, + }; +} + +async function testFromSyncSourceBatching() { + // Single chunks are collected into batches of up to 128 chunks; any other + // value is yielded after the chunks collected before it. + const log = []; + const chunks = Array.from({ length: 130 }, () => new Uint8Array(1)); + const iterator = from(createLoggedSyncSource(log, [ + ...chunks, [Uint8Array.of(1), Uint8Array.of(2)], Uint8Array.of(3), 'ab', + ]))[Symbol.asyncIterator](); + for (let i = 0; i < 6; i++) await settle(log, `result ${i}`, iterator.next()); + assert.deepStrictEqual(log, [ + 'iterator', ...Array.from({ length: 128 }, (_, i) => `next ${i}`), + 'result 0: 128', 'next 128', 'next 129', 'next 130', 'result 1: 2', + 'result 2: 2', 'next 131', 'next 132', 'result 3: 1', 'result 4: 1', + 'next 133', 'result 5: done', + ]); +} + +async function testFromSyncSourceErrors() { + // An error from the source does not close it. + let log = []; + let iterator = from(createLoggedSyncSource(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', + ]); + + // An error processing a value closes it, also after flushing the chunks + // collected before the value, and when normalizing a promise fails. + for (const value of [42, Promise.reject(new Error('rejected'))]) { + log = []; + iterator = from(createLoggedSyncSource(log, [Uint8Array.of(1), value]))[ + Symbol.asyncIterator](); + for (let i = 0; i < 3; i++) { + await settle(log, `result ${i}`, iterator.next()); + } + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'next 1', 'result 0: 1', 'return', + `result 1: ${value === 42 ? 'ERR_INVALID_ARG_TYPE' : 'rejected'}`, + 'result 2: done', + ]); + } +} + +async function testFromSyncSourceReturnAndThrow() { + const returnError = new Error('return failed'); + for (const method of ['return', 'throw']) { + // While reading the source, it is closed: return() propagates errors + // from closing it, throw() keeps its own error. + let log = []; + let iterator = from(createLoggedSyncSource(log, [ + [Uint8Array.of(1)], [Uint8Array.of(2)], + ], { 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.deepStrictEqual(log, [ + 'iterator', 'next 0', 'result: 1', 'return', + method === 'return' ? 'return: return failed' : 'throw: thrown', + 'after: done', + ]); + + // Once the source has ended, it is not closed. + log = []; + iterator = from(createLoggedSyncSource(log, [Uint8Array.of(1)]))[ + Symbol.asyncIterator](); + await settle(log, 'result', iterator.next()); + await settle(log, method, iterator[method](new Error('thrown'))); + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'next 1', 'result: 1', + method === 'return' ? 'return: done' : 'throw: thrown', + ]); + } +} + +async function testFromSyncSourceQueuesBehindReturn() { + // A next() made synchronously after another waits for it, and so sees a + // return() made synchronously after it as well. + const log = []; + const iterator = from(createLoggedSyncSource(log, [ + [Uint8Array.of(1)], 'a', [Uint8Array.of(2)], + ]))[Symbol.asyncIterator](); + const results = [iterator.next(), iterator.next(), iterator.return()]; + for (let i = 0; i < results.length; i++) { + await settle(log, `result ${i}`, results[i]); + } + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'next 1', 'return', 'result 0: 1', + 'result 1: AbortError', 'result 2: done', + ]); +} + Promise.all([ testFromString(), testFromAsyncGenerator(), @@ -719,4 +841,8 @@ Promise.all([ testFromNormalizationErrorClosesSource(), testFromReturnAndThrowBeforeStart(), testFromReturnAndThrowCloseSource(), + testFromSyncSourceBatching(), + testFromSyncSourceErrors(), + testFromSyncSourceReturnAndThrow(), + testFromSyncSourceQueuesBehindReturn(), ]).then(common.mustCall());