Skip to content

Commit 1ca7ec5

Browse files
jasnelladuh95
authored andcommitted
stream: read stream/iter consumer sources without a layer per signal
bytes(), text(), arrayBuffer() and array() with a signal read their source through an abortable iterator, which adds a promise, a reaction and an iterator result to every batch. Read the source as for await...of does, checking between batches whether the signal has aborted, and race the whole read once with the abort, as pipeTo() does without transforms: move that race to raceSignal() in utils.js and use it for both. When the signal aborts, the consumer rejects at once with the abort reason, after calling the source's return() without waiting for it, and the source is not read further. For 16-byte chunks one per batch, array() of a sync generator with a signal is about 1.9 times faster, and of an async generator about 1.35 times faster: about as fast as without a signal. 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 09dbcd0 commit 1ca7ec5

4 files changed

Lines changed: 122 additions & 59 deletions

File tree

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

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ const {
5858
kNullOnceOption,
5959
concatBytes,
6060
getProtocolMethod,
61+
raceSignal,
6162
recordChunk,
6263
validateRecordedChunks,
6364
yieldAbortable,
@@ -150,10 +151,7 @@ async function collectAsync(source, signal, limit) {
150151

151152
// Slow path: with signal or limit checks
152153
let totalBytes = 0;
153-
const iterable = signal ? yieldAbortable(normalized, signal) : normalized;
154-
155-
for await (const batch of iterable) {
156-
signal?.throwIfAborted();
154+
function recordBatch(batch) {
157155
for (let i = 0; i < batch.length; i++) {
158156
totalBytes += recordChunk(chunks, checks, batch[i]);
159157
if (limit !== undefined && totalBytes > limit) {
@@ -162,6 +160,33 @@ async function collectAsync(source, signal, limit) {
162160
}
163161
}
164162

163+
if (!signal) {
164+
for await (const batch of normalized) recordBatch(batch);
165+
return validateRecordedChunks(chunks, checks);
166+
}
167+
168+
// Read as for await...of does, stopping once the signal aborts; see
169+
// raceSignal().
170+
const state = { __proto__: null, aborted: false };
171+
async function consume(iterator) {
172+
for (;;) {
173+
const result = await iterator.next();
174+
if (result.done || state.aborted) return;
175+
try {
176+
recordBatch(result.value);
177+
} catch (error) {
178+
// As for await closes the source when its body throws, ignoring
179+
// errors from closing it.
180+
try {
181+
await iterator.return?.();
182+
} catch {
183+
// The error recording the batch is thrown.
184+
}
185+
throw error;
186+
}
187+
}
188+
}
189+
await raceSignal(normalized[SymbolAsyncIterator](), signal, state, consume);
165190
return validateRecordedChunks(chunks, checks);
166191
}
167192

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

Lines changed: 10 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ const {
6868
fixedBatchToEntry,
6969
isTransformObject,
7070
parsePullArgs,
71+
raceSignal,
7172
snapshotFixedBatch,
7273
snapshotTransform,
7374
toUint8Array,
@@ -1740,7 +1741,7 @@ async function pipeTo(source, ...args) {
17401741
const writeOptions = signal ? { __proto__: null, signal } : undefined;
17411742
// Without transforms, whether `signal` has aborted the pipe: the batches
17421743
// are then no longer read or written (see raceSignal()).
1743-
let signalAborted = false;
1744+
const abortState = { __proto__: null, aborted: false };
17441745

17451746
let totalBytes = 0;
17461747
const hasWritev = typeof writer.writev === 'function';
@@ -1794,11 +1795,11 @@ async function pipeTo(source, ...args) {
17941795
// ignoring errors closing it.
17951796
async function pipeSyncSource(iterator) {
17961797
for (;;) {
1797-
if (signalAborted) return;
1798+
if (abortState.aborted) return;
17981799
let batch = iterator[kNextSyncBatch]();
17991800
if (batch === undefined) {
18001801
const result = await iterator.next();
1801-
if (result.done || signalAborted) return;
1802+
if (result.done || abortState.aborted) return;
18021803
batch = result.value;
18031804
} else if (batch === null) {
18041805
return;
@@ -1807,7 +1808,7 @@ async function pipeTo(source, ...args) {
18071808
const p = writeBatch(batch);
18081809
if (p) await p;
18091810
} catch (error) {
1810-
if (!signalAborted) {
1811+
if (!abortState.aborted) {
18111812
try {
18121813
await iterator.return();
18131814
} catch {
@@ -1824,12 +1825,12 @@ async function pipeTo(source, ...args) {
18241825
async function pipeSourceWithSignal(iterator) {
18251826
for (;;) {
18261827
const result = await iterator.next();
1827-
if (result.done || signalAborted) return;
1828+
if (result.done || abortState.aborted) return;
18281829
try {
18291830
const p = writeBatch(result.value);
18301831
if (p) await p;
18311832
} catch (error) {
1832-
if (!signalAborted) {
1833+
if (!abortState.aborted) {
18331834
try {
18341835
await iterator.return();
18351836
} catch {
@@ -1841,53 +1842,6 @@ async function pipeTo(source, ...args) {
18411842
}
18421843
}
18431844

1844-
// Wait for `pipe(iterator)` to write the batches of `iterator`, the
1845-
// normalized source, unless `signal` aborts first. On an abort, the source
1846-
// is closed, without waiting, and the abort reason is thrown at once, as a
1847-
// pull() pipeline with `signal` would reject its pending pull; `piped`
1848-
// then stops before reading or writing another batch. This takes one
1849-
// listener and one promise for the whole pipe, instead of a layer reading
1850-
// the source for every batch. The listener is added first, as the signal
1851-
// can abort while the source is read.
1852-
function raceSignal(iterator, pipe) {
1853-
const { promise, resolve, reject } = PromiseWithResolvers();
1854-
let settled = false;
1855-
function closeAndReject() {
1856-
try {
1857-
const returnMethod = iterator.return;
1858-
if (typeof returnMethod === 'function') {
1859-
markPromiseAsHandled(PromiseResolve(
1860-
FunctionPrototypeCall(returnMethod, iterator)));
1861-
}
1862-
} catch {
1863-
// The abort takes precedence over errors closing the source.
1864-
}
1865-
reject(signal.reason);
1866-
}
1867-
1868-
function onAbort() {
1869-
if (settled) return;
1870-
settled = true;
1871-
signalAborted = true;
1872-
// The signal can abort while the source is called: close it once that
1873-
// call has returned.
1874-
PromisePrototypeThen(kResolvedPromise, closeAndReject);
1875-
}
1876-
signal.addEventListener('abort', onAbort, kNullOnceOption);
1877-
PromisePrototypeThen(pipe(iterator), (value) => {
1878-
if (settled) return;
1879-
settled = true;
1880-
signal.removeEventListener('abort', onAbort);
1881-
resolve(value);
1882-
}, (error) => {
1883-
if (settled) return;
1884-
settled = true;
1885-
signal.removeEventListener('abort', onAbort);
1886-
reject(error);
1887-
});
1888-
return promise;
1889-
}
1890-
18911845
// Write the batches of an async source as the for await...of loop below
18921846
// does. Nothing cancels the normalization while a batch is read: return()
18931847
// is only called after an error writing one.
@@ -1967,8 +1921,9 @@ async function pipeTo(source, ...args) {
19671921
// Async reads go through next(), which return() can cancel while it
19681922
// is pending, unlike kNextUncancellable.
19691923
const iterator = normalized[SymbolAsyncIterator]();
1970-
await raceSignal(iterator, iterator[kNextSyncBatch] !== undefined ?
1971-
pipeSyncSource : pipeSourceWithSignal);
1924+
await raceSignal(iterator, signal, abortState,
1925+
iterator[kNextSyncBatch] !== undefined ?
1926+
pipeSyncSource : pipeSourceWithSignal);
19721927
} else if (normalized[kNextSyncBatch] !== undefined) {
19731928
await pipeSyncSource(normalized);
19741929
} else if (normalized[kNextUncancellable] !== undefined) {

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

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,67 @@ class PipelineAbort {
158158
}
159159
}
160160

161+
/**
162+
* Wait for `consume(iterator)`, which reads `iterator` (a normalized source)
163+
* to the end, unless `signal` aborts first. On an abort, `state.aborted` is
164+
* set, the source is closed without waiting, ignoring errors, and the
165+
* returned promise rejects with the abort reason at once, as a pull()
166+
* pipeline with `signal` would reject its pending pull; `consume` must check
167+
* `state.aborted` after each read and stop. Closing and rejecting wait for a
168+
* microtask, as the signal can abort while the source is called.
169+
*
170+
* This takes one listener and one promise for the whole read, instead of a
171+
* layer around the source adding a promise to every read.
172+
* @param {AsyncIterator} iterator
173+
* @param {AbortSignal} signal
174+
* @param {{ aborted: boolean }} state
175+
* @param {Function} consume
176+
* @returns {Promise<any>}
177+
*/
178+
function raceSignal(iterator, signal, state, consume) {
179+
const { promise, resolve, reject } = PromiseWithResolvers();
180+
let settled = false;
181+
function closeAndReject() {
182+
try {
183+
const returnMethod = iterator.return;
184+
if (typeof returnMethod === 'function') {
185+
markPromiseAsHandled(PromiseResolve(
186+
FunctionPrototypeCall(returnMethod, iterator)));
187+
}
188+
} catch {
189+
// The abort takes precedence over errors closing the source.
190+
}
191+
reject(signal.reason);
192+
}
193+
194+
function onAbort() {
195+
if (settled) return;
196+
settled = true;
197+
state.aborted = true;
198+
PromisePrototypeThen(kResolvedPromise, closeAndReject);
199+
}
200+
// Added first, as the signal can abort while the source is read.
201+
signal.addEventListener('abort', onAbort, kNullOnceOption);
202+
let consumed;
203+
try {
204+
consumed = consume(iterator);
205+
} catch (error) {
206+
consumed = PromiseReject(error);
207+
}
208+
PromisePrototypeThen(consumed, (value) => {
209+
if (settled) return;
210+
settled = true;
211+
signal.removeEventListener('abort', onAbort);
212+
resolve(value);
213+
}, (error) => {
214+
if (settled) return;
215+
settled = true;
216+
signal.removeEventListener('abort', onAbort);
217+
reject(error);
218+
});
219+
return promise;
220+
}
221+
161222
/**
162223
* Wrap an async source so each pending read is abort-aware.
163224
* @param {AsyncIterable<Uint8Array[]>} source - The source to read from.
@@ -1013,6 +1074,7 @@ module.exports = {
10131074
isTransformObject,
10141075
onSignalAbort,
10151076
parsePullArgs,
1077+
raceSignal,
10161078
snapshotTransform,
10171079
toUint8Array,
10181080
toWriterUint8Array,

‎test/parallel/test-stream-iter-consumers-bytes.js‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
const common = require('../common');
55
const assert = require('assert');
6+
const { getEventListeners } = require('events');
67
const {
78
from,
89
fromSync,
@@ -272,7 +273,27 @@ async function testTextStringSource() {
272273
assert.strictEqual(result, 'direct-string');
273274
}
274275

276+
// With a signal, exceeding the limit closes the source, rejects with the
277+
// limit error, and leaves no listener on the signal.
278+
async function testBytesSignalAndLimit() {
279+
const ac = new AbortController();
280+
let closed = false;
281+
async function* source() {
282+
try {
283+
for (;;) yield [new Uint8Array(8)];
284+
} finally {
285+
closed = true;
286+
}
287+
}
288+
await assert.rejects(
289+
bytes(source(), { signal: ac.signal, limit: 20 }),
290+
{ code: 'ERR_OUT_OF_RANGE' });
291+
assert.strictEqual(closed, true);
292+
assert.strictEqual(getEventListeners(ac.signal, 'abort').length, 0);
293+
}
294+
275295
Promise.all([
296+
testBytesSignalAndLimit(),
276297
testBytesSyncBasic(),
277298
testBytesSyncLimit(),
278299
testBytesAsync(),

0 commit comments

Comments
 (0)