Skip to content

Commit 09dbcd0

Browse files
jasnelladuh95
authored andcommitted
stream: keep stream/iter pipeTo() fast paths with a signal
Without transforms, pipeTo() with a signal read its source through an abortable iterator, which adds a promise, a reaction and an iterator result to every batch, and gave up reading sync sources synchronously. Every write(), writev() and end() was passed a new options object. Instead, read the source as without a signal, synchronously when possible, checking between batches whether the signal has aborted, and race the whole pipe once with the abort: one listener and one promise for the pipe. When the signal aborts, the pipe rejects at once with the abort reason, after calling the source's return() without waiting for it, as a pull() pipeline with the signal rejects its pending pull, and no other batch is read or written. Async sources are read with next(), which return() can cancel while it is pending. Pass the same options object to every write(), writev() and end(). This departs from the specification, where WriteOptions is a dictionary, converted to a new object for every call. For 16-byte chunks one per batch, piping a sync generator with a signal is about 3.9 times faster, as fast as without one, and piping an async generator with a signal about 1.55 times faster. 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 e447e75 commit 09dbcd0

3 files changed

Lines changed: 178 additions & 19 deletions

File tree

‎doc/api/stream_iter.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -674,7 +674,9 @@ added:
674674
* `writer` {Object} Destination with `write(chunk)` method.
675675
* `options` {Object}
676676
* `signal` {AbortSignal} Abort the pipeline. Aborting fails the destination
677-
writer unless `preventFail` is `true`.
677+
writer unless `preventFail` is `true`. The signal is passed to the
678+
writer's `write()`, `writev()` and `end()` in an options object, the same
679+
object for every call.
678680
* `preventClose` {boolean} If `true`, do not call `writer.end()` when
679681
the source ends. **Default:** `false`.
680682
* `preventFail` {boolean} If `true`, do not call `writer.fail()` on

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

Lines changed: 94 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,6 @@ const {
7373
toUint8Array,
7474
validateBatchEntry,
7575
validateByteView,
76-
yieldAbortable,
7776
} = require('internal/streams/iter/utils');
7877
const {
7978
converters,
@@ -1737,6 +1736,11 @@ async function pipeTo(source, ...args) {
17371736

17381737
const hasWriteSync = typeof writer.writeSync === 'function';
17391738
const normalized = from(source);
1739+
// The options passed to every write(), writev() and end().
1740+
const writeOptions = signal ? { __proto__: null, signal } : undefined;
1741+
// Without transforms, whether `signal` has aborted the pipe: the batches
1742+
// are then no longer read or written (see raceSignal()).
1743+
let signalAborted = false;
17401744

17411745
let totalBytes = 0;
17421746
const hasWritev = typeof writer.writev === 'function';
@@ -1757,9 +1761,7 @@ async function pipeTo(source, ...args) {
17571761
}
17581762
validateByteView(view);
17591763
}
1760-
const result = writer.write(
1761-
validateByteView(view),
1762-
signal ? { __proto__: null, signal } : undefined);
1764+
const result = writer.write(validateByteView(view), writeOptions);
17631765
if (result !== undefined) {
17641766
await result;
17651767
}
@@ -1792,10 +1794,11 @@ async function pipeTo(source, ...args) {
17921794
// ignoring errors closing it.
17931795
async function pipeSyncSource(iterator) {
17941796
for (;;) {
1797+
if (signalAborted) return;
17951798
let batch = iterator[kNextSyncBatch]();
17961799
if (batch === undefined) {
17971800
const result = await iterator.next();
1798-
if (result.done) return;
1801+
if (result.done || signalAborted) return;
17991802
batch = result.value;
18001803
} else if (batch === null) {
18011804
return;
@@ -1804,16 +1807,87 @@ async function pipeTo(source, ...args) {
18041807
const p = writeBatch(batch);
18051808
if (p) await p;
18061809
} catch (error) {
1807-
try {
1808-
await iterator.return();
1809-
} catch {
1810-
// The error writing the batch is thrown.
1810+
if (!signalAborted) {
1811+
try {
1812+
await iterator.return();
1813+
} catch {
1814+
// The error writing the batch is thrown.
1815+
}
1816+
}
1817+
throw error;
1818+
}
1819+
}
1820+
}
1821+
1822+
// Write the batches of a source read with next(), as the for await...of
1823+
// loop below does, stopping once `signal` aborts.
1824+
async function pipeSourceWithSignal(iterator) {
1825+
for (;;) {
1826+
const result = await iterator.next();
1827+
if (result.done || signalAborted) return;
1828+
try {
1829+
const p = writeBatch(result.value);
1830+
if (p) await p;
1831+
} catch (error) {
1832+
if (!signalAborted) {
1833+
try {
1834+
await iterator.return();
1835+
} catch {
1836+
// The error writing the batch is thrown.
1837+
}
18111838
}
18121839
throw error;
18131840
}
18141841
}
18151842
}
18161843

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+
18171891
// Write the batches of an async source as the for await...of loop below
18181892
// does. Nothing cancels the normalization while a batch is read: return()
18191893
// is only called after an error writing one.
@@ -1856,8 +1930,8 @@ async function pipeTo(source, ...args) {
18561930
if (!hasWritevSync ||
18571931
!writer.writevSync(validateBatchEntry(entry))) {
18581932
validateBatchEntry(entry);
1859-
const opts = signal ? { __proto__: null, signal } : undefined;
1860-
const writevResult = writer.writev(validateBatchEntry(entry), opts);
1933+
const writevResult = writer.writev(
1934+
validateBatchEntry(entry), writeOptions);
18611935
if (writevResult === undefined) {
18621936
validateBatchEntry(entry);
18631937
totalBytes += entry.byteLength;
@@ -1889,11 +1963,12 @@ async function pipeTo(source, ...args) {
18891963
if (transforms.length === 0) {
18901964
// Fast path: no transforms - iterate normalized source directly
18911965
if (signal) {
1892-
for await (const batch of yieldAbortable(normalized, signal)) {
1893-
signal.throwIfAborted();
1894-
const p = writeBatch(batch);
1895-
if (p) await p;
1896-
}
1966+
// Batches are read synchronously when possible, as without a signal.
1967+
// Async reads go through next(), which return() can cancel while it
1968+
// is pending, unlike kNextUncancellable.
1969+
const iterator = normalized[SymbolAsyncIterator]();
1970+
await raceSignal(iterator, iterator[kNextSyncBatch] !== undefined ?
1971+
pipeSyncSource : pipeSourceWithSignal);
18971972
} else if (normalized[kNextSyncBatch] !== undefined) {
18981973
await pipeSyncSource(normalized);
18991974
} else if (normalized[kNextUncancellable] !== undefined) {
@@ -1909,8 +1984,9 @@ async function pipeTo(source, ...args) {
19091984
normalized, transforms, signal, signal !== undefined);
19101985

19111986
if (signal) {
1987+
// The pipeline rejects its pending pull when `signal` aborts.
19121988
for await (const batch of pipeline) {
1913-
signal.throwIfAborted();
1989+
if (signal.aborted) throw signal.reason;
19141990
const p = writeBatch(batch);
19151991
if (p) await p;
19161992
}
@@ -1924,7 +2000,7 @@ async function pipeTo(source, ...args) {
19242000

19252001
if (!options.preventClose) {
19262002
if (!hasEndSync || writer.endSync() < 0) {
1927-
await writer.end?.(signal ? { __proto__: null, signal } : undefined);
2003+
await writer.end?.(writeOptions);
19282004
}
19292005
}
19302006
} catch (error) {

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

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,84 @@ async function testSignalAbortedWhileReadingSource() {
195195
}
196196
}
197197

198+
// write(), writev() and end() are all passed the same options object.
199+
async function testWriteOptionsShared() {
200+
const ac = new AbortController();
201+
const seen = [];
202+
const writer = {
203+
async write(chunk, options) { seen.push(options); },
204+
async writev(chunks, options) { seen.push(options); },
205+
async end(options) { seen.push(options); },
206+
};
207+
async function* source() {
208+
yield [new Uint8Array([1])];
209+
yield [new Uint8Array([2]), new Uint8Array([3])];
210+
yield [new Uint8Array([4])];
211+
}
212+
await pipeTo(source(), writer, { signal: ac.signal });
213+
assert.strictEqual(seen.length, 4);
214+
assert.strictEqual(new Set(seen).size, 1);
215+
assert.strictEqual(seen[0].signal, ac.signal);
216+
}
217+
218+
// The signal aborting while a chunk is written synchronously stops the pipe:
219+
// no other chunk is written, the source is closed, and the pipe rejects with
220+
// the abort reason.
221+
async function testAbortDuringWriteSync() {
222+
for (const sync of [true, false]) {
223+
const ac = new AbortController();
224+
const reason = new Error('abort in writeSync');
225+
const written = [];
226+
let closed = false;
227+
function* syncSource() {
228+
try {
229+
for (let i = 0; i < 5; i++) yield [new Uint8Array([i])];
230+
} finally {
231+
closed = true;
232+
}
233+
}
234+
235+
async function* asyncSource() {
236+
try {
237+
for (let i = 0; i < 5; i++) yield [new Uint8Array([i])];
238+
} finally {
239+
closed = true;
240+
}
241+
}
242+
const writer = {
243+
write: common.mustNotCall(),
244+
writeSync(chunk) {
245+
written.push(chunk[0]);
246+
if (chunk[0] === 1) ac.abort(reason);
247+
return true;
248+
},
249+
fail: common.mustCall((error) => assert.strictEqual(error, reason)),
250+
};
251+
await assert.rejects(
252+
pipeTo(sync ? syncSource() : asyncSource(), writer,
253+
{ signal: ac.signal }),
254+
reason);
255+
assert.deepStrictEqual(written, [0, 1]);
256+
await setTimeout(1);
257+
assert.strictEqual(closed, true);
258+
}
259+
}
260+
261+
// The signal aborting while a write is pending rejects the pipe at once,
262+
// even if the write never completes.
263+
async function testAbortWhileWritePending() {
264+
const ac = new AbortController();
265+
const reason = new Error('abort while writing');
266+
const writer = {
267+
write() {
268+
ac.abort(reason);
269+
return new Promise(() => {});
270+
},
271+
};
272+
await assert.rejects(pipeTo(from('a'), writer, { signal: ac.signal }),
273+
reason);
274+
}
275+
198276
async function testSignalListenersRemoved() {
199277
// No abort listener is left on the signal once reading completes, fails
200278
// or is aborted.
@@ -226,4 +304,7 @@ Promise.all([
226304
testPipeToLiveSignalWithTransformsCompletes(),
227305
testSignalAbortedWhileReadingSource(),
228306
testSignalListenersRemoved(),
307+
testWriteOptionsShared(),
308+
testAbortDuringWriteSync(),
309+
testAbortWhileWritePending(),
229310
]).then(common.mustCall());

0 commit comments

Comments
 (0)