Skip to content

Commit 35af1d5

Browse files
jasnelladuh95
authored andcommitted
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 <jasnell@gmail.com> PR-URL: #66504 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
1 parent d7786f1 commit 35af1d5

2 files changed

Lines changed: 249 additions & 61 deletions

File tree

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

Lines changed: 194 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,11 @@ const {
1111
FunctionPrototypeCall,
1212
ObjectDefineProperty,
1313
ObjectFreeze,
14+
ObjectSetPrototypeOf,
1415
PromisePrototypeThen,
16+
PromiseReject,
1517
PromiseResolve,
1618
PromiseWithResolvers,
17-
SafePromisePrototypeFinally,
18-
SafePromiseRace,
1919
SafeWeakSet,
2020
SymbolAsyncIterator,
2121
TypedArrayPrototypeGetBuffer,
@@ -38,6 +38,7 @@ const {
3838
} = require('internal/errors');
3939

4040
const { isSharedArrayBuffer, isUint8Array } = require('internal/util/types');
41+
const { kWeakHandler } = require('internal/event_target');
4142

4243
const {
4344
validateInteger,
@@ -110,36 +111,6 @@ function onSignalAbort(signal, handler) {
110111
}
111112
}
112113

113-
function getOnAbort(reject, signal) {
114-
return () => reject(signal.reason);
115-
}
116-
117-
/**
118-
* Read one item from an async iterator, rejecting early if the signal aborts.
119-
* @param {AsyncIterator} iterator - The iterator to read from.
120-
* @param {AbortSignal|undefined} signal - Optional abort signal.
121-
* @returns {Promise<IteratorResult<Uint8Array[]>>|IteratorResult<Uint8Array[]>}
122-
*/
123-
function abortableNext(iterator, signal) {
124-
if (signal === undefined) {
125-
return iterator.next();
126-
}
127-
128-
signal.throwIfAborted();
129-
130-
const next = iterator.next();
131-
const { promise, reject } = PromiseWithResolvers();
132-
const onAbort = getOnAbort(reject, signal);
133-
signal.addEventListener('abort', onAbort, kNullOnceOption);
134-
if (signal.aborted) {
135-
onAbort();
136-
}
137-
138-
return SafePromisePrototypeFinally(SafePromiseRace([next, promise]), () => {
139-
signal.removeEventListener('abort', onAbort);
140-
});
141-
}
142-
143114
/**
144115
* Wrap an async source so each pending read is abort-aware.
145116
* @param {AsyncIterable<Uint8Array[]>} source - The source to read from.
@@ -153,39 +124,202 @@ function yieldAbortable(source, signal) {
153124

154125
return {
155126
__proto__: null,
156-
async *[SymbolAsyncIterator]() {
157-
const iterator = source[SymbolAsyncIterator]();
158-
let completed = false;
159-
let aborted = false;
127+
[SymbolAsyncIterator]() {
128+
return createAbortableIterator(source, signal);
129+
},
130+
};
131+
}
160132

133+
/**
134+
* Iterator reading `source` until `signal` aborts, for yieldAbortable().
135+
*
136+
* This is what an async generator looping over the source with
137+
* abortableNext() would do, written out by hand: that costs an abort
138+
* listener, a promise race and an async generator layer for every value.
139+
* Instead, a single abort listener is added for the whole iteration, held
140+
* weakly so that the signal does not keep the iterator alive, and each
141+
* next() waits with a single promise that an abort rejects. As with the
142+
* generator:
143+
* - the source is opened by the first next(), and calls made while one is in
144+
* progress are queued;
145+
* - an abort before or while reading a value, or once it has been read,
146+
* rejects with the abort reason;
147+
* - unless the source has ended, an error (including an abort) closes it:
148+
* if the signal is aborted, without waiting, otherwise waiting and
149+
* rejecting with an error from closing it instead;
150+
* - return() closes the source, propagating errors from closing it.
151+
* @param {AsyncIterable} source
152+
* @param {AbortSignal} signal
153+
* @returns {AsyncIterator}
154+
*/
155+
function createAbortableIterator(source, signal) {
156+
let state = kStart;
157+
let iterator;
158+
let completed = false;
159+
// The settling functions of the pending next(), if any.
160+
let resolveNext = null;
161+
let rejectNext = null;
162+
const operations = createOperationQueue();
163+
164+
const self = ObjectSetPrototypeOf({
165+
next() { return operations.run(doNext); },
166+
return(value) { return operations.run(doReturn, value); },
167+
throw(error) { return operations.run(doThrow, error); },
168+
[SymbolAsyncIterator]() { return this; },
169+
}, null);
170+
171+
function onAbort() {
172+
if (rejectNext === null) return;
173+
const reject = rejectNext;
174+
resolveNext = rejectNext = null;
175+
fail(reject, signal.reason);
176+
}
177+
178+
// What the generator did in its `catch` and `finally` blocks for `error`.
179+
function fail(reject, error) {
180+
state = kDone;
181+
signal.removeEventListener('abort', onAbort);
182+
const aborted = signal.aborted;
183+
if (!completed && typeof iterator.return === 'function') {
184+
let closed;
161185
try {
162-
while (true) {
163-
const { done, value } = await abortableNext(iterator, signal);
164-
if (done) {
165-
completed = true;
166-
return;
167-
}
168-
signal.throwIfAborted();
169-
yield value;
186+
const result = iterator.return();
187+
if (aborted) {
188+
// PromiseResolve(result) can reject if result is a thenable that
189+
// rejects, so mark it as handled even though the abort takes
190+
// precedence over the result of iterator.return().
191+
markPromiseAsHandled(PromiseResolve(result));
192+
} else {
193+
closed = PromiseResolve(result);
170194
}
195+
} catch (closeError) {
196+
operations.settled();
197+
reject(closeError);
198+
return;
199+
}
200+
if (closed !== undefined) {
201+
PromisePrototypeThen(closed, () => {
202+
operations.settled();
203+
reject(error);
204+
}, (closeError) => {
205+
operations.settled();
206+
reject(closeError);
207+
});
208+
return;
209+
}
210+
}
211+
operations.settled();
212+
reject(error);
213+
}
214+
215+
function onResult(result) {
216+
if (resolveNext === null) return; // Settled by an abort.
217+
const resolve = resolveNext;
218+
const reject = rejectNext;
219+
resolveNext = rejectNext = null;
220+
let done;
221+
let value;
222+
try {
223+
({ done, value } = result);
224+
if (!done) signal.throwIfAborted();
225+
} catch (error) {
226+
fail(reject, error);
227+
return;
228+
}
229+
if (done) {
230+
completed = true;
231+
state = kDone;
232+
signal.removeEventListener('abort', onAbort);
233+
operations.settled();
234+
resolve(new IterResult(true, undefined));
235+
return;
236+
}
237+
operations.settled();
238+
resolve(new IterResult(false, value));
239+
}
240+
241+
function onError(error) {
242+
if (rejectNext === null) return; // Settled by an abort.
243+
const reject = rejectNext;
244+
resolveNext = rejectNext = null;
245+
fail(reject, error);
246+
}
247+
248+
function doNext() {
249+
if (state === kDone) {
250+
operations.settled();
251+
return PromiseResolve(new IterResult(true, undefined));
252+
}
253+
if (state === kStart) {
254+
try {
255+
iterator = source[SymbolAsyncIterator]();
171256
} catch (error) {
172-
aborted = signal.aborted;
173-
throw error;
174-
} finally {
175-
if (!completed && typeof iterator.return === 'function') {
176-
const result = iterator.return();
177-
if (aborted) {
178-
// PromiseResolve(result) can reject if result is a thenable that
179-
// rejects, so mark it as handled even though the abort takes
180-
// precedence over the result of iterator.return().
181-
markPromiseAsHandled(PromiseResolve(result));
182-
} else {
183-
await result;
184-
}
185-
}
257+
state = kDone;
258+
operations.settled();
259+
return PromiseReject(error);
186260
}
187-
},
188-
};
261+
state = kActive;
262+
signal.addEventListener('abort', onAbort,
263+
{ __proto__: null, [kWeakHandler]: self });
264+
}
265+
const { promise, resolve, reject } = PromiseWithResolvers();
266+
let next;
267+
try {
268+
signal.throwIfAborted();
269+
next = PromiseResolve(iterator.next());
270+
} catch (error) {
271+
fail(reject, error);
272+
return promise;
273+
}
274+
resolveNext = resolve;
275+
rejectNext = reject;
276+
PromisePrototypeThen(next, onResult, onError);
277+
// The signal can abort while iterator.next() runs.
278+
if (signal.aborted) onAbort();
279+
return promise;
280+
}
281+
282+
function doReturn(value) {
283+
const result = new IterResult(true, value);
284+
if (state !== kActive) {
285+
state = kDone;
286+
operations.settled();
287+
return PromiseResolve(result);
288+
}
289+
state = kDone;
290+
signal.removeEventListener('abort', onAbort);
291+
if (typeof iterator.return !== 'function') {
292+
operations.settled();
293+
return PromiseResolve(result);
294+
}
295+
let closed;
296+
try {
297+
closed = PromiseResolve(iterator.return());
298+
} catch (error) {
299+
operations.settled();
300+
return PromiseReject(error);
301+
}
302+
return PromisePrototypeThen(closed, () => {
303+
operations.settled();
304+
return result;
305+
}, (error) => {
306+
operations.settled();
307+
throw error;
308+
});
309+
}
310+
311+
function doThrow(error) {
312+
if (state !== kActive) {
313+
state = kDone;
314+
operations.settled();
315+
return PromiseReject(error);
316+
}
317+
const { promise, reject } = PromiseWithResolvers();
318+
fail(reject, error);
319+
return promise;
320+
}
321+
322+
return self;
189323
}
190324

191325
/**

‎test/parallel/test-stream-iter-pipeto-signal.js‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
const common = require('../common');
88
const assert = require('assert');
99
const { setTimeout } = require('timers/promises');
10-
const { pipeTo, from } = require('stream/iter');
10+
const { getEventListeners } = require('events');
11+
const { bytes, pipeTo, from } = require('stream/iter');
1112

1213
async function testPipeToPreAbortedSignalFailsWriter() {
1314
const reason = new Error('already aborted');
@@ -160,6 +161,57 @@ async function testPipeToLiveSignalWithTransformsCompletes() {
160161
assert.ok(written.length > 0);
161162
}
162163

164+
async function testSignalAbortedWhileReadingSource() {
165+
// The signal can abort while the source is producing a value; the read
166+
// must still reject with the abort reason, and the source be closed, even
167+
// if the value never comes.
168+
for (const consume of [
169+
(source, signal) => pipeTo(source, { write() {} }, { signal }),
170+
(source, signal) => bytes(source, { signal }),
171+
]) {
172+
const ac = new AbortController();
173+
const reason = new Error('aborted while reading');
174+
let closed = false;
175+
const source = {
176+
[Symbol.asyncIterator]() {
177+
return {
178+
next() {
179+
ac.abort(reason);
180+
return new Promise(() => {});
181+
},
182+
async return() {
183+
closed = true;
184+
return { done: true };
185+
},
186+
};
187+
},
188+
};
189+
await assert.rejects(consume(source, ac.signal), reason);
190+
assert.strictEqual(closed, true);
191+
}
192+
}
193+
194+
async function testSignalListenersRemoved() {
195+
// No abort listener is left on the signal once reading completes, fails
196+
// or is aborted.
197+
const ac = new AbortController();
198+
await pipeTo(from('abc'), { write() {} }, { signal: ac.signal });
199+
await bytes(from('abc'), { signal: ac.signal });
200+
await assert.rejects(bytes((async function*() {
201+
yield 'a';
202+
throw new Error('source failed');
203+
})(), { signal: ac.signal }), /source failed/);
204+
assert.strictEqual(getEventListeners(ac.signal, 'abort').length, 0);
205+
206+
const aborting = new AbortController();
207+
await assert.rejects(bytes((async function*() {
208+
yield 'a';
209+
aborting.abort();
210+
yield 'b';
211+
})(), { signal: aborting.signal }), { name: 'AbortError' });
212+
assert.strictEqual(getEventListeners(aborting.signal, 'abort').length, 0);
213+
}
214+
163215
Promise.all([
164216
testPipeToPreAbortedSignalFailsWriter(),
165217
testPipeToPreAbortedSignalPreventFail(),
@@ -168,4 +220,6 @@ Promise.all([
168220
testPipeToLiveSignalWithTransforms(),
169221
testPipeToLiveSignalCompletes(),
170222
testPipeToLiveSignalWithTransformsCompletes(),
223+
testSignalAbortedWhileReadingSource(),
224+
testSignalListenersRemoved(),
171225
]).then(common.mustCall());

0 commit comments

Comments
 (0)