From 7d8f93f278f9df8a87b871be7d4f7ac9f736f738 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 4 Oct 2026 04:22:36 +0000 Subject: [PATCH] stream: read stream/iter sources with one abort listener To read a source until a signal aborts, yieldAbortable() used an async generator calling abortableNext() for every value, which added an abort listener, raced the value against the abort with SafePromiseRace() and removed the listener again with SafePromisePrototypeFinally(). This made pull(), which always reads through its own signal, and pipeTo() and the consumers with a signal about four times slower than without one. Write the generator out by hand with a single abort listener for the whole iteration, held weakly so that the signal does not keep the iterator alive, and wait for each value with a single promise that an abort rejects. Aborts before, while and after reading a value, closing the source on errors and aborts, and return() and throw() behave as before. With an async generator yielding 16-byte chunks, one per batch, pull() is about 3.6x faster with or without a transform, pipeTo() with a signal and a transform about 3.4x, and bytes() and array() with a signal about 4.4x; pull() allocates about 7 KB less per chunk. New tests cover an abort while the source is producing a value and the removal of the listener. Assisted-by: OpenCode Signed-off-by: James M Snell PR-URL: https://github.com/nodejs/node/pull/66504 Reviewed-By: Matteo Collina Reviewed-By: Trivikram Kamat --- lib/internal/streams/iter/utils.js | 260 +++++++++++++----- .../test-stream-iter-pipeto-signal.js | 56 +++- 2 files changed, 252 insertions(+), 64 deletions(-) diff --git a/lib/internal/streams/iter/utils.js b/lib/internal/streams/iter/utils.js index 86d9b11aab7..01c21fd946d 100644 --- a/lib/internal/streams/iter/utils.js +++ b/lib/internal/streams/iter/utils.js @@ -11,11 +11,11 @@ const { FunctionPrototypeCall, ObjectDefineProperty, ObjectFreeze, + ObjectSetPrototypeOf, PromisePrototypeThen, + PromiseReject, PromiseResolve, PromiseWithResolvers, - SafePromisePrototypeFinally, - SafePromiseRace, SafeWeakSet, SymbolAsyncIterator, TypedArrayPrototypeGetBuffer, @@ -38,6 +38,7 @@ const { } = require('internal/errors'); const { isSharedArrayBuffer, isUint8Array } = require('internal/util/types'); +const { kWeakHandler } = require('internal/event_target'); const { validateInteger, @@ -110,36 +111,6 @@ function onSignalAbort(signal, handler) { } } -function getOnAbort(reject, signal) { - return () => reject(signal.reason); -} - -/** - * Read one item from an async iterator, rejecting early if the signal aborts. - * @param {AsyncIterator} iterator - The iterator to read from. - * @param {AbortSignal|undefined} signal - Optional abort signal. - * @returns {Promise>|IteratorResult} - */ -function abortableNext(iterator, signal) { - if (signal === undefined) { - return iterator.next(); - } - - signal.throwIfAborted(); - - const next = iterator.next(); - const { promise, reject } = PromiseWithResolvers(); - const onAbort = getOnAbort(reject, signal); - signal.addEventListener('abort', onAbort, kNullOnceOption); - if (signal.aborted) { - onAbort(); - } - - return SafePromisePrototypeFinally(SafePromiseRace([next, promise]), () => { - signal.removeEventListener('abort', onAbort); - }); -} - /** * Wrap an async source so each pending read is abort-aware. * @param {AsyncIterable} source - The source to read from. @@ -153,41 +124,204 @@ function yieldAbortable(source, signal) { return { __proto__: null, - async *[SymbolAsyncIterator]() { - const iterator = source[SymbolAsyncIterator](); - let completed = false; - let aborted = false; - - try { - while (true) { - const { done, value } = await abortableNext(iterator, signal); - if (done) { - completed = true; - return; - } - signal.throwIfAborted(); - yield value; - } - } catch (error) { - aborted = signal.aborted; - throw error; - } finally { - if (!completed && typeof iterator.return === 'function') { - const result = iterator.return(); - if (aborted) { - // PromiseResolve(result) can reject if result is a thenable that - // rejects, so mark it as handled even though the abort takes - // precedence over the result of iterator.return(). - markPromiseAsHandled(PromiseResolve(result)); - } else { - await result; - } - } - } + [SymbolAsyncIterator]() { + return createAbortableIterator(source, signal); }, }; } +/** + * Iterator reading `source` until `signal` aborts, for yieldAbortable(). + * + * This is what an async generator looping over the source with + * abortableNext() would do, written out by hand: that costs an abort + * listener, a promise race and an async generator layer for every value. + * Instead, a single abort listener is added for the whole iteration, held + * weakly so that the signal does not keep the iterator alive, and each + * next() waits with a single promise that an abort rejects. As with the + * generator: + * - the source is opened by the first next(), and calls made while one is in + * progress are queued; + * - an abort before or while reading a value, or once it has been read, + * rejects with the abort reason; + * - unless the source has ended, an error (including an abort) closes it: + * if the signal is aborted, without waiting, otherwise waiting and + * rejecting with an error from closing it instead; + * - return() closes the source, propagating errors from closing it. + * @param {AsyncIterable} source + * @param {AbortSignal} signal + * @returns {AsyncIterator} + */ +function createAbortableIterator(source, signal) { + let state = kStart; + let iterator; + let completed = false; + // The settling functions of the pending next(), if any. + let resolveNext = null; + let rejectNext = null; + const operations = createOperationQueue(); + + const self = ObjectSetPrototypeOf({ + next() { return operations.run(doNext); }, + return(value) { return operations.run(doReturn, value); }, + throw(error) { return operations.run(doThrow, error); }, + [SymbolAsyncIterator]() { return this; }, + }, null); + + function onAbort() { + if (rejectNext === null) return; + const reject = rejectNext; + resolveNext = rejectNext = null; + fail(reject, signal.reason); + } + + // What the generator did in its `catch` and `finally` blocks for `error`. + function fail(reject, error) { + state = kDone; + signal.removeEventListener('abort', onAbort); + const aborted = signal.aborted; + if (!completed && typeof iterator.return === 'function') { + let closed; + try { + const result = iterator.return(); + if (aborted) { + // PromiseResolve(result) can reject if result is a thenable that + // rejects, so mark it as handled even though the abort takes + // precedence over the result of iterator.return(). + markPromiseAsHandled(PromiseResolve(result)); + } else { + closed = PromiseResolve(result); + } + } catch (closeError) { + operations.settled(); + reject(closeError); + return; + } + if (closed !== undefined) { + PromisePrototypeThen(closed, () => { + operations.settled(); + reject(error); + }, (closeError) => { + operations.settled(); + reject(closeError); + }); + return; + } + } + operations.settled(); + reject(error); + } + + function onResult(result) { + if (resolveNext === null) return; // Settled by an abort. + const resolve = resolveNext; + const reject = rejectNext; + resolveNext = rejectNext = null; + let done; + let value; + try { + ({ done, value } = result); + if (!done) signal.throwIfAborted(); + } catch (error) { + fail(reject, error); + return; + } + if (done) { + completed = true; + state = kDone; + signal.removeEventListener('abort', onAbort); + operations.settled(); + resolve(new IterResult(true, undefined)); + return; + } + operations.settled(); + resolve(new IterResult(false, value)); + } + + function onError(error) { + if (rejectNext === null) return; // Settled by an abort. + const reject = rejectNext; + resolveNext = rejectNext = null; + fail(reject, error); + } + + function doNext() { + if (state === kDone) { + operations.settled(); + return PromiseResolve(new IterResult(true, undefined)); + } + if (state === kStart) { + try { + iterator = source[SymbolAsyncIterator](); + } catch (error) { + state = kDone; + operations.settled(); + return PromiseReject(error); + } + state = kActive; + signal.addEventListener('abort', onAbort, + { __proto__: null, [kWeakHandler]: self }); + } + const { promise, resolve, reject } = PromiseWithResolvers(); + let next; + try { + signal.throwIfAborted(); + next = PromiseResolve(iterator.next()); + } catch (error) { + fail(reject, error); + return promise; + } + resolveNext = resolve; + rejectNext = reject; + PromisePrototypeThen(next, onResult, onError); + // The signal can abort while iterator.next() runs. + if (signal.aborted) onAbort(); + return promise; + } + + function doReturn(value) { + const result = new IterResult(true, value); + if (state !== kActive) { + state = kDone; + operations.settled(); + return PromiseResolve(result); + } + state = kDone; + signal.removeEventListener('abort', onAbort); + if (typeof iterator.return !== 'function') { + operations.settled(); + return PromiseResolve(result); + } + let closed; + try { + closed = PromiseResolve(iterator.return()); + } catch (error) { + operations.settled(); + return PromiseReject(error); + } + return PromisePrototypeThen(closed, () => { + operations.settled(); + return result; + }, (error) => { + operations.settled(); + throw error; + }); + } + + function doThrow(error) { + if (state !== kActive) { + state = kDone; + operations.settled(); + return PromiseReject(error); + } + const { promise, reject } = PromiseWithResolvers(); + fail(reject, error); + return promise; + } + + return self; +} + /** * Compute the minimum cursor across a set of consumers and count how many * consumers are at that cursor. diff --git a/test/parallel/test-stream-iter-pipeto-signal.js b/test/parallel/test-stream-iter-pipeto-signal.js index be04c8c635d..3645db1a92f 100644 --- a/test/parallel/test-stream-iter-pipeto-signal.js +++ b/test/parallel/test-stream-iter-pipeto-signal.js @@ -7,7 +7,8 @@ const common = require('../common'); const assert = require('assert'); const { setTimeout } = require('timers/promises'); -const { pipeTo, from } = require('stream/iter'); +const { getEventListeners } = require('events'); +const { bytes, pipeTo, from } = require('stream/iter'); async function testPipeToPreAbortedSignalFailsWriter() { const reason = new Error('already aborted'); @@ -160,6 +161,57 @@ async function testPipeToLiveSignalWithTransformsCompletes() { assert.ok(written.length > 0); } +async function testSignalAbortedWhileReadingSource() { + // The signal can abort while the source is producing a value; the read + // must still reject with the abort reason, and the source be closed, even + // if the value never comes. + for (const consume of [ + (source, signal) => pipeTo(source, { write() {} }, { signal }), + (source, signal) => bytes(source, { signal }), + ]) { + const ac = new AbortController(); + const reason = new Error('aborted while reading'); + let closed = false; + const source = { + [Symbol.asyncIterator]() { + return { + next() { + ac.abort(reason); + return new Promise(() => {}); + }, + async return() { + closed = true; + return { done: true }; + }, + }; + }, + }; + await assert.rejects(consume(source, ac.signal), reason); + assert.strictEqual(closed, true); + } +} + +async function testSignalListenersRemoved() { + // No abort listener is left on the signal once reading completes, fails + // or is aborted. + const ac = new AbortController(); + await pipeTo(from('abc'), { write() {} }, { signal: ac.signal }); + await bytes(from('abc'), { signal: ac.signal }); + await assert.rejects(bytes((async function*() { + yield 'a'; + throw new Error('source failed'); + })(), { signal: ac.signal }), /source failed/); + assert.strictEqual(getEventListeners(ac.signal, 'abort').length, 0); + + const aborting = new AbortController(); + await assert.rejects(bytes((async function*() { + yield 'a'; + aborting.abort(); + yield 'b'; + })(), { signal: aborting.signal }), { name: 'AbortError' }); + assert.strictEqual(getEventListeners(aborting.signal, 'abort').length, 0); +} + Promise.all([ testPipeToPreAbortedSignalFailsWriter(), testPipeToPreAbortedSignalPreventFail(), @@ -168,4 +220,6 @@ Promise.all([ testPipeToLiveSignalWithTransforms(), testPipeToLiveSignalCompletes(), testPipeToLiveSignalWithTransformsCompletes(), + testSignalAbortedWhileReadingSource(), + testSignalListenersRemoved(), ]).then(common.mustCall());