From d41b0d10870cea8d57d325f4596bc59571cc53ee Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 17:12:00 +0000 Subject: [PATCH 01/26] stream: call stateless iter transforms without this Stateless transforms in fused runs were called as run[i](...), so `this` inside a transform was the internal array of the run. A transform could read or mutate it, for example `this.push(fn)` added a transform to the pipeline while it was running. Call them as plain functions, so `this` is undefined, as the Iterable Streams specification requires. Stateful transforms are still called with the transform object as `this`. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 4 + lib/internal/streams/iter/pull.js | 22 ++-- .../test-stream-iter-transform-this.js | 114 ++++++++++++++++++ 3 files changed, 133 insertions(+), 7 deletions(-) create mode 100644 test/parallel/test-stream-iter-transform-this.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index 03c14e21afa3..3ee1edaa1324 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -148,6 +148,10 @@ Both forms receive an `options` parameter with the following property: can check `signal.aborted` or listen for the `'abort'` event to perform early cleanup. +A stateless transform is called as a plain function, with `this` undefined. +The `transform` method of a stateful transform is called as a method of its +object. + Each transform of a pipeline receives its own `options` object, the same one for every call of a stateless transform, so a transform can modify its `options` without affecting other transforms. The object does not inherit diff --git a/lib/internal/streams/iter/pull.js b/lib/internal/streams/iter/pull.js index 06c204e78c67..697f1c0b93a0 100644 --- a/lib/internal/streams/iter/pull.js +++ b/lib/internal/streams/iter/pull.js @@ -473,7 +473,9 @@ function* applyFusedStatelessSyncTransforms(source, run) { for (const chunks of source) { let current = chunks; for (let i = 0; i < run.length; i++) { - const result = run[i](current); + // Called with `this` undefined, so the run is not exposed. + const fn = run[i]; + const result = fn(current); if (result === null) { current = null; break; @@ -512,10 +514,11 @@ function* applyFusedStatelessSyncTransforms(source, run) { let pending = []; for (let i = 0; i < run.length; i++) { const next = []; + const fn = run[i]; for (let j = 0; j < pending.length; j++) { - appendTransformResultSync(next, run[i](pending[j])); + appendTransformResultSync(next, fn(pending[j])); } - appendTransformResultSync(next, run[i](null)); + appendTransformResultSync(next, fn(null)); pending = next; } for (let i = 0; i < pending.length; i++) { @@ -691,7 +694,10 @@ async function* yieldFusedStatelessOutput(current) { async function* continueFusedStatelessBatch(run, index, result, runOptions) { let current; for (let i = index; i < run.length; i++) { - if (i !== index) result = run[i](current, runOptions[i]); + if (i !== index) { + const fn = run[i]; + result = fn(current, runOptions[i]); + } if (isPromise(result)) result = await result; if (result === null) return; if (i === run.length - 1) { @@ -722,17 +728,18 @@ async function* flushFusedStatelessAsyncTransforms(run, runOptions) { let pending = []; for (let i = 0; i < run.length; i++) { const next = []; + const fn = run[i]; for (let j = 0; j < pending.length; j++) { const pendingResult = appendTransformResultAsync( next, - run[i](pending[j], runOptions[i])); + fn(pending[j], runOptions[i])); if (pendingResult !== undefined) { await pendingResult; } } const flushResult = appendTransformResultAsync( next, - run[i](null, runOptions[i])); + fn(null, runOptions[i])); if (flushResult !== undefined) { await flushResult; } @@ -826,7 +833,8 @@ function applyFusedStatelessAsyncTransforms(source, run, abort) { function applyBatch(chunks) { let current = chunks; for (let i = 0; i < run.length; i++) { - const result = run[i](current, runOptions[i]); + const fn = run[i]; + const result = fn(current, runOptions[i]); if (isPromise(result)) { delegate = continueFusedStatelessBatch(run, i, result, runOptions); return kDelegated; diff --git a/test/parallel/test-stream-iter-transform-this.js b/test/parallel/test-stream-iter-transform-this.js new file mode 100644 index 000000000000..727adae01f51 --- /dev/null +++ b/test/parallel/test-stream-iter-transform-this.js @@ -0,0 +1,114 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// Stateless transforms are called with `this` undefined, so they cannot +// reach (or alter) the internal list of transforms of the pipeline. +// Stateful transforms are called as methods of the transform object. + +const common = require('../common'); +const assert = require('assert'); +const { + from, fromSync, pull, pullSync, push, broadcast, share, shareSync, + text, textSync, +} = require('stream/iter'); + +function strictTransform(chunks) { + assert.strictEqual(this, undefined); + return chunks; +} + +// A sloppy-mode function called with `this` undefined sees globalThis. +// (The functions of this file are strict.) +const sloppyTransform = new Function('chunks', ` + if (this !== globalThis) throw new Error('unexpected this'); + return chunks; +`); + +// A transform that tries to inject another transform through `this`. +function injectingTransform(chunks) { + if (this != null && typeof this.push === 'function') { + this.push(() => [new TextEncoder().encode('INJECTED')]); + } + return chunks; +} + +async function testAsyncPull() { + assert.strictEqual( + await text(pull(from(['a', 'b']), strictTransform, strictTransform)), + 'ab'); + assert.strictEqual( + await text(pull(from('a'), sloppyTransform, sloppyTransform)), 'a'); + assert.strictEqual( + await text(pull(from(['a', 'b']), injectingTransform, strictTransform)), + 'ab'); + // Async results and flushes are called the same way. + const asyncTransform = common.mustCallAtLeast(async function(chunks) { + assert.strictEqual(this, undefined); + return chunks; + }); + assert.strictEqual( + await text(pull(from('xy'), asyncTransform, strictTransform)), 'xy'); +} + +function testSyncPull() { + assert.strictEqual( + textSync(pullSync(fromSync(['a', 'b']), strictTransform, strictTransform)), + 'ab'); + assert.strictEqual( + textSync(pullSync(fromSync('a'), sloppyTransform)), 'a'); + assert.strictEqual( + textSync(pullSync(fromSync(['a', 'b']), injectingTransform, + strictTransform)), + 'ab'); +} + +async function testMultiConsumer() { + { + const { writer, readable } = push(injectingTransform, strictTransform); + writer.writeSync('p'); + writer.endSync(); + assert.strictEqual(await text(readable), 'p'); + } + { + const { writer, broadcast: bc } = broadcast(); + const consumer = bc.push(injectingTransform, strictTransform); + writer.writeSync('b'); + writer.endSync(); + assert.strictEqual(await text(consumer), 'b'); + } + { + const shared = share(from('s')); + assert.strictEqual( + await text(shared.pull(injectingTransform, strictTransform)), 's'); + } + { + const shared = shareSync(fromSync('t')); + assert.strictEqual( + textSync(shared.pull(injectingTransform, strictTransform)), 't'); + } +} + +async function testStatefulReceiver() { + const asyncTransform = { + transform: common.mustCall(async function*(source) { + assert.strictEqual(this, asyncTransform); + yield* source; + }), + }; + assert.strictEqual(await text(pull(from('a'), asyncTransform)), 'a'); + + const syncTransform = { + transform: common.mustCall(function*(source) { + assert.strictEqual(this, syncTransform); + yield* source; + }), + }; + assert.strictEqual(textSync(pullSync(fromSync('a'), syncTransform)), 'a'); +} + +testSyncPull(); +Promise.all([ + testAsyncPull(), + testMultiConsumer(), + testStatefulReceiver(), +]).then(common.mustCall()); From d529649719495fc4ead0c52d9f99677d6ab64ad0 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 17:12:08 +0000 Subject: [PATCH 02/26] stream: enforce the range of iter budget options The budget option of push(), duplex(), broadcast(), share() and shareSync() is an [EnforceRange] unsigned long long, but it was converted without EnforceRange and then validated separately, so negative, non-finite and out of range values threw a RangeError. Convert it with EnforceRange so these throw a TypeError. A budget of 0 is still rejected with a RangeError afterwards. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 3 +- lib/internal/streams/iter/duplex.js | 7 +++- lib/internal/streams/iter/webidl.js | 10 ++--- .../test-stream-iter-duplex-shared-budget.js | 25 +++++++++++++ test/parallel/test-stream-iter-validation.js | 37 ++++++++++++++++--- 5 files changed, 69 insertions(+), 13 deletions(-) create mode 100644 test/parallel/test-stream-iter-duplex-shared-budget.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index 3ee1edaa1324..6c4a1a9cb42a 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -947,7 +947,8 @@ added: * `options` {Object} * `budget` {number} Buffer size in bytes for both directions. - Must be a positive integer. **Default:** `16384`. + Must be a positive integer, even if `a` and `b` both override it. + **Default:** `16384`. * `backpressure` {string} Policy for both directions. **Default:** `'strict'`. * `signal` {AbortSignal} Cancellation signal for both channels. diff --git a/lib/internal/streams/iter/duplex.js b/lib/internal/streams/iter/duplex.js index ce5ccadd060d..aa4dee9babca 100644 --- a/lib/internal/streams/iter/duplex.js +++ b/lib/internal/streams/iter/duplex.js @@ -18,7 +18,10 @@ const { const { converters, } = require('internal/streams/iter/webidl'); -const { kNullOnceOption } = require('internal/streams/iter/utils'); +const { + kNullOnceOption, + validateBudget, +} = require('internal/streams/iter/utils'); /** * Create a pair of connected duplex channels for bidirectional communication. @@ -32,6 +35,8 @@ function duplex(options = { __proto__: null }) { context: 'options', }); const { budget, backpressure, signal, a, b } = options; + // A shared budget is validated even if both directions override it. + if (budget !== undefined) validateBudget(budget); // Channel A writes to B's readable (A->B direction). // Signal is NOT passed to push() -- we handle abort via close() below. diff --git a/lib/internal/streams/iter/webidl.js b/lib/internal/streams/iter/webidl.js index 6ee1afd622a5..79e711a1e64b 100644 --- a/lib/internal/streams/iter/webidl.js +++ b/lib/internal/streams/iter/webidl.js @@ -13,10 +13,6 @@ const { isUint8Array } = require('internal/util/types'); const converters = { __proto__: null }; -function unsignedLongLong(value, options) { - return convertToInt(value, 64, 'unsigned', options); -} - function enforceRangeUnsignedLongLong(value, options = { __proto__: null }) { return convertToInt(value, 64, 'unsigned', { __proto__: null, @@ -34,7 +30,6 @@ converters.BackpressurePolicy = createEnumConverter('BackpressurePolicy', [ 'drop-oldest', 'drop-newest', ]); -converters.unsignedLongLong = unsignedLongLong; converters.enforceRangeUnsignedLongLong = enforceRangeUnsignedLongLong; converters.WriterChunk = (value, options = { __proto__: null }) => { // The chunk is a Uint8Array with [AllowShared] and [AllowResizable]. The @@ -52,10 +47,13 @@ const signalMember = { key: 'signal', converter: converters.AbortSignal, }; +// [EnforceRange] unsigned long long: negative, non-finite, and out of range +// values throw a TypeError here; a budget of 0 is rejected afterwards with +// a RangeError by validateBudget(). const budgetMember = { __proto__: null, key: 'budget', - converter: converters.unsignedLongLong, + converter: converters.enforceRangeUnsignedLongLong, }; const backpressureMember = { __proto__: null, diff --git a/test/parallel/test-stream-iter-duplex-shared-budget.js b/test/parallel/test-stream-iter-duplex-shared-budget.js new file mode 100644 index 000000000000..53c494753d6c --- /dev/null +++ b/test/parallel/test-stream-iter-duplex-shared-budget.js @@ -0,0 +1,25 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// duplex() validates a shared budget even when both directions override it. + +require('../common'); +const assert = require('assert'); +const { duplex } = require('stream/iter'); + +assert.throws(() => duplex({ budget: 0, a: { budget: 1 }, b: { budget: 1 } }), + { name: 'RangeError', code: 'ERR_OUT_OF_RANGE' }); +assert.throws(() => duplex({ budget: 0, a: { budget: 1 } }), + { name: 'RangeError', code: 'ERR_OUT_OF_RANGE' }); +assert.throws(() => duplex({ budget: 0 }), + { name: 'RangeError', code: 'ERR_OUT_OF_RANGE' }); + +assert.throws(() => duplex({ a: { budget: 0 } }), + { name: 'RangeError', code: 'ERR_OUT_OF_RANGE' }); +assert.throws(() => duplex({ budget: 1, b: { budget: 0 } }), + { name: 'RangeError', code: 'ERR_OUT_OF_RANGE' }); + +// Valid budgets are accepted. +assert.strictEqual( + duplex({ budget: 1, a: { budget: 2 }, b: { budget: 3 } }).length, 2); +assert.strictEqual(duplex({ a: { budget: 2 } }).length, 2); diff --git a/test/parallel/test-stream-iter-validation.js b/test/parallel/test-stream-iter-validation.js index 16ff12c060e7..59cb4fcdb7ab 100644 --- a/test/parallel/test-stream-iter-validation.js +++ b/test/parallel/test-stream-iter-validation.js @@ -22,7 +22,7 @@ const { // ============================================================================= // Budget must be an integer >= 1 -assert.throws(() => push({ budget: 'bad' }), { code: 'ERR_OUT_OF_RANGE' }); +assert.throws(() => push({ budget: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' }); // WebIDL conversion truncates fractions: 0.5 becomes 0, 1.5 becomes 1. assert.throws(() => push({ budget: 0.5 }), { code: 'ERR_OUT_OF_RANGE' }); assert.strictEqual(push({ budget: 1.5 }).writer.canWrite, true); @@ -41,6 +41,33 @@ assert.strictEqual(push({ budget: Number.MAX_SAFE_INTEGER }).writer.canWrite, assert.throws(() => push({ budget: Number.MAX_SAFE_INTEGER + 1 }), { code: 'ERR_OUT_OF_RANGE' }); +// The budget is an [EnforceRange] unsigned long long: negative, non-finite and +// out of range values throw a TypeError. A budget of 0 is a RangeError. +{ + const factories = [ + ['push', (options) => push(options)], + ['duplex', (options) => duplex(options)], + ['duplex a', (options) => duplex({ a: options })], + ['duplex b', (options) => duplex({ b: options })], + ['broadcast', (options) => broadcast(options)], + ['share', (options) => share(from('a'), options)], + ['shareSync', (options) => shareSync(fromSync('a'), options)], + ]; + for (const [name, factory] of factories) { + for (const budget of [-1, -0.5 - 1, Infinity, -Infinity, NaN, 2 ** 60, + Number.MAX_SAFE_INTEGER + 1]) { + assert.throws(() => factory({ budget }), { name: 'TypeError' }, + `${name} budget ${budget}`); + } + assert.throws(() => factory({ budget: 0 }), + { name: 'RangeError', code: 'ERR_OUT_OF_RANGE' }, name); + // -0.5 is truncated to -0, which converts to 0. + assert.throws(() => factory({ budget: -0.5 }), + { name: 'RangeError', code: 'ERR_OUT_OF_RANGE' }, name); + factory({ budget: 1 }); + } +} + // Signal must be AbortSignal assert.throws(() => push({ signal: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' }); assert.throws(() => push({ signal: {} }), { code: 'ERR_INVALID_ARG_TYPE' }); @@ -89,7 +116,7 @@ assert.throws(() => duplex({ a: 42 }), { code: 'ERR_INVALID_ARG_TYPE' }); assert.throws(() => duplex({ b: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' }); // Budget validation (cascades through to push()) -assert.throws(() => duplex({ budget: 'bad' }), { code: 'ERR_OUT_OF_RANGE' }); +assert.throws(() => duplex({ budget: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' }); assert.throws(() => duplex({ budget: 0.5 }), { code: 'ERR_OUT_OF_RANGE' }); assert.throws(() => duplex({ budget: Number.MAX_SAFE_INTEGER + 1 }), { code: 'ERR_OUT_OF_RANGE' }); @@ -131,7 +158,7 @@ assert.throws(() => pullSync(fromSync('a'), 42), { code: 'ERR_INVALID_ARG_TYPE' // broadcast() validation // ============================================================================= -assert.throws(() => broadcast({ budget: 'bad' }), { code: 'ERR_OUT_OF_RANGE' }); +assert.throws(() => broadcast({ budget: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' }); assert.throws(() => broadcast({ budget: 0.5 }), { code: 'ERR_OUT_OF_RANGE' }); assert.throws(() => broadcast({ budget: Number.MAX_SAFE_INTEGER + 1 }), { code: 'ERR_OUT_OF_RANGE' }); @@ -236,7 +263,7 @@ assert.throws( // ============================================================================= assert.throws(() => share(42), { code: 'ERR_INVALID_ARG_TYPE' }); -assert.throws(() => share(from('a'), { budget: 'bad' }), { code: 'ERR_OUT_OF_RANGE' }); +assert.throws(() => share(from('a'), { budget: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' }); assert.throws(() => share(from('a'), { budget: 0.5 }), { code: 'ERR_OUT_OF_RANGE' }); assert.throws(() => share(from('a'), { budget: Number.MAX_SAFE_INTEGER + 1 }), { code: 'ERR_OUT_OF_RANGE' }); @@ -261,7 +288,7 @@ share(from('a'), { budget: Number.MAX_SAFE_INTEGER }).cancel(); assert.throws(() => shareSync(42), { code: 'ERR_INVALID_ARG_TYPE' }); assert.throws(() => shareSync(fromSync('a'), { budget: 'bad' }), - { code: 'ERR_OUT_OF_RANGE' }); + { code: 'ERR_INVALID_ARG_TYPE' }); assert.throws(() => shareSync(fromSync('a'), { budget: 0.5 }), { code: 'ERR_OUT_OF_RANGE' }); assert.throws(() => shareSync(fromSync('a'), { budget: Number.MAX_SAFE_INTEGER + 1 }), From 1efcbc35b8e751bc6e09633bb3c930edba270547 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 17:12:22 +0000 Subject: [PATCH 03/26] stream: reject on iter Writer argument errors The write(), writev() and end() methods of the Writers in stream/iter return promises, but threw synchronously when their arguments could not be converted, for example write(Symbol()) or end({ signal: 1 }). Web IDL operations that return a promise report conversion errors by returning a rejected promise. Do that for the push, broadcast, fromWritable(), FileHandle and generic Writers. The synchronous methods still throw. Assisted-by: Claude Signed-off-by: James M Snell --- lib/internal/fs/promises.js | 31 ++++++++++-- lib/internal/streams/iter/broadcast.js | 34 ++++++++++--- lib/internal/streams/iter/classic.js | 32 +++++++++++-- lib/internal/streams/iter/push.js | 33 +++++++++++-- lib/internal/streams/iter/writer.js | 32 +++++++++++-- .../test-fs-promises-file-handle-writer.js | 8 ++-- test/parallel/test-stream-iter-validation.js | 48 ++++++++++++++----- test/parallel/test-stream-iter-webidl.js | 12 ++--- .../test-stream-iter-writable-interop.js | 26 +++++----- 9 files changed, 194 insertions(+), 62 deletions(-) diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index a5fa59e557bb..216f3d48d001 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -967,8 +967,15 @@ if (getOptionValue('--experimental-stream-iter')) { return { __proto__: null, write(chunk, options = kNullPrototo) { - chunk = newStreamsToWriterUint8Array(chunk); - const signal = newStreamsGetWriterSignal(options); + let signal; + // Argument conversion errors reject the returned promise, as Web IDL + // requires for operations returning a promise. + try { + chunk = newStreamsToWriterUint8Array(chunk); + signal = newStreamsGetWriterSignal(options); + } catch (err) { + return PromiseReject(err); + } if (errored) { return PromiseReject(error); } @@ -997,8 +1004,15 @@ if (getOptionValue('--experimental-stream-iter')) { }, writev(chunks, options = kNullPrototo) { - chunks = newStreamsConvertChunks(chunks); - const signal = newStreamsGetWriterSignal(options); + let signal; + // Argument conversion errors reject the returned promise, as Web IDL + // requires for operations returning a promise. + try { + chunks = newStreamsConvertChunks(chunks); + signal = newStreamsGetWriterSignal(options); + } catch (err) { + return PromiseReject(err); + } if (errored) { return PromiseReject(error); } @@ -1097,7 +1111,14 @@ if (getOptionValue('--experimental-stream-iter')) { }, end(options = kNullPrototo) { - const signal = newStreamsGetWriterSignal(options); + let signal; + // Argument conversion errors reject the returned promise, as Web IDL + // requires for operations returning a promise. + try { + signal = newStreamsGetWriterSignal(options); + } catch (err) { + return PromiseReject(err); + } if (errored) { return PromiseReject(error); } diff --git a/lib/internal/streams/iter/broadcast.js b/lib/internal/streams/iter/broadcast.js index 54a39f33c101..0b465b5ff3f1 100644 --- a/lib/internal/streams/iter/broadcast.js +++ b/lib/internal/streams/iter/broadcast.js @@ -681,8 +681,16 @@ class BroadcastWriter { } write(chunk, options) { - const converted = toWriterUint8Array(chunk); - const signal = getWriterSignal(options); + let converted; + let signal; + // Argument conversion errors reject the returned promise, as Web IDL + // requires for operations returning a promise. + try { + converted = toWriterUint8Array(chunk); + signal = getWriterSignal(options); + } catch (err) { + return PromiseReject(err); + } // Fast path: no signal, writer open, buffer has space if (this.#canUseWriteFastPath(signal)) { const batch = snapshotByteView(converted); @@ -694,9 +702,16 @@ class BroadcastWriter { } writev(chunks, options) { - const converted = convertChunks(chunks); - const signal = getWriterSignal(options); - const batch = createEntry(converted); + let batch; + let signal; + // Argument conversion errors reject the returned promise, as Web IDL + // requires for operations returning a promise. + try { + batch = createEntry(convertChunks(chunks)); + signal = getWriterSignal(options); + } catch (err) { + return PromiseReject(err); + } // Fast path: no signal, writer open, buffer has space if (this.#canUseWriteFastPath(signal)) { if (this.#state === 'open' && this.#broadcast[kWrite](batch)) { @@ -775,7 +790,14 @@ class BroadcastWriter { } end(options) { - const signal = getWriterSignal(options); + let signal; + // Argument conversion errors reject the returned promise, as Web IDL + // requires for operations returning a promise. + try { + signal = getWriterSignal(options); + } catch (err) { + return PromiseReject(err); + } if (this.#state === 'errored') return PromiseReject(this.#error); if (this.#state === 'closed') return PromiseResolve(this.#totalBytes); if (signal?.aborted) return PromiseReject(signal.reason); diff --git a/lib/internal/streams/iter/classic.js b/lib/internal/streams/iter/classic.js index 2fe90d58a463..288dabb0e665 100644 --- a/lib/internal/streams/iter/classic.js +++ b/lib/internal/streams/iter/classic.js @@ -924,8 +924,16 @@ function fromWritable(writable, options = kNullPrototype) { // Writable. Writes made while it is full stay in this adapter until drain, // so operation signals can cancel them before they are committed. write(chunk, options) { - const bytes = toWriterUint8Array(chunk); - const signal = getWriterSignal(options); + let bytes; + let signal; + // Argument conversion errors reject the returned promise, as Web IDL + // requires for operations returning a promise. + try { + bytes = toWriterUint8Array(chunk); + signal = getWriterSignal(options); + } catch (err) { + return PromiseReject(err); + } syncWritableError(); if (errored) return PromiseReject(error); if (!isWritable()) { @@ -956,8 +964,15 @@ function fromWritable(writable, options = kNullPrototype) { }, writev(chunks, options) { - chunks = convertChunks(chunks); - const signal = getWriterSignal(options); + let signal; + // Argument conversion errors reject the returned promise, as Web IDL + // requires for operations returning a promise. + try { + chunks = convertChunks(chunks); + signal = getWriterSignal(options); + } catch (err) { + return PromiseReject(err); + } syncWritableError(); if (errored) return PromiseReject(error); if (!isWritable()) { @@ -996,7 +1011,14 @@ function fromWritable(writable, options = kNullPrototype) { }, end(options) { - const signal = getWriterSignal(options); + let signal; + // Argument conversion errors reject the returned promise, as Web IDL + // requires for operations returning a promise. + try { + signal = getWriterSignal(options); + } catch (err) { + return PromiseReject(err); + } syncWritableError(); if (errored) return PromiseReject(error); if (signal?.aborted) return PromiseReject(signal.reason); diff --git a/lib/internal/streams/iter/push.js b/lib/internal/streams/iter/push.js index 66c66a0a6d2d..22dd47913ca3 100644 --- a/lib/internal/streams/iter/push.js +++ b/lib/internal/streams/iter/push.js @@ -685,8 +685,16 @@ class PushWriter { } write(chunk, options) { - const entry = snapshotByteView(toWriterUint8Array(chunk)); - const signal = getWriterSignal(options); + let entry; + let signal; + // Argument conversion errors reject the returned promise, as Web IDL + // requires for operations returning a promise. + try { + entry = snapshotByteView(toWriterUint8Array(chunk)); + signal = getWriterSignal(options); + } catch (err) { + return PromiseReject(err); + } if (!signal && this.#queue.canWriteSync()) { this.#queue.writeSync(entry); return kResolvedPromise; @@ -695,8 +703,16 @@ class PushWriter { } writev(chunks, options) { - const entry = createEntry(convertChunks(chunks)); - const signal = getWriterSignal(options); + let entry; + let signal; + // Argument conversion errors reject the returned promise, as Web IDL + // requires for operations returning a promise. + try { + entry = createEntry(convertChunks(chunks)); + signal = getWriterSignal(options); + } catch (err) { + return PromiseReject(err); + } if (!signal && this.#queue.writeSync(entry)) { return kResolvedPromise; } @@ -712,7 +728,14 @@ class PushWriter { } end(options) { - const signal = getWriterSignal(options); + let signal; + // Argument conversion errors reject the returned promise, as Web IDL + // requires for operations returning a promise. + try { + signal = getWriterSignal(options); + } catch (err) { + return PromiseReject(err); + } const state = this.#queue.writerState; if (state === 'errored') return PromiseReject(this.#queue.error); if (state === 'closed') { diff --git a/lib/internal/streams/iter/writer.js b/lib/internal/streams/iter/writer.js index 575e476b7052..6fb6ba1491c9 100644 --- a/lib/internal/streams/iter/writer.js +++ b/lib/internal/streams/iter/writer.js @@ -6,6 +6,7 @@ const { PromisePrototypeThen, + PromiseReject, PromiseResolve, PromiseWithResolvers, SymbolAsyncDispose, @@ -141,8 +142,15 @@ function getWriter(obj) { } function write(chunk, options = kEmptyObject) { - chunk = toWriterUint8Array(chunk); - const signal = getWriterSignal(options); + let signal; + // Argument conversion errors reject the returned promise, as Web IDL + // requires for operations returning a promise. + try { + chunk = toWriterUint8Array(chunk); + signal = getWriterSignal(options); + } catch (err) { + return PromiseReject(err); + } return writeAsync(chunk, signal); } @@ -211,8 +219,15 @@ function getWriter(obj) { } function writev(chunks, options = kEmptyObject) { - chunks = convertChunks(chunks); - const signal = getWriterSignal(options); + let signal; + // Argument conversion errors reject the returned promise, as Web IDL + // requires for operations returning a promise. + try { + chunks = convertChunks(chunks); + signal = getWriterSignal(options); + } catch (err) { + return PromiseReject(err); + } return writevAsync(chunks, signal); } @@ -248,7 +263,14 @@ function getWriter(obj) { } function end(options = kEmptyObject) { - const signal = getWriterSignal(options); + let signal; + // Argument conversion errors reject the returned promise, as Web IDL + // requires for operations returning a promise. + try { + signal = getWriterSignal(options); + } catch (err) { + return PromiseReject(err); + } return endAsync(signal); } diff --git a/test/parallel/test-fs-promises-file-handle-writer.js b/test/parallel/test-fs-promises-file-handle-writer.js index 1074c8156aad..63b0309dbaa5 100644 --- a/test/parallel/test-fs-promises-file-handle-writer.js +++ b/test/parallel/test-fs-promises-file-handle-writer.js @@ -1115,12 +1115,12 @@ async function testWriterWebIDLConversion() { await w.write(42, null); await w.writev(new Set([true, { toString: () => 'object' }])); - assert.throws( - () => w.write(Symbol('invalid')), + await assert.rejects( + w.write(Symbol('invalid')), { code: 'ERR_INVALID_ARG_TYPE' }, ); - assert.throws( - () => w.write('invalid options', 1), + await assert.rejects( + w.write('invalid options', 1), { code: 'ERR_INVALID_ARG_TYPE' }, ); assert.strictEqual(await w.end(null), 12); diff --git a/test/parallel/test-stream-iter-validation.js b/test/parallel/test-stream-iter-validation.js index 59cb4fcdb7ab..66aa91dfae65 100644 --- a/test/parallel/test-stream-iter-validation.js +++ b/test/parallel/test-stream-iter-validation.js @@ -17,6 +17,13 @@ const { decompressGzip, decompressBrotli, decompressZstd, } = require('zlib/iter'); +// Promise-returning Writer methods reject on argument conversion errors +// rather than throwing synchronously. +function assertRejects(promise, error) { + assert(promise instanceof Promise); + assert.rejects(promise, error).then(common.mustCall()); +} + // ============================================================================= // push() validation // ============================================================================= @@ -80,11 +87,11 @@ assert.throws(() => push('bad', {}), { code: 'ERR_INVALID_ARG_TYPE' }); { const { writer } = push(); const badOptions = { signal: 'bad' }; - assert.throws(() => writer.write('a', badOptions), + assertRejects(writer.write('a', badOptions), { code: 'ERR_INVALID_ARG_TYPE' }); - assert.throws(() => writer.writev(['b'], badOptions), + assertRejects(writer.writev(['b'], badOptions), { code: 'ERR_INVALID_ARG_TYPE' }); - assert.throws(() => writer.end(badOptions), + assertRejects(writer.end(badOptions), { code: 'ERR_INVALID_ARG_TYPE' }); writer.endSync(); } @@ -92,12 +99,27 @@ assert.throws(() => push('bad', {}), { code: 'ERR_INVALID_ARG_TYPE' }); // Writer.writev requires array { const { writer } = push(); - assert.throws(() => writer.writev('bad'), { code: 'ERR_INVALID_ARG_TYPE' }); - assert.throws(() => writer.writev(42), { code: 'ERR_INVALID_ARG_TYPE' }); + assertRejects(writer.writev('bad'), { code: 'ERR_INVALID_ARG_TYPE' }); + assertRejects(writer.writev(42), { code: 'ERR_INVALID_ARG_TYPE' }); assert.throws(() => writer.writevSync('bad'), { code: 'ERR_INVALID_ARG_TYPE' }); writer.endSync(); } +// Conversion errors of the promise-returning Writer methods reject the +// returned promise; the sync methods keep throwing. +for (const writer of [push().writer, broadcast().writer]) { + assertRejects(writer.write(Symbol('bad')), { name: 'TypeError' }); + assertRejects(writer.write('a', { signal: 1 }), { name: 'TypeError' }); + assertRejects(writer.writev(5), { name: 'TypeError' }); + assertRejects(writer.writev([Symbol('bad')]), { name: 'TypeError' }); + assertRejects(writer.end({ signal: 1 }), { name: 'TypeError' }); + assert.throws(() => writer.writeSync(Symbol('bad')), { name: 'TypeError' }); + assert.throws(() => writer.writevSync(5), { name: 'TypeError' }); + // The writer is still open. + assert.strictEqual(writer.canWrite, true); + assert.strictEqual(writer.endSync(), 0); +} + // Writer chunks use the Web IDL (Uint8Array or USVString) conversion. { const { writer } = push(); @@ -197,11 +219,11 @@ assert.throws(() => broadcast({ backpressure: 'bad' }), { code: 'ERR_INVALID_ARG { const { writer } = broadcast(); const badOptions = { signal: 'bad' }; - assert.throws(() => writer.write('a', badOptions), + assertRejects(writer.write('a', badOptions), { code: 'ERR_INVALID_ARG_TYPE' }); - assert.throws(() => writer.writev(['b'], badOptions), + assertRejects(writer.writev(['b'], badOptions), { code: 'ERR_INVALID_ARG_TYPE' }); - assert.throws(() => writer.end(badOptions), + assertRejects(writer.end(badOptions), { code: 'ERR_INVALID_ARG_TYPE' }); writer.endSync(); } @@ -209,8 +231,8 @@ assert.throws(() => broadcast({ backpressure: 'bad' }), { code: 'ERR_INVALID_ARG // BroadcastWriter.writev requires array { const { writer } = broadcast(); - assert.throws(() => writer.writev('bad'), { code: 'ERR_INVALID_ARG_TYPE' }); - assert.throws(() => writer.writev(42), { code: 'ERR_INVALID_ARG_TYPE' }); + assertRejects(writer.writev('bad'), { code: 'ERR_INVALID_ARG_TYPE' }); + assertRejects(writer.writev(42), { code: 'ERR_INVALID_ARG_TYPE' }); assert.throws(() => writer.writevSync('bad'), { code: 'ERR_INVALID_ARG_TYPE' }); assert.throws(() => writer.writevSync(42), { code: 'ERR_INVALID_ARG_TYPE' }); writer.endSync(); @@ -249,11 +271,11 @@ assert.throws( }); const writer = fromWritable(writable); const badOptions = { signal: 'bad' }; - assert.throws(() => writer.write('a', badOptions), + assertRejects(writer.write('a', badOptions), { code: 'ERR_INVALID_ARG_TYPE' }); - assert.throws(() => writer.writev(['b'], badOptions), + assertRejects(writer.writev(['b'], badOptions), { code: 'ERR_INVALID_ARG_TYPE' }); - assert.throws(() => writer.end(badOptions), + assertRejects(writer.end(badOptions), { code: 'ERR_INVALID_ARG_TYPE' }); writable.destroy(); } diff --git a/test/parallel/test-stream-iter-webidl.js b/test/parallel/test-stream-iter-webidl.js index 904bf77a647f..205a66295cd5 100644 --- a/test/parallel/test-stream-iter-webidl.js +++ b/test/parallel/test-stream-iter-webidl.js @@ -102,16 +102,16 @@ async function testWriterConversion() { { toString: () => 'object' }, ])), true); - assert.throws( - () => writer.write(Symbol('invalid')), + await assert.rejects( + writer.write(Symbol('invalid')), { code: 'ERR_INVALID_ARG_TYPE' }, ); - assert.throws( - () => writer.writev('not a sequence object'), + await assert.rejects( + writer.writev('not a sequence object'), { code: 'ERR_INVALID_ARG_TYPE' }, ); - assert.throws( - () => writer.write('invalid options', 1), + await assert.rejects( + writer.write('invalid options', 1), { code: 'ERR_INVALID_ARG_TYPE' }, ); diff --git a/test/parallel/test-stream-iter-writable-interop.js b/test/parallel/test-stream-iter-writable-interop.js index f00aae924259..e1af4cea7529 100644 --- a/test/parallel/test-stream-iter-writable-interop.js +++ b/test/parallel/test-stream-iter-writable-interop.js @@ -803,12 +803,12 @@ async function testAsyncDispose() { // write() rejects values that cannot be converted to USVString // ============================================================================= -function testWriteInvalidChunkType() { +async function testWriteInvalidChunkType() { const writable = new Writable({ write(chunk, enc, cb) { cb(); } }); const writer = fromWritable(writable); - assert.throws( - () => writer.write(Symbol('invalid')), + await assert.rejects( + writer.write(Symbol('invalid')), { code: 'ERR_INVALID_ARG_TYPE' }, ); writable.destroy(); @@ -818,16 +818,16 @@ function testWriteInvalidChunkType() { // writev() validates chunks is an array // ============================================================================= -function testWritevInvalidChunksType() { +async function testWritevInvalidChunksType() { const writable = new Writable({ write(chunk, enc, cb) { cb(); } }); const writer = fromWritable(writable); - assert.throws( - () => writer.writev('not an array'), + await assert.rejects( + writer.writev('not an array'), { code: 'ERR_INVALID_ARG_TYPE' }, ); - assert.throws( - () => writer.writev(42), + await assert.rejects( + writer.writev(42), { code: 'ERR_INVALID_ARG_TYPE' }, ); } @@ -836,7 +836,7 @@ function testWritevInvalidChunksType() { // writev() uncorks when chunk validation throws // ============================================================================= -function testWritevInvalidChunkUncorks() { +async function testWritevInvalidChunkUncorks() { let writes = 0; const writable = new Writable({ write(chunk, enc, cb) { @@ -846,8 +846,8 @@ function testWritevInvalidChunkUncorks() { }); const writer = fromWritable(writable); - assert.throws( - () => writer.writev([new Uint8Array([1]), Symbol('invalid')]), + await assert.rejects( + writer.writev([new Uint8Array([1]), Symbol('invalid')]), { code: 'ERR_INVALID_ARG_TYPE' }, ); assert.strictEqual(writable.writableCorked, 0); @@ -995,8 +995,8 @@ testCanWriteNull(); testDrainableNull(); testDropOldestThrows(); testInvalidBackpressureThrows(); -testWritevInvalidChunksType(); -testWritevInvalidChunkUncorks(); +testWritevInvalidChunksType().then(common.mustCall()); +testWritevInvalidChunkUncorks().then(common.mustCall()); testCachedWriter(); testObjectModeThrows(); From f6d0e75fd28ef71ea003a854670164663e29d902 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 17:12:30 +0000 Subject: [PATCH 04/26] stream: throw a TypeError on incomplete pipeToSync() close When the destination's endSync() returns a negative number, pipeToSync() throws because the writer could not be closed synchronously. The Iterable Streams specification requires a TypeError, but a plain Error was thrown. Use the TypeError variant of ERR_INVALID_STATE, so the error code is unchanged. Assisted-by: Claude Signed-off-by: James M Snell --- lib/internal/streams/iter/pull.js | 2 +- test/parallel/test-stream-iter-pipeto-edge.js | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/internal/streams/iter/pull.js b/lib/internal/streams/iter/pull.js index 697f1c0b93a0..8f405ae485b5 100644 --- a/lib/internal/streams/iter/pull.js +++ b/lib/internal/streams/iter/pull.js @@ -1927,7 +1927,7 @@ function pipeToSync(source, ...args) { // that the caller can still close it (e.g. with `await writer.end()`); // `failOnIncompleteClose` fails it instead, for callers that cannot. if (!closedSync) { - const error = new ERR_INVALID_STATE( + const error = new ERR_INVALID_STATE.TypeError( 'Writer could not be closed synchronously'); if (options.failOnIncompleteClose && !options.preventFail) { failWriterQuietly(writer, error); diff --git a/test/parallel/test-stream-iter-pipeto-edge.js b/test/parallel/test-stream-iter-pipeto-edge.js index 082871a9e4c1..5c2d245a5dbc 100644 --- a/test/parallel/test-stream-iter-pipeto-edge.js +++ b/test/parallel/test-stream-iter-pipeto-edge.js @@ -22,6 +22,12 @@ async function testPipeToSyncEndSyncFailure() { { code: 'ERR_INVALID_STATE' }, ); assert.strictEqual(endCalled, false); + + // The error is a TypeError. + assert.throws( + () => pipeToSync(fromSync('data'), writer), + { name: 'TypeError', code: 'ERR_INVALID_STATE' }, + ); } // The data was accepted, so endSync() returning -1 does not fail the writer, From e02e910b0ee05862b2be8d096a139ea98a880dd8 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 17:12:36 +0000 Subject: [PATCH 05/26] stream: fail the broadcast writer when its signal aborts Aborting the signal passed to broadcast() only cancelled the broadcast, which closes its writer. An abort therefore looked like a normal finish to the producer: end() resolved with the byte count and later writes rejected with a TypeError. Fail the writer with the abort reason first, as push() does, and then cancel the broadcast, as the Iterable Streams specification requires. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 5 + lib/internal/streams/iter/broadcast.js | 8 +- ...test-stream-iter-broadcast-signal-abort.js | 92 +++++++++++++++++++ 3 files changed, 104 insertions(+), 1 deletion(-) create mode 100644 test/parallel/test-stream-iter-broadcast-signal-abort.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index 6c4a1a9cb42a..2bfb9a238ad1 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -1451,6 +1451,11 @@ Create a push-model multi-consumer broadcast channel. A single writer pushes data to multiple consumers. Each consumer has an independent cursor into a shared buffer. +Aborting `signal` fails the writer and then cancels the broadcast, both with +the abort reason: pending writes and a pending `writer.end()` reject with the +reason, as do later writes (`writeSync()` and `writevSync()` return `false`), +and every consumer rejects with the reason. + ```mjs import { broadcast, text } from 'node:stream/iter'; diff --git a/lib/internal/streams/iter/broadcast.js b/lib/internal/streams/iter/broadcast.js index 0b465b5ff3f1..941f6bcf07c7 100644 --- a/lib/internal/streams/iter/broadcast.js +++ b/lib/internal/streams/iter/broadcast.js @@ -155,7 +155,13 @@ class BroadcastImpl { } [kSetFactorySignal](signal) { - this.#abortHandler = () => this.cancel(signal.reason); + // Aborting the signal errors the writer, then cancels the broadcast, + // both with the abort reason: the writer is not reported as closed. + this.#abortHandler = () => { + const reason = signal.reason; + this.#writer?.fail(reason); + this.cancel(reason); + }; onSignalAbort(signal, this.#abortHandler); } diff --git a/test/parallel/test-stream-iter-broadcast-signal-abort.js b/test/parallel/test-stream-iter-broadcast-signal-abort.js new file mode 100644 index 000000000000..0603a860a223 --- /dev/null +++ b/test/parallel/test-stream-iter-broadcast-signal-abort.js @@ -0,0 +1,92 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// Aborting the signal of broadcast() fails the writer, then cancels the +// broadcast, both with the abort reason. + +const common = require('../common'); +const assert = require('assert'); +const { broadcast } = require('stream/iter'); + +async function testAbortFailsWriter() { + const ac = new AbortController(); + const reason = new Error('aborted'); + const { writer, broadcast: bc } = broadcast({ signal: ac.signal, budget: 1 }); + // A consumer waiting for data, and a slow one holding the buffer. + const fast = bc.push()[Symbol.asyncIterator](); + const slow = bc.push()[Symbol.asyncIterator](); + + assert.strictEqual(writer.writeSync('a'), true); + assert.strictEqual((await fast.next()).done, false); + const pendingRead = assert.rejects(fast.next(), reason); + // The buffer is full: this write waits. + assert.strictEqual(writer.canWrite, false); + const pendingWrite = assert.rejects(writer.write('b'), reason); + const drain = assert.rejects( + writer[Symbol.for('Stream.drainableProtocol')](), reason); + + ac.abort(reason); + + await pendingRead; + await pendingWrite; + await drain; + // The data still buffered is not delivered after the abort. + await assert.rejects(slow.next(), reason); + // The writer is errored, not closed. + assert.strictEqual(writer.canWrite, null); + await assert.rejects(writer.write('d'), reason); + await assert.rejects(writer.writev(['d']), reason); + assert.strictEqual(writer.writeSync('d'), false); + assert.strictEqual(writer.writevSync(['d']), false); + await assert.rejects(writer.end(), reason); + assert.strictEqual(writer.endSync(), -1); + // Consumers created afterwards are already errored. + assert.strictEqual(bc.consumerCount, 0); + await assert.rejects(bc.push()[Symbol.asyncIterator]().next(), reason); + assert.strictEqual(bc.consumerCount, 0); +} + +async function testAbortRejectsPendingEnd() { + const ac = new AbortController(); + const reason = new Error('aborted'); + const { writer, broadcast: bc } = broadcast({ signal: ac.signal }); + const iterator = bc.push()[Symbol.asyncIterator](); + writer.writeSync('a'); + // The consumer has not read the data yet: end() waits for it. + const ended = assert.rejects(writer.end(), reason); + ac.abort(reason); + await ended; + await assert.rejects(iterator.next(), reason); +} + +async function testPreAborted() { + const reason = new Error('pre-aborted'); + const { writer, broadcast: bc } = + broadcast({ signal: AbortSignal.abort(reason) }); + assert.strictEqual(writer.canWrite, null); + await assert.rejects(writer.write('a'), reason); + assert.strictEqual(writer.writeSync('a'), false); + await assert.rejects(writer.end(), reason); + await assert.rejects(bc.push()[Symbol.asyncIterator]().next(), reason); + assert.strictEqual(bc.consumerCount, 0); +} + +async function testAbortAfterCancelHasNoEffect() { + const ac = new AbortController(); + const { writer, broadcast: bc } = broadcast({ signal: ac.signal }); + bc.cancel(); + ac.abort(new Error('ignored')); + // The writer was closed by cancel(). + assert.strictEqual(writer.canWrite, null); + assert.strictEqual(await writer.end(), 0); + const result = await bc.push()[Symbol.asyncIterator]().next(); + assert.strictEqual(result.done, true); + assert.strictEqual(result.value, undefined); +} + +Promise.all([ + testAbortFailsWriter(), + testAbortRejectsPendingEnd(), + testPreAborted(), + testAbortAfterCancelHasNoEffect(), +]).then(common.mustCall()); From a4e9a2e7a8ca2fa84cfc079614e4c869427943f5 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 17:12:44 +0000 Subject: [PATCH 06/26] stream: finish iter consumers of a cancelled broadcast After Broadcast.cancel(), push() still registered a consumer, so consumerCount became 1, and that consumer read the data left in the buffer before reporting the cancellation. cancel() also kept the buffered data. Discard the buffer on cancel(), and have push() on a cancelled broadcast return an unregistered consumer that does not call its transforms and whose pulls reject with the cancel reason, or report done if there was none. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 5 ++ lib/internal/streams/iter/broadcast.js | 37 ++++++++++++ ...st-stream-iter-broadcast-cancelled-push.js | 59 +++++++++++++++++++ 3 files changed, 101 insertions(+) create mode 100644 test/parallel/test-stream-iter-broadcast-cancelled-push.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index 2bfb9a238ad1..42b32d74bb02 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -1515,6 +1515,11 @@ Cancelling also closes the paired writer: afterwards its `canWrite` is `null` and `write()` rejects with a `TypeError`. This lets a [`Broadcast.from()`][] pump stop pulling from its source. +The buffered data is discarded. Consumers created with `broadcast.push()` +after cancelling are not registered and read none of the buffered data: their +first read rejects with `reason` if one was provided, and otherwise completes +with `{ done: true }`. + #### `broadcast.consumerCount` * {number} diff --git a/lib/internal/streams/iter/broadcast.js b/lib/internal/streams/iter/broadcast.js index 941f6bcf07c7..f7ed45e0aa9b 100644 --- a/lib/internal/streams/iter/broadcast.js +++ b/lib/internal/streams/iter/broadcast.js @@ -135,6 +135,9 @@ class BroadcastImpl { #error; #errored = false; #cancelled = false; + // The reason given to cancel(), if any, for consumers created afterwards. + #cancelReason; + #hasCancelReason = false; #options; #writer = null; #cachedMinCursor = 0; @@ -182,6 +185,12 @@ class BroadcastImpl { }); const { signal } = options; + // A consumer of a cancelled broadcast is not registered, reads no + // buffered data and does not call any of the transforms. + if (this.#cancelled) { + return this.#createCancelledConsumer(); + } + // Avoid registering a consumer that the pre-aborted pipeline will never // read or detach. if (signal?.aborted) { @@ -206,6 +215,28 @@ class BroadcastImpl { return rawConsumer; } + #createCancelledConsumer() { + const hasReason = this.#hasCancelReason; + const reason = this.#cancelReason; + const kDone = PromiseResolve(new IterResult(true, undefined)); + return { + __proto__: null, + [SymbolAsyncIterator]() { + return ObjectSetPrototypeOf({ + next() { + return hasReason ? PromiseReject(reason) : kDone; + }, + return() { + return kDone; + }, + throw() { + return kDone; + }, + }, null); + }, + }; + } + #createRawConsumer() { const state = ObjectSetPrototypeOf({ // Start at the oldest buffered entry so late-joining consumers @@ -323,6 +354,8 @@ class BroadcastImpl { this.#ended = true; // Prevents [kAbort]() from redundantly iterating consumers if (hasReason) { + this.#cancelReason = reason; + this.#hasCancelReason = true; this.#error = reason; this.#errored = true; } @@ -351,6 +384,10 @@ class BroadcastImpl { this.#consumers.clear(); this.#waiters.clear(); this.#cachedMinCursorConsumers = 0; + // Discard the buffered data: no consumer can read it anymore. + this.#bufferStart += this.#buffer.length; + this.#buffer.clear(); + this.#bufferedBytes = 0; this.#cleanupFactorySignal(); const onCancel = this[kOnCancel]; this[kOnCancel] = null; diff --git a/test/parallel/test-stream-iter-broadcast-cancelled-push.js b/test/parallel/test-stream-iter-broadcast-cancelled-push.js new file mode 100644 index 000000000000..73afc7fa3937 --- /dev/null +++ b/test/parallel/test-stream-iter-broadcast-cancelled-push.js @@ -0,0 +1,59 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// After Broadcast.cancel(), push() returns a consumer that is not registered +// and is already finished, and the buffered data is discarded. + +const common = require('../common'); +const assert = require('assert'); +const { broadcast } = require('stream/iter'); + +async function testCancelWithoutReason() { + const { writer, broadcast: bc } = broadcast(); + writer.writeSync('buffered'); + bc.cancel(); + const transform = common.mustNotCall(); + for (const consumer of [bc.push(), bc.push(transform), + bc.push(transform, { signal: AbortSignal.abort() })]) { + assert.strictEqual(bc.consumerCount, 0); + const result = await consumer[Symbol.asyncIterator]().next(); + assert.strictEqual(result.done, true); + assert.strictEqual(result.value, undefined); + } + assert.strictEqual(bc.consumerCount, 0); +} + +async function testCancelWithReason() { + const reason = new Error('cancelled'); + const { writer, broadcast: bc } = broadcast(); + writer.writeSync('buffered'); + bc.cancel(reason); + const consumer = bc.push(common.mustNotCall()); + assert.strictEqual(bc.consumerCount, 0); + await assert.rejects(consumer[Symbol.asyncIterator]().next(), reason); + assert.strictEqual(bc.consumerCount, 0); + // An undefined reason is still a reason. + const { broadcast: bc2 } = broadcast(); + bc2.cancel(undefined); + await assert.rejects(bc2.push()[Symbol.asyncIterator]().next(), + (error) => error === undefined); +} + +async function testCancelDiscardsBuffer() { + const { writer, broadcast: bc } = broadcast({ budget: 4 }); + writer.writeSync('abcd'); + assert.strictEqual(writer.canWrite, false); + bc.cancel(); + // The writer was closed with the bytes written. + assert.strictEqual(writer.canWrite, null); + assert.strictEqual(await writer.end(), 4); + for await (const batch of bc.push()) { + assert.fail(`unexpected ${batch}`); + } +} + +Promise.all([ + testCancelWithoutReason(), + testCancelWithReason(), + testCancelDiscardsBuffer(), +]).then(common.mustCall()); From dcd5352ef3ccf785850cd87857e70d85adfa9fb3 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 17:13:54 +0000 Subject: [PATCH 07/26] stream: add stream/iter broadcastFrom() The Iterable Streams specification defines Stream.broadcastFrom(), which creates a broadcast channel fed from an existing source and returns its Broadcast. Node.js only had Broadcast.from(), which returns both the writer and the broadcast. Add broadcastFrom() as a named export and on the Stream namespace, sharing the pump used by Broadcast.from(). As in Broadcast.from(), an input implementing Symbol.for('Stream.broadcastProtocol') creates the broadcast itself. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 44 ++++ lib/internal/streams/iter/broadcast.js | 238 ++++++++++-------- lib/stream/iter.js | 8 +- .../test-stream-iter-broadcastfrom.js | 144 +++++++++++ 4 files changed, 329 insertions(+), 105 deletions(-) create mode 100644 test/parallel/test-stream-iter-broadcastfrom.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index 42b32d74bb02..288091557f31 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -1556,6 +1556,49 @@ added: Create a {BroadcastChannel} from an existing source. The source is consumed automatically and pushed to all subscribers. +### `broadcastFrom(input[, options])` + + + +* `input` {AsyncIterable|Iterable|BroadcastChannel|string|ArrayBuffer|ArrayBufferView|Object} +* `options` {Object} Same as `broadcast()`. +* Returns: {BroadcastChannel} + +Create a {BroadcastChannel} fed from `input`, and return it. Unlike +[`Broadcast.from()`][], no writer is returned: the data comes from `input`. + +If `input` implements `Symbol.for('Stream.broadcastProtocol')`, that method is +called with `options` and its result is returned; it must be an object. +Otherwise, `input` is normalized with [`from()`][] and written to a new +[`broadcast()`][] channel created with `options`. The source is read as the +consumers make room in the buffer. Cancelling the broadcast (including by +aborting `options.signal`) stops reading the source and closes it. If reading +the source fails, the consumers reject with the error. + +```mjs +import { broadcastFrom, text } from 'node:stream/iter'; + +const bc = broadcastFrom(['hello', ' ', 'world']); +const [a, b] = await Promise.all([text(bc.push()), text(bc.push())]); +console.log(a); // 'hello world' +console.log(b); // 'hello world' +``` + +```cjs +const { broadcastFrom, text } = require('node:stream/iter'); + +async function run() { + const bc = broadcastFrom(['hello', ' ', 'world']); + const [a, b] = await Promise.all([text(bc.push()), text(bc.push())]); + console.log(a); // 'hello world' + console.log(b); // 'hello world' +} + +run().catch(console.error); +``` + ### `share(source[, options])` -* `drainable` {Object} An object implementing the drainable protocol. +* `drainable` {Object|Function} An object (or function) implementing the + drainable protocol. * Returns: {Promise|null} Wait for a drainable writer to regain physical buffer capacity. Returns `null` diff --git a/lib/internal/streams/iter/consumers.js b/lib/internal/streams/iter/consumers.js index d8fd1bee495d..a06752acbc0a 100644 --- a/lib/internal/streams/iter/consumers.js +++ b/lib/internal/streams/iter/consumers.js @@ -475,14 +475,7 @@ function tapSync(callback) { * @returns {Promise|null} */ function ondrain(drainable) { - if ( - drainable === null || - drainable === undefined || - typeof drainable !== 'object' - ) { - return null; - } - + // getProtocolMethod() accepts objects and functions carrying the method. const protocol = getProtocolMethod(drainable, drainableProtocol); return protocol === undefined ? null : FunctionPrototypeCall(protocol, drainable); diff --git a/test/parallel/test-stream-iter-push-writer.js b/test/parallel/test-stream-iter-push-writer.js index 0278ce569b9d..976a89dd1411 100644 --- a/test/parallel/test-stream-iter-push-writer.js +++ b/test/parallel/test-stream-iter-push-writer.js @@ -3,7 +3,9 @@ const common = require('../common'); const assert = require('assert'); -const { dump, push, ondrain, text, array } = require('stream/iter'); +const { + array, drainableProtocol, dump, ondrain, push, text, +} = require('stream/iter'); const { setImmediate } = require('timers/promises'); async function testOndrain() { @@ -57,6 +59,20 @@ async function testOndrainNonDrainable() { assert.strictEqual(ondrain('string'), null); } +async function testOndrainFunctionDrainable() { + // A function carrying the protocol method is a drainable too. + const result = Promise.resolve(true); + const drainable = () => {}; + drainable[drainableProtocol] = common.mustCall(function() { + assert.strictEqual(this, drainable); + return result; + }); + assert.strictEqual(ondrain(drainable), result); + assert.strictEqual(ondrain(() => {}), null); + assert.strictEqual(ondrain(undefined), null); + assert.strictEqual(ondrain(42), null); +} + async function testOndrainProtocolErrorPropagates() { const badDrainable = { [Symbol.for('Stream.drainableProtocol')]() { @@ -707,6 +723,7 @@ Promise.all([ testWritevMixedTypes(), testWriteAfterEnd(), testWriteAfterFail(), + testOndrainFunctionDrainable(), testOndrainProtocolErrorPropagates(), testFail(), testEndAsyncReturnValue(), From a249fa318caf85809d02dce8ecf95e7fb60da638 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 17:37:09 +0000 Subject: [PATCH 11/26] stream: copy shared and resizable memory in stream/iter Bytes received by from(), fromSync(), transform output normalization and writers are now copied when they are backed by a SharedArrayBuffer or a resizable ArrayBuffer, so that what was received cannot change or be resized afterwards. Fixed-length buffers are still used without a copy. Receiving bytes from a detached ArrayBuffer throws a TypeError. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 15 +- lib/internal/streams/iter/classic.js | 4 +- lib/internal/streams/iter/from.js | 70 ++-- lib/internal/streams/iter/pull.js | 52 +-- lib/internal/streams/iter/utils.js | 119 +++++- .../test-stream-iter-receive-bytes.js | 339 ++++++++++++++++++ .../test-stream-iter-resizable-buffers.js | 115 +++--- 7 files changed, 592 insertions(+), 122 deletions(-) create mode 100644 test/parallel/test-stream-iter-receive-bytes.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index a1df9489866a..cf9cbe9850b5 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -98,6 +98,17 @@ Like [`Buffer.from()`][] for strings, small strings are encoded into a shared pool: the resulting {Uint8Array} is a view of a larger {ArrayBuffer}, which cannot be transferred. +{ArrayBuffer} and {ArrayBufferView} values are used without copying: the +resulting {Uint8Array} is a view of the same memory, so changing that memory +afterwards changes the data in the stream. Memory that another thread or the +owner of the buffer could change or resize is copied instead when it is +received: a {SharedArrayBuffer}, a resizable {ArrayBuffer}, and any view of +one (including a length-tracking view) are copied into a new fixed-length +{ArrayBuffer}, holding the bytes the value covers at that time. Bytes are +received when `from()` or `fromSync()` is called with them, when a value +yielded by a source or a transform is normalized, and when they are passed to +a writer. Receiving bytes from a detached {ArrayBuffer} throws a {TypeError}. + ### Batching Each iteration yields a **batch** -- an {Array} of {Uint8Array} chunks @@ -603,7 +614,8 @@ added: * Returns: {AsyncIterable} whose chunks fulfill with {Uint8Array\[]}. Create an async byte stream from the given input. Strings are UTF-8 encoded. -`ArrayBuffer` and `ArrayBufferView` values are wrapped as `Uint8Array`. Arrays +`ArrayBuffer` and `ArrayBufferView` values are wrapped as `Uint8Array`, or +copied if they are shared or resizable (see [Byte streams][]). Arrays and iterables in `input` are recursively flattened and normalized. Flattened values may be split across implementation-defined bounded batches. @@ -2481,6 +2493,7 @@ const stream = fromSync(new Greeting('world')); console.log(textSync(stream)); // 'hello world' ``` +[Byte streams]: #byte-streams [Iterable Streams API]: https://iter-streams.proposal.wintertc.org/ [`--experimental-stream-iter`]: cli.md#--experimental-stream-iter [`Broadcast.from()`]: #broadcastfrominput-options diff --git a/lib/internal/streams/iter/classic.js b/lib/internal/streams/iter/classic.js index 288dabb0e665..1a638ae47b6e 100644 --- a/lib/internal/streams/iter/classic.js +++ b/lib/internal/streams/iter/classic.js @@ -66,6 +66,7 @@ const { kNullOnceOption, convertChunks, getWriterSignal, + isFixedUint8Array, onSignalAbort, validateBackpressure, toWriterUint8Array, @@ -153,7 +154,6 @@ const fromReadableCache = new SafeWeakMap(); const MAX_DRAIN_BATCH = 128; const { normalizeAsyncValue } = require('internal/streams/iter/from'); -const { isUint8Array } = require('internal/util/types'); // Normalize a batch of raw chunks from an object-mode or encoded // Readable into Uint8Array values. Returns the normalized batch, @@ -162,7 +162,7 @@ async function normalizeBatch(raw) { const batch = []; for (let i = 0; i < raw.length; i++) { const value = raw[i]; - if (isUint8Array(value)) { + if (isFixedUint8Array(value)) { batch[batch.length] = value; } else { // normalizeAsyncValue may await for async protocols (e.g. diff --git a/lib/internal/streams/iter/from.js b/lib/internal/streams/iter/from.js index 7f424e3735ec..b4b3b6be1024 100644 --- a/lib/internal/streams/iter/from.js +++ b/lib/internal/streams/iter/from.js @@ -10,9 +10,6 @@ const { ArrayIsArray, ArrayPrototypeEvery, ArrayPrototypeSlice, - DataViewPrototypeGetBuffer, - DataViewPrototypeGetByteLength, - DataViewPrototypeGetByteOffset, FunctionPrototypeCall, ObjectFreeze, ObjectGetOwnPropertyDescriptor, @@ -24,10 +21,6 @@ const { Symbol, SymbolAsyncIterator, SymbolIterator, - TypedArrayPrototypeGetBuffer, - TypedArrayPrototypeGetByteLength, - TypedArrayPrototypeGetByteOffset, - Uint8Array, } = primordials; const { markPromiseAsHandled } = internalBinding('util'); @@ -45,8 +38,6 @@ const { isAnyArrayBuffer, isGeneratorObject, isPromise, - isTypedArray, - isUint8Array, } = require('internal/util/types'); const { @@ -66,6 +57,8 @@ const { kStart, createOperationQueue, getProtocolMethod, + isFixedUint8Array, + receiveBytes, toUint8Array, } = require('internal/streams/iter/utils'); @@ -315,8 +308,8 @@ function isAsyncIterable(value) { /** * Convert a primitive chunk to Uint8Array. * - string: UTF-8 encoded - * - ArrayBuffer: wrapped as Uint8Array view (no copy) - * - ArrayBufferView: converted to Uint8Array view of same memory + * - ArrayBuffer, SharedArrayBuffer, ArrayBufferView: received as bytes; + * see receiveBytes() * @param {string|ArrayBuffer|ArrayBufferView} chunk * @returns {Uint8Array} */ @@ -324,29 +317,18 @@ function primitiveToUint8Array(chunk) { if (typeof chunk === 'string') { return toUint8Array(chunk); } - if (isAnyArrayBuffer(chunk)) { - return new Uint8Array(chunk); - } - if (isUint8Array(chunk)) { - return chunk; - } - // Other ArrayBufferView types (Int8Array, DataView, etc.) - return arrayBufferViewToUint8Array(chunk); + return receiveBytes(chunk); } +/** + * Convert an ArrayBuffer, SharedArrayBuffer or ArrayBufferView to a + * Uint8Array. A view of shared or resizable memory is copied; other views + * are not. + * @param {ArrayBuffer|SharedArrayBuffer|ArrayBufferView} chunk + * @returns {Uint8Array} + */ function arrayBufferViewToUint8Array(chunk) { - if (isTypedArray(chunk)) { - return new Uint8Array( - TypedArrayPrototypeGetBuffer(chunk), - TypedArrayPrototypeGetByteOffset(chunk), - TypedArrayPrototypeGetByteLength(chunk), - ); - } - return new Uint8Array( - DataViewPrototypeGetBuffer(chunk), - DataViewPrototypeGetByteOffset(chunk), - DataViewPrototypeGetByteLength(chunk), - ); + return receiveBytes(chunk); } // ============================================================================= @@ -399,7 +381,8 @@ function* normalizeSyncValue(value, depth = 0) { } /** - * Check if value is already a Uint8Array[] batch (fast path). + * Check if value is already a Uint8Array[] batch (fast path): one whose + * chunks are received as they are (see isFixedUint8Array()). * @returns {boolean} */ function isUint8ArrayBatch(value) { @@ -407,12 +390,12 @@ function isUint8ArrayBatch(value) { const len = value.length; if (len === 0) return true; // Fast path: single-element batch (most common from transforms) - if (len === 1) return isUint8Array(value[0]); + if (len === 1) return isFixedUint8Array(value[0]); // Check first and last before iterating all elements - if (!isUint8Array(value[0]) || !isUint8Array(value[len - 1])) return false; + if (!isFixedUint8Array(value[0]) || !isFixedUint8Array(value[len - 1])) return false; if (len === 2) return true; for (let i = 1; i < len - 1; i++) { - if (!isUint8Array(value[i])) return false; + if (!isFixedUint8Array(value[i])) return false; } return true; } @@ -941,7 +924,9 @@ function createAsyncSourceNormalizer(source, context) { boundedBatches = yieldBoundedBatch(value); return pullValue(); } - if (isUint8Array(value)) return finish(new IterResult(false, [value])); + if (isFixedUint8Array(value)) { + return finish(new IterResult(false, [value])); + } valueBatches = normalizeAsyncSourceValue(value, context); return pullValue(); } @@ -1270,9 +1255,10 @@ class SyncSourceReader { throw context.reason; } // Fast path 1: value is a single Uint8Array (very common). Checking - // ArrayIsArray() first keeps batches from paying for isUint8Array(). + // ArrayIsArray() first keeps batches from paying for + // isFixedUint8Array(). const isArray = ArrayIsArray(value); - if (!isArray && isUint8Array(value)) { + if (!isArray && isFixedUint8Array(value)) { batch[batch.length] = value; if (batch.length === FROM_BATCH_SIZE) { return new IterResult(false, this.#takeBatch()); @@ -1794,8 +1780,8 @@ function fromSyncWithDepth(input, depth) { // An empty array yields nothing. if (input.length === 0) return new SyncBatchSource(input); // Check if it's an array of Uint8Array (common case) - if (isUint8Array(input[0])) { - const allUint8 = ArrayPrototypeEvery(input, isUint8Array); + if (isFixedUint8Array(input[0])) { + const allUint8 = ArrayPrototypeEvery(input, isFixedUint8Array); if (allUint8) return new SyncBatchSource(input); } } @@ -1977,8 +1963,8 @@ function fromWithDepth(input, depth) { if (input.length === 0) { return createBatchSource(input); } - if (isUint8Array(input[0])) { - const allUint8 = ArrayPrototypeEvery(input, isUint8Array); + if (isFixedUint8Array(input[0])) { + const allUint8 = ArrayPrototypeEvery(input, isFixedUint8Array); if (allUint8) { return createBatchSource(input); } diff --git a/lib/internal/streams/iter/pull.js b/lib/internal/streams/iter/pull.js index 8f405ae485b5..206345adcb6f 100644 --- a/lib/internal/streams/iter/pull.js +++ b/lib/internal/streams/iter/pull.js @@ -21,7 +21,6 @@ const { SymbolAsyncIterator, SymbolIterator, TypedArrayPrototypeGetByteLength, - Uint8Array, } = primordials; const { @@ -37,7 +36,6 @@ const { lazyDOMException } = require('internal/util'); const { isAnyArrayBuffer, isPromise, - isUint8Array, } = require('internal/util/types'); const { kWeakHandler } = require('internal/event_target'); @@ -68,9 +66,11 @@ const { createBatchEntry, createOperationQueue, fixedBatchToEntry, + isFixedUint8Array, isTransformObject, parsePullArgs, raceSignal, + receiveBytes, snapshotFixedBatch, throwByteViewChanged, snapshotTransform, @@ -160,7 +160,7 @@ function parsePipeToArgs(args, requiredMethod) { * @yields {Uint8Array} */ function* flattenTransformYieldSync(value) { - if (isUint8Array(value)) { + if (isFixedUint8Array(value)) { yield value; return; } @@ -169,7 +169,7 @@ function* flattenTransformYieldSync(value) { return; } if (isAnyArrayBuffer(value)) { - yield new Uint8Array(value); + yield receiveBytes(value); return; } if (ArrayBufferIsView(value)) { @@ -194,7 +194,7 @@ function* flattenTransformYieldSync(value) { * @yields {Uint8Array} */ async function* flattenTransformYieldAsync(value) { - if (isUint8Array(value)) { + if (isFixedUint8Array(value)) { yield value; return; } @@ -203,7 +203,7 @@ async function* flattenTransformYieldAsync(value) { return; } if (isAnyArrayBuffer(value)) { - yield new Uint8Array(value); + yield receiveBytes(value); return; } if (ArrayBufferIsView(value)) { @@ -240,7 +240,7 @@ function* processTransformResultSync(result) { return; } // Single Uint8Array -> wrap as batch - if (isUint8Array(result)) { + if (isFixedUint8Array(result)) { yield [result]; return; } @@ -251,7 +251,7 @@ function* processTransformResultSync(result) { } // ArrayBuffer / ArrayBufferView -> convert and wrap if (isAnyArrayBuffer(result)) { - yield [new Uint8Array(result)]; + yield [receiveBytes(result)]; return; } if (ArrayBufferIsView(result)) { @@ -300,7 +300,7 @@ function appendTransformResultSync(target, result) { } return; } - if (isUint8Array(result)) { + if (isFixedUint8Array(result)) { target[target.length] = [result]; return; } @@ -309,7 +309,7 @@ function appendTransformResultSync(target, result) { return; } if (isAnyArrayBuffer(result)) { - target[target.length] = [new Uint8Array(result)]; + target[target.length] = [receiveBytes(result)]; return; } if (ArrayBufferIsView(result)) { @@ -336,7 +336,7 @@ async function* processTransformResultAsync(result) { return; } // Single Uint8Array -> wrap as batch - if (isUint8Array(result)) { + if (isFixedUint8Array(result)) { yield [result]; return; } @@ -347,7 +347,7 @@ async function* processTransformResultAsync(result) { } // ArrayBuffer / ArrayBufferView -> convert and wrap if (isAnyArrayBuffer(result)) { - yield [new Uint8Array(result)]; + yield [receiveBytes(result)]; return; } if (ArrayBufferIsView(result)) { @@ -365,7 +365,7 @@ async function* processTransformResultAsync(result) { if (isAsyncIterable(result)) { const batch = []; for await (const item of result) { - if (isUint8Array(item)) { + if (isFixedUint8Array(item)) { batch[batch.length] = item; continue; } @@ -382,7 +382,7 @@ async function* processTransformResultAsync(result) { if (isSyncIterable(result)) { const batch = []; for (const item of result) { - if (isUint8Array(item)) { + if (isFixedUint8Array(item)) { batch[batch.length] = item; continue; } @@ -420,7 +420,7 @@ function appendTransformResultAsync(target, result) { } return; } - if (isUint8Array(result)) { + if (isFixedUint8Array(result)) { target[target.length] = [result]; return; } @@ -429,7 +429,7 @@ function appendTransformResultAsync(target, result) { return; } if (isAnyArrayBuffer(result)) { - target[target.length] = [new Uint8Array(result)]; + target[target.length] = [receiveBytes(result)]; return; } if (ArrayBufferIsView(result)) { @@ -449,9 +449,9 @@ function normalizeTransformResultFast(result) { if (isUint8ArrayBatch(result)) { return result.length === 0 ? null : result; } - if (isUint8Array(result)) return [result]; + if (isFixedUint8Array(result)) return [result]; if (typeof result === 'string') return [toUint8Array(result)]; - if (isAnyArrayBuffer(result)) return [new Uint8Array(result)]; + if (isAnyArrayBuffer(result)) return [receiveBytes(result)]; if (ArrayBufferIsView(result)) return [arrayBufferViewToUint8Array(result)]; } @@ -497,12 +497,12 @@ function* applyFusedStatelessSyncTransforms(source, run) { // matching the async pipeline's check order. if (isUint8ArrayBatch(current)) { if (current.length > 0) yield current; - } else if (isUint8Array(current)) { + } else if (isFixedUint8Array(current)) { yield [current]; } else if (typeof current === 'string') { yield [toUint8Array(current)]; } else if (isAnyArrayBuffer(current)) { - yield [new Uint8Array(current)]; + yield [receiveBytes(current)]; } else if (ArrayBufferIsView(current)) { yield [arrayBufferViewToUint8Array(current)]; } else { @@ -668,12 +668,12 @@ function closeAsyncIterator(iterator, quiet) { async function* yieldFusedStatelessOutput(current) { if (isUint8ArrayBatch(current)) { if (current.length > 0) yield current; - } else if (isUint8Array(current)) { + } else if (isFixedUint8Array(current)) { yield [current]; } else if (typeof current === 'string') { yield [toUint8Array(current)]; } else if (isAnyArrayBuffer(current)) { - yield [new Uint8Array(current)]; + yield [receiveBytes(current)]; } else if (ArrayBufferIsView(current)) { yield [arrayBufferViewToUint8Array(current)]; } else { @@ -854,9 +854,9 @@ function applyFusedStatelessAsyncTransforms(source, run, abort) { if (isUint8ArrayBatch(current)) { return current.length > 0 ? current : null; } - if (isUint8Array(current)) return [current]; + if (isFixedUint8Array(current)) return [current]; if (typeof current === 'string') return [toUint8Array(current)]; - if (isAnyArrayBuffer(current)) return [new Uint8Array(current)]; + if (isAnyArrayBuffer(current)) return [receiveBytes(current)]; if (ArrayBufferIsView(current)) { return [arrayBufferViewToUint8Array(current)]; } @@ -1084,7 +1084,7 @@ async function* yieldStatefulOutput(output) { continue; } // Fast path: single Uint8Array - if (isUint8Array(item)) { + if (isFixedUint8Array(item)) { yield [item]; continue; } @@ -1149,7 +1149,7 @@ function createStatefulTransformIterator( if (isUint8ArrayBatch(item)) { return item.length > 0 ? new IterResult(false, item) : pull(); } - if (isUint8Array(item)) return new IterResult(false, [item]); + if (isFixedUint8Array(item)) return new IterResult(false, [item]); // Slow path: flatten arbitrary transform yield. An error doing so // closes the output, as for await does when its body throws. return PromisePrototypeThen(flattenItem(item), (batch) => { diff --git a/lib/internal/streams/iter/utils.js b/lib/internal/streams/iter/utils.js index 01e4ea0ce67c..b0e0890e8d78 100644 --- a/lib/internal/streams/iter/utils.js +++ b/lib/internal/streams/iter/utils.js @@ -3,7 +3,12 @@ const { Array, ArrayBufferPrototypeGetByteLength, + ArrayBufferPrototypeGetDetached, + ArrayBufferPrototypeGetResizable, ArrayPrototypeSlice, + DataViewPrototypeGetBuffer, + DataViewPrototypeGetByteLength, + DataViewPrototypeGetByteOffset, FunctionPrototypeCall, ObjectDefineProperty, ObjectFreeze, @@ -23,6 +28,7 @@ const { } = primordials; const { + arrayBufferViewHasBuffer, markPromiseAsHandled, } = internalBinding('util'); @@ -36,7 +42,12 @@ const { }, } = require('internal/errors'); -const { isSharedArrayBuffer, isUint8Array } = require('internal/util/types'); +const { + isAnyArrayBuffer, + isSharedArrayBuffer, + isTypedArray, + isUint8Array, +} = require('internal/util/types'); const { kWeakHandler } = require('internal/event_target'); const { AbortController, @@ -846,6 +857,93 @@ function copyBytes(chunk) { return copy; } +// V8 keeps typed arrays of up to this many bytes on the heap, without an +// ArrayBuffer, until their buffer is read. Larger ones always have one. +const kMaxOnHeapByteLength = 64; + +/** + * Whether `buffer` is a fixed-length, non-shared ArrayBuffer that is not + * detached, whose bytes are received without a copy. `byteLength` is what + * the receiver covers: only when it is 0 can the buffer be detached. + * @param {ArrayBuffer|SharedArrayBuffer} buffer + * @param {number} byteLength + * @returns {boolean} + */ +function isFixedArrayBuffer(buffer, byteLength) { + try { + // The resizable getter is an ArrayBuffer brand check: it throws for a + // SharedArrayBuffer, which saves a separate check on this hot path. + if (ArrayBufferPrototypeGetResizable(buffer)) return false; + } catch { + return false; + } + return byteLength !== 0 || !ArrayBufferPrototypeGetDetached(buffer); +} + +/** + * Whether `value` is a Uint8Array that is received as it is: one that is + * not backed by a SharedArrayBuffer or a resizable ArrayBuffer, and not + * detached. receiveBytes() copies or rejects the others. + * @param {any} value + * @returns {boolean} + */ +function isFixedUint8Array(value) { + if (!isUint8Array(value)) return false; + const byteLength = TypedArrayPrototypeGetByteLength(value); + // A typed array without a buffer is on the heap: neither shared, + // resizable nor detached. Reading its buffer would move its contents to + // a new ArrayBuffer. + if (byteLength <= kMaxOnHeapByteLength && + !arrayBufferViewHasBuffer(value)) { + return true; + } + return isFixedArrayBuffer(TypedArrayPrototypeGetBuffer(value), byteLength); +} + +/** + * Receive bytes from an ArrayBuffer, a SharedArrayBuffer or an + * ArrayBufferView, as a Uint8Array. Shared and resizable memory is copied, + * so that what was received cannot change or be resized afterwards; other + * buffers are not. Throws a TypeError for a detached buffer. + * @param {ArrayBuffer|SharedArrayBuffer|ArrayBufferView} source + * @returns {Uint8Array} + */ +function receiveBytes(source) { + if (isFixedUint8Array(source)) return source; + let buffer; + let byteOffset = 0; + let byteLength; + if (isAnyArrayBuffer(source)) { + buffer = source; + } else if (isTypedArray(source)) { + buffer = TypedArrayPrototypeGetBuffer(source); + byteOffset = TypedArrayPrototypeGetByteOffset(source); + byteLength = TypedArrayPrototypeGetByteLength(source); + } else { + buffer = DataViewPrototypeGetBuffer(source); + try { + byteOffset = DataViewPrototypeGetByteOffset(source); + byteLength = DataViewPrototypeGetByteLength(source); + } catch { + // The buffer is detached, or the view is out of bounds of a shrunk + // resizable buffer: like a typed array, it covers no bytes. + byteOffset = 0; + byteLength = 0; + } + } + // A byteLength of 0 for a buffer has its detached state checked. + const fixed = isFixedArrayBuffer(buffer, byteLength ?? 0); + if (!fixed && !isSharedArrayBuffer(buffer) && + ArrayBufferPrototypeGetDetached(buffer)) { + throw new ERR_INVALID_STATE.TypeError( + 'Cannot receive bytes from a detached ArrayBuffer'); + } + // For a buffer, a view of all of it: what it currently covers. + const view = byteLength === undefined ? + new Uint8Array(buffer) : new Uint8Array(buffer, byteOffset, byteLength); + return fixed ? view : copyBytes(view); +} + /** * Concatenate multiple Uint8Arrays into a single Uint8Array. * @param {Uint8Array[]} chunks @@ -896,9 +994,10 @@ const kWriteOptionsContext = ObjectFreeze({ __proto__: null, context: 'options' }); /** - * Convert an array of chunks (strings or Uint8Arrays) to a Uint8Array[]. + * Convert an iterable of Writer chunks (strings, buffers and views, or + * values converted to strings) to a Uint8Array[]. * Always returns a fresh copy of the array. - * @param {Array} chunks + * @param {Iterable} chunks * @returns {Uint8Array[]} */ function convertChunks(chunks) { @@ -906,7 +1005,7 @@ function convertChunks(chunks) { const len = chunks.length; const result = new Array(len); for (let i = 0; i < len; i++) { - result[i] = toUint8Array(chunks[i]); + result[i] = writerChunkToUint8Array(chunks[i]); } return result; } @@ -923,8 +1022,16 @@ function getWriterSignal(options) { return converters.WriteOptions(options, kWriteOptionsContext).signal; } +// A converted WriterChunk to a Uint8Array: a string is UTF-8 encoded, and +// bytes are received (see receiveBytes()). +function writerChunkToUint8Array(chunk) { + if (typeof chunk === 'string') return encodeString(chunk); + return receiveBytes(chunk); +} + function toWriterUint8Array(chunk) { - return toUint8Array(converters.WriterChunk(chunk, kChunkContext)); + return writerChunkToUint8Array( + converters.WriterChunk(chunk, kChunkContext)); } /** @@ -1080,6 +1187,8 @@ module.exports = { snapshotTransform, toUint8Array, toWriterUint8Array, + isFixedUint8Array, + receiveBytes, validateBackpressure, validateBatchEntry, validateBudget, diff --git a/test/parallel/test-stream-iter-receive-bytes.js b/test/parallel/test-stream-iter-receive-bytes.js new file mode 100644 index 000000000000..f90f995744f7 --- /dev/null +++ b/test/parallel/test-stream-iter-receive-bytes.js @@ -0,0 +1,339 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// Shared and resizable memory is copied when stream/iter receives it, so +// that what was received cannot change or be resized afterwards. Other +// buffers are received without a copy, and detached ones are rejected. + +const common = require('../common'); +const assert = require('assert'); +const { open } = require('fs/promises'); +const { readFileSync } = require('fs'); +const tmpdir = require('../common/tmpdir'); +const { + broadcast, + bytes, + bytesSync, + from, + fromSync, + pull, + pullSync, + push, +} = require('stream/iter'); + +const kDetached = { + name: 'TypeError', + code: 'ERR_INVALID_STATE', + message: /detached/, +}; + +// Each factory returns [value, change]: `value` covers the bytes 1, 2, 3, +// and `change()` changes or resizes that memory. +function sharedAndResizable() { + const cases = []; + { + const sab = new SharedArrayBuffer(3); + new Uint8Array(sab).set([1, 2, 3]); + cases.push(['SharedArrayBuffer', sab, () => { + new Uint8Array(sab).fill(9); + }]); + } + { + const sab = new SharedArrayBuffer(4); + new Uint8Array(sab).set([0, 1, 2, 3]); + cases.push(['Uint8Array over SharedArrayBuffer', + new Uint8Array(sab, 1), () => new Uint8Array(sab).fill(9)]); + } + { + const sab = new SharedArrayBuffer(3, { maxByteLength: 8 }); + new Uint8Array(sab).set([1, 2, 3]); + cases.push(['length-tracking view of growable SharedArrayBuffer', + new Uint8Array(sab), () => { + sab.grow(8); + new Uint8Array(sab).fill(9); + }]); + } + { + const sab = new SharedArrayBuffer(3); + new Uint8Array(sab).set([1, 2, 3]); + cases.push(['DataView over SharedArrayBuffer', new DataView(sab), () => { + new Uint8Array(sab).fill(9); + }]); + } + { + const rab = new ArrayBuffer(3, { maxByteLength: 8 }); + new Uint8Array(rab).set([1, 2, 3]); + cases.push(['resizable ArrayBuffer', rab, () => { + rab.resize(8); + new Uint8Array(rab).fill(9); + }]); + } + { + const rab = new ArrayBuffer(3, { maxByteLength: 8 }); + new Uint8Array(rab).set([1, 2, 3]); + cases.push(['length-tracking Uint8Array', new Uint8Array(rab), () => { + rab.resize(1); + }]); + } + { + const rab = new ArrayBuffer(4, { maxByteLength: 8 }); + new Uint8Array(rab).set([1, 2, 3, 4]); + cases.push(['fixed-length view of resizable ArrayBuffer', + new Uint8Array(rab, 0, 3), () => { + new Uint8Array(rab).fill(9); + rab.resize(0); + }]); + } + { + const rab = new ArrayBuffer(3, { maxByteLength: 8 }); + new Uint8Array(rab).set([1, 2, 3]); + cases.push(['DataView of resizable ArrayBuffer', new DataView(rab), () => { + rab.resize(8); + new Uint8Array(rab).fill(9); + }]); + } + return cases; +} + +const kExpected = Uint8Array.of(1, 2, 3); + +function assertReceived(chunk) { + assert.deepStrictEqual(chunk, kExpected); + const buffer = chunk.buffer; + assert.ok(buffer instanceof ArrayBuffer); + assert.strictEqual(buffer.resizable, false); +} + +// from() and fromSync() copy a top-level input when they are called. +async function testTopLevelInput() { + for (const [name, value, change] of sharedAndResizable()) { + const source = from(value); + change(); + const batches = []; + for await (const batch of source) batches.push(batch); + assert.strictEqual(batches.length, 1, name); + assert.strictEqual(batches[0].length, 1, name); + assertReceived(batches[0][0]); + } + for (const [name, value, change] of sharedAndResizable()) { + const source = fromSync(value); + change(); + const batches = [...source]; + assert.strictEqual(batches.length, 1, name); + assertReceived(batches[0][0]); + } +} + +// Values yielded by a source are copied when they are normalized. +async function testYieldedValues() { + for (const asBatch of [false, true]) { + for (const [, value, change] of sharedAndResizable()) { + async function* source() { + yield asBatch ? [value] : value; + change(); + } + const chunks = []; + for await (const batch of from(source())) chunks.push(...batch); + assert.strictEqual(chunks.length, 1); + assertReceived(chunks[0]); + } + for (const [, value, change] of sharedAndResizable()) { + function* source() { + yield asBatch ? [value] : value; + change(); + } + const chunks = []; + for (const batch of fromSync(source())) chunks.push(...batch); + assert.strictEqual(chunks.length, 1); + assertReceived(chunks[0]); + } + } + + // In a batch of several chunks, only the shared one is copied. + const fixed = Uint8Array.of(4, 5); + const sab = new SharedArrayBuffer(3); + new Uint8Array(sab).set([1, 2, 3]); + const [batch] = [...fromSync([[fixed, new Uint8Array(sab)]])]; + new Uint8Array(sab).fill(9); + assert.strictEqual(batch[0], fixed); + assertReceived(batch[1]); +} + +// Transform output is copied when it is normalized, for stateless and +// stateful, sync and async transforms. +async function testTransformOutput() { + const shapes = [ + (value) => value, + (value) => [value], + (value) => [Uint8Array.of(0), value], + ]; + for (const shape of shapes) { + for (const [, value, change] of sharedAndResizable()) { + let changed = false; + const result = await bytes(pull(from('x'), (chunks) => { + if (chunks === null) { + if (!changed) change(); + changed = true; + return null; + } + return shape(value); + })); + assert.deepStrictEqual(result.subarray(-3), kExpected); + } + for (const [, value, change] of sharedAndResizable()) { + const result = bytesSync(pullSync(fromSync('x'), (chunks) => { + if (chunks === null) { + change(); + return null; + } + return shape(value); + })); + assert.deepStrictEqual(result.subarray(-3), kExpected); + } + } + // Two transforms: the output of the first is copied before the second + // sees it. + for (const [, value, change] of sharedAndResizable()) { + const seen = []; + await bytes(pull(from('x'), + (chunks) => (chunks === null ? null : value), + (chunks) => { + if (chunks !== null) { + change(); + seen.push(...chunks); + } + return chunks; + })); + assert.strictEqual(seen.length, 1); + assertReceived(seen[0]); + } + for (const [, value, change] of sharedAndResizable()) { + const stateful = { + async* transform(source) { + for await (const chunks of source) { + if (chunks === null) continue; + yield value; + change(); + } + }, + }; + const result = await bytes(pull(from('x'), stateful)); + assertReceived(result); + } + for (const [, value, change] of sharedAndResizable()) { + const stateful = { + * transform(source) { + for (const chunks of source) { + if (chunks === null) continue; + yield [value]; + change(); + } + }, + }; + const result = bytesSync(pullSync(fromSync('x'), stateful)); + assertReceived(result); + } +} + +// Chunks passed to a writer are copied when they are passed. +async function testWriters() { + const writers = [ + () => { + const { writer, readable } = push(); + return { writer, readable }; + }, + () => { + const { writer, broadcast: bc } = broadcast(); + return { writer, readable: bc.push() }; + }, + ]; + for (const createWriter of writers) { + for (const method of ['write', 'writeSync', 'writev', 'writevSync']) { + for (const [, value, change] of sharedAndResizable()) { + if (!(value instanceof Uint8Array)) continue; + const { writer, readable } = createWriter(); + const result = writer[method]( + method.startsWith('writev') ? [value] : value); + change(); + await result; + writer.endSync(); + assertReceived(await bytes(readable)); + } + } + } +} + +async function testFileHandleWriter() { + tmpdir.refresh(); + const file = tmpdir.resolve('receive-bytes.bin'); + const fh = await open(file, 'w'); + const w = fh.writer(); + const sab = new SharedArrayBuffer(3); + new Uint8Array(sab).set([1, 2, 3]); + const pending = w.write(new Uint8Array(sab)); + new Uint8Array(sab).fill(9); + await pending; + const rab = new ArrayBuffer(2, { maxByteLength: 4 }); + new Uint8Array(rab).set([4, 5]); + const pending2 = w.writev([new Uint8Array(rab)]); + rab.resize(0); + await pending2; + await w.end(); + await fh.close(); + assert.deepStrictEqual(readFileSync(file), Buffer.from([1, 2, 3, 4, 5])); +} + +// Fixed-length, non-shared buffers are not copied. +async function testFixedBuffersNotCopied() { + const ab = new ArrayBuffer(4); + const [[chunk]] = [...fromSync(ab)]; + assert.strictEqual(chunk.buffer, ab); + const u8 = new Uint8Array(ab, 1, 2); + assert.strictEqual([...fromSync(u8)][0][0], u8); + const u16 = new Uint16Array(ab); + const [[fromU16]] = [...fromSync(u16)]; + assert.strictEqual(fromU16.buffer, ab); + const { writer, readable } = push(); + writer.writeSync(u8); + writer.endSync(); + for await (const batch of readable) assert.strictEqual(batch[0], u8); +} + +// Detached buffers are rejected with a TypeError. +async function testDetached() { + const detached = () => { + const ab = new ArrayBuffer(4); + const view = new Uint8Array(ab); + const u16 = new Uint16Array(ab); + ab.transfer(); + return { ab, view, u16 }; + }; + for (const key of ['ab', 'view', 'u16']) { + assert.throws(() => fromSync(detached()[key]), kDetached); + assert.throws(() => from(detached()[key]), kDetached); + const value = detached()[key]; + await assert.rejects(bytes(from((async function*() { + yield value; + })())), kDetached); + assert.throws(() => bytesSync(fromSync([[detached()[key]]])), kDetached); + await assert.rejects( + bytes(pull(from('x'), (c) => (c === null ? null : [value]))), + kDetached); + } + const { view } = detached(); + const { writer } = push(); + assert.throws(() => writer.writeSync(view), kDetached); + assert.throws(() => writer.writevSync([view]), kDetached); + await assert.rejects(writer.write(view), kDetached); + await assert.rejects(writer.writev([view]), kDetached); +} + +Promise.all([ + testTopLevelInput(), + testYieldedValues(), + testTransformOutput(), + testWriters(), + testFileHandleWriter(), + testFixedBuffersNotCopied(), + testDetached(), +]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-resizable-buffers.js b/test/parallel/test-stream-iter-resizable-buffers.js index 675e69496535..fbc0dda0837e 100644 --- a/test/parallel/test-stream-iter-resizable-buffers.js +++ b/test/parallel/test-stream-iter-resizable-buffers.js @@ -35,15 +35,22 @@ async function testBufferedViewMutationRejected() { const { writer, readable } = push(); assert.strictEqual(writer.writeSync(view), true); mutate(); - await assert.rejects( - readable[Symbol.asyncIterator]().next(), - kResizeError, - ); + if (view.buffer === detachable) { + await assert.rejects( + readable[Symbol.asyncIterator]().next(), + kResizeError, + ); + } else { + // Shared and resizable memory is copied when it is written: resizing + // it afterwards does not change what was written. + const { value } = await readable[Symbol.asyncIterator]().next(); + assert.deepStrictEqual(value, [new Uint8Array(1)]); + } } } // Several buffered writes, single chunks and batches, read as one batch: -// they are delivered in order, and a view resized after it was written +// they are delivered in order, and a view detached after it was written // among them rejects the read. async function testBufferedEntriesReadTogether() { { @@ -56,7 +63,7 @@ async function testBufferedEntriesReadTogether() { assert.deepStrictEqual(batches.map((c) => c[0]), [1, 2, 3, 4]); } for (const single of [true, false]) { - const buffer = new ArrayBuffer(1, { maxByteLength: 2 }); + const buffer = new ArrayBuffer(1); const { writer, readable } = push(); writer.writeSync(Uint8Array.of(1)); writer.writevSync([Uint8Array.of(2), Uint8Array.of(3)]); @@ -65,7 +72,7 @@ async function testBufferedEntriesReadTogether() { } else { writer.writevSync([Uint8Array.of(4), new Uint8Array(buffer)]); } - buffer.resize(2); + buffer.transfer(); await assert.rejects( readable[Symbol.asyncIterator]().next(), kResizeError, @@ -74,7 +81,7 @@ async function testBufferedEntriesReadTogether() { } async function testDropOldestUsesAcceptedByteLength() { - const buffer = new ArrayBuffer(16384, { maxByteLength: 16384 }); + const buffer = new ArrayBuffer(16384); const { writer, broadcast: bc } = broadcast({ budget: 16384, backpressure: 'drop-oldest', @@ -82,7 +89,7 @@ async function testDropOldestUsesAcceptedByteLength() { const iterator = bc.push()[Symbol.asyncIterator](); assert.strictEqual(writer.writeSync(new Uint8Array(buffer)), true); - buffer.resize(0); + buffer.transfer(); assert.strictEqual(writer.writeSync(Uint8Array.of(2)), true); assert.strictEqual(writer.writeSync(Uint8Array.of(3)), true); writer.endSync(); @@ -96,10 +103,10 @@ async function testPendingWritesRejectResizedViews() { const pushResult = push({ budget: 16384, backpressure: 'unbounded' }); assert.strictEqual( pushResult.writer.writeSync(new Uint8Array(16384)), true); - const pushBuffer = new ArrayBuffer(1, { maxByteLength: 2 }); + const pushBuffer = new ArrayBuffer(1); const pushPending = pushResult.writer.write(new Uint8Array(pushBuffer)); const pushRejected = assert.rejects(pushPending, kResizeError); - pushBuffer.resize(2); + pushBuffer.transfer(); const pushIterator = pushResult.readable[Symbol.asyncIterator](); assert.strictEqual((await pushIterator.next()).done, false); await pushRejected; @@ -112,10 +119,10 @@ async function testPendingWritesRejectResizedViews() { }); const broadcastIterator = bc.push()[Symbol.asyncIterator](); assert.strictEqual(writer.writeSync(new Uint8Array(16384)), true); - const broadcastBuffer = new ArrayBuffer(1, { maxByteLength: 2 }); + const broadcastBuffer = new ArrayBuffer(1); const broadcastPending = writer.write(new Uint8Array(broadcastBuffer)); const broadcastRejected = assert.rejects(broadcastPending, kResizeError); - broadcastBuffer.resize(2); + broadcastBuffer.transfer(); assert.strictEqual((await broadcastIterator.next()).done, false); await broadcastRejected; writer.endSync(); @@ -123,12 +130,12 @@ async function testPendingWritesRejectResizedViews() { } async function testBroadcastRejectsResizedBufferedView() { - const buffer = new ArrayBuffer(1, { maxByteLength: 2 }); + const buffer = new ArrayBuffer(1); const { writer, broadcast: bc } = broadcast(); const iterator = bc.push()[Symbol.asyncIterator](); assert.strictEqual(writer.writeSync(new Uint8Array(buffer)), true); - buffer.resize(2); + buffer.transfer(); await assert.rejects(iterator.next(), kResizeError); await assert.rejects(writer.end(), kResizeError); @@ -137,67 +144,67 @@ async function testBroadcastRejectsResizedBufferedView() { // The same, for a view buffered in a batch of several chunks. async function testBufferedBatchViewResizeRejected() { { - const buffer = new ArrayBuffer(1, { maxByteLength: 2 }); + const buffer = new ArrayBuffer(1); const { writer, broadcast: bc } = broadcast(); const iterator = bc.push()[Symbol.asyncIterator](); assert.strictEqual( writer.writevSync([Uint8Array.of(1), new Uint8Array(buffer)]), true); - buffer.resize(2); + buffer.transfer(); await assert.rejects(iterator.next(), kResizeError); await assert.rejects(writer.end(), kResizeError); } { - const buffer = new ArrayBuffer(1, { maxByteLength: 2 }); + const buffer = new ArrayBuffer(1); const shared = share([[Uint8Array.of(1), new Uint8Array(buffer)]]); const first = shared.pull()[Symbol.asyncIterator](); const second = shared.pull()[Symbol.asyncIterator](); assert.strictEqual((await first.next()).value.length, 2); - buffer.resize(2); + buffer.transfer(); await assert.rejects(second.next(), kResizeError); } } async function testShareRejectsResizedBufferedView() { - const asyncBuffer = new ArrayBuffer(1, { maxByteLength: 2 }); + const asyncBuffer = new ArrayBuffer(1); const shared = share([[new Uint8Array(asyncBuffer)]]); const first = shared.pull()[Symbol.asyncIterator](); const second = shared.pull()[Symbol.asyncIterator](); assert.strictEqual((await first.next()).done, false); - asyncBuffer.resize(2); + asyncBuffer.transfer(); await assert.rejects(second.next(), kResizeError); - const syncBuffer = new ArrayBuffer(1, { maxByteLength: 2 }); + const syncBuffer = new ArrayBuffer(1); const sharedSync = shareSync([[new Uint8Array(syncBuffer)]]); const firstSync = sharedSync.pull()[Symbol.iterator](); const secondSync = sharedSync.pull()[Symbol.iterator](); assert.strictEqual(firstSync.next().done, false); - syncBuffer.resize(2); + syncBuffer.transfer(); assert.throws(() => secondSync.next(), kResizeError); } async function testConsumersRejectResizedViews() { - const asyncBuffer = new ArrayBuffer(1, { maxByteLength: 2 }); + const asyncBuffer = new ArrayBuffer(1); async function* asyncSource() { yield [new Uint8Array(asyncBuffer)]; - asyncBuffer.resize(2); + asyncBuffer.transfer(); } await assert.rejects(array(asyncSource(), { limit: 1 }), kResizeError); - const syncBuffer = new ArrayBuffer(1, { maxByteLength: 2 }); + const syncBuffer = new ArrayBuffer(1); function* syncSource() { yield [new Uint8Array(syncBuffer)]; - syncBuffer.resize(2); + syncBuffer.transfer(); } assert.throws(() => arraySync(syncSource(), { limit: 1 }), kResizeError); } async function testPipeRejectsWriterResize() { - const asyncBuffer = new ArrayBuffer(1, { maxByteLength: 2 }); + const asyncBuffer = new ArrayBuffer(1); const asyncWriter = { write() { - asyncBuffer.resize(2); + asyncBuffer.transfer(); }, fail: common.mustCall(), }; @@ -206,10 +213,10 @@ async function testPipeRejectsWriterResize() { kResizeError, ); - const syncBuffer = new ArrayBuffer(1, { maxByteLength: 2 }); + const syncBuffer = new ArrayBuffer(1); const syncWriter = { writeSync() { - syncBuffer.resize(2); + syncBuffer.transfer(); return true; }, fail: common.mustCall(), @@ -222,8 +229,9 @@ async function testPipeRejectsWriterResize() { } // Single-chunk batches are checked around writeSync() without a snapshot -// object. Detaching or resizing the view in writeSync() must still be -// rejected, for views on ArrayBuffers and on growable SharedArrayBuffers. +// object. Detaching the view in writeSync() must still be rejected. Views on +// resizable ArrayBuffers and growable SharedArrayBuffers are copied when +// they are received, so resizing them in writeSync() changes nothing. async function testPipeRejectsSyncWriteDetachOrResize() { const cases = [ ['detach', () => new ArrayBuffer(2), (buffer) => buffer.transfer()], @@ -232,25 +240,37 @@ async function testPipeRejectsSyncWriteDetachOrResize() { ['grow shared', () => new SharedArrayBuffer(1, { maxByteLength: 2 }), (buffer) => buffer.grow(2)], ]; - for (const [, createBuffer, change] of cases) { + for (const [name, createBuffer, change] of cases) { const asyncBuffer = createBuffer(); - await assert.rejects(pipeTo([new Uint8Array(asyncBuffer)], { + const asyncPipe = pipeTo([new Uint8Array(asyncBuffer)], { writeSync() { change(asyncBuffer); return true; }, write: common.mustNotCall(), - fail: common.mustCall(), - }), kResizeError); + fail: common.mustCall(name === 'detach' ? 1 : 0), + }, { preventClose: true }); + if (name === 'detach') { + await assert.rejects(asyncPipe, kResizeError); + } else { + assert.strictEqual(await asyncPipe, 1); + } const syncBuffer = createBuffer(); - assert.throws(() => pipeToSync([new Uint8Array(syncBuffer)], { + const syncWriter = { writeSync() { change(syncBuffer); return true; }, - fail: common.mustCall(), - }, { preventClose: true }), kResizeError); + fail: common.mustCall(name === 'detach' ? 1 : 0), + }; + const syncPipe = () => pipeToSync( + [new Uint8Array(syncBuffer)], syncWriter, { preventClose: true }); + if (name === 'detach') { + assert.throws(syncPipe, kResizeError); + } else { + assert.strictEqual(syncPipe(), 1); + } } // An unchanged view is written; when writeSync() declines it, pipeTo() @@ -366,24 +386,27 @@ async function testPipeRejectsDetachWithWriteOnly() { }), kResizeError); } -// Only what was accounted for a view is checked: its byteLength. A -// fixed-length view of a resizable buffer that stays in bounds is unchanged. +// A fixed-length view of a resizable buffer is copied when it is written: +// resizing the buffer afterwards, even so that the view is out of bounds, +// does not change what was written. async function testFixedLengthViewOfResizedBuffer() { const buffer = new ArrayBuffer(4, { maxByteLength: 8 }); const view = new Uint8Array(buffer, 0, 2); + view.set([1, 2]); const { writer, readable } = push(); assert.strictEqual(writer.writeSync(view), true); buffer.resize(8); + view[0] = 3; writer.endSync(); const [chunk] = await array(readable); - assert.strictEqual(chunk, view); + assert.notStrictEqual(chunk, view); + assert.deepStrictEqual(chunk, Uint8Array.of(1, 2)); - // Shrinking the buffer so that the view is out of bounds makes its - // byteLength 0: rejected. const { writer: writer2, readable: readable2 } = push(); assert.strictEqual(writer2.writeSync(view), true); buffer.resize(1); - await assert.rejects(readable2[Symbol.asyncIterator]().next(), kResizeError); + writer2.endSync(); + assert.deepStrictEqual(await array(readable2), [Uint8Array.of(3, 2)]); } Promise.all([ From 3148222037e2710ed899dcbebafb9c196dbbc3f8 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 17:37:09 +0000 Subject: [PATCH 12/26] stream: accept buffer sources in stream/iter writers Writer chunks may now be any ArrayBuffer, SharedArrayBuffer or ArrayBufferView, which are written as their bytes, matching the Iterable Streams WriterChunk type. Previously, anything other than a Uint8Array was converted to a string. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/fs.md | 13 +- doc/api/stream_iter.md | 17 +- lib/internal/streams/iter/webidl.js | 24 ++- test/parallel/test-stream-iter-validation.js | 2 +- .../test-stream-iter-writer-buffersource.js | 196 ++++++++++++++++++ 5 files changed, 233 insertions(+), 19 deletions(-) create mode 100644 test/parallel/test-stream-iter-writer-buffersource.js diff --git a/doc/api/fs.md b/doc/api/fs.md index 186ab76c0989..1296de527cd2 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -1093,15 +1093,16 @@ added: performance. **Default:** `131072` (128 KB). * Returns: {Object} * `write(chunk[, options])` {Function} Returns {Promise}. - Accepts `Uint8Array`, `Buffer`, or string (UTF-8 encoded). - * `chunk` {Buffer|TypedArray|DataView|string} + Accepts any `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `DataView`, + or `Buffer`, or a string (UTF-8 encoded). + * `chunk` {Buffer|TypedArray|DataView|ArrayBuffer|SharedArrayBuffer|string} * `options` {Object} * `signal` {AbortSignal} If the signal is already aborted, the write rejects with `AbortError` without performing I/O. * `writev(chunks[, options])` {Function} Returns {Promise}. Uses scatter/gather I/O via a single `writev()` syscall. Accepts mixed - `Uint8Array`/string arrays. - * `chunks` {Buffer\[]|TypedArray\[]|DataView\[]|string\[]} + arrays of the same chunk types as `write()`. + * `chunks` {Buffer\[]|TypedArray\[]|DataView\[]|ArrayBuffer\[]|SharedArrayBuffer\[]|string\[]} * `options` {Object} * `signal` {AbortSignal} If the signal is already aborted, the write rejects with `AbortError` without performing I/O. @@ -1110,10 +1111,10 @@ added: should fall back to async `write()`. Returns `false` when: the writer is closed/errored, an async operation is in flight, the chunk exceeds `chunkSize`, or the write would exceed `limit`. - * `chunk` {Buffer|TypedArray|DataView|string} + * `chunk` {Buffer|TypedArray|DataView|ArrayBuffer|SharedArrayBuffer|string} * `writevSync(chunks)` {Function} Returns {boolean}. Synchronous batch write. Same fallback semantics as `writeSync()`. - * `chunks` {Buffer\[]|TypedArray\[]|DataView\[]|string\[]} + * `chunks` {Buffer\[]|TypedArray\[]|DataView\[]|ArrayBuffer\[]|SharedArrayBuffer\[]|string\[]} * `end([options])` {Function} Returns {Promise}, fulfills with the total number of bytes written. Idempotent: returns `totalBytesWritten` if already closed, returns the pending promise if already closing. Rejects if the writer diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index cf9cbe9850b5..3d8447a8d79e 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -440,8 +440,11 @@ const { writer, readable } = push({ A writer is any object conforming to the Writer interface. Only `write()` is required; all other methods are optional. -Writer arguments use Web IDL conversion semantics. A non-`Uint8Array` chunk is -converted to a `USVString` and then UTF-8 encoded. `writev()` and +Writer arguments use Web IDL conversion semantics. A chunk is a string, which +is UTF-8 encoded, or an {ArrayBuffer}, {SharedArrayBuffer}, or +{ArrayBufferView} (such as a {Buffer}, {DataView}, or any typed array), which +is written as its bytes (see [Byte streams][]). Any other value is converted to +a `USVString` and then UTF-8 encoded. `writev()` and `writevSync()` accept any iterable object whose values can be converted to chunks. Writer option dictionaries treat `null` as an empty dictionary and ignore unknown members. @@ -533,7 +536,7 @@ already closed or errored, resolves immediately. #### `writer.write(chunk[, options])` -* `chunk` {Uint8Array|string} +* `chunk` {string|ArrayBuffer|SharedArrayBuffer|ArrayBufferView} * `options` {Object} * `signal` {AbortSignal} Cancel just this write operation. The signal cancels only the pending `write()` call; it does not fail the writer itself. @@ -543,7 +546,7 @@ Write a chunk. #### `writer.writeSync(chunk)` -* `chunk` {Uint8Array|string} +* `chunk` {string|ArrayBuffer|SharedArrayBuffer|ArrayBufferView} * Returns: {boolean} `true` if the write was accepted, `false` if the buffer is full. @@ -551,7 +554,8 @@ Synchronous write. Does not block; returns `false` if backpressure is active. #### `writer.writev(chunks[, options])` -* `chunks` {Iterable} of {Uint8Array|string} values +* `chunks` {Iterable} of {string|ArrayBuffer|SharedArrayBuffer|ArrayBufferView} + values * `options` {Object} * `signal` {AbortSignal} Cancel just this write operation. The signal cancels only the pending `writev()` call; it does not fail the writer itself. @@ -561,7 +565,8 @@ Write multiple chunks as a single batch. #### `writer.writevSync(chunks)` -* `chunks` {Iterable} of {Uint8Array|string} values +* `chunks` {Iterable} of {string|ArrayBuffer|SharedArrayBuffer|ArrayBufferView} + values * Returns: {boolean} `true` if the write was accepted, `false` if the buffer is full. diff --git a/lib/internal/streams/iter/webidl.js b/lib/internal/streams/iter/webidl.js index 79e711a1e64b..812cc03c3aee 100644 --- a/lib/internal/streams/iter/webidl.js +++ b/lib/internal/streams/iter/webidl.js @@ -1,5 +1,9 @@ 'use strict'; +const { + ArrayBufferIsView, +} = primordials; + const { converters: baseConverters, convertToInt, @@ -9,7 +13,7 @@ const { } = require('internal/webidl'); // Load AbortSignal to register its Web IDL converter in baseConverters. require('internal/abort_controller'); -const { isUint8Array } = require('internal/util/types'); +const { isAnyArrayBuffer, isUint8Array } = require('internal/util/types'); const converters = { __proto__: null }; @@ -31,12 +35,20 @@ converters.BackpressurePolicy = createEnumConverter('BackpressurePolicy', [ 'drop-newest', ]); converters.enforceRangeUnsignedLongLong = enforceRangeUnsignedLongLong; +// typedef ([AllowShared, AllowResizable] ArrayBufferView or +// [AllowResizable] ArrayBuffer or +// [AllowResizable] SharedArrayBuffer or USVString) WriterChunk; converters.WriterChunk = (value, options = { __proto__: null }) => { - // The chunk is a Uint8Array with [AllowShared] and [AllowResizable]. The - // Uint8Array conversion cannot reject a value isUint8Array() accepts when - // both are allowed, and returns the same object, so skip it: writes are - // hot, and the conversion would need its own options object. - if (isUint8Array(value)) return value; + // With [AllowShared] and [AllowResizable], the buffer source conversions + // cannot reject a value these checks accept, and return the same object, + // so skip them: writes are hot, and the conversions would need their own + // options objects. Uint8Array, the common case, is checked first. + if (isUint8Array(value) || + (typeof value === 'object' && value !== null && + (ArrayBufferIsView(value) || isAnyArrayBuffer(value)))) { + return value; + } + // Any other value is converted to a string, as for a union. return baseConverters.USVString(value, options); }; converters.WriterChunkSequence = createSequenceConverter( diff --git a/test/parallel/test-stream-iter-validation.js b/test/parallel/test-stream-iter-validation.js index 66aa91dfae65..c89719ed3b1f 100644 --- a/test/parallel/test-stream-iter-validation.js +++ b/test/parallel/test-stream-iter-validation.js @@ -120,7 +120,7 @@ for (const writer of [push().writer, broadcast().writer]) { assert.strictEqual(writer.endSync(), 0); } -// Writer chunks use the Web IDL (Uint8Array or USVString) conversion. +// Writer chunks use the Web IDL (BufferSource or USVString) conversion. { const { writer } = push(); assert.throws(() => writer.writeSync(Symbol()), diff --git a/test/parallel/test-stream-iter-writer-buffersource.js b/test/parallel/test-stream-iter-writer-buffersource.js new file mode 100644 index 000000000000..3603f368d0fa --- /dev/null +++ b/test/parallel/test-stream-iter-writer-buffersource.js @@ -0,0 +1,196 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// Writers accept any BufferSource as bytes: an ArrayBuffer, a +// SharedArrayBuffer, or any ArrayBufferView. Shared and resizable memory is +// copied when it is written. Other values are converted to strings. + +const common = require('../common'); +const assert = require('assert'); +const { open } = require('fs/promises'); +const { readFileSync } = require('fs'); +const { Writable } = require('stream'); +const tmpdir = require('../common/tmpdir'); +const { + broadcast, + bytes, + fromWritable, + push, +} = require('stream/iter'); + +// Each returns a chunk whose bytes are 1, 2, 3, 4. +function bufferSources() { + const bytes = [1, 2, 3, 4]; + const ab = Uint8Array.from(bytes).buffer; + const sab = new SharedArrayBuffer(4); + new Uint8Array(sab).set(bytes); + const rab = new ArrayBuffer(4, { maxByteLength: 8 }); + new Uint8Array(rab).set(bytes); + const offset = new ArrayBuffer(6); + new Uint8Array(offset).set(bytes, 1); + return [ + ['ArrayBuffer', ab], + ['SharedArrayBuffer', sab], + ['resizable ArrayBuffer', rab], + ['DataView', new DataView(offset, 1, 4)], + ['Uint16Array', new Uint16Array(Uint8Array.from(bytes).buffer)], + ['Int8Array', Int8Array.from(bytes)], + ['Float32Array', new Float32Array(Uint8Array.from(bytes).buffer)], + ['Buffer', Buffer.from(bytes)], + ['Uint16Array over SharedArrayBuffer', new Uint16Array(sab)], + ['DataView over SharedArrayBuffer', new DataView(sab)], + ['length-tracking Uint16Array', new Uint16Array(rab)], + ]; +} + +const kExpected = Uint8Array.of(1, 2, 3, 4); + +function writers() { + return [ + ['push', () => { + const { writer, readable } = push(); + const result = bytes(readable); + return { writer, done: () => result }; + }], + ['broadcast', () => { + const { writer, broadcast: bc } = broadcast(); + const result = bytes(bc.push()); + return { writer, done: () => result }; + }], + ['fromWritable', () => { + const chunks = []; + const writable = new Writable({ + write(chunk, encoding, callback) { + chunks.push(chunk); + callback(); + }, + }); + const writer = fromWritable(writable); + return { + writer, + done: async () => new Uint8Array(Buffer.concat(chunks)), + }; + }], + ]; +} + +async function testWritersAcceptBufferSources() { + for (const [writerName, createWriter] of writers()) { + for (const method of ['write', 'writeSync', 'writev', 'writevSync']) { + for (const [name, chunk] of bufferSources()) { + const { writer, done } = createWriter(); + const vector = method.startsWith('writev'); + const accepted = await writer[method](vector ? [chunk] : chunk); + // fromWritable() has no synchronous writes. + if (accepted === false) { + assert.strictEqual(writerName, 'fromWritable'); + await writer[method.slice(0, -4)](vector ? [chunk] : chunk); + } + await writer.end(); + assert.deepStrictEqual(await done(), kExpected, + `${writerName} ${method} ${name}`); + } + } + } +} + +// A mixed writev() batch. +async function testMixedBatch() { + const { writer, readable } = push(); + const sab = new SharedArrayBuffer(1); + new Uint8Array(sab)[0] = 0x63; + writer.writevSync([ + 'a', Uint8Array.of(0x62).buffer, new DataView(sab), new Uint16Array(0), + ]); + writer.endSync(); + assert.deepStrictEqual(await bytes(readable), Uint8Array.of(0x61, 0x62, 0x63)); +} + +// Fixed-length, non-shared buffers are written without a copy; shared and +// resizable ones are copied when they are written. +async function testCopyOnWrite() { + { + const ab = new ArrayBuffer(4); + const { writer, readable } = push(); + writer.writeSync(ab); + writer.writeSync(new DataView(ab, 1, 2)); + writer.endSync(); + const batches = []; + for await (const batch of readable) batches.push(...batch); + assert.strictEqual(batches[0].buffer, ab); + assert.strictEqual(batches[1].buffer, ab); + assert.strictEqual(batches[1].byteOffset, 1); + assert.strictEqual(batches[1].byteLength, 2); + } + for (let i = 0; i < bufferSources().length; i++) { + // Fresh sources each time: some of them share a buffer. + const [name, chunk] = bufferSources()[i]; + const buffer = ArrayBuffer.isView(chunk) ? chunk.buffer : chunk; + if (!(buffer instanceof SharedArrayBuffer) && !buffer.resizable) continue; + const { writer, readable } = push(); + writer.writeSync(chunk); + new Uint8Array(buffer).fill(9); + if (buffer.resizable) buffer.resize(1); + writer.endSync(); + const result = await bytes(readable); + assert.deepStrictEqual(result, kExpected, name); + assert.strictEqual(result.buffer.resizable, false); + assert.ok(result.buffer instanceof ArrayBuffer); + } +} + +// Detached buffers are rejected with a TypeError. +async function testDetached() { + const ab = new ArrayBuffer(4); + const u16 = new Uint16Array(ab); + ab.transfer(); + const kDetached = { name: 'TypeError', code: 'ERR_INVALID_STATE' }; + for (const chunk of [ab, u16]) { + const { writer } = push(); + assert.throws(() => writer.writeSync(chunk), kDetached); + assert.throws(() => writer.writevSync([chunk]), kDetached); + await assert.rejects(writer.write(chunk), kDetached); + await assert.rejects(writer.writev([chunk]), kDetached); + assert.strictEqual(writer.endSync(), 0); + } +} + +// Other values keep the Web IDL union conversion to a string. +async function testOtherValuesConvertedToStrings() { + const { writer, readable } = push(); + writer.writeSync(12); + writer.writeSync({ toString() { return 'ab'; } }); + writer.writevSync([null, true]); + writer.writeSync([1, 2]); + writer.endSync(); + assert.strictEqual(new TextDecoder().decode(await bytes(readable)), + '12abnulltrue1,2'); +} + +async function testFileHandleWriter() { + tmpdir.refresh(); + const file = tmpdir.resolve('writer-buffersource.bin'); + const fh = await open(file, 'w'); + const w = fh.writer(); + const chunks = bufferSources().map(([, chunk]) => chunk); + for (let i = 0; i < chunks.length; i++) { + if (i % 4 === 0) await w.write(chunks[i]); + else if (i % 4 === 1) assert.strictEqual(w.writeSync(chunks[i]), true); + else if (i % 4 === 2) await w.writev([chunks[i]]); + else assert.strictEqual(w.writevSync([chunks[i]]), true); + } + await w.end(); + await fh.close(); + const expected = Buffer.alloc(chunks.length * 4); + for (let i = 0; i < chunks.length; i++) expected.set(kExpected, i * 4); + assert.deepStrictEqual(readFileSync(file), expected); +} + +Promise.all([ + testWritersAcceptBufferSources(), + testMixedBatch(), + testCopyOnWrite(), + testDetached(), + testOtherValuesConvertedToStrings(), + testFileHandleWriter(), +]).then(common.mustCall()); From d361c7114f58bd7c9b72e4dd554e96995b28450e Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 17:56:45 +0000 Subject: [PATCH 13/26] stream: add a lazy signal to stream/iter writers Writers created by push(), broadcast() and duplex() now have a signal that aborts when the writer stops accepting data for a reason other than end(): the consumer stopped reading, fail() was called, or the broadcast was cancelled. The AbortController is created on first access; if the writer had already stopped, the signal is created aborted with the same reason. Broadcast.cancel() now rejects pending writes with its reason, or with the same TypeError the signal aborts with, after settling the consumers, and pending writes are no longer promoted after cancel. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 75 +++++- lib/internal/streams/iter/broadcast.js | 43 +++- lib/internal/streams/iter/push.js | 46 +++- ...est-stream-iter-broadcast-cancel-writes.js | 86 +++++++ .../test-stream-iter-writer-signal.js | 242 ++++++++++++++++++ 5 files changed, 482 insertions(+), 10 deletions(-) create mode 100644 test/parallel/test-stream-iter-broadcast-cancel-writes.js create mode 100644 test/parallel/test-stream-iter-writer-signal.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index 3d8447a8d79e..6c55319eaf66 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -528,6 +528,75 @@ unconditionally synchronous because failing a writer is a pure state transition with no async work to perform. The reason is stored and propagated without modification. If omitted, the reason is `undefined`. +#### `writer.signal` + + + +* {AbortSignal} + +An {AbortSignal} that aborts when the writer stops accepting data for any +reason other than `end()` or `endSync()`. It lets a producer that is not +currently writing learn that it should stop. This property is optional: a +writer that is not created by this module may not have it. + +The writers created by [`push()`][], [`broadcast()`][], and [`duplex()`][] +have it. Their signal aborts: + +* when the consumer stops reading (for example, it breaks out of a + `for await` loop, or its iterator's `throw()` is called). The reason is the + error that later writes reject with. +* when `writer.fail()` is called, including by an aborted `signal` option of + `push()`, `broadcast()`, or `duplex()`. The reason is the `fail()` reason. If + `fail()` was called with no argument, the reason is an `AbortError` + {DOMException}, as for `abortController.abort()` with no argument. +* for a `broadcast()` writer that is open or closing, when + [`broadcast.cancel()`][] is called. The reason is the cancel reason, or an + `ERR_INVALID_STATE` `TypeError` if none is given: the same value that the + pending writes reject with. + +The signal is aborted once the writer's state, pending writes, `end()` promise, +and drain waiters are updated, so abort listeners observe the stopped writer. +A writer that closes normally never aborts its signal. + +Every access returns the same {AbortSignal}. It is created on first access, so +a writer whose `signal` is never read does not create one. If the writer has +already stopped when `signal` is first read, the signal is created already +aborted, with the same reason. + +```mjs +import { push } from 'node:stream/iter'; + +const { writer, readable } = push(); + +// Stop producing when the writer stops, e.g. because the consumer did. +const timer = setInterval(() => writer.writeSync('tick'), 100); +writer.signal.addEventListener('abort', () => clearInterval(timer)); + +for await (const batch of readable) { + break; // Aborts writer.signal, which clears the interval. +} +``` + +```cjs +const { push } = require('node:stream/iter'); + +async function run() { + const { writer, readable } = push(); + + // Stop producing when the writer stops, e.g. because the consumer did. + const timer = setInterval(() => writer.writeSync('tick'), 100); + writer.signal.addEventListener('abort', () => clearInterval(timer)); + + for await (const batch of readable) { + break; // Aborts writer.signal, which clears the interval. + } +} + +run().catch(console.error); +``` + #### `writer[Symbol.asyncDispose]()` If the writer is open, calls `writer.fail()`. If the writer is closing after @@ -1533,7 +1602,9 @@ exact reason. If it is omitted, consumers complete normally. Cancelling also closes the paired writer: afterwards its `canWrite` is `null` and `write()` rejects with a `TypeError`. This lets a [`Broadcast.from()`][] -pump stop pulling from its source. +pump stop pulling from its source. Writes still pending are not written: they +reject with `reason`, or if none is given with an `ERR_INVALID_STATE` +`TypeError`, the same object that [`writer.signal`][]'s `reason` is. The buffered data is discarded. Consumers created with `broadcast.push()` after cancelling are not registered and read none of the buffered data: their @@ -2508,8 +2579,10 @@ console.log(textSync(stream)); // 'hello world' [`array()`]: #arraysource-options [`arrayBuffer()`]: #arraybuffersource-options [`broadcast()`]: #broadcastoptions +[`broadcast.cancel()`]: #broadcastcancelreason [`bytes()`]: #bytessource-options [`dump()`]: #drainsource-options +[`duplex()`]: #duplexoptions [`from()`]: #frominput [`fromReadable()`]: #fromreadablereadable [`fromSync()`]: #fromsyncinput diff --git a/lib/internal/streams/iter/broadcast.js b/lib/internal/streams/iter/broadcast.js index 9e554fe5615c..133645507674 100644 --- a/lib/internal/streams/iter/broadcast.js +++ b/lib/internal/streams/iter/broadcast.js @@ -360,9 +360,6 @@ class BroadcastImpl { this.#errored = true; } - // Reject pending writes on the writer so the pump doesn't hang - this.#writer?.[kCancelWriter](); - for (const consumer of this.#consumers) { if (consumer.resolve) { if (hasReason) { @@ -388,6 +385,9 @@ class BroadcastImpl { this.#bufferStart += this.#buffer.length; this.#buffer.clear(); this.#bufferedBytes = 0; + // Then reject the pending writes, so that the pump doesn't hang. The + // buffer has no room for them anymore: they are not written. + this.#writer?.[kCancelWriter](reason); this.#cleanupFactorySignal(); const onCancel = this[kOnCancel]; this[kOnCancel] = null; @@ -682,6 +682,11 @@ class BroadcastWriter { #pendingEnd; #pendingWrites = new RingBuffer(); #pendingDrains = []; + // AbortController behind writer.signal, created on first access. + #stopController = null; + // Whether the writer stopped for a reason other than end(). + #stopped = false; + #stopReason; static { // Used in wireBroadcastWriteSignal ensure the signal listener can be @@ -718,6 +723,14 @@ class BroadcastWriter { return this.#state === 'open' ? this.#broadcast[kCanWrite]() : null; } + get signal() { + if (this.#stopController === null) { + this.#stopController = new AbortController(); + if (this.#stopped) this.#stopController.abort(this.#stopReason); + } + return this.#stopController.signal; + } + #canUseWriteFastPath(signal) { return !signal && this.#state === 'open' && this.#broadcast[kCanWrite](); @@ -873,6 +886,7 @@ class BroadcastWriter { this.#rejectPendingDrains(reason); this.#pendingEnd?.reject(reason); this.#broadcast[kAbort](reason); + this.#stop(reason); } [SymbolAsyncDispose]() { @@ -885,13 +899,28 @@ class BroadcastWriter { this.fail(); } - [kCancelWriter]() { + [kCancelWriter](reason) { if (this.#state === 'closed' || this.#state === 'errored') return; this.#state = 'closed'; - this.#rejectPendingWrites( - lazyDOMException('Broadcast cancelled', 'AbortError')); - this.#resolvePendingDrains(false); + // Pending writes reject with the cancel reason, or without one with a + // TypeError, which is also the reason writer.signal aborts with. + const error = reason !== undefined ? reason : + new ERR_INVALID_STATE.TypeError('Broadcast was cancelled'); + this.#rejectPendingWrites(error); this.#pendingEnd?.resolve(this.#totalBytes); + this.#resolvePendingDrains(false); + this.#stop(error); + } + + // Record that the writer stopped accepting data for a reason other than + // end(), and abort writer.signal if it has been created. Called last, once + // the writer's state, pending writes, end promise and drain waiters are + // updated, so that abort listeners observe the stopped writer. + #stop(reason) { + if (this.#stopped) return; + this.#stopped = true; + this.#stopReason = reason; + this.#stopController?.abort(reason); } #getEndPromise() { diff --git a/lib/internal/streams/iter/push.js b/lib/internal/streams/iter/push.js index 22dd47913ca3..cdbaaa8525c1 100644 --- a/lib/internal/streams/iter/push.js +++ b/lib/internal/streams/iter/push.js @@ -23,6 +23,7 @@ const { ERR_INVALID_STATE, }, } = require('internal/errors'); +const { AbortController } = require('internal/abort_controller'); const { drainableProtocol, @@ -119,6 +120,11 @@ class PushQueue { #bytesWritten = 0; /** Pending end promise (resolves when consumer drains past end sentinel) */ #pendingEnd = null; + /** AbortController behind writer.signal, created on first access */ + #stopController = null; + /** Whether the writer stopped for a reason other than end() */ + #stopped = false; + #stopReason; /** Configuration */ #budget; @@ -175,6 +181,19 @@ class PushQueue { return this.#signal; } + /** + * The writer's signal, created on first access. It aborts when the writer + * stops accepting data for a reason other than end(): see #stop(). + * @returns {AbortSignal} + */ + get writerSignal() { + if (this.#stopController === null) { + this.#stopController = new AbortController(); + if (this.#stopped) this.#stopController.abort(this.#stopReason); + } + return this.#stopController.signal; + } + /** * Check if a sync write would be accepted. * @returns {boolean} @@ -406,6 +425,7 @@ class PushQueue { this.#pendingEnd = null; } } + this.#stop(reason); } get totalBytesWritten() { @@ -489,20 +509,22 @@ class PushQueue { this.#consumerState = 'returned'; const error = new ERR_INVALID_STATE.TypeError('Stream closed by consumer'); consumerReturnErrors.add(error); - this.#terminateWriterFromConsumer(error); + const stopped = this.#terminateWriterFromConsumer(error); this.#resolvePendingReads(); // Resolve pending drains with false - no more data will be consumed this.#resolvePendingDrains(false); + if (stopped) this.#stop(error); } consumerThrow(error) { if (this.#consumerState !== 'active') return; this.#consumerState = 'thrown'; this.#consumerError = error; - this.#terminateWriterFromConsumer(error); + const stopped = this.#terminateWriterFromConsumer(error); this.#rejectPendingReads(error); // Reject pending drains - the consumer errored this.#rejectPendingDrains(error); + if (stopped) this.#stop(error); } // =========================================================================== @@ -543,12 +565,16 @@ class PushQueue { } } + // Returns true if this errored the writer: the caller then stops it (see + // #stop()) once the drain waiters are settled. #terminateWriterFromConsumer(error) { this.#slots.clear(); this.#bufferedBytes = 0; + let errored = false; if (this.#writerState === 'open' || this.#writerState === 'closing') { this.#writerState = 'errored'; this.#writerError = error; + errored = true; } this.#cleanup(); this.#rejectPendingWrites(error); @@ -556,6 +582,18 @@ class PushQueue { this.#pendingEnd.reject(error); this.#pendingEnd = null; } + return errored; + } + + // Record that the writer stopped accepting data for a reason other than + // end(), and abort writer.signal if it has been created. Called last, once + // the writer's state, pending writes, end promise and drain waiters are + // updated, so that abort listeners observe the stopped writer. + #stop(reason) { + if (this.#stopped) return; + this.#stopped = true; + this.#stopReason = reason; + this.#stopController?.abort(reason); } #resolvePendingReads() { @@ -684,6 +722,10 @@ class PushWriter { return this.#queue.canWrite; } + get signal() { + return this.#queue.writerSignal; + } + write(chunk, options) { let entry; let signal; diff --git a/test/parallel/test-stream-iter-broadcast-cancel-writes.js b/test/parallel/test-stream-iter-broadcast-cancel-writes.js new file mode 100644 index 000000000000..a17ce33315da --- /dev/null +++ b/test/parallel/test-stream-iter-broadcast-cancel-writes.js @@ -0,0 +1,86 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// Broadcast cancel() and the writer: pending writes reject with the cancel +// reason, or without one with a TypeError, which is also writer.signal's +// abort reason. The writer is stopped last, once the consumers and the +// writer are settled. Pending writes are not written once the broadcast is +// cancelled, even if the consumers detaching frees budget. + +const common = require('../common'); +const assert = require('assert'); +const { broadcast, ondrain } = require('stream/iter'); + +async function testReasonless() { + const { writer, broadcast: bc } = broadcast({ budget: 4 }); + bc.push(); + writer.writeSync('1234'); + const write = writer.write('abcd'); + bc.cancel(); + let error; + await assert.rejects(write, (e) => { + error = e; + return true; + }); + assert.strictEqual(error.name, 'TypeError'); + assert.strictEqual(error.code, 'ERR_INVALID_STATE'); + assert.strictEqual(writer.signal.aborted, true); + assert.strictEqual(writer.signal.reason, error); +} + +// writer.signal created before the cancel. +async function testReasonlessSignalFirst() { + const { writer, broadcast: bc } = broadcast({ budget: 4 }); + const { signal } = writer; + writer.writeSync('1234'); + const write = writer.write('abcd'); + bc.cancel(undefined); + await assert.rejects(write, (error) => error === signal.reason); + assert.strictEqual(signal.reason.name, 'TypeError'); +} + +async function testWithReason() { + for (const reason of [new Error('cancelled'), null, 0, 'reason']) { + const { writer, broadcast: bc } = broadcast({ budget: 4 }); + writer.writeSync('1234'); + const write = writer.write('abcd'); + bc.cancel(reason); + await assert.rejects(write, (error) => error === reason); + assert.strictEqual(writer.signal.reason, reason); + } +} + +// The writer is stopped last: its abort listeners see the consumers detached +// and the writer closed. The pending write is not written, though the +// holding consumer detaching frees the budget. +async function testStopLastAndNoPromotion() { + const { writer, broadcast: bc } = broadcast({ + budget: 4, + backpressure: 'unbounded', + }); + const waiting = bc.push()[Symbol.asyncIterator](); + const holding = bc.push()[Symbol.asyncIterator](); + writer.writeSync('1234'); + await waiting.next(); + const read = waiting.next(); + const write = writer.write('abcd'); + const drain = ondrain(writer); + const end = writer.end(); + writer.signal.addEventListener('abort', common.mustCall(() => { + assert.strictEqual(bc.consumerCount, 0); + assert.strictEqual(writer.canWrite, null); + })); + bc.cancel(); + assert.strictEqual((await read).done, true); + await assert.rejects(write, { name: 'TypeError' }); + assert.strictEqual(await drain, false); + assert.strictEqual(await end, 4); + assert.strictEqual((await holding.next()).done, true); +} + +(async () => { + await testReasonless(); + await testReasonlessSignalFirst(); + await testWithReason(); + await testStopLastAndNoPromotion(); +})().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-writer-signal.js b/test/parallel/test-stream-iter-writer-signal.js new file mode 100644 index 000000000000..b6dfb8e5ed91 --- /dev/null +++ b/test/parallel/test-stream-iter-writer-signal.js @@ -0,0 +1,242 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// Tests for the lazy writer.signal of push(), broadcast() and duplex() +// writers: it aborts when the writer stops for a reason other than end(). + +const common = require('../common'); +const assert = require('assert'); +const { broadcast, duplex, push } = require('stream/iter'); + +function assertAbortError(reason) { + assert.ok(reason instanceof DOMException); + assert.strictEqual(reason.name, 'AbortError'); +} + +// Every get returns the same AbortSignal, not aborted while the writer is open. +{ + const { writer } = push(); + const signal = writer.signal; + assert.ok(signal instanceof AbortSignal); + assert.strictEqual(writer.signal, signal); + assert.strictEqual(signal.aborted, false); +} + +// fail(reason) aborts the signal with that reason. +{ + const { writer } = push(); + const signal = writer.signal; + const reason = new Error('boom'); + signal.addEventListener('abort', common.mustCall(() => { + // Aborted last: the writer is already errored. + assert.strictEqual(writer.canWrite, null); + })); + writer.fail(reason); + assert.strictEqual(signal.aborted, true); + assert.strictEqual(signal.reason, reason); + // A later fail() does not change the reason. + writer.fail(new Error('other')); + assert.strictEqual(signal.reason, reason); +} + +// fail() with no argument: the default AbortError. +{ + const { writer } = push(); + const signal = writer.signal; + writer.fail(); + assert.strictEqual(signal.aborted, true); + assertAbortError(signal.reason); +} + +// First read after the writer stopped: created already aborted. +{ + const { writer } = push(); + const reason = new Error('boom'); + writer.fail(reason); + const signal = writer.signal; + assert.strictEqual(signal.aborted, true); + assert.strictEqual(signal.reason, reason); + assert.strictEqual(writer.signal, signal); +} + +// The push() signal option aborts the writer's signal through fail(). +{ + const ac = new AbortController(); + const { writer } = push({ signal: ac.signal }); + const signal = writer.signal; + assert.notStrictEqual(signal, ac.signal); + const reason = new Error('option abort'); + ac.abort(reason); + assert.strictEqual(signal.aborted, true); + assert.strictEqual(signal.reason, reason); +} + +// A writer that ends normally never aborts its signal, even after the +// consumer stops reading. +(async () => { + const { writer, readable } = push(); + const signal = writer.signal; + signal.addEventListener('abort', common.mustNotCall()); + writer.writeSync('a'); + const ending = writer.end(); + // eslint-disable-next-line no-unused-vars + for await (const _ of readable); + assert.strictEqual(await ending, 1); + writer.fail(new Error('ignored')); + assert.strictEqual(signal.aborted, false); + assert.strictEqual(writer.signal.aborted, false); +})().then(common.mustCall()); + +// endSync() closes without aborting. +{ + const { writer } = push(); + assert.strictEqual(writer.endSync(), 0); + assert.strictEqual(writer.signal.aborted, false); +} + +// Consumer return() aborts the signal with the error later writes reject +// with, after pending writes and drain waiters are settled. +(async () => { + const { writer, readable } = push({ budget: 1 }); + const signal = writer.signal; + writer.writeSync('a'); + const pending = writer.write('b'); + const iterator = readable[Symbol.asyncIterator](); + let pendingSettled = false; + pending.catch(common.mustCall(() => { pendingSettled = true; })); + signal.addEventListener('abort', common.mustCall(() => { + assert.strictEqual(writer.canWrite, null); + })); + await iterator.return(); + assert.strictEqual(signal.aborted, true); + assert.ok(signal.reason instanceof TypeError); + assert.strictEqual(signal.reason.code, 'ERR_INVALID_STATE'); + await assert.rejects(pending, signal.reason); + assert.ok(pendingSettled); + await assert.rejects(writer.write('c'), signal.reason); +})().then(common.mustCall()); + +// A consumer break aborts the signal of a writer that is closing. +(async () => { + const { writer, readable } = push(); + const signal = writer.signal; + writer.writeSync('a'); + writer.writeSync('b'); + const ending = writer.end(); + // eslint-disable-next-line no-unused-vars + for await (const _ of readable) break; + await assert.rejects(ending, signal.reason); + assert.strictEqual(signal.aborted, true); +})().then(common.mustCall()); + +// Consumer throw() aborts the signal with the thrown error. +(async () => { + const { writer, readable } = push(); + const signal = writer.signal; + const error = new Error('consumer threw'); + const iterator = readable[Symbol.asyncIterator](); + await assert.rejects(iterator.throw(error), error); + assert.strictEqual(signal.aborted, true); + assert.strictEqual(signal.reason, error); +})().then(common.mustCall()); + +// The consumer stopping after the writer already failed keeps the reason. +(async () => { + const { writer, readable } = push(); + const reason = new Error('failed first'); + writer.writeSync('a'); + writer.fail(reason); + const iterator = readable[Symbol.asyncIterator](); + await iterator.next(); + await iterator.return(); + assert.strictEqual(writer.signal.reason, reason); +})().then(common.mustCall()); + +// Broadcast writer: fail(), cancel() with and without a reason. +{ + const { writer } = broadcast(); + const signal = writer.signal; + assert.strictEqual(writer.signal, signal); + const reason = new Error('boom'); + writer.fail(reason); + assert.strictEqual(signal.aborted, true); + assert.strictEqual(signal.reason, reason); +} + +{ + const { writer, broadcast: bc } = broadcast(); + const signal = writer.signal; + const reason = new Error('cancelled'); + signal.addEventListener('abort', common.mustCall(() => { + assert.strictEqual(writer.canWrite, null); + })); + bc.cancel(reason); + assert.strictEqual(signal.aborted, true); + assert.strictEqual(signal.reason, reason); +} + +{ + const { writer, broadcast: bc } = broadcast(); + const signal = writer.signal; + bc.cancel(); + assert.strictEqual(signal.aborted, true); + assert.ok(signal.reason instanceof TypeError); + assert.strictEqual(signal.reason.code, 'ERR_INVALID_STATE'); +} + +// Broadcast cancel() first read after the cancel: created already aborted. +{ + const { writer, broadcast: bc } = broadcast(); + const reason = new Error('cancelled'); + bc.cancel(reason); + assert.strictEqual(writer.signal.aborted, true); + assert.strictEqual(writer.signal.reason, reason); +} + +// Broadcast cancel() after the writer closed or failed does not change it. +(async () => { + const { writer, broadcast: bc } = broadcast(); + assert.strictEqual(await writer.end(), 0); + bc.cancel(new Error('late')); + assert.strictEqual(writer.signal.aborted, false); + + const { writer: w2, broadcast: bc2 } = broadcast(); + const reason = new Error('first'); + w2.fail(reason); + bc2.cancel(new Error('late')); + assert.strictEqual(w2.signal.reason, reason); +})().then(common.mustCall()); + +// The broadcast() signal option aborts the writer's signal. +{ + const ac = new AbortController(); + const { writer } = broadcast({ signal: ac.signal }); + const signal = writer.signal; + const reason = new Error('option abort'); + ac.abort(reason); + assert.strictEqual(signal.aborted, true); + assert.strictEqual(signal.reason, reason); +} + +// Duplex writers: the peer stopping to read, the duplex() signal option. +(async () => { + const [a, b] = duplex(); + const signal = a.writer.signal; + // The peer closing stops reading from a: a's writer is cancelled. + await b.close(); + assert.strictEqual(signal.aborted, true); + assert.ok(signal.reason instanceof TypeError); + // The writer of b was ended by close(): its signal does not abort. + assert.strictEqual(b.writer.signal.aborted, false); + await a.close(); +})().then(common.mustCall()); + +{ + const ac = new AbortController(); + const [a, b] = duplex({ signal: ac.signal }); + const reason = new Error('duplex abort'); + const signalA = a.writer.signal; + ac.abort(reason); + assert.strictEqual(signalA.reason, reason); + assert.strictEqual(b.writer.signal.reason, reason); +} From 6f1048dfe7633471a3d40f6f87d26bdcecd6d11b Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 17:56:53 +0000 Subject: [PATCH 14/26] stream: throw the stop reason from stream/iter pipeToSync() When writeSync(), writevSync() or endSync() fails because the writer has stopped, pipeToSync() now throws the abort reason of the writer's signal instead of a RangeError saying the budget is exhausted, or a TypeError saying the writer could not be closed. A write refused by a closed or closing writer throws a TypeError. The signal and canWrite are read only on those failure paths. pipeTo() and pipeToSync() now fail the writer only while it is open, or while awaiting the pipe's own end(), so piping into a writer that another producer is closing no longer interrupts its drain. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 29 +++ lib/internal/abort_controller.js | 8 +- lib/internal/streams/iter/pull.js | 71 +++++++- .../test-stream-iter-pipeto-closing-writer.js | 124 +++++++++++++ ...st-stream-iter-pipetosync-closed-writer.js | 91 ++++++++++ ...test-stream-iter-pipetosync-stop-reason.js | 169 ++++++++++++++++++ 6 files changed, 482 insertions(+), 10 deletions(-) create mode 100644 test/parallel/test-stream-iter-pipeto-closing-writer.js create mode 100644 test/parallel/test-stream-iter-pipetosync-closed-writer.js create mode 100644 test/parallel/test-stream-iter-pipetosync-stop-reason.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index 6c55319eaf66..b86ec69a6366 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -789,6 +789,15 @@ first as a fast path, and fall back to the async versions only when the sync methods indicate they cannot complete (e.g., backpressure or waiting for the next tick). `fail()` is always called synchronously. +When the pipe fails, `writer.fail()` is called with the error (unless +`preventFail` is `true`) only if the writer is still open. A writer whose +`canWrite` is `null` because it is closing (for example, because another +producer called `writer.end()`), closed, or errored is left as it is, so that +a closing writer can still deliver its data. The returned promise rejects with +the error either way. A writer that was open when `pipeTo()` called its +`endSync()` or `end()` is closing because of the pipe, so an error after that, +for example `signal` aborting while `end()` is pending, still fails it. + ```mjs import { from, pipeTo } from 'node:stream/iter'; import { compressGzip } from 'node:zlib/iter'; @@ -857,6 +866,25 @@ example with `await writer.end()`. If the writer cannot be closed any other way (for example, it has no `end()` method), or the caller will not close it, set `failOnIncompleteClose` to fail it with the thrown error instead. +If `writeSync()` or `writevSync()` returns `false`, `pipeToSync()` throws an +`ERR_OUT_OF_RANGE` `RangeError`, since the writer's byte budget is exhausted. +When a write is refused, or `endSync()` returns `-1`, because the writer has +stopped (for example, it was failed, or its consumer stopped reading), +`pipeToSync()` instead throws the reason the writer stopped: if +[`writer.signal`][] is an aborted {AbortSignal}, its `reason` is thrown in place +of the `RangeError` or `TypeError`. `writer.signal` is read only in these cases, +so a writer that creates it lazily does not create it for a pipe that succeeds. + +If a write is refused by a writer that has not stopped but whose `canWrite` is +`null` because it is closed or closing, `pipeToSync()` throws an +`ERR_INVALID_STATE` `TypeError` saying that the writer is closed, instead of +the `RangeError`. `canWrite` is read only once a write was refused. + +As for [`pipeTo()`][], only a writer that is still open is failed when the +pipe fails: a writer that is closing, closed, or errored is left as it is, and +`pipeToSync()` throws the error. `failOnIncompleteClose` is an explicit +request, so it still fails a writer that `endSync()` left closing. + ### `pull(source[, ...transforms][, options])` + +* `reason` {any} **Default:** a new `AbortError` {DOMException}. +* Returns: {Promise} Fulfills with `undefined`. + +Close this end of the duplex channel at once with an error. `abort()` fails +this end's `writer` with `reason`, and stops this end's `readable`: it yields +no more data, and the peer's writer is errored with `reason`, so the peer's +pending and later writes and its [`ondrain()`][] waiters reject with `reason`. +If either writer has already closed, it is not affected. Data already written +to this end's `writer` is still delivered to the peer before it observes +`reason`, as for `writer.fail()`. + +`abort()` does not wait for the peer, and the returned promise is already +fulfilled. Calling `abort()` again has no effect. A pending `close()` promise +rejects with `reason` (it fulfills if the writer had already closed), and +`close()` called after `abort()` returns that same promise. If `close()` was +not called before `abort()`, `close()` returns a promise that fulfills with +`undefined`, so that an `await using` declaration disposing an aborted channel +does not throw. + +```mjs +import { duplex } from 'node:stream/iter'; + +const [client, server] = duplex(); +await using channel = client; + +await channel.writer.write('request'); +// Give up without waiting for the server to read. +await channel.abort(new Error('timed out')); + +try { + for await (const batch of server.readable); +} catch (err) { + console.log(err.message); // 'timed out' +} +``` + +```cjs +const { duplex } = require('node:stream/iter'); + +async function run() { + const [client, server] = duplex(); + await using channel = client; + + await channel.writer.write('request'); + // Give up without waiting for the server to read. + await channel.abort(new Error('timed out')); + + try { + for await (const batch of server.readable); + } catch (err) { + console.log(err.message); // 'timed out' + } +} + +run().catch(console.error); +``` + ## Consumers ### `array(source[, options])` @@ -2609,6 +2677,7 @@ console.log(textSync(stream)); // 'hello world' [`broadcast()`]: #broadcastoptions [`broadcast.cancel()`]: #broadcastcancelreason [`bytes()`]: #bytessource-options +[`channel.abort()`]: #channelabortreason [`dump()`]: #drainsource-options [`duplex()`]: #duplexoptions [`from()`]: #frominput diff --git a/lib/internal/streams/iter/duplex.js b/lib/internal/streams/iter/duplex.js index aa4dee9babca..ee86dbe0da5f 100644 --- a/lib/internal/streams/iter/duplex.js +++ b/lib/internal/streams/iter/duplex.js @@ -6,13 +6,16 @@ // channel's writer appears in the other channel's readable. const { + PromiseResolve, SafePromiseAllReturnVoid, SymbolAsyncDispose, SymbolAsyncIterator, } = primordials; +const { lazyDOMException } = require('internal/util'); const { isConsumerReturnError, + kCancelConsumer, push, } = require('internal/streams/iter/push'); const { @@ -84,15 +87,35 @@ function createDuplexChannel(writer, readable, onClose) { // creation lets close() terminate that state even if no caller has iterated. const closeIterator = readable[SymbolAsyncIterator](); let closePromise; + let aborted = false; return { __proto__: null, get writer() { return writer; }, get readable() { return readable; }, close() { - closePromise ??= closeDuplexChannel(writer, closeIterator, onClose); + // Once close() has been called, later calls return its promise, even + // after abort(). + if (closePromise !== undefined) return closePromise; + // After abort(), closing (e.g. by `await using`) does not throw. + if (aborted) return PromiseResolve(); + closePromise = closeDuplexChannel(writer, closeIterator, onClose); return closePromise; }, + abort(reason) { + if (aborted) return PromiseResolve(); + aborted = true; + if (reason === undefined) { + reason = lazyDOMException('This operation was aborted', 'AbortError'); + } + // Errors this end's writer: data it already buffered is still read by + // the other end before the error, and a pending close() rejects. + writer.fail(reason); + // Stop reading, and error the other end's writer with the reason. + closeIterator[kCancelConsumer](reason); + onClose(); + return PromiseResolve(); + }, [SymbolAsyncDispose]() { return this.close(); }, diff --git a/lib/internal/streams/iter/push.js b/lib/internal/streams/iter/push.js index cdbaaa8525c1..dec013a464ac 100644 --- a/lib/internal/streams/iter/push.js +++ b/lib/internal/streams/iter/push.js @@ -13,6 +13,7 @@ const { PromiseResolve, PromiseWithResolvers, SafeWeakSet, + Symbol, SymbolAsyncDispose, SymbolAsyncIterator, SymbolDispose, @@ -65,6 +66,10 @@ const { const consumerReturnErrors = new SafeWeakSet(); +// A method of a push readable's iterator: stop reading as return() does, but +// error the writer with the given reason (see DuplexChannel abort()). +const kCancelConsumer = Symbol('kCancelConsumer'); + function isConsumerReturnError(error) { return consumerReturnErrors.has(error); } @@ -504,6 +509,17 @@ class PushQueue { return promise; } + // Stop reading as consumerReturn() does, but error the writer, its pending + // writes and its drain waiters with `error`. + consumerCancel(error) { + if (this.#consumerState !== 'active') return; + this.#consumerState = 'returned'; + const stopped = this.#terminateWriterFromConsumer(error); + this.#resolvePendingReads(); + this.#rejectPendingDrains(error); + if (stopped) this.#stop(error); + } + consumerReturn() { if (this.#consumerState !== 'active') return; this.#consumerState = 'returned'; @@ -847,6 +863,9 @@ function createReadable(queue) { queue.consumerThrow(error); throw error; }, + [kCancelConsumer](reason) { + queue.consumerCancel(reason); + }, }, null); }, }; @@ -891,5 +910,6 @@ function push(...args) { module.exports = { isConsumerReturnError, + kCancelConsumer, push, }; diff --git a/test/parallel/test-stream-iter-duplex-abort.js b/test/parallel/test-stream-iter-duplex-abort.js new file mode 100644 index 000000000000..a0e786edffd1 --- /dev/null +++ b/test/parallel/test-stream-iter-duplex-abort.js @@ -0,0 +1,138 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// Tests for DuplexChannel abort(reason). + +const common = require('../common'); +const assert = require('assert'); +const { duplex, ondrain, text } = require('stream/iter'); + +const dec = new TextDecoder(); + +// abort() returns a resolved promise and is idempotent. +(async () => { + const [a] = duplex(); + assert.strictEqual(typeof a.abort, 'function'); + const p1 = a.abort(new Error('first')); + assert.ok(p1 instanceof Promise); + assert.strictEqual(await p1, undefined); + assert.strictEqual(await a.abort(new Error('second')), undefined); + // The first reason is kept. + assert.strictEqual(a.writer.signal.reason.message, 'first'); +})().then(common.mustCall()); + +// The writer is failed with the reason; data already written is delivered +// to the other end before it sees the reason. +(async () => { + const [a, b] = duplex(); + const reason = new Error('aborted'); + a.writer.writeSync('hello'); + await a.abort(reason); + assert.strictEqual(a.writer.canWrite, null); + await assert.rejects(a.writer.write('more'), reason); + assert.strictEqual(a.writer.signal.reason, reason); + + const iterator = b.readable[Symbol.asyncIterator](); + const first = await iterator.next(); + assert.strictEqual(first.done, false); + assert.strictEqual(dec.decode(first.value[0]), 'hello'); + await assert.rejects(iterator.next(), reason); +})().then(common.mustCall()); + +// The other end's pending and later writes, and its drain waiters, reject +// with the reason. abort() does not wait for the other end. +(async () => { + const [a, b] = duplex({ budget: 1 }); + const reason = new Error('aborted'); + b.writer.writeSync('x'); + const pending = b.writer.write('y'); + const drain = ondrain(b.writer); + await a.abort(reason); + await assert.rejects(pending, reason); + await assert.rejects(drain, reason); + await assert.rejects(b.writer.write('z'), reason); + assert.strictEqual(b.writer.writeSync('z'), false); + assert.strictEqual(b.writer.signal.reason, reason); + // Closing b reports the reason too: its writer is errored. + await assert.rejects(b.close(), reason); +})().then(common.mustCall()); + +// This end's readable stops: a pending read finishes, it yields no data. +(async () => { + const [a] = duplex(); + const iterator = a.readable[Symbol.asyncIterator](); + const read = iterator.next(); + await a.abort(new Error('aborted')); + assert.strictEqual((await read).done, true); + assert.strictEqual((await iterator.next()).done, true); +})().then(common.mustCall()); + +(async () => { + const [a, b] = duplex(); + b.writer.writeSync('discarded'); + await a.abort(new Error('aborted')); + assert.strictEqual(await text(a.readable), ''); +})().then(common.mustCall()); + +// No reason: an AbortError DOMException. +(async () => { + const [a, b] = duplex(); + await a.abort(); + const reason = a.writer.signal.reason; + assert.ok(reason instanceof DOMException); + assert.strictEqual(reason.name, 'AbortError'); + assert.strictEqual(b.writer.signal.reason, reason); + await assert.rejects(text(b.readable), reason); +})().then(common.mustCall()); + +// A pending close() rejects with the reason; close() after abort() returns +// the promise of the first close(). +(async () => { + const [a, b] = duplex(); + const reason = new Error('aborted while closing'); + a.writer.writeSync('unread'); + const closing = a.close(); + await a.abort(reason); + await assert.rejects(closing, reason); + assert.strictEqual(a.close(), closing); + await assert.rejects(text(b.readable), reason); +})().then(common.mustCall()); + +(async () => { + const [a] = duplex(); + await a.abort(new Error('aborted')); + assert.strictEqual(await a.close(), undefined); + assert.strictEqual(await a[Symbol.asyncDispose](), undefined); +})().then(common.mustCall()); + +// `await using` disposing an aborted channel does not throw. +(async () => { + const [a, b] = duplex(); + { + await using channel = a; + channel.writer.writeSync('x'); + await channel.abort(new Error('aborted')); + } + await assert.rejects(text(b.readable), { message: 'aborted' }); +})().then(common.mustCall()); + +// abort() after close() completed: the writer is already closed, so the +// other end still sees a normal end. +(async () => { + const [a, b] = duplex(); + await a.close(); + await a.abort(new Error('late')); + assert.strictEqual(await text(b.readable), ''); + assert.strictEqual(a.writer.signal.aborted, false); +})().then(common.mustCall()); + +// abort() after the duplex() signal aborted keeps the signal's reason. +(async () => { + const ac = new AbortController(); + const [a, b] = duplex({ signal: ac.signal }); + const reason = new Error('signal'); + ac.abort(reason); + await a.abort(new Error('late')); + assert.strictEqual(a.writer.signal.reason, reason); + assert.strictEqual(b.writer.signal.reason, reason); +})().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-duplex-close-after-abort.js b/test/parallel/test-stream-iter-duplex-close-after-abort.js new file mode 100644 index 000000000000..0f2cc924a661 --- /dev/null +++ b/test/parallel/test-stream-iter-duplex-close-after-abort.js @@ -0,0 +1,46 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// DuplexChannel close() after abort(): if close() was called before abort(), +// later close() calls return the promise of the first close(), which rejected +// with the abort reason, or resolved if the writer had already closed. If +// close() was never called, close() after abort() resolves with undefined. + +const common = require('../common'); +const assert = require('assert'); +const { duplex, text } = require('stream/iter'); + +(async () => { + // close() pending when abort() is called. + { + const [a] = duplex(); + const reason = new Error('aborted'); + a.writer.writeSync('unread'); + const closing = a.close(); + await a.abort(reason); + await assert.rejects(closing, reason); + assert.strictEqual(a.close(), closing); + assert.strictEqual(a[Symbol.asyncDispose](), closing); + } + + // close() completed before abort(): later calls return its promise, which + // has resolved. + { + const [a, b] = duplex(); + const closing = a.close(); + assert.strictEqual(await closing, undefined); + await a.abort(new Error('late')); + assert.strictEqual(a.close(), closing); + assert.strictEqual(await a.close(), undefined); + assert.strictEqual(await text(b.readable), ''); + } + + // close() never called: close() after abort() resolves with undefined. + { + const [a] = duplex(); + await a.abort(new Error('aborted')); + const first = a.close(); + assert.strictEqual(await first, undefined); + assert.strictEqual(await a.close(), undefined); + } +})().then(common.mustCall()); From bec400307af29bae3abd72a3b4d726fb643f58e6 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 18:00:42 +0000 Subject: [PATCH 16/26] stream: treat an undefined cancel reason as absent in stream/iter broadcast.cancel(undefined), share.cancel(undefined) and the shareSync() equivalent now behave like cancel() with no argument: consumers complete instead of rejecting with undefined. This matches the Iterable Streams spec, which treats an undefined reason as not given. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 15 +++++++++------ lib/internal/streams/iter/broadcast.js | 2 +- lib/internal/streams/iter/share.js | 4 ++-- .../test-stream-iter-broadcast-cancelled-push.js | 6 +++--- .../test-stream-iter-reason-propagation.js | 10 +++++++--- 5 files changed, 22 insertions(+), 15 deletions(-) diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index 5c8908052fb4..e39a343629a4 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -1693,8 +1693,9 @@ run().catch(console.error); * `reason` {any} -Cancel the broadcast. If `reason` is provided, all consumers reject with that -exact reason. If it is omitted, consumers complete normally. +Cancel the broadcast. If `reason` is provided and is not `undefined`, all +consumers reject with that exact reason. If it is omitted or `undefined`, +consumers complete normally. Cancelling also closes the paired writer: afterwards its `canWrite` is `null` and `write()` rejects with a `TypeError`. This lets a [`Broadcast.from()`][] @@ -1884,8 +1885,9 @@ Create a {Share} from an existing source. * `reason` {any} -Cancel the share. If `reason` is provided, all consumers reject with that exact -reason. If it is omitted, consumers complete normally. +Cancel the share. If `reason` is provided and is not `undefined`, all consumers +reject with that exact reason. If it is omitted or `undefined`, consumers +complete normally. #### `share.consumerCount` @@ -1961,8 +1963,9 @@ added: * `reason` {any} -Cancel the share. If `reason` is provided, all consumers throw that exact -reason. If it is omitted, consumers complete normally. +Cancel the share. If `reason` is provided and is not `undefined`, all consumers +throw that exact reason. If it is omitted or `undefined`, consumers complete +normally. #### `share.consumerCount` diff --git a/lib/internal/streams/iter/broadcast.js b/lib/internal/streams/iter/broadcast.js index 133645507674..d80782584ec8 100644 --- a/lib/internal/streams/iter/broadcast.js +++ b/lib/internal/streams/iter/broadcast.js @@ -349,7 +349,7 @@ class BroadcastImpl { cancel(reason) { if (this.#cancelled) return; - const hasReason = arguments.length > 0; + const hasReason = reason !== undefined; this.#cancelled = true; this.#ended = true; // Prevents [kAbort]() from redundantly iterating consumers diff --git a/lib/internal/streams/iter/share.js b/lib/internal/streams/iter/share.js index bc612b8e8ae3..273c87ec85d6 100644 --- a/lib/internal/streams/iter/share.js +++ b/lib/internal/streams/iter/share.js @@ -258,7 +258,7 @@ class ShareImpl { cancel(reason) { if (this.#cancelled) return; - const hasReason = arguments.length > 0; + const hasReason = reason !== undefined; this.#cancelled = true; if (hasReason) { @@ -890,7 +890,7 @@ class SyncShareImpl { cancel(reason) { if (this.#cancelled) return; - const hasReason = arguments.length > 0; + const hasReason = reason !== undefined; this.#cancelled = true; if (hasReason) { diff --git a/test/parallel/test-stream-iter-broadcast-cancelled-push.js b/test/parallel/test-stream-iter-broadcast-cancelled-push.js index 73afc7fa3937..c7078a506057 100644 --- a/test/parallel/test-stream-iter-broadcast-cancelled-push.js +++ b/test/parallel/test-stream-iter-broadcast-cancelled-push.js @@ -32,11 +32,11 @@ async function testCancelWithReason() { assert.strictEqual(bc.consumerCount, 0); await assert.rejects(consumer[Symbol.asyncIterator]().next(), reason); assert.strictEqual(bc.consumerCount, 0); - // An undefined reason is still a reason. + // An undefined reason is treated as no reason. const { broadcast: bc2 } = broadcast(); bc2.cancel(undefined); - await assert.rejects(bc2.push()[Symbol.asyncIterator]().next(), - (error) => error === undefined); + assert.deepStrictEqual({ ...await bc2.push()[Symbol.asyncIterator]().next() }, + { done: true, value: undefined }); } async function testCancelDiscardsBuffer() { diff --git a/test/parallel/test-stream-iter-reason-propagation.js b/test/parallel/test-stream-iter-reason-propagation.js index 58ae7d4e5f4d..d7bdd3e9ab80 100644 --- a/test/parallel/test-stream-iter-reason-propagation.js +++ b/test/parallel/test-stream-iter-reason-propagation.js @@ -138,18 +138,22 @@ async function testExplicitUndefinedCancellation() { const broadcasted = broadcast(); const broadcastNext = broadcasted.broadcast .push()[Symbol.asyncIterator]().next(); + // An undefined reason is treated as no reason: consumers finish. broadcasted.broadcast.cancel(undefined); - await rejectsWith(broadcastNext, undefined); + assert.deepStrictEqual({ ...await broadcastNext }, + { done: true, value: undefined }); const shared = share(from('data')); const shareIterator = shared.pull()[Symbol.asyncIterator](); shared.cancel(undefined); - await rejectsWith(shareIterator.next(), undefined); + assert.deepStrictEqual({ ...await shareIterator.next() }, + { done: true, value: undefined }); const syncShared = shareSync(fromSync('data')); const syncIterator = syncShared.pull()[Symbol.iterator](); syncShared.cancel(undefined); - throwsWith(() => syncIterator.next(), undefined); + assert.deepStrictEqual({ ...syncIterator.next() }, + { done: true, value: undefined }); } async function testPendingWriteAbortReasons() { From d7a1b7e3f975ef6b177a677a667f782e8c668f08 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 18:17:09 +0000 Subject: [PATCH 17/26] stream: normalize stream/iter transform output like from() Transform output in pull(), pipeTo(), pullSync(), pipeToSync() and the push, broadcast and share pipelines is now normalized with the same algorithm as from() and fromSync(). Output may use the toStreamable and (in async pipelines) toAsyncStreamable protocols, and async pipelines await nested promises and read nested async iterables. Sync pipelines reject async values as fromSync() does. The conversion depth bound and the copy of shared and resizable memory apply to transform output too. The common cases (a batch, a Uint8Array, a string or a buffer) keep their synchronous fast paths. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 22 +- lib/internal/streams/iter/from.js | 102 ++++ lib/internal/streams/iter/pull.js | 522 +++-------------- ...est-stream-iter-transform-normalization.js | 532 ++++++++++++++++++ 4 files changed, 746 insertions(+), 432 deletions(-) create mode 100644 test/parallel/test-stream-iter-transform-normalization.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index e39a343629a4..ac8c7ec403fc 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -144,13 +144,30 @@ Transforms come in two forms: * **Stateless** -- a function `(chunks, options) => result` called once per batch. Receives `Uint8Array[]` (or `null` as the flush signal) and an - `options` object. Returns {Uint8Array\[]|null|Iterable}. + `options` object. Returns `null` (no output) or any value [`from()`][] + accepts, such as a `Uint8Array[]` batch, a {Uint8Array}, or a string; in an + async pipeline, it may also return a {Promise} of one. * **Stateful** -- an object `{ transform(source, options) }` where `transform` is a generator (sync or async) that receives the entire upstream iterable and an `options` object, and yields output. This form is used for compression, encryption, and any transform that needs to buffer across - batches. + batches. Each value it yields is handled like the return value of a + stateless transform, and `null` values are skipped. + +The output of a transform is normalized into a batch as [`from()`][] normalizes +a value in an async pipeline, and as [`fromSync()`][] does in a sync pipeline +([`pullSync()`][] and [`pipeToSync()`][]). Arrays and iterables are flattened, +strings are UTF-8 encoded, shared and resizable memory is copied (see +[Byte streams][]), and objects implementing +`Symbol.for('Stream.toAsyncStreamable')` or `Symbol.for('Stream.toStreamable')` +are converted via those protocols, with the same limit of 100 conversions one +after the other. In an async pipeline, nested promises (for example, +`[Promise.resolve('a')]`) are awaited and nested async iterables are read. In a +sync pipeline, promises, async iterables, and objects that implement only +`toAsyncStreamable` are rejected with a {TypeError}. Output that contains no +chunks produces no batch. How the chunks of the output are divided into +batches is not specified. Both forms receive an `options` parameter with the following property: @@ -2690,6 +2707,7 @@ console.log(textSync(stream)); // 'hello world' [`node:zlib/iter`]: zlib.md#iterable-compression [`ondrain()`]: #ondraindrainable [`pipeTo()`]: #pipetosource-transforms-writer-options +[`pipeToSync()`]: #pipetosyncsource-transforms-writer-options [`pull()`]: #pullsource-transforms-options [`pullSync()`]: #pullsyncsource-transforms [`push()`]: #pushtransforms-options diff --git a/lib/internal/streams/iter/from.js b/lib/internal/streams/iter/from.js index b4b3b6be1024..023cc4d526a6 100644 --- a/lib/internal/streams/iter/from.js +++ b/lib/internal/streams/iter/from.js @@ -380,6 +380,43 @@ function* normalizeSyncValue(value, depth = 0) { ); } +/** + * Append the chunks of `value`, normalized as normalizeSyncValue() does, to + * `batch`. The items of an array or iterable that are strings or buffers + * (the common case) are appended without a generator each. + * @param {Uint8Array[]} batch + * @param {any} value + */ +function appendSyncValueChunks(batch, value) { + if (isPrimitiveChunk(value) || + getProtocolMethod(value, toStreamable) !== undefined || + !isSyncIterable(value)) { + for (const chunk of normalizeSyncValue(value)) { + batch[batch.length] = chunk; + } + return; + } + if (ArrayIsArray(value)) { + for (let i = 0; i < value.length; i++) { + appendSyncItemChunks(batch, value[i]); + } + return; + } + for (const item of value) { + appendSyncItemChunks(batch, item); + } +} + +function appendSyncItemChunks(batch, item) { + if (isPrimitiveChunk(item)) { + batch[batch.length] = primitiveToUint8Array(item); + return; + } + for (const chunk of normalizeSyncValue(item)) { + batch[batch.length] = chunk; + } +} + /** * Check if value is already a Uint8Array[] batch (fast path): one whose * chunks are received as they are (see isFixedUint8Array()). @@ -792,6 +829,69 @@ async function* normalizeAsyncValue( ); } +/** + * Append the chunks of `value`, normalized as normalizeAsyncValue() does + * (with nested async values allowed), to `batch`. The items of an array + * that are strings or buffers (the common case) are appended synchronously, + * and those of a sync iterable without an async generator each. + * @param {Uint8Array[]} batch + * @param {any} value + * @returns {Promise|undefined} A promise if the chunks are appended + * asynchronously; undefined if they have all been appended. + */ +function appendAsyncValueChunks(batch, value) { + if (isPrimitiveChunk(value)) { + batch[batch.length] = primitiveToUint8Array(value); + return; + } + if (isPromise(value) || + getProtocolMethod(value, toAsyncStreamable) !== undefined || + getProtocolMethod(value, toStreamable) !== undefined || + isAsyncIterable(value) || !isSyncIterable(value)) { + return appendAsyncItemChunks(batch, value); + } + if (ArrayIsArray(value)) { + for (let i = 0; i < value.length; i++) { + const item = value[i]; + if (!isPrimitiveChunk(item)) { + return appendAsyncArrayChunks(batch, value, i, item); + } + batch[batch.length] = primitiveToUint8Array(item); + } + return; + } + return appendAsyncIterableChunks(batch, value); +} + +// Normalize `item`, the value at `index` of `array`, and the values after it. +async function appendAsyncArrayChunks(batch, array, index, item) { + await appendAsyncItemChunks(batch, item); + for (let i = index + 1; i < array.length; i++) { + const next = array[i]; + if (isPrimitiveChunk(next)) { + batch[batch.length] = primitiveToUint8Array(next); + } else { + await appendAsyncItemChunks(batch, next); + } + } +} + +async function appendAsyncIterableChunks(batch, iterable) { + for (const item of iterable) { + if (isPrimitiveChunk(item)) { + batch[batch.length] = primitiveToUint8Array(item); + } else { + await appendAsyncItemChunks(batch, item); + } + } +} + +async function appendAsyncItemChunks(batch, item) { + for await (const chunk of normalizeAsyncValue(item)) { + batch[batch.length] = chunk; + } +} + /** * Normalize a value of an async source that is neither a Uint8Array nor a * Uint8Array[] batch, yielding batches of Uint8Array. Chunks are batched, @@ -1990,6 +2090,8 @@ function fromWithDepth(input, depth) { // ============================================================================= module.exports = { + appendAsyncValueChunks, + appendSyncValueChunks, arrayBufferViewToUint8Array, from, fromSync, diff --git a/lib/internal/streams/iter/pull.js b/lib/internal/streams/iter/pull.js index 3a7fc9885d46..eae4f8cdef9d 100644 --- a/lib/internal/streams/iter/pull.js +++ b/lib/internal/streams/iter/pull.js @@ -41,11 +41,11 @@ const { kWeakHandler } = require('internal/event_target'); const { isAbortSignal } = require('internal/abort_controller'); const { + appendAsyncValueChunks, + appendSyncValueChunks, arrayBufferViewToUint8Array, from, fromSync, - isSyncIterable, - isAsyncIterable, isUint8ArrayBatch, kNextSyncBatch, kNextUncancellable, @@ -153,317 +153,84 @@ function parsePipeToArgs(args, requiredMethod) { } // ============================================================================= -// Transform Output Flattening +// Transform Output Normalization // ============================================================================= -/** - * Flatten transform yield to Uint8Array chunks (sync). - * @yields {Uint8Array} - */ -function* flattenTransformYieldSync(value) { - if (isFixedUint8Array(value)) { - yield value; - return; - } - if (typeof value === 'string') { - yield toUint8Array(value); - return; - } - if (isAnyArrayBuffer(value)) { - yield receiveBytes(value); - return; - } - if (ArrayBufferIsView(value)) { - yield arrayBufferViewToUint8Array(value); - return; - } - // Must be Iterable - if (isSyncIterable(value)) { - for (const item of value) { - yield* flattenTransformYieldSync(item); - } - return; - } - throw new ERR_INVALID_ARG_TYPE( - 'value', - ['Uint8Array', 'string', 'ArrayBuffer', 'ArrayBufferView', 'Iterable'], - value); -} - -/** - * Flatten transform yield to Uint8Array chunks (async). - * @yields {Uint8Array} - */ -async function* flattenTransformYieldAsync(value) { - if (isFixedUint8Array(value)) { - yield value; - return; - } - if (typeof value === 'string') { - yield toUint8Array(value); - return; - } - if (isAnyArrayBuffer(value)) { - yield receiveBytes(value); - return; - } - if (ArrayBufferIsView(value)) { - yield arrayBufferViewToUint8Array(value); - return; - } - // Check for async iterable first - if (isAsyncIterable(value)) { - for await (const item of value) { - yield* flattenTransformYieldAsync(item); - } - return; - } - // Must be sync Iterable, no nested async iterables - if (isSyncIterable(value)) { - for (const item of value) { - yield* flattenTransformYieldSync(item); - } - return; - } - throw new ERR_INVALID_ARG_TYPE( - 'value', - ['Uint8Array', 'string', 'ArrayBuffer', 'ArrayBufferView', - 'Iterable', 'AsyncIterable'], - value); -} +// The output of a transform (a stateless transform's result, or a value a +// stateful transform yields) is normalized as from() and fromSync() normalize +// a value (see normalizeAsyncValue() and normalizeSyncValue() in from.js), +// into a single batch, or null if there are no chunks. The common cases are +// handled synchronously by normalizeTransformResultFast(), and the rest +// (protocols, iterables, and in async mode nested promises and async +// iterables) by appendSyncValueChunks() and appendAsyncValueChunks(). /** - * Process transform result (sync). - * @yields {Uint8Array[]} + * Normalize a transform result in the common cases, synchronously. + * @param {any} result + * @returns {Uint8Array[]|null|undefined} The batch, null if there is no + * output, or undefined if `result` has to be normalized by + * normalizeTransformOutputSync() or normalizeTransformOutputAsync(). */ -function* processTransformResultSync(result) { - if (result === null) { - return; - } - // Single Uint8Array -> wrap as batch - if (isFixedUint8Array(result)) { - yield [result]; - return; - } - // String -> UTF-8 encode and wrap as batch - if (typeof result === 'string') { - yield [toUint8Array(result)]; - return; - } - // ArrayBuffer / ArrayBufferView -> convert and wrap - if (isAnyArrayBuffer(result)) { - yield [receiveBytes(result)]; - return; - } - if (ArrayBufferIsView(result)) { - yield [arrayBufferViewToUint8Array(result)]; - return; - } - // Uint8Array[] batch +function normalizeTransformResultFast(result) { + if (result === null) return null; if (isUint8ArrayBatch(result)) { - if (result.length > 0) { - yield result; - } - return; - } - // Iterable or Generator - if (isSyncIterable(result)) { - const batch = []; - for (const item of result) { - for (const chunk of flattenTransformYieldSync(item)) { - batch[batch.length] = chunk; - } - } - if (batch.length > 0) { - yield batch; - } - return; + return result.length === 0 ? null : result; } - throw new ERR_INVALID_ARG_TYPE( - 'result', - ['null', 'Uint8Array', 'string', 'ArrayBuffer', - 'ArrayBufferView', 'Array', 'Iterable'], - result); + if (isFixedUint8Array(result)) return [result]; + if (typeof result === 'string') return [toUint8Array(result)]; + if (isAnyArrayBuffer(result)) return [receiveBytes(result)]; + if (ArrayBufferIsView(result)) return [arrayBufferViewToUint8Array(result)]; } /** - * Append normalized transform result batches to an array (sync). - * @param {Array} target - * @param {*} result + * Normalize a transform result in a sync pipeline, as fromSync() normalizes + * a value: promises, async iterables and toAsyncStreamable objects are + * rejected. + * @param {any} result + * @returns {Uint8Array[]|null} The batch, or null if there is no output. */ -function appendTransformResultSync(target, result) { - if (result === null) { - return; - } - if (isUint8ArrayBatch(result)) { - if (result.length > 0) { - target[target.length] = result; - } - return; - } - if (isFixedUint8Array(result)) { - target[target.length] = [result]; - return; - } - if (typeof result === 'string') { - target[target.length] = [toUint8Array(result)]; - return; - } - if (isAnyArrayBuffer(result)) { - target[target.length] = [receiveBytes(result)]; - return; - } - if (ArrayBufferIsView(result)) { - target[target.length] = [arrayBufferViewToUint8Array(result)]; - return; - } - for (const batch of processTransformResultSync(result)) { - target[target.length] = batch; - } +function normalizeTransformOutputSync(result) { + const fast = normalizeTransformResultFast(result); + if (fast !== undefined) return fast; + const batch = []; + appendSyncValueChunks(batch, result); + return batch.length === 0 ? null : batch; } /** - * Process transform result (async). - * @yields {Uint8Array[]} + * Normalize a transform result in an async pipeline, as from() normalizes a + * value: nested promises are waited for, and nested async iterables read. + * The caller waits for a promise returned by the transform first. + * @param {any} result - Not a promise + * @returns {Uint8Array[]|null|Promise} The batch, or null + * if there is no output, or a promise of one if it has to be waited for. + * May throw synchronously. */ -async function* processTransformResultAsync(result) { - // Handle Promise - if (isPromise(result)) { - const resolved = await result; - yield* processTransformResultAsync(resolved); - return; - } - if (result === null) { - return; - } - // Single Uint8Array -> wrap as batch - if (isFixedUint8Array(result)) { - yield [result]; - return; - } - // String -> UTF-8 encode and wrap as batch - if (typeof result === 'string') { - yield [toUint8Array(result)]; - return; - } - // ArrayBuffer / ArrayBufferView -> convert and wrap - if (isAnyArrayBuffer(result)) { - yield [receiveBytes(result)]; - return; - } - if (ArrayBufferIsView(result)) { - yield [arrayBufferViewToUint8Array(result)]; - return; - } - // Uint8Array[] batch - if (isUint8ArrayBatch(result)) { - if (result.length > 0) { - yield result; - } - return; - } - // Check for async iterable/generator first - if (isAsyncIterable(result)) { - const batch = []; - for await (const item of result) { - if (isFixedUint8Array(item)) { - batch[batch.length] = item; - continue; - } - for await (const chunk of flattenTransformYieldAsync(item)) { - batch[batch.length] = chunk; - } - } - if (batch.length > 0) { - yield batch; - } - return; - } - // Sync Iterable or Generator - if (isSyncIterable(result)) { - const batch = []; - for (const item of result) { - if (isFixedUint8Array(item)) { - batch[batch.length] = item; - continue; - } - // Note: This iteration is synchronous, since async iterables - // may not be nested within sync iterables. - for (const chunk of flattenTransformYieldSync(item)) { - batch[batch.length] = chunk; - } - } - if (batch.length > 0) { - yield batch; - } - return; - } - throw new ERR_INVALID_ARG_TYPE( - 'result', - ['null', 'Uint8Array', 'string', 'ArrayBuffer', - 'ArrayBufferView', 'Array', 'Iterable', 'AsyncIterable', 'Promise'], - result); +function normalizeTransformOutputAsync(result) { + const fast = normalizeTransformResultFast(result); + if (fast !== undefined) return fast; + const batch = []; + const pending = appendAsyncValueChunks(batch, result); + if (pending === undefined) return batch.length === 0 ? null : batch; + return PromisePrototypeThen( + pending, () => (batch.length === 0 ? null : batch)); } /** - * Append normalized transform result batches to an array (async). - * @param {Array} target - * @param {*} result - * @returns {Promise|undefined} + * normalizeTransformOutputAsync() of a value that may be a promise, always + * giving a promise. + * @param {any} result + * @returns {Promise} */ -function appendTransformResultAsync(target, result) { - if (result === null) { - return; - } - if (isUint8ArrayBatch(result)) { - if (result.length > 0) { - target[target.length] = result; - } - return; - } - if (isFixedUint8Array(result)) { - target[target.length] = [result]; - return; - } - if (typeof result === 'string') { - target[target.length] = [toUint8Array(result)]; - return; - } - if (isAnyArrayBuffer(result)) { - target[target.length] = [receiveBytes(result)]; - return; - } - if (ArrayBufferIsView(result)) { - target[target.length] = [arrayBufferViewToUint8Array(result)]; - return; - } - return appendTransformResultAsyncSlow(target, result); -} - -async function appendTransformResultAsyncSlow(target, result) { - for await (const batch of processTransformResultAsync(result)) { - target[target.length] = batch; - } -} - -function normalizeTransformResultFast(result) { - if (isUint8ArrayBatch(result)) { - return result.length === 0 ? null : result; - } - if (isFixedUint8Array(result)) return [result]; - if (typeof result === 'string') return [toUint8Array(result)]; - if (isAnyArrayBuffer(result)) return [receiveBytes(result)]; - if (ArrayBufferIsView(result)) return [arrayBufferViewToUint8Array(result)]; +async function normalizeTransformValueAsync(result) { + if (isPromise(result)) result = await result; + return normalizeTransformOutputAsync(result); } // ============================================================================= // Sync Pipeline Implementation // ============================================================================= -/** - * Apply a single stateless sync transform to a source. - * @yields {Uint8Array[]} - */ /** * Apply a fused run of stateless sync transforms. * @param {Iterable} source @@ -476,39 +243,10 @@ function* applyFusedStatelessSyncTransforms(source, run) { for (let i = 0; i < run.length; i++) { // Called with `this` undefined, so the run is not exposed. const fn = run[i]; - const result = fn(current); - if (result === null) { - current = null; - break; - } - if (i === run.length - 1) { - current = result; - continue; - } - current = normalizeTransformResultFast(result); - if (current === undefined) { - const normalized = []; - appendTransformResultSync(normalized, result); - current = normalized.length === 0 ? null : normalized[0]; - } + current = normalizeTransformOutputSync(fn(current)); if (current === null) break; } - if (current === null) continue; - // Inline normalization with Uint8Array[] batch as the fast path, - // matching the async pipeline's check order. - if (isUint8ArrayBatch(current)) { - if (current.length > 0) yield current; - } else if (isFixedUint8Array(current)) { - yield [current]; - } else if (typeof current === 'string') { - yield [toUint8Array(current)]; - } else if (isAnyArrayBuffer(current)) { - yield [receiveBytes(current)]; - } else if (ArrayBufferIsView(current)) { - yield [arrayBufferViewToUint8Array(current)]; - } else { - yield* processTransformResultSync(current); - } + if (current !== null) yield current; } // Flush each transform after all upstream data, including data emitted by // earlier flushes, has been processed by that transform. @@ -517,9 +255,11 @@ function* applyFusedStatelessSyncTransforms(source, run) { const next = []; const fn = run[i]; for (let j = 0; j < pending.length; j++) { - appendTransformResultSync(next, fn(pending[j])); + const batch = normalizeTransformOutputSync(fn(pending[j])); + if (batch !== null) next[next.length] = batch; } - appendTransformResultSync(next, fn(null)); + const batch = normalizeTransformOutputSync(fn(null)); + if (batch !== null) next[next.length] = batch; pending = next; } for (let i = 0; i < pending.length; i++) { @@ -540,14 +280,8 @@ function* applyStatefulSyncTransform(source, transform, receiver) { const output = FunctionPrototypeCall( transform, receiver, withFlushSync(source)); for (const item of output) { - if (item === null) continue; - const batch = []; - for (const chunk of flattenTransformYieldSync(item)) { - batch[batch.length] = chunk; - } - if (batch.length > 0) { - yield batch; - } + const batch = normalizeTransformOutputSync(item); + if (batch !== null) yield batch; } } @@ -662,26 +396,6 @@ function closeAsyncIterator(iterator, quiet) { }); } -/** - * Normalize the output of a fused run of stateless transforms for a batch. - * @yields {Uint8Array[]} - */ -async function* yieldFusedStatelessOutput(current) { - if (isUint8ArrayBatch(current)) { - if (current.length > 0) yield current; - } else if (isFixedUint8Array(current)) { - yield [current]; - } else if (typeof current === 'string') { - yield [toUint8Array(current)]; - } else if (isAnyArrayBuffer(current)) { - yield [receiveBytes(current)]; - } else if (ArrayBufferIsView(current)) { - yield [arrayBufferViewToUint8Array(current)]; - } else { - yield* processTransformResultAsync(current); - } -} - /** * Apply a fused run of stateless transforms to a batch from transform * `index` on, given the result of that transform, when the result has to be @@ -694,27 +408,16 @@ async function* yieldFusedStatelessOutput(current) { */ async function* continueFusedStatelessBatch(run, index, result, runOptions) { let current; - for (let i = index; i < run.length; i++) { - if (i !== index) { - const fn = run[i]; - result = fn(current, runOptions[i]); - } + for (let i = index; ;) { if (isPromise(result)) result = await result; - if (result === null) return; - if (i === run.length - 1) { - current = result; - break; - } - current = normalizeTransformResultFast(result); - if (current === undefined) { - const normalized = []; - const pendingResult = appendTransformResultAsync(normalized, result); - if (pendingResult !== undefined) await pendingResult; - current = normalized.length === 0 ? null : normalized[0]; - } + current = normalizeTransformOutputAsync(result); + if (isPromise(current)) current = await current; if (current === null) return; + if (++i === run.length) break; + const fn = run[i]; + result = fn(current, runOptions[i]); } - yield* yieldFusedStatelessOutput(current); + yield current; } /** @@ -730,19 +433,13 @@ async function* flushFusedStatelessAsyncTransforms(run, runOptions) { for (let i = 0; i < run.length; i++) { const next = []; const fn = run[i]; - for (let j = 0; j < pending.length; j++) { - const pendingResult = appendTransformResultAsync( - next, - fn(pending[j], runOptions[i])); - if (pendingResult !== undefined) { - await pendingResult; - } - } - const flushResult = appendTransformResultAsync( - next, - fn(null, runOptions[i])); - if (flushResult !== undefined) { - await flushResult; + for (let j = 0; j <= pending.length; j++) { + // The flush signal (null) follows the pending batches. + let result = fn(j < pending.length ? pending[j] : null, runOptions[i]); + if (isPromise(result)) result = await result; + let batch = normalizeTransformOutputAsync(result); + if (isPromise(batch)) batch = await batch; + if (batch !== null) next[next.length] = batch; } pending = next; } @@ -840,29 +537,19 @@ function applyFusedStatelessAsyncTransforms(source, run, abort) { delegate = continueFusedStatelessBatch(run, i, result, runOptions); return kDelegated; } - if (result === null) return null; - if (i === run.length - 1) { - current = result; - break; - } current = normalizeTransformResultFast(result); if (current === undefined) { - delegate = continueFusedStatelessBatch(run, i, result, runOptions); - return kDelegated; + current = normalizeTransformOutputAsync(result); + if (isPromise(current)) { + // The batch, once normalized, is the result of the transform as + // continueFusedStatelessBatch() sees it. + delegate = continueFusedStatelessBatch(run, i, current, runOptions); + return kDelegated; + } } if (current === null) return null; } - if (isUint8ArrayBatch(current)) { - return current.length > 0 ? current : null; - } - if (isFixedUint8Array(current)) return [current]; - if (typeof current === 'string') return [toUint8Array(current)]; - if (isAnyArrayBuffer(current)) return [receiveBytes(current)]; - if (ArrayBufferIsView(current)) { - return [arrayBufferViewToUint8Array(current)]; - } - delegate = processTransformResultAsync(current); - return kDelegated; + return current; } function onSourceResult(result) { @@ -1076,27 +763,9 @@ function createFlushSource(source) { // that are not async iterables: see createStatefulTransformIterator(). async function* yieldStatefulOutput(output) { for await (const item of output) { - if (item === null) continue; - // Fast path: item is already a Uint8Array[] batch (e.g. compression transforms) - if (isUint8ArrayBatch(item)) { - if (item.length > 0) { - yield item; - } - continue; - } - // Fast path: single Uint8Array - if (isFixedUint8Array(item)) { - yield [item]; - continue; - } - // Slow path: flatten arbitrary transform yield - const batch = []; - for await (const chunk of flattenTransformYieldAsync(item)) { - batch[batch.length] = chunk; - } - if (batch.length > 0) { - yield batch; - } + let batch = normalizeTransformOutputAsync(item); + if (isPromise(batch)) batch = await batch; + if (batch !== null) yield batch; } } @@ -1151,10 +820,11 @@ function createStatefulTransformIterator( return item.length > 0 ? new IterResult(false, item) : pull(); } if (isFixedUint8Array(item)) return new IterResult(false, [item]); - // Slow path: flatten arbitrary transform yield. An error doing so + // Slow path: normalize the item as from() does. An error doing so // closes the output, as for await does when its body throws. - return PromisePrototypeThen(flattenItem(item), (batch) => { - return batch.length > 0 ? new IterResult(false, batch) : pull(); + const normalized = normalizeTransformValueAsync(item); + return PromisePrototypeThen(normalized, (batch) => { + return batch !== null ? new IterResult(false, batch) : pull(); }, (error) => { state = kDone; return PromisePrototypeThen(closeAsyncIterator(iterator, true), () => { @@ -1163,14 +833,6 @@ function createStatefulTransformIterator( }); } - async function flattenItem(item) { - const batch = []; - for await (const chunk of flattenTransformYieldAsync(item)) { - batch[batch.length] = chunk; - } - return batch; - } - function onError(error) { state = kDone; throw error; diff --git a/test/parallel/test-stream-iter-transform-normalization.js b/test/parallel/test-stream-iter-transform-normalization.js new file mode 100644 index 000000000000..0d0b3615d537 --- /dev/null +++ b/test/parallel/test-stream-iter-transform-normalization.js @@ -0,0 +1,532 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// Transform output is normalized as from() and fromSync() normalize a value: +// toStreamable / toAsyncStreamable protocols, nested promises (async only), +// rejection of async values in sync pipelines, the bound on protocol +// conversions, and the copy of shared and resizable memory, for stateless +// and stateful transforms in async and sync pipelines. + +const common = require('../common'); +const assert = require('assert'); +const { + from, + fromSync, + pipeTo, + pipeToSync, + pull, + pullSync, + push, + share, + text, + textSync, +} = require('stream/iter'); + +const toStreamable = Symbol.for('Stream.toStreamable'); +const toAsyncStreamable = Symbol.for('Stream.toAsyncStreamable'); +const decoder = new TextDecoder(); + +function decode(chunks) { + let result = ''; + for (const chunk of chunks) result += decoder.decode(chunk); + return result; +} + +// Each mode runs a pipeline over the one-batch source 'a' with a transform +// that outputs `out()` for the batch (and nothing for the flush signal), and +// resolves to the text of the output, or returns it for sync modes. +const asyncModes = { + 'stateless': (out) => + text(pull(from('a'), (chunks) => (chunks === null ? null : out()))), + 'async stateless': (out) => + text(pull(from('a'), async (chunks) => (chunks === null ? null : out()))), + 'stateful': (out) => text(pull(from('a'), { + async *transform(source) { + for await (const chunks of source) { + if (chunks !== null) yield out(); + } + }, + })), + // A sync generator: its values are not awaited by the generator itself. + 'stateful sync generator': (out) => text(pull(from('a'), { + *transform() { yield out(); }, + })), + // An async iterator whose results hold the values as they are. + 'stateful async iterator': (out) => text(pull(from('a'), { + transform() { + let done = false; + return { + [Symbol.asyncIterator]() { return this; }, + async next() { + if (done) return { done: true, value: undefined }; + done = true; + return { done: false, value: out() }; + }, + }; + }, + })), + 'stateless flush': (out) => + text(pull(from('a'), (chunks) => (chunks === null ? out() : null))), + 'pipeTo': async (out) => { + const chunks = []; + await pipeTo(from('a'), (batch) => (batch === null ? null : out()), { + write(chunk) { chunks.push(chunk); }, + writev(batch) { chunks.push(...batch); }, + }); + return decode(chunks); + }, + 'push': async (out) => { + const { writer, readable } = + push((batch) => (batch === null ? null : out())); + const result = text(readable); + await writer.write('a'); + await writer.end(); + return result; + }, + 'share': (out) => { + const shared = share(from('a')); + return text(shared.pull((batch) => (batch === null ? null : out()))); + }, +}; + +const syncModes = { + 'stateless': (out) => + textSync(pullSync(fromSync('a'), + (chunks) => (chunks === null ? null : out()))), + 'stateful': (out) => textSync(pullSync(fromSync('a'), { + *transform(source) { + for (const chunks of source) { + if (chunks !== null) yield out(); + } + }, + })), + 'stateless flush': (out) => + textSync(pullSync(fromSync('a'), + (chunks) => (chunks === null ? out() : null))), + 'pipeToSync': (out) => { + const chunks = []; + pipeToSync(fromSync('a'), (batch) => (batch === null ? null : out()), { + writeSync(chunk) { chunks.push(chunk); return true; }, + writevSync(batch) { chunks.push(...batch); return true; }, + }); + return decode(chunks); + }, +}; + +// A chain of `n` toStreamable conversions ending with 'x'. +function chain(n, symbol = toStreamable) { + let value = 'x'; + for (let i = 0; i < n; i++) { + const next = value; + value = { [symbol]() { return next; } }; + } + return value; +} + +// Values that normalize to 'xyz' in both async and sync pipelines. +const syncValues = { + 'toStreamable': () => ({ [toStreamable]() { return 'xyz'; } }), + 'toStreamable in an array': () => + ['x', { [toStreamable]() { return ['y', 'z']; } }], + 'toStreamable returning a toStreamable': () => + ({ [toStreamable]() { return { [toStreamable]() { return 'xyz'; } }; } }), + 'toStreamable over an iterator': () => + ({ *[Symbol.iterator]() { yield 'no'; }, [toStreamable]() { return 'xyz'; } }), + 'nested arrays': () => [['x'], [['y']], new TextEncoder().encode('z')], + 'generator': () => (function*() { yield 'x'; yield ['y', 'z']; })(), + 'String object': () => new String('xyz'), + '100 conversions': () => { + const value = chain(100); + return [value, 'yz']; + }, +}; + +// Values that normalize to 'xyz' in async pipelines only. +const asyncValues = { + 'toAsyncStreamable': () => ({ [toAsyncStreamable]() { return 'xyz'; } }), + 'toAsyncStreamable returning a promise': () => + ({ async [toAsyncStreamable]() { return ['x', 'yz']; } }), + 'toAsyncStreamable over toStreamable': () => ({ + [toAsyncStreamable]() { return 'xyz'; }, + [toStreamable]() { return 'no'; }, + }), + 'nested promise': () => [Promise.resolve('x'), 'y', Promise.resolve('z')], + 'nested promise of an array': () => ['x', Promise.resolve(['y', 'z'])], + 'promise in a generator': () => + (function*() { yield 'x'; yield Promise.resolve('yz'); })(), + 'nested async generator': () => + ['x', (async function*() { yield 'y'; yield Promise.resolve('z'); })()], + 'async generator': () => + (async function*() { yield 'x'; yield ['y', Promise.resolve('z')]; })(), + 'toStreamable returning a promise': () => + ({ [toStreamable]() { return Promise.resolve('xyz'); } }), + 'promise': () => Promise.resolve(['x', 'y', 'z']), + '100 async conversions': () => [chain(100, toAsyncStreamable), 'yz'], +}; + +// Values that are rejected with a TypeError in sync pipelines. +const asyncOnlyValues = { + 'toAsyncStreamable': asyncValues.toAsyncStreamable, + 'nested promise': asyncValues['nested promise'], + 'nested async generator': asyncValues['nested async generator'], + 'promise in a generator': asyncValues['promise in a generator'], + 'toStreamable returning a promise': + asyncValues['toStreamable returning a promise'], + 'promise': () => Promise.resolve('xyz'), + 'async generator': asyncValues['async generator'], +}; + +// Values that are invalid in both async and sync pipelines. +const invalidValues = { + 'nested null': () => ['x', null], + 'nested undefined': () => ['x', undefined], + 'number': () => 1, + 'nested number': () => ['x', 1], + 'toStreamable returning null': () => ({ [toStreamable]() { return null; } }), + 'toStreamable returning undefined': () => ({ [toStreamable]() {} }), + 'non-callable toStreamable': () => ({ [toStreamable]: 'xyz' }), +}; + +async function testAsyncValues() { + for (const mode in asyncModes) { + const run = asyncModes[mode]; + for (const name in syncValues) { + assert.strictEqual(await run(syncValues[name]), 'xyz', `${mode}: ${name}`); + } + for (const name in asyncValues) { + assert.strictEqual(await run(asyncValues[name]), 'xyz', `${mode}: ${name}`); + } + } +} + +function testSyncValues() { + for (const mode in syncModes) { + const run = syncModes[mode]; + for (const name in syncValues) { + assert.strictEqual(run(syncValues[name]), 'xyz', `${mode}: ${name}`); + } + } +} + +// In a sync pipeline, promises, async iterables and toAsyncStreamable-only +// objects are rejected as fromSync() rejects them. +function testSyncRejectsAsyncValues() { + for (const mode in syncModes) { + const run = syncModes[mode]; + for (const name in asyncOnlyValues) { + // fromSync() rejects the same values. + assert.throws(() => textSync(fromSync([asyncOnlyValues[name]()])), + { name: 'TypeError' }, name); + assert.throws(() => run(asyncOnlyValues[name]), + { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError' }, + `${mode}: ${name}`); + } + } +} + +async function testInvalidValues() { + for (const mode in asyncModes) { + for (const name in invalidValues) { + await assert.rejects(asyncModes[mode](invalidValues[name]), + { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError' }, + `${mode}: ${name}`); + } + } + for (const mode in syncModes) { + for (const name in invalidValues) { + assert.throws(() => syncModes[mode](invalidValues[name]), + { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError' }, + `${mode}: ${name}`); + } + } +} + +// A promise resolving to null, from a stateless transform or yielded by a +// stateful one, is no output; a nested null is an error (see above). +async function testPromiseOfNull() { + for (const mode of ['async stateless', 'stateful sync generator', + 'stateful async iterator', 'stateless']) { + assert.strictEqual(await asyncModes[mode](() => Promise.resolve(null)), '', + mode); + } +} + +// More than 100 protocol conversions one after the other are a RangeError. +async function testDepthBound() { + const error = { code: 'ERR_INVALID_ARG_VALUE', name: 'RangeError' }; + const self = () => { + const value = { [toStreamable]() { return value; } }; + return value; + }; + const asyncSelf = () => { + const value = { [toAsyncStreamable]() { return value; } }; + return value; + }; + for (const mode in asyncModes) { + await assert.rejects(asyncModes[mode](self), error, mode); + await assert.rejects(asyncModes[mode](asyncSelf), error, mode); + await assert.rejects(asyncModes[mode](() => chain(101)), error, mode); + await assert.rejects(asyncModes[mode](() => ['x', chain(101)]), error, + mode); + await assert.rejects( + asyncModes[mode](() => chain(101, toAsyncStreamable)), error, mode); + } + for (const mode in syncModes) { + assert.throws(() => syncModes[mode](self), error, mode); + assert.throws(() => syncModes[mode](() => chain(101)), error, mode); + assert.throws(() => syncModes[mode](() => ['x', chain(101)]), error, + mode); + } +} + +// Change the buffers given as transform output, and check that `chunks`, the +// output, holds a copy of their bytes as they were. +function checkCopied(chunks, buffers, label) { + assert.ok(buffers.length > 0, label); + for (const buffer of buffers) new Uint8Array(buffer).fill(0x41); + assert.strictEqual(decode(chunks), 'xyz', label); + for (const chunk of chunks) { + assert.ok(chunk instanceof Uint8Array, label); + assert.ok(chunk.buffer instanceof ArrayBuffer, label); + assert.strictEqual(chunk.buffer.resizable, false, label); + } +} + +// Shared and resizable memory in transform output is copied when the output +// is normalized: changing it afterwards does not change the data. +async function testSharedAndResizableMemoryCopied() { + const makers = { + 'SharedArrayBuffer': () => new SharedArrayBuffer(3), + 'resizable ArrayBuffer': () => new ArrayBuffer(3, { maxByteLength: 8 }), + }; + for (const kind in makers) { + const shapes = { + 'buffer': (buffer) => buffer, + 'Uint8Array': (buffer) => new Uint8Array(buffer), + 'batch': (buffer) => [new Uint8Array(buffer)], + 'DataView in an array': (buffer) => ['', new DataView(buffer)], + 'toStreamable': (buffer) => + ({ [toStreamable]() { return new Uint8Array(buffer); } }), + 'generator': (buffer) => + (function*() { yield new Uint8Array(buffer); })(), + }; + for (const shape in shapes) { + const label = `${kind}, ${shape}`; + const out = (buffers) => () => { + const buffer = makers[kind](); + new Uint8Array(buffer).set([0x78, 0x79, 0x7a]); + buffers.push(buffer); + return shapes[shape](buffer); + }; + + // Async: stateless and stateful. + for (const transform of [ + (out) => (chunks) => (chunks === null ? null : out()), + (out) => async (chunks) => (chunks === null ? null : out()), + (out) => ({ + async *transform(source) { + for await (const chunks of source) { + if (chunks !== null) yield out(); + } + }, + }), + ]) { + const buffers = []; + const chunks = []; + for await (const batch of pull(from('a'), transform(out(buffers)))) { + chunks.push(...batch); + } + checkCopied(chunks, buffers, label); + } + + // Sync: stateless and stateful. + for (const transform of [ + (out) => (chunks) => (chunks === null ? null : out()), + (out) => ({ + *transform(source) { + for (const chunks of source) { + if (chunks !== null) yield out(); + } + }, + }), + ]) { + const buffers = []; + const chunks = []; + for (const batch of pullSync(fromSync('a'), transform(out(buffers)))) { + chunks.push(...batch); + } + checkCopied(chunks, buffers, label); + } + } + } +} + +// The output of a stateless transform is normalized before it is passed to +// the next transform of the pipeline. +async function testIntermediateOutputNormalized() { + const seen = []; + const record = (chunks) => { + if (chunks !== null) seen.push(chunks); + return chunks; + }; + const tx = (chunks) => (chunks === null ? null : + [{ [toStreamable]() { return 'x'; } }, Promise.resolve('y')]); + assert.strictEqual(await text(pull(from('a'), tx, record)), 'xy'); + assert.strictEqual(seen.length, 1); + assert.ok(Array.isArray(seen[0])); + assert.strictEqual(decode(seen[0]), 'xy'); + for (const chunk of seen[0]) assert.ok(chunk instanceof Uint8Array); + + seen.length = 0; + const syncTx = (chunks) => (chunks === null ? null : + [{ [toStreamable]() { return 'x'; } }, 'y']); + assert.strictEqual(textSync(pullSync(fromSync('a'), syncTx, record)), 'xy'); + assert.strictEqual(seen.length, 1); + assert.strictEqual(decode(seen[0]), 'xy'); +} + +// An error normalizing the output closes the iterators being read: nested +// iterables, the stateful transform, and the source. +async function testErrorClosesIterators() { + // Nested generator (async pipeline). + { + let closed = 0; + function* nested() { + try { + yield 'x'; + yield null; + } finally { + closed++; + } + } + await assert.rejects( + text(pull(from('a'), (chunks) => (chunks === null ? null : [nested()]))), + { code: 'ERR_INVALID_ARG_TYPE' }); + await assert.rejects( + text(pull(from('a'), (chunks) => (chunks === null ? null : nested()))), + { code: 'ERR_INVALID_ARG_TYPE' }); + assert.strictEqual(closed, 2); + } + + // Nested async generator, and a rejected nested promise. + { + let closed = 0; + async function* nested() { + try { + yield 'x'; + yield Promise.reject(new Error('nested boom')); + } finally { + closed++; + } + } + await assert.rejects( + text(pull(from('a'), (chunks) => (chunks === null ? null : ['', nested()]))), + { message: 'nested boom' }); + assert.strictEqual(closed, 1); + await assert.rejects( + text(pull(from('a'), (chunks) => (chunks === null ? null : + ['x', Promise.reject(new Error('promise boom'))]))), + { message: 'promise boom' }); + } + + // A stateful transform is closed when a value it yields is invalid. + { + let closed = false; + const tx = { + async *transform(source) { + try { + for await (const chunks of source) { + if (chunks !== null) yield [Promise.resolve('x'), null]; + } + } finally { + closed = true; + } + }, + }; + await assert.rejects(text(pull(from('a'), tx)), + { code: 'ERR_INVALID_ARG_TYPE' }); + assert.strictEqual(closed, true); + } + + // The source is closed when a stateless transform's output is invalid. + { + let closed = false; + async function* source() { + try { + yield 'a'; + yield 'b'; + } finally { + closed = true; + } + } + await assert.rejects( + text(pull(source(), (chunks) => (chunks === null ? null : + [Promise.resolve('x'), 1]))), + { code: 'ERR_INVALID_ARG_TYPE' }); + assert.strictEqual(closed, true); + } + + // Sync: the stateful transform and the source are closed. + { + let transformClosed = false; + let sourceClosed = false; + function* source() { + try { + yield 'a'; + yield 'b'; + } finally { + sourceClosed = true; + } + } + const tx = { + *transform(input) { + try { + for (const chunks of input) { + if (chunks !== null) yield [Promise.resolve('x')]; + } + } finally { + transformClosed = true; + } + }, + }; + assert.throws(() => textSync(pullSync(source(), tx)), + { code: 'ERR_INVALID_ARG_TYPE' }); + assert.strictEqual(transformClosed, true); + assert.strictEqual(sourceClosed, true); + } +} + +// Protocol methods are called with the object as `this`, and only once. +async function testProtocolCalls() { + function track(symbol) { + const value = { + receivers: [], + [symbol]() { + this.receivers.push(this); + return 'xyz'; + }, + }; + return value; + } + for (const symbol of [toStreamable, toAsyncStreamable]) { + const value = track(symbol); + assert.strictEqual(await asyncModes.stateless(() => value), 'xyz'); + assert.deepStrictEqual(value.receivers, [value]); + } + const value = track(toStreamable); + assert.strictEqual(syncModes.stateless(() => value), 'xyz'); + assert.deepStrictEqual(value.receivers, [value]); +} + +Promise.all([ + testAsyncValues(), + testSyncValues(), + testSyncRejectsAsyncValues(), + testInvalidValues(), + testPromiseOfNull(), + testDepthBound(), + testSharedAndResizableMemoryCopied(), + testIntermediateOutputNormalized(), + testErrorClosesIterators(), + testProtocolCalls(), +]).then(common.mustCall()); From 3ba205a2d952c16bbaaf4bce9b674e1d9230db0e Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 18:58:48 +0000 Subject: [PATCH 18/26] stream: default the stream/iter writer fail() reason writer.fail() with no reason, including through Symbol.dispose and Symbol.asyncDispose, now fails the writer with an AbortError instead of undefined. This applies to push(), broadcast() and duplex() writers, the fromWritable() writer, filehandle.writer() and the QUIC stream writer. Later writes, end(), consumers, writer.signal and pipeToSync() all report that same error. Reasons other than undefined are kept as given. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/fs.md | 2 + doc/api/quic.md | 2 + doc/api/stream_iter.md | 15 +- lib/internal/fs/promises.js | 6 + lib/internal/streams/iter/broadcast.js | 4 + lib/internal/streams/iter/classic.js | 8 +- lib/internal/streams/iter/push.js | 16 +- lib/internal/streams/iter/writer.js | 7 +- .../test-fs-promises-file-handle-writer.js | 27 ++- ...quic-stream-writer-fail-default-reason.mjs | 81 ++++++++ ...test-stream-iter-broadcast-backpressure.js | 2 +- ...stream-iter-fail-default-reason-writers.js | 117 ++++++++++++ .../test-stream-iter-fail-default-reason.js | 175 ++++++++++++++++++ .../test-stream-iter-reason-propagation.js | 35 ++-- .../test-stream-iter-writable-interop.js | 3 +- 15 files changed, 474 insertions(+), 26 deletions(-) create mode 100644 test/parallel/test-quic-stream-writer-fail-default-reason.mjs create mode 100644 test/parallel/test-stream-iter-fail-default-reason-writers.js create mode 100644 test/parallel/test-stream-iter-fail-default-reason.js diff --git a/doc/api/fs.md b/doc/api/fs.md index 1296de527cd2..7262ceb43164 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -1128,6 +1128,8 @@ added: * `fail(reason)` {Function} Puts the writer into a terminal error state. Synchronous. If the writer is already closed or errored, this is a no-op. If `autoClose` is true, closes the file handle synchronously. + Pending and later writes, and `end()`, reject with `reason`. If `reason` + is omitted or `undefined`, it is an `AbortError` {DOMException}. Return a [`node:stream/iter`][] writer backed by this file handle. diff --git a/doc/api/quic.md b/doc/api/quic.md index 234be7238cf2..7a2af0aa6087 100644 --- a/doc/api/quic.md +++ b/doc/api/quic.md @@ -2515,6 +2515,8 @@ The Writer has the following methods: * `end([options])` — Async close. If a drain is already pending, waits for it before closing. * `fail(reason)` — Errors the stream (sends `RESET_STREAM` to peer). + Later writes and `end()` reject with `reason`, or with an `AbortError` + {DOMException} if `reason` is omitted or `undefined`. When `reason` is a [`QuicError`][], its [`error.errorCode`][] is used as the wire code on the resulting `RESET_STREAM` frame; otherwise the wire code falls back to the negotiated application protocol's diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index ac8c7ec403fc..624f2620090c 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -543,7 +543,12 @@ Put the writer into a terminal error state. If the writer is already closed or errored, this is a no-op. Unlike `write()` and `end()`, `fail()` is unconditionally synchronous because failing a writer is a pure state transition with no async work to perform. The reason is stored and propagated -without modification. If omitted, the reason is `undefined`. +without modification. For the writers created by [`push()`][], +[`broadcast()`][], [`duplex()`][], [`fromWritable()`][], +[`filehandle.writer()`][], and a QUIC [`stream.writer`][], if `reason` is +omitted or `undefined`, the reason is an `AbortError` {DOMException}: later +writes, `end()`, consumers, and `writer.signal` all see that error. Other +falsy reasons, such as `null`, are kept as given. #### `writer.signal` @@ -565,9 +570,9 @@ have it. Their signal aborts: `for await` loop, or its iterator's `throw()` is called). The reason is the error that later writes reject with. * when `writer.fail()` is called, including by an aborted `signal` option of - `push()`, `broadcast()`, or `duplex()`. The reason is the `fail()` reason. If - `fail()` was called with no argument, the reason is an `AbortError` - {DOMException}, as for `abortController.abort()` with no argument. + `push()`, `broadcast()`, or `duplex()`. The reason is the `fail()` reason: + if `fail()` was called with no argument, the `AbortError` {DOMException} + that the writer was failed with. * for a `broadcast()` writer that is open or closing, when [`broadcast.cancel()`][] is called. The reason is the cancel reason, or an `ERR_INVALID_STATE` `TypeError` if none is given: the same value that the @@ -2700,6 +2705,7 @@ console.log(textSync(stream)); // 'hello world' [`channel.abort()`]: #channelabortreason [`dump()`]: #drainsource-options [`duplex()`]: #duplexoptions +[`filehandle.writer()`]: fs.md#filehandlewriteroptions [`from()`]: #frominput [`fromReadable()`]: #fromreadablereadable [`fromSync()`]: #fromsyncinput @@ -2714,6 +2720,7 @@ console.log(textSync(stream)); // 'hello world' [`share()`]: #sharesource-options [`stream.Readable`]: stream.md#class-streamreadable [`stream.Writable`]: stream.md#class-streamwritable +[`stream.writer`]: quic.md#streamwriter [`tap()`]: #tapcallback [`text()`]: #textsource-options [`toAsyncStreamable`]: #streamtoasyncstreamable diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index 216f3d48d001..ff5c7dc116ba 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -1154,6 +1154,12 @@ if (getOptionValue('--experimental-stream-iter')) { fail(reason) { if (closed || errored) return; + // Without a reason, fail with an AbortError, as a push() writer + // does, so that later writes and end() reject with an error. + if (reason === undefined) { + reason = lazyDOMException('This operation was aborted', + 'AbortError'); + } errored = true; error = reason; closing = false; diff --git a/lib/internal/streams/iter/broadcast.js b/lib/internal/streams/iter/broadcast.js index d80782584ec8..7fe9f47e17e5 100644 --- a/lib/internal/streams/iter/broadcast.js +++ b/lib/internal/streams/iter/broadcast.js @@ -880,6 +880,10 @@ class BroadcastWriter { fail(reason) { if (this.#state === 'errored' || this.#state === 'closed') return; + // Without a reason, fail with an AbortError, as a push() writer does. + if (reason === undefined) { + reason = lazyDOMException('This operation was aborted', 'AbortError'); + } this.#state = 'errored'; this.#error = reason; this.#rejectPendingWrites(reason); diff --git a/lib/internal/streams/iter/classic.js b/lib/internal/streams/iter/classic.js index 1a638ae47b6e..571fbdd9c37c 100644 --- a/lib/internal/streams/iter/classic.js +++ b/lib/internal/streams/iter/classic.js @@ -77,7 +77,7 @@ const { const { Buffer } = require('buffer'); const destroyImpl = require('internal/streams/destroy'); -const { isError } = require('internal/util'); +const { isError, lazyDOMException } = require('internal/util'); const { RingBuffer } = require('internal/streams/iter/ringbuffer'); // Classic stream error channels require a truthy Error object. @@ -1043,6 +1043,12 @@ function fromWritable(writable, options = kNullPrototype) { (writable.destroyed ?? false)) { return; } + // Without a reason, fail with an AbortError, as a push() writer does: + // later writes and end() reject with it, and the Writable is + // destroyed with it. + if (reason === undefined) { + reason = lazyDOMException('This operation was aborted', 'AbortError'); + } errored = true; error = reason; ending = false; diff --git a/lib/internal/streams/iter/push.js b/lib/internal/streams/iter/push.js index dec013a464ac..2571ba31bc78 100644 --- a/lib/internal/streams/iter/push.js +++ b/lib/internal/streams/iter/push.js @@ -25,6 +25,7 @@ const { }, } = require('internal/errors'); const { AbortController } = require('internal/abort_controller'); +const { lazyDOMException } = require('internal/util'); const { drainableProtocol, @@ -419,8 +420,9 @@ class PushQueue { this.#writerState = 'errored'; this.#writerError = reason; this.#cleanup(); + // Settle the reads, then the pending writes, the end promise and the + // drain waiters, as when the consumer stops. this.#rejectPendingReads(this.#writerError); - this.#rejectPendingDrains(this.#writerError); this.#rejectPendingWrites(this.#writerError); if (wasClosing) { @@ -430,6 +432,7 @@ class PushQueue { this.#pendingEnd = null; } } + this.#rejectPendingDrains(this.#writerError); this.#stop(reason); } @@ -514,8 +517,8 @@ class PushQueue { consumerCancel(error) { if (this.#consumerState !== 'active') return; this.#consumerState = 'returned'; - const stopped = this.#terminateWriterFromConsumer(error); this.#resolvePendingReads(); + const stopped = this.#terminateWriterFromConsumer(error); this.#rejectPendingDrains(error); if (stopped) this.#stop(error); } @@ -525,8 +528,8 @@ class PushQueue { this.#consumerState = 'returned'; const error = new ERR_INVALID_STATE.TypeError('Stream closed by consumer'); consumerReturnErrors.add(error); - const stopped = this.#terminateWriterFromConsumer(error); this.#resolvePendingReads(); + const stopped = this.#terminateWriterFromConsumer(error); // Resolve pending drains with false - no more data will be consumed this.#resolvePendingDrains(false); if (stopped) this.#stop(error); @@ -536,8 +539,8 @@ class PushQueue { if (this.#consumerState !== 'active') return; this.#consumerState = 'thrown'; this.#consumerError = error; - const stopped = this.#terminateWriterFromConsumer(error); this.#rejectPendingReads(error); + const stopped = this.#terminateWriterFromConsumer(error); // Reject pending drains - the consumer errored this.#rejectPendingDrains(error); if (stopped) this.#stop(error); @@ -821,6 +824,11 @@ class PushWriter { } fail(reason) { + // Without a reason, fail with an AbortError, as DuplexChannel abort() + // does, so that writes, consumers and writer.signal see an error. + if (reason === undefined) { + reason = lazyDOMException('This operation was aborted', 'AbortError'); + } this.#queue.fail(reason); } diff --git a/lib/internal/streams/iter/writer.js b/lib/internal/streams/iter/writer.js index 6fb6ba1491c9..e8b234d6bf55 100644 --- a/lib/internal/streams/iter/writer.js +++ b/lib/internal/streams/iter/writer.js @@ -28,7 +28,7 @@ const { markPromiseAsHandled, } = internalBinding('util'); -const { kEmptyObject } = require('internal/util'); +const { kEmptyObject, lazyDOMException } = require('internal/util'); const { codes: { @@ -322,6 +322,11 @@ function getWriter(obj) { function fail(reason) { if (closed || errored) return; + // Without a reason, fail with an AbortError, as a push() writer does, so + // that later writes and end() reject with an error. + if (reason === undefined) { + reason = lazyDOMException('This operation was aborted', 'AbortError'); + } errored = true; error = reason; resetStream(error); diff --git a/test/parallel/test-fs-promises-file-handle-writer.js b/test/parallel/test-fs-promises-file-handle-writer.js index 63b0309dbaa5..57240ee072dd 100644 --- a/test/parallel/test-fs-promises-file-handle-writer.js +++ b/test/parallel/test-fs-promises-file-handle-writer.js @@ -855,7 +855,9 @@ async function testEndRejectsOnErrored() { } async function testFailPreservesReason() { - for (const reason of [undefined, null, false, 0, '', 'failure']) { + // fail() without a reason uses an AbortError (see + // testFailDefaultReason()); falsy reasons are kept as given. + for (const reason of [null, false, 0, '', 'failure']) { const suffix = String(reason).replaceAll(' ', '-'); const filePath = path.join(tmpDir, `writer-fail-${suffix}.txt`); const fh = await open(filePath, 'w'); @@ -869,6 +871,23 @@ async function testFailPreservesReason() { } } +async function testFailDefaultReason() { + for (const failWith of [(w) => w.fail(), (w) => w.fail(undefined), + (w) => w[Symbol.dispose]()]) { + const filePath = path.join(tmpDir, 'writer-fail-default.txt'); + const fh = await open(filePath, 'w'); + const w = fh.writer(); + failWith(w); + let first; + await assert.rejects(w.write('data'), (error) => { + first = error; + return error.name === 'AbortError'; + }); + await assert.rejects(w.end(), (error) => error === first); + await fh.close(); + } +} + async function testFailRejectsPendingWriteWithReason() { const filePath = path.join(tmpDir, 'writer-fail-pending.txt'); const fh = await open(filePath, 'w'); @@ -959,10 +978,11 @@ async function testAsyncDisposeCallsFail() { // Dispose without end() - should call fail(), not graceful cleanup await w[Symbol.asyncDispose](); - // Writer should be in errored state - write should reject + // Writer should be in errored state - write should reject, with the + // AbortError fail() uses without a reason await assert.rejects( w.write(Buffer.from('more')), - (reason) => reason === undefined, + { name: 'AbortError' }, ); // Handle should be unlocked and reusable @@ -1237,6 +1257,7 @@ Promise.all([ testFullSyncPipeline(), testEndRejectsOnErrored(), testFailPreservesReason(), + testFailDefaultReason(), testFailRejectsPendingWriteWithReason(), testFailWhileClosingPreservesReason(), testEndIdempotent(), diff --git a/test/parallel/test-quic-stream-writer-fail-default-reason.mjs b/test/parallel/test-quic-stream-writer-fail-default-reason.mjs new file mode 100644 index 000000000000..49ee4f65eddc --- /dev/null +++ b/test/parallel/test-quic-stream-writer-fail-default-reason.mjs @@ -0,0 +1,81 @@ +// Flags: --experimental-quic --experimental-stream-iter --no-warnings + +// Test: stream writer.fail() with no reason (or undefined, or through +// Symbol.dispose) fails the writer with an AbortError: later writes and +// end() reject with that same error. The peer still receives RESET_STREAM +// with the session's internalErrorCode (0x1 for the non-h3 test ALPN). +// Explicit falsy reasons are kept as given. + +import { hasQuic, skip, mustCall } from '../common/index.mjs'; +import assert from 'node:assert'; + +if (!hasQuic) { + skip('QUIC is not enabled'); +} + +const { listen, connect } = await import('../common/quic.mjs'); + +const failures = [ + (writer) => writer.fail(), + (writer) => writer.fail(undefined), + (writer) => writer[Symbol.dispose](), +]; +const falsyReasons = [null, 0, '']; +const expectedResets = failures.length + falsyReasons.length; + +let resets = 0; +const allReset = Promise.withResolvers(); + +const serverEndpoint = await listen(mustCall((serverSession) => { + serverSession.onstream = mustCall(async (stream) => { + // Attached synchronously so that the reset finds it. + stream.onreset = mustCall((err) => { + assert.strictEqual(err.code, 'ERR_QUIC_APPLICATION_ERROR'); + assert.strictEqual(err.errorCode, 0x1n); + if (++resets === expectedResets) allReset.resolve(); + }); + await assert.rejects(stream.closed, { + code: 'ERR_QUIC_APPLICATION_ERROR', + }); + }, expectedResets); +})); + +const clientSession = await connect(serverEndpoint.address, { + verifyPeer: 'manual', +}); +await clientSession.opened; + +for (const failWith of failures) { + const stream = clientSession.createBidirectionalStream(); + const writer = stream.writer; + // Make sure the server-side stream exists before the reset arrives. + writer.writeSync('x'); + failWith(writer); + + let failure; + await assert.rejects(writer.write('more'), (error) => { + failure = error; + return error.name === 'AbortError'; + }); + await assert.rejects(writer.writev(['more']), (error) => error === failure); + await assert.rejects(writer.end(), (error) => error === failure); + assert.strictEqual(writer.writeSync('more'), false); + assert.strictEqual(writer.endSync(), -1); + // Failing again does not change the error. + writer.fail(new Error('later')); + await assert.rejects(writer.write('more'), (error) => error === failure); +} + +for (const reason of falsyReasons) { + const stream = clientSession.createBidirectionalStream(); + const writer = stream.writer; + writer.writeSync('y'); + writer.fail(reason); + await assert.rejects(writer.write('more'), (error) => error === reason); + await assert.rejects(writer.end(), (error) => error === reason); +} + +await allReset.promise; + +await clientSession.close(); +await serverEndpoint.close(); diff --git a/test/parallel/test-stream-iter-broadcast-backpressure.js b/test/parallel/test-stream-iter-broadcast-backpressure.js index e42bb93d5f1f..41c82cd7ff04 100644 --- a/test/parallel/test-stream-iter-broadcast-backpressure.js +++ b/test/parallel/test-stream-iter-broadcast-backpressure.js @@ -159,7 +159,7 @@ async function testStrictBackpressureOverflow() { }); writer.fail(); - await assert.rejects(pending, (reason) => reason === undefined); + await assert.rejects(pending, { name: 'AbortError' }); } async function testEndDrainsPendingWrite() { diff --git a/test/parallel/test-stream-iter-fail-default-reason-writers.js b/test/parallel/test-stream-iter-fail-default-reason-writers.js new file mode 100644 index 000000000000..dbdf1a373e19 --- /dev/null +++ b/test/parallel/test-stream-iter-fail-default-reason-writers.js @@ -0,0 +1,117 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// fail() with no reason (or undefined, or through Symbol.dispose and +// Symbol.asyncDispose) on the writer of fromWritable() and of +// filehandle.writer() fails it with an AbortError, as for push() writers: +// pending and later writes, and end(), reject with that same error, and the +// Writable is destroyed with it. Explicit falsy reasons are kept as given. +// (The QUIC stream writer is covered by +// test-quic-stream-writer-fail-default-reason.mjs.) + +const common = require('../common'); +const assert = require('assert'); +const path = require('path'); +const { Writable } = require('stream'); +const { open } = require('fs/promises'); +const tmpdir = require('../common/tmpdir'); +const { fromWritable } = require('stream/iter'); + +tmpdir.refresh(); + +const failures = { + 'fail()': (writer) => writer.fail(), + 'fail(undefined)': (writer) => writer.fail(undefined), + 'Symbol.dispose': (writer) => writer[Symbol.dispose](), + 'Symbol.asyncDispose': (writer) => writer[Symbol.asyncDispose](), +}; + +async function checkFailed(name, writer, pendingWrite) { + let failure; + await assert.rejects(writer.write('more'), (error) => { + failure = error; + return error.name === 'AbortError'; + }, name); + if (pendingWrite !== undefined) { + await assert.rejects(pendingWrite, (error) => error === failure, name); + } + await assert.rejects(writer.writev(['more']), (error) => error === failure, + name); + await assert.rejects(writer.end(), (error) => error === failure, name); + assert.strictEqual(writer.writeSync('more'), false, name); + assert.strictEqual(writer.endSync(), -1, name); + // Failing again does not change the error. + writer.fail(new Error('later')); + await assert.rejects(writer.write('more'), (error) => error === failure, + name); + return failure; +} + +async function testFromWritable() { + for (const name in failures) { + let destroyedWith; + const writable = new Writable({ + highWaterMark: 1, + write(chunk, encoding, callback) { + // Never calls back: later writes stay pending. + }, + }); + writable.on('error', common.mustCall((error) => { + destroyedWith = error; + })); + const writer = fromWritable(writable, { backpressure: 'unbounded' }); + await writer.write('a'); + const pendingWrite = writer.write('pending'); + failures[name](writer); + const failure = await checkFailed(`fromWritable: ${name}`, writer, + pendingWrite); + await new Promise(setImmediate); + assert.strictEqual(writable.destroyed, true); + assert.strictEqual(destroyedWith, failure, name); + } +} + +async function testFromWritableFalsyReasons() { + for (const reason of [null, 0, '', false]) { + const writable = new Writable({ write(chunk, encoding, callback) {} }); + writable.on('error', common.mustCall()); + const writer = fromWritable(writable); + writer.fail(reason); + await assert.rejects(writer.write('more'), (error) => error === reason); + await assert.rejects(writer.end(), (error) => error === reason); + } +} + +async function testFileHandle() { + let i = 0; + for (const name in failures) { + const fh = await open(path.join(tmpdir.path, `fail-${i++}.txt`), 'w'); + const writer = fh.writer(); + await writer.write('a'); + failures[name](writer); + await checkFailed(`filehandle.writer(): ${name}`, writer); + // The handle is released, and can be written again. + const writer2 = fh.writer(); + await writer2.end(); + await fh.close(); + } +} + +async function testFileHandleFalsyReasons() { + let i = 0; + for (const reason of [null, 0, '', false]) { + const fh = await open(path.join(tmpdir.path, `falsy-${i++}.txt`), 'w'); + const writer = fh.writer(); + writer.fail(reason); + await assert.rejects(writer.write('more'), (error) => error === reason); + await assert.rejects(writer.end(), (error) => error === reason); + await fh.close(); + } +} + +(async () => { + await testFromWritable(); + await testFromWritableFalsyReasons(); + await testFileHandle(); + await testFileHandleFalsyReasons(); +})().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-fail-default-reason.js b/test/parallel/test-stream-iter-fail-default-reason.js new file mode 100644 index 000000000000..9a125a73f3ce --- /dev/null +++ b/test/parallel/test-stream-iter-fail-default-reason.js @@ -0,0 +1,175 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// writer.fail() with no reason, or an undefined one, fails a push(), +// broadcast() or duplex() writer with an AbortError DOMException: later +// writes, end(), consumers, writer.signal and pipeToSync() all see that +// same error. Symbol.dispose and Symbol.asyncDispose of an open writer call +// fail() with no reason. + +const common = require('../common'); +const assert = require('assert'); +const { + broadcast, + duplex, + pipeToSync, + push, +} = require('stream/iter'); + +function assertAbortError(error) { + assert.ok(error instanceof DOMException); + assert.strictEqual(error.name, 'AbortError'); + assert.strictEqual(error.message, 'This operation was aborted'); +} + +const failures = { + 'fail()': (writer) => writer.fail(), + 'fail(undefined)': (writer) => writer.fail(undefined), + 'Symbol.dispose': (writer) => writer[Symbol.dispose](), + 'Symbol.asyncDispose': (writer) => writer[Symbol.asyncDispose](), +}; + +async function assertFailedWith(writer, error) { + assertAbortError(error); + assert.strictEqual(writer.canWrite, null); + assert.strictEqual(writer.signal.aborted, true); + assert.strictEqual(writer.signal.reason, error); + await assert.rejects(writer.write('x'), (e) => e === error); + await assert.rejects(writer.writev(['x']), (e) => e === error); + await assert.rejects(writer.end(), (e) => e === error); + assert.strictEqual(writer.writeSync('x'), false); + assert.strictEqual(writer.endSync(), -1); + // A later fail() does not replace the error. + writer.fail(new Error('later')); + assert.strictEqual(writer.signal.reason, error); +} + +async function testPush() { + for (const name in failures) { + const { writer, readable } = push(); + const iterator = readable[Symbol.asyncIterator](); + const pending = iterator.next(); + // Read writer.signal first, so that it is aborted by fail() rather than + // created already aborted. + const { signal } = writer; + await failures[name](writer); + const error = signal.reason; + await assert.rejects(pending, (e) => e === error, name); + await assertFailedWith(writer, error); + } +} + +async function testPushBufferedDataThenError() { + const { writer, readable } = push(); + writer.writeSync('a'); + writer.fail(); + const iterator = readable[Symbol.asyncIterator](); + const error = writer.signal.reason; + assertAbortError(error); + // The data written before fail() is read first. + assert.strictEqual((await iterator.next()).done, false); + await assert.rejects(iterator.next(), (e) => e === error); +} + +async function testPushPendingWriteAndEnd() { + const { writer } = push({ budget: 1 }); + writer.writeSync('a'); + const writing = writer.write('b'); + const ending = writer.end(); + writer.fail(); + const error = writer.signal.reason; + assertAbortError(error); + await assert.rejects(writing, (e) => e === error); + await assert.rejects(ending, (e) => e === error); +} + +async function testBroadcast() { + for (const name in failures) { + const { writer, broadcast: channel } = broadcast(); + const iterator = channel.push()[Symbol.asyncIterator](); + const pending = iterator.next(); + const { signal } = writer; + await failures[name](writer); + const error = signal.reason; + await assert.rejects(pending, (e) => e === error, name); + // A consumer added later sees the same error. + await assert.rejects(channel.push()[Symbol.asyncIterator]().next(), + (e) => e === error, name); + await assertFailedWith(writer, error); + } +} + +async function testDuplex() { + for (const name in failures) { + const [a, b] = duplex(); + const pending = b.readable[Symbol.asyncIterator]().next(); + const { signal } = a.writer; + await failures[name](a.writer); + const error = signal.reason; + await assert.rejects(pending, (e) => e === error, name); + await assertFailedWith(a.writer, error); + } +} + +// The error is created by fail(), not shared between writers. +function testDistinctErrors() { + const first = push().writer; + const second = push().writer; + first.fail(); + second.fail(); + assert.notStrictEqual(first.signal.reason, second.signal.reason); +} + +// pipeToSync() to a writer failed without a reason throws its error. +function testPipeToSync() { + for (const make of [() => push().writer, () => broadcast().writer]) { + const writer = make(); + writer.fail(); + const error = writer.signal.reason; + assertAbortError(error); + assert.throws(() => pipeToSync(['data'], writer), (e) => e === error); + } +} + +// An explicit reason, including other falsy values, is kept as it is. +async function testExplicitReasons() { + for (const reason of [null, false, 0, '']) { + const { writer, readable } = push(); + writer.fail(reason); + assert.strictEqual(writer.signal.reason, reason); + await assert.rejects(readable[Symbol.asyncIterator]().next(), + (e) => e === reason); + } +} + +// Disposing a closed writer, or async disposing a closing one, does not fail +// it. +async function testDisposeClosedWriter() { + const closed = push().writer; + assert.strictEqual(closed.endSync(), 0); + closed[Symbol.dispose](); + await closed[Symbol.asyncDispose](); + assert.strictEqual(closed.signal.aborted, false); + + const { writer, readable } = push(); + writer.writeSync('a'); + writer.endSync(); + const disposing = writer[Symbol.asyncDispose](); + const chunks = []; + for await (const batch of readable) chunks.push(...batch); + assert.strictEqual(chunks.length, 1); + assert.strictEqual(await disposing, 1); + assert.strictEqual(writer.signal.aborted, false); +} + +Promise.all([ + testPush(), + testPushBufferedDataThenError(), + testPushPendingWriteAndEnd(), + testBroadcast(), + testDuplex(), + testDistinctErrors(), + testPipeToSync(), + testExplicitReasons(), + testDisposeClosedWriter(), +]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-reason-propagation.js b/test/parallel/test-stream-iter-reason-propagation.js index d7bdd3e9ab80..5c815c0d76ac 100644 --- a/test/parallel/test-stream-iter-reason-propagation.js +++ b/test/parallel/test-stream-iter-reason-propagation.js @@ -100,38 +100,51 @@ async function testBroadcastFromReason() { await rejectsWith(channel.push()[Symbol.asyncIterator]().next(), reason); } +// fail() with an undefined reason fails the writer with an AbortError: the +// writer's signal gives that error. +function failReason(writer, reason) { + if (reason !== undefined) return reason; + const error = writer.signal.reason; + assert.strictEqual(error.name, 'AbortError'); + return error; +} + async function testWriterFailReasons() { for (const reason of reasons) { const pushed = push(); pushed.writer.fail(reason); + const pushedReason = failReason(pushed.writer, reason); await rejectsWith( - pushed.readable[Symbol.asyncIterator]().next(), reason); - await rejectsWith(pushed.writer.write('data'), reason); - await rejectsWith(pushed.writer.end(), reason); + pushed.readable[Symbol.asyncIterator]().next(), pushedReason); + await rejectsWith(pushed.writer.write('data'), pushedReason); + await rejectsWith(pushed.writer.end(), pushedReason); const broadcasted = broadcast(); const iterator = broadcasted.broadcast.push()[Symbol.asyncIterator](); const pendingRead = iterator.next(); broadcasted.writer.fail(reason); - await rejectsWith(pendingRead, reason); - await rejectsWith(broadcasted.writer.write('data'), reason); - await rejectsWith(broadcasted.writer.end(), reason); + const broadcastedReason = failReason(broadcasted.writer, reason); + await rejectsWith(pendingRead, broadcastedReason); + await rejectsWith(broadcasted.writer.write('data'), broadcastedReason); + await rejectsWith(broadcasted.writer.end(), broadcastedReason); await rejectsWith( - broadcasted.broadcast.push()[Symbol.asyncIterator]().next(), reason); + broadcasted.broadcast.push()[Symbol.asyncIterator]().next(), + broadcastedReason); } } -async function testDisposeFailsWithUndefined() { +async function testDisposeFailsWithAbortError() { const pushed = push(); pushed.writer[Symbol.dispose](); + const pushedReason = failReason(pushed.writer, undefined); await rejectsWith( - pushed.readable[Symbol.asyncIterator]().next(), undefined); + pushed.readable[Symbol.asyncIterator]().next(), pushedReason); const broadcasted = broadcast(); const next = broadcasted.broadcast .push()[Symbol.asyncIterator]().next(); broadcasted.writer[Symbol.dispose](); - await rejectsWith(next, undefined); + await rejectsWith(next, failReason(broadcasted.writer, undefined)); } async function testExplicitUndefinedCancellation() { @@ -264,7 +277,7 @@ Promise.all([ testSharedSourceReasons(), testBroadcastFromReason(), testWriterFailReasons(), - testDisposeFailsWithUndefined(), + testDisposeFailsWithAbortError(), testExplicitUndefinedCancellation(), testPendingWriteAbortReasons(), testTransformReasons(), diff --git a/test/parallel/test-stream-iter-writable-interop.js b/test/parallel/test-stream-iter-writable-interop.js index e1af4cea7529..750b5c7ff7e6 100644 --- a/test/parallel/test-stream-iter-writable-interop.js +++ b/test/parallel/test-stream-iter-writable-interop.js @@ -963,7 +963,8 @@ async function testDisposeRejectsPendingWaiters() { writer[Symbol.dispose](); - await assert.rejects(writePromise, (reason) => reason === undefined); + // Dispose fails the writer without a reason: an AbortError. + await assert.rejects(writePromise, { name: 'AbortError' }); } // ============================================================================= From 05072ea4b3a681fae481e349ad1443dfd2f7fc94 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 18:58:57 +0000 Subject: [PATCH 19/26] stream: resolve stream/iter end() once all data is delivered If a push stream's consumer stops after reading the last batch while the writer is closing, end() now resolves with the byte count instead of rejecting: all of the data was delivered. This also applies when the other end of a duplex channel is closed or aborted after reading everything. If undelivered data remains, end() still rejects. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 11 +- lib/internal/streams/iter/push.js | 9 + .../test-stream-iter-end-after-delivery.js | 158 ++++++++++++++++++ .../test-stream-iter-writer-signal.js | 9 +- 4 files changed, 182 insertions(+), 5 deletions(-) create mode 100644 test/parallel/test-stream-iter-end-after-delivery.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index 624f2620090c..9921c5645138 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -515,7 +515,10 @@ the write. Use [`ondrain()`][] to wait for capacity rather than polling. Signals that no more data will be written. Writes already waiting for buffer space remain ordered before the end of the stream, while later writes fail. If data is outstanding, the returned promise fulfills after the consumer pulls -`done: true` beyond the final batch. If no data is buffered or pending, the +`done: true` beyond the final batch, or once the consumer has read the final +batch and then stops reading (for example, it breaks out of a `for await` +loop): all the data has been delivered. If the consumer stops before reading +all the data, the promise rejects. If no data is buffered or pending, the writer closes immediately. #### `writer.endSync()` @@ -1173,7 +1176,10 @@ Close this end of the duplex channel at once with an error. `abort()` fails this end's `writer` with `reason`, and stops this end's `readable`: it yields no more data, and the peer's writer is errored with `reason`, so the peer's pending and later writes and its [`ondrain()`][] waiters reject with `reason`. -If either writer has already closed, it is not affected. Data already written +If either writer has already closed, it is not affected. If the peer's writer +is closing and this end has already read all of its data, the peer's writer +closes instead, as when a consumer stops reading after the final batch (see +[`writer.end()`][]). Data already written to this end's `writer` is still delivered to the peer before it observes `reason`, as for `writer.fail()`. @@ -2727,4 +2733,5 @@ console.log(textSync(stream)); // 'hello world' [`toReadable()`]: #toreadablesource-options [`toReadableSync()`]: #toreadablesyncsource-options [`toWritable()`]: #towritablewriter +[`writer.end()`]: #writerendoptions [`writer.signal`]: #writersignal diff --git a/lib/internal/streams/iter/push.js b/lib/internal/streams/iter/push.js index 2571ba31bc78..f168af9ae971 100644 --- a/lib/internal/streams/iter/push.js +++ b/lib/internal/streams/iter/push.js @@ -587,6 +587,15 @@ class PushQueue { // Returns true if this errored the writer: the caller then stops it (see // #stop()) once the drain waiters are settled. #terminateWriterFromConsumer(error) { + // The writer is closing and every batch it accepted has been read: the + // data has all been delivered, so the writer closes, and its end() + // resolves with the byte count, as when the consumer reads the end. + if (this.#writerState === 'closing' && + this.#slots.length === 0 && + this.#pendingWrites.length === 0) { + this.endDrained(); + return false; + } this.#slots.clear(); this.#bufferedBytes = 0; let errored = false; diff --git a/test/parallel/test-stream-iter-end-after-delivery.js b/test/parallel/test-stream-iter-end-after-delivery.js new file mode 100644 index 000000000000..e5aecdd0115d --- /dev/null +++ b/test/parallel/test-stream-iter-end-after-delivery.js @@ -0,0 +1,158 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// Once a consumer has read the final batch of a closing push() writer, it +// stopping (return(), throw(), or a peer's DuplexChannel abort()) closes the +// writer: end() fulfills with the byte count, and writer.signal does not +// abort. If data is left to deliver, end() still rejects. + +const common = require('../common'); +const assert = require('assert'); +const { duplex, push } = require('stream/iter'); + +async function testBreakAfterFinalBatch() { + const { writer, readable } = push(); + writer.writeSync('abc'); + const ending = writer.end(); + // eslint-disable-next-line no-unused-vars + for await (const _ of readable) break; + assert.strictEqual(await ending, 3); + assert.strictEqual(writer.signal.aborted, false); + assert.strictEqual(writer.canWrite, null); + assert.strictEqual(writer.endSync(), 3); + assert.strictEqual(await writer.end(), 3); +} + +async function testReturnAfterFinalBatch() { + const { writer, readable } = push(); + writer.writeSync('ab'); + writer.writeSync('cd'); + const ending = writer.end(); + const iterator = readable[Symbol.asyncIterator](); + const { value } = await iterator.next(); + assert.strictEqual(value.length, 2); + assert.deepStrictEqual({ ...await iterator.return() }, + { done: true, value: undefined }); + assert.strictEqual(await ending, 4); + assert.deepStrictEqual({ ...await iterator.next() }, + { done: true, value: undefined }); +} + +async function testThrowAfterFinalBatch() { + const { writer, readable } = push(); + writer.writeSync('abc'); + const ending = writer.end(); + const iterator = readable[Symbol.asyncIterator](); + await iterator.next(); + const error = new Error('consumer error'); + await assert.rejects(iterator.throw(error), error); + assert.strictEqual(await ending, 3); + assert.strictEqual(writer.signal.aborted, false); +} + +async function testEndWithSignalAfterFinalBatch() { + const { writer, readable } = push(); + writer.writeSync('abc'); + const ending = writer.end({ signal: new AbortController().signal }); + // eslint-disable-next-line no-unused-vars + for await (const _ of readable) break; + assert.strictEqual(await ending, 3); +} + +async function testAsyncDisposeAfterFinalBatch() { + const { writer, readable } = push(); + writer.writeSync('abc'); + writer.endSync(); + const disposing = writer[Symbol.asyncDispose](); + // eslint-disable-next-line no-unused-vars + for await (const _ of readable) break; + assert.strictEqual(await disposing, 3); +} + +// Data left in the buffer, or waiting for buffer space, is not delivered. +async function testBreakWithBufferedData() { + const { writer, readable } = push({ budget: 1 }); + writer.writeSync('a'); + const writing = writer.write('b'); + const ending = writer.end(); + // eslint-disable-next-line no-unused-vars + for await (const _ of readable) break; + await writing; + await assert.rejects(ending, { + name: 'TypeError', + code: 'ERR_INVALID_STATE', + }); + assert.strictEqual(writer.signal.aborted, true); +} + +async function testBreakWithPendingWrite() { + const { writer, readable } = push({ budget: 1, backpressure: 'unbounded' }); + writer.writeSync('a'); + const writing = writer.write('b'); + const iterator = readable[Symbol.asyncIterator](); + await iterator.next(); + await writing; + // 'b' was promoted into the buffer by the read, and is not read. + const ending = writer.end(); + await iterator.return(); + await assert.rejects(ending, { code: 'ERR_INVALID_STATE' }); +} + +// A writer that is still open is errored when the consumer stops, even if +// everything written so far was read. +async function testBreakWhileOpen() { + const { writer, readable } = push(); + writer.writeSync('abc'); + // eslint-disable-next-line no-unused-vars + for await (const _ of readable) break; + assert.strictEqual(writer.signal.aborted, true); + await assert.rejects(writer.end(), { code: 'ERR_INVALID_STATE' }); +} + +// Duplex: the peer closing or aborting after reading all of a closing +// writer's data closes that writer. +async function testDuplexPeerCloseAfterFinalBatch() { + const [a, b] = duplex(); + a.writer.writeSync('xy'); + const ending = a.writer.end(); + const iterator = b.readable[Symbol.asyncIterator](); + await iterator.next(); + assert.strictEqual(await b.close(), undefined); + assert.strictEqual(await ending, 2); + assert.strictEqual(await a.close(), undefined); +} + +async function testDuplexPeerAbortAfterFinalBatch() { + const [a, b] = duplex(); + a.writer.writeSync('xy'); + const ending = a.writer.end(); + const iterator = b.readable[Symbol.asyncIterator](); + await iterator.next(); + const reason = new Error('aborted'); + await b.abort(reason); + assert.strictEqual(await ending, 2); + assert.strictEqual(a.writer.signal.aborted, false); +} + +async function testDuplexPeerAbortWithUnreadData() { + const [a, b] = duplex(); + a.writer.writeSync('xy'); + const ending = a.writer.end(); + const reason = new Error('aborted'); + await b.abort(reason); + await assert.rejects(ending, reason); +} + +Promise.all([ + testBreakAfterFinalBatch(), + testReturnAfterFinalBatch(), + testThrowAfterFinalBatch(), + testEndWithSignalAfterFinalBatch(), + testAsyncDisposeAfterFinalBatch(), + testBreakWithBufferedData(), + testBreakWithPendingWrite(), + testBreakWhileOpen(), + testDuplexPeerCloseAfterFinalBatch(), + testDuplexPeerAbortAfterFinalBatch(), + testDuplexPeerAbortWithUnreadData(), +]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-writer-signal.js b/test/parallel/test-stream-iter-writer-signal.js index b6dfb8e5ed91..921a8b7365c8 100644 --- a/test/parallel/test-stream-iter-writer-signal.js +++ b/test/parallel/test-stream-iter-writer-signal.js @@ -116,15 +116,18 @@ function assertAbortError(reason) { await assert.rejects(writer.write('c'), signal.reason); })().then(common.mustCall()); -// A consumer break aborts the signal of a writer that is closing. +// A consumer break aborts the signal of a writer that is closing with data +// left to deliver. (async () => { - const { writer, readable } = push(); + const { writer, readable } = push({ budget: 1 }); const signal = writer.signal; writer.writeSync('a'); - writer.writeSync('b'); + // Waits for buffer space: it is not read before the break. + const writing = writer.write('b'); const ending = writer.end(); // eslint-disable-next-line no-unused-vars for await (const _ of readable) break; + await writing; await assert.rejects(ending, signal.reason); assert.strictEqual(signal.aborted, true); })().then(common.mustCall()); From adf4928c52e7926134fc48133f408e1a9d0244b8 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 18:59:07 +0000 Subject: [PATCH 20/26] stream: deliver buffered broadcast data after writer fail() After a broadcast writer is failed without the broadcast being cancelled, each consumer, including one added later, now reads the data still buffered for it before rejecting with the failure reason. Previously, consumers that already existed were detached at once and lost that data. A later cancel() with no reason no longer turns that failure, or a share's source error, into a clean end: consumers, including ones added afterwards, still reject with the stored error. After Broadcast.cancel(), the writer rejects later writes and end() with the cancel reason or TypeError, and a closing writer whose data was discarded rejects end() instead of resolving it. end() and endSync() settle pending reads before drain waiters, and a shareSync() consumer reads its buffered data before a source error. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 60 ++++++++-- lib/internal/streams/iter/broadcast.js | 88 +++++++++++--- lib/internal/streams/iter/push.js | 8 +- lib/internal/streams/iter/share.js | 101 ++++++++++++++-- .../test-stream-iter-broadcast-basic.js | 44 +++---- .../test-stream-iter-broadcast-cancel-end.js | 73 ++++++++++++ ...est-stream-iter-broadcast-cancel-writes.js | 3 +- ...st-stream-iter-broadcast-cancelled-push.js | 5 +- ...-stream-iter-broadcast-end-no-consumers.js | 98 ++++++++++++++++ ...est-stream-iter-broadcast-fail-buffered.js | 101 ++++++++++++++++ ...test-stream-iter-broadcast-ondrain-true.js | 62 ++++++++++ ...test-stream-iter-broadcast-signal-abort.js | 6 +- .../test-stream-iter-cancel-keep-error.js | 110 ++++++++++++++++++ ...test-stream-iter-end-reads-before-drain.js | 31 +++++ ...st-stream-iter-pipe-cancelled-broadcast.js | 40 +++++++ ...am-iter-sharesync-buffered-before-error.js | 48 ++++++++ 16 files changed, 812 insertions(+), 66 deletions(-) create mode 100644 test/parallel/test-stream-iter-broadcast-cancel-end.js create mode 100644 test/parallel/test-stream-iter-broadcast-end-no-consumers.js create mode 100644 test/parallel/test-stream-iter-broadcast-fail-buffered.js create mode 100644 test/parallel/test-stream-iter-broadcast-ondrain-true.js create mode 100644 test/parallel/test-stream-iter-cancel-keep-error.js create mode 100644 test/parallel/test-stream-iter-end-reads-before-drain.js create mode 100644 test/parallel/test-stream-iter-pipe-cancelled-broadcast.js create mode 100644 test/parallel/test-stream-iter-sharesync-buffered-before-error.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index 9921c5645138..f3443d8cbeb4 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -1664,6 +1664,16 @@ Create a push-model multi-consumer broadcast channel. A single writer pushes data to multiple consumers. Each consumer has an independent cursor into a shared buffer. +After `writer.fail()`, each consumer, including one added later, still reads +the data buffered for it, then rejects with the `fail()` reason. + +`writer.end()` with no consumers completes at once if no write is pending; +consumers added later read the buffered data and then the end. If a write is +pending, the writer is closing instead: `end()` fulfills once no write is +pending and every consumer registered while the writer is closing, including +ones added after `end()` was called, has read past the end or detached. Until +a consumer is added, `end()` and the pending write stay pending. + Aborting `signal` fails the writer and then cancels the broadcast, both with the abort reason: pending writes and a pending `writer.end()` reject with the reason, as do later writes (`writeSync()` and `writevSync()` return `false`), @@ -1725,16 +1735,31 @@ Cancel the broadcast. If `reason` is provided and is not `undefined`, all consumers reject with that exact reason. If it is omitted or `undefined`, consumers complete normally. -Cancelling also closes the paired writer: afterwards its `canWrite` is `null` -and `write()` rejects with a `TypeError`. This lets a [`Broadcast.from()`][] -pump stop pulling from its source. Writes still pending are not written: they -reject with `reason`, or if none is given with an `ERR_INVALID_STATE` -`TypeError`, the same object that [`writer.signal`][]'s `reason` is. +Cancelling also closes the paired writer: afterwards its `canWrite` is `null`. +This lets a [`Broadcast.from()`][] pump stop pulling from its source. Writes +still pending are not written: they reject with `reason`, or if none is given +with an `ERR_INVALID_STATE` `TypeError`, the same object that +[`writer.signal`][]'s `reason` is. Later `write()`, `writev()`, and `end()` +calls reject with that same value, and `endSync()` returns `-1`, so +[`pipeTo()`][] and [`pipeToSync()`][] into the cancelled writer both report +it. The buffered data is discarded. Consumers created with `broadcast.push()` after cancelling are not registered and read none of the buffered data: their -first read rejects with `reason` if one was provided, and otherwise completes -with `{ done: true }`. +first read rejects with `reason` if one was provided, or with the error +described below, and otherwise completes with `{ done: true }`. + +If `writer.end()` had been called and the data written has not all been +delivered to every consumer, that data is discarded, and the promise that +`end()` returned rejects with the value that the pending writes reject with. +If all of it had been delivered, the promise fulfills with the number of +bytes written. + +If the writer had already failed when `cancel()` is called without a reason +(including by `broadcast[Symbol.dispose]()`), the error is kept: the consumers +still read the data buffered for them, then reject with the `fail()` reason, +and consumers created later reject with it too. Such consumers stay counted in +`consumerCount` until they detach. #### `broadcast.consumerCount` @@ -1917,6 +1942,15 @@ Cancel the share. If `reason` is provided and is not `undefined`, all consumers reject with that exact reason. If it is omitted or `undefined`, consumers complete normally. +Consumers created with `share.pull()` after cancelling are not registered: +their first read rejects with `reason` if one was provided, or with the error +described below, and otherwise completes with `{ done: true }`. + +If the source had already failed when `cancel()` is called without a reason +(including by `share[Symbol.dispose]()`), the error is kept: the consumers +still read the data buffered for them, then reject with the source's error, +and consumers created later reject with it too. + #### `share.consumerCount` * {number} @@ -1973,6 +2007,9 @@ and the slowest consumer cannot advance while another consumer's read is running. `'unbounded'` and `'drop-newest'` are therefore not supported and throw `ERR_INVALID_ARG_VALUE`. +When the source throws, each consumer still reads the data buffered for it +first, and then throws the source's error. + ### Class: `SyncShare` #### Static method: `SyncShare.fromSync(input[, options])` @@ -1995,6 +2032,15 @@ Cancel the share. If `reason` is provided and is not `undefined`, all consumers throw that exact reason. If it is omitted or `undefined`, consumers complete normally. +Consumers created with `share.pull()` after cancelling are not registered: +their first read throws `reason` if one was provided, or the error described +below, and otherwise completes with `{ done: true }`. + +If the source had already failed when `cancel()` is called without a reason +(including by `share[Symbol.dispose]()`), the error is kept: the consumers +still read the data buffered for them, then throw the source's error, and +consumers created later throw it too. + #### `share.consumerCount` * {number} diff --git a/lib/internal/streams/iter/broadcast.js b/lib/internal/streams/iter/broadcast.js index 7fe9f47e17e5..fef168dfeebe 100644 --- a/lib/internal/streams/iter/broadcast.js +++ b/lib/internal/streams/iter/broadcast.js @@ -135,9 +135,6 @@ class BroadcastImpl { #error; #errored = false; #cancelled = false; - // The reason given to cancel(), if any, for consumers created afterwards. - #cancelReason; - #hasCancelReason = false; #options; #writer = null; #cachedMinCursor = 0; @@ -215,9 +212,11 @@ class BroadcastImpl { return rawConsumer; } + // Its pulls reject with the reason given to cancel(), or the error the + // writer had failed with before a cancel() without a reason. #createCancelledConsumer() { - const hasReason = this.#hasCancelReason; - const reason = this.#cancelReason; + const hasReason = this.#errored; + const reason = this.#error; const kDone = PromiseResolve(new IterResult(true, undefined)); return { __proto__: null, @@ -307,7 +306,8 @@ class BroadcastImpl { if (self.#errored) { state.detached = true; state.error = self.#error; - self.#deleteConsumer(state); + if (self.#deleteConsumer(state)) self.#tryTrimBuffer(); + self.#notifyEndDrained(); return PromiseReject(self.#error); } @@ -350,12 +350,22 @@ class BroadcastImpl { cancel(reason) { if (this.#cancelled) return; const hasReason = reason !== undefined; + if (!hasReason && this.#errored) { + // The writer has failed: a cancel() without a reason (or a dispose) + // does not turn its error into a clean end. The consumers still read + // the data buffered for them and then reject with the error, as do + // consumers created later. + this.#cancelled = true; + this.#cleanupFactorySignal(); + const onCancel = this[kOnCancel]; + this[kOnCancel] = null; + onCancel?.(reason); + return; + } this.#cancelled = true; this.#ended = true; // Prevents [kAbort]() from redundantly iterating consumers if (hasReason) { - this.#cancelReason = reason; - this.#hasCancelReason = true; this.#error = reason; this.#errored = true; } @@ -381,13 +391,15 @@ class BroadcastImpl { this.#consumers.clear(); this.#waiters.clear(); this.#cachedMinCursorConsumers = 0; - // Discard the buffered data: no consumer can read it anymore. + // Discard the buffered data: no consumer can read it anymore. Data still + // buffered has not been delivered to every consumer. + const discarded = this.#buffer.length > 0; this.#bufferStart += this.#buffer.length; this.#buffer.clear(); this.#bufferedBytes = 0; // Then reject the pending writes, so that the pump doesn't hang. The // buffer has no room for them anymore: they are not written. - this.#writer?.[kCancelWriter](reason); + this.#writer?.[kCancelWriter](reason, discarded); this.#cleanupFactorySignal(); const onCancel = this[kOnCancel]; this[kOnCancel] = null; @@ -486,7 +498,27 @@ class BroadcastImpl { this.#error = reason; this.#ended = true; - // Notify all waiting consumers and detach them + // A consumer reads the entries still buffered for it, then rejects with + // the reason (see next()), as a consumer added later does. A consumer + // waiting for data has none left: its pending reads reject now, and it + // is detached. + for (const consumer of this.#consumers) { + if (consumer.reject) { + consumer.reject(reason); + consumer.resolve = null; + consumer.reject = null; + this.#rejectPending(consumer, reason); + consumer.error = reason; + consumer.detached = true; + if (this.#deleteConsumer(consumer)) this.#tryTrimBuffer(); + } + } + this.#waiters.clear(); + this.#notifyEndDrained(); + } + + // Detach every consumer with `reason`, discarding what they have not read. + #rejectConsumers(reason) { for (const consumer of this.#consumers) { if (consumer.reject) { consumer.reject(reason); @@ -567,6 +599,8 @@ class BroadcastImpl { } catch (error) { this.#writer.fail(error); if (!this.#errored) this[kAbort](error); + // The buffered data can no longer be read. + this.#rejectConsumers(error); this.#buffer.clear(); this.#bufferedBytes = 0; return null; @@ -784,6 +818,9 @@ class BroadcastWriter { throw this.#error; } if (this.#state !== 'open') { + // A writer closed by Broadcast.cancel() rejects with the reason it + // stopped, as pipeToSync() reports it from writer.signal. + if (this.#stopped) throw this.#stopReason; throw new ERR_INVALID_STATE.TypeError('Writer is closed'); } @@ -855,26 +892,32 @@ class BroadcastWriter { return PromiseReject(err); } if (this.#state === 'errored') return PromiseReject(this.#error); - if (this.#state === 'closed') return PromiseResolve(this.#totalBytes); + if (this.#state === 'closed') { + // Closed by Broadcast.cancel(): the reason it stopped. + if (this.#stopped) return PromiseReject(this.#stopReason); + return PromiseResolve(this.#totalBytes); + } if (signal?.aborted) return PromiseReject(signal.reason); const endPromise = this.#getEndPromise(); if (this.#state === 'open') { this.#state = 'closing'; - this.#resolvePendingDrains(false); + // Pending reads that can report the end do so before the drain + // waiters are told that no more data can be written. this.#finishEndIfReady(); + this.#resolvePendingDrains(false); } return raceEndWithSignal(endPromise, signal); } endSync() { - if (this.#state === 'closed') return this.#totalBytes; + if (this.#state === 'closed') return this.#stopped ? -1 : this.#totalBytes; if (this.#state === 'errored' || this.#state === 'closing') return -1; this.#state = 'closing'; - this.#resolvePendingDrains(false); this.#finishEndIfReady(); + this.#resolvePendingDrains(false); return this.#state === 'closed' ? this.#totalBytes : -1; } @@ -903,15 +946,26 @@ class BroadcastWriter { this.fail(); } - [kCancelWriter](reason) { + // `discarded`: whether the cancel discarded buffered data. + [kCancelWriter](reason, discarded) { if (this.#state === 'closed' || this.#state === 'errored') return; + // A closing writer whose data has not all been delivered: data buffered + // or written after end() is discarded, so its end() does not report + // success. + const undelivered = this.#state === 'closing' && + (discarded || this.#pendingWrites.length > 0); this.#state = 'closed'; // Pending writes reject with the cancel reason, or without one with a // TypeError, which is also the reason writer.signal aborts with. const error = reason !== undefined ? reason : new ERR_INVALID_STATE.TypeError('Broadcast was cancelled'); this.#rejectPendingWrites(error); - this.#pendingEnd?.resolve(this.#totalBytes); + // end() rejects with that error too. + if (undelivered) { + this.#pendingEnd?.reject(error); + } else { + this.#pendingEnd?.resolve(this.#totalBytes); + } this.#resolvePendingDrains(false); this.#stop(error); } diff --git a/lib/internal/streams/iter/push.js b/lib/internal/streams/iter/push.js index f168af9ae971..f715b7602e25 100644 --- a/lib/internal/streams/iter/push.js +++ b/lib/internal/streams/iter/push.js @@ -373,18 +373,20 @@ class PushQueue { return this.#bytesWritten; // Idempotent } - this.#resolvePendingDrains(false); - - // If there is no accepted work to drain, close immediately. + // If there is no accepted work to drain, close immediately. A pending + // read reports the end before the drain waiters are told that no more + // data can be written. if (this.#slots.length === 0 && this.#pendingWrites.length === 0) { this.#writerState = 'closed'; this.#cleanup(); this.#resolvePendingReads(); + this.#resolvePendingDrains(false); return this.#bytesWritten; } // Accepted work remains: close after it drains and the consumer pulls EOF. this.#writerState = 'closing'; + this.#resolvePendingDrains(false); return -3; // Signal to PushWriter: create deferred end promise } diff --git a/lib/internal/streams/iter/share.js b/lib/internal/streams/iter/share.js index 273c87ec85d6..6c1363556e55 100644 --- a/lib/internal/streams/iter/share.js +++ b/lib/internal/streams/iter/share.js @@ -111,6 +111,9 @@ class ShareImpl { #resolvePull = null; #pullDiscard = false; #cancelError = kNoShareError; + // Whether cancel() was called without a reason after the source errored: + // the consumers still read their buffered data, then reject with the error. + #keepError = false; #cachedMinCursor = 0; #cachedMinCursorConsumers = 0; #abortHandler; @@ -140,6 +143,12 @@ class ShareImpl { }); const { signal } = options; + // A consumer of a cancelled share is not registered, reads no buffered + // data and does not call any of the transforms. + if (this.#cancelled) { + return this.#createCancelledConsumer(); + } + // Avoid registering a consumer that the pre-aborted pipeline will never // read or detach. if (signal?.aborted) { @@ -160,6 +169,29 @@ class ShareImpl { return rawConsumer; } + // Its pulls reject with the reason given to cancel(), or the error the + // source had failed with before a cancel() without a reason. + #createCancelledConsumer() { + const error = this.#keepError ? this.#sourceError : this.#cancelError; + return { + __proto__: null, + [SymbolAsyncIterator]() { + return ObjectSetPrototypeOf({ + next() { + if (error !== kNoShareError) return PromiseReject(error); + return PromiseResolve(new IterResult(true, undefined)); + }, + return() { + return PromiseResolve(new IterResult(true, undefined)); + }, + throw() { + return PromiseResolve(new IterResult(true, undefined)); + }, + }, null); + }, + }; + } + #createRawConsumer() { const state = ObjectSetPrototypeOf({ cursor: this.#bufferStart, @@ -263,6 +295,12 @@ class ShareImpl { if (hasReason) { this.#cancelError = reason; + } else if (this.#sourceError !== kNoShareError) { + // The source has failed, and is done: a cancel() without a reason (or + // a dispose) does not turn its error into a clean end. + this.#keepError = true; + this.#cleanupFactorySignal(); + return; } if (this.#resolvePull !== null) this.#finishPull(); @@ -319,7 +357,7 @@ class ShareImpl { return new IterResult(true, undefined); } - if (this.#cancelled) { + if (this.#cancelled && !this.#keepError) { state.detached = true; state.error = this.#cancelError; this.#deleteConsumer(state); @@ -737,6 +775,12 @@ class SyncShareImpl { } pull(...transforms) { + // A consumer of a cancelled share is not registered, reads no buffered + // data and does not call any of the transforms. + if (this.#cancelled) { + return this.#createCancelledConsumer(); + } + const rawConsumer = this.#createRawConsumer(); if (transforms.length > 0) { @@ -745,6 +789,30 @@ class SyncShareImpl { return rawConsumer; } + // Its next() throws the reason given to cancel(), or the error the source + // had failed with before a cancel() without a reason (both are stored as + // the source error). + #createCancelledConsumer() { + const error = this.#sourceError; + return { + __proto__: null, + [SymbolIterator]() { + return ObjectSetPrototypeOf({ + next() { + if (error !== kNoShareError) throw error; + return new IterResult(true, undefined); + }, + return() { + return new IterResult(true, undefined); + }, + throw() { + return new IterResult(true, undefined); + }, + }, null); + }, + }; + } + #createRawConsumer() { const state = ObjectSetPrototypeOf({ cursor: this.#bufferStart, @@ -772,18 +840,10 @@ class SyncShareImpl { if (state.error !== kNoShareError) throw state.error; return new IterResult(true, undefined); } - if (self.#sourceError !== kNoShareError) { - state.detached = true; - state.error = self.#sourceError; - self.#deleteConsumer(state); - throw state.error; - } - if (self.#cancelled) { - state.detached = true; - self.#deleteConsumer(state); - return new IterResult(true, undefined); - } + // The data buffered for the consumer is read first, even once + // the source has failed (also after a cancel() without a reason, + // which keeps the error), as for the async share. const bufferIndex = state.cursor - self.#bufferStart; if (bufferIndex < self.#buffer.length) { const chunk = self.#readEntry(self.#buffer.get(bufferIndex)); @@ -796,6 +856,18 @@ class SyncShareImpl { return new IterResult(false, chunk); } + if (self.#sourceError !== kNoShareError) { + state.detached = true; + state.error = self.#sourceError; + self.#deleteConsumer(state); + throw state.error; + } + if (self.#cancelled) { + state.detached = true; + self.#deleteConsumer(state); + return new IterResult(true, undefined); + } + if (self.#sourceExhausted) { state.detached = true; self.#deleteConsumer(state); @@ -895,6 +967,11 @@ class SyncShareImpl { if (hasReason) { this.#sourceError = reason; + } else if (this.#sourceError !== kNoShareError) { + // The source has failed, and is done: a cancel() without a reason (or + // a dispose) does not turn its error into a clean end. The consumers + // still throw it. + return; } try { diff --git a/test/parallel/test-stream-iter-broadcast-basic.js b/test/parallel/test-stream-iter-broadcast-basic.js index 7b2187f94e32..ca4132b0a47c 100644 --- a/test/parallel/test-stream-iter-broadcast-basic.js +++ b/test/parallel/test-stream-iter-broadcast-basic.js @@ -178,6 +178,8 @@ async function testWriterFailWhileClosing() { writer.fail(reason); await endRejected; + // The data buffered before fail() is read first. + assert.strictEqual((await iter.next()).done, false); await assert.rejects(iter.next(), (error) => error === reason); } @@ -269,7 +271,7 @@ async function testPushPreAbortedSignalDoesNotAddConsumer() { } // ============================================================================= -// Writer fail detaches consumers +// Writer fail detaches consumers once they have read their buffered data // ============================================================================= async function testFailDetachesConsumers() { @@ -283,29 +285,27 @@ async function testFailDetachesConsumers() { await writer.write('data'); await writer.fail(new Error('writer failed')); - // After fail, consumers are detached - assert.strictEqual(bc.consumerCount, 0); + // After fail, consumers stay attached until they have read the data + // buffered for them. + assert.strictEqual(bc.consumerCount, 2); - // Both consumers should see the error - await assert.rejects( - async () => { - // eslint-disable-next-line no-unused-vars - for await (const _ of consumer1) { - assert.fail('Should not reach here'); - } - }, - { message: 'writer failed' }, - ); + // Both consumers read the data, then see the error + for (const consumer of [consumer1, consumer2]) { + const chunks = []; + await assert.rejects( + async () => { + for await (const batch of consumer) { + chunks.push(...batch); + } + }, + { message: 'writer failed' }, + ); + assert.strictEqual(new TextDecoder().decode(chunks[0]), 'data'); + assert.strictEqual(chunks.length, 1); + } - await assert.rejects( - async () => { - // eslint-disable-next-line no-unused-vars - for await (const _ of consumer2) { - assert.fail('Should not reach here'); - } - }, - { message: 'writer failed' }, - ); + // After reading the error, consumers are detached + assert.strictEqual(bc.consumerCount, 0); } // ============================================================================= diff --git a/test/parallel/test-stream-iter-broadcast-cancel-end.js b/test/parallel/test-stream-iter-broadcast-cancel-end.js new file mode 100644 index 000000000000..f8d57086ba5b --- /dev/null +++ b/test/parallel/test-stream-iter-broadcast-cancel-end.js @@ -0,0 +1,73 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// Broadcast.cancel() closes and stops the writer. If the writer was closing +// with data that not every consumer had received, its end() rejects with the +// cancel reason, or without one with the TypeError that the pending writes +// reject with, rather than resolve with the byte count. Later end() calls +// reject with that value too, and endSync() returns -1. + +const common = require('../common'); +const assert = require('assert'); +const { broadcast } = require('stream/iter'); + +async function testReason() { + const { writer, broadcast: bc } = broadcast({ budget: 1 }); + bc.push(); + writer.writeSync('ab'); + const write = writer.write('c'); + const end = writer.end(); + const reason = new Error('cancelled'); + bc.cancel(reason); + await assert.rejects(write, reason); + await assert.rejects(end, reason); + await assert.rejects(writer.end(), reason); + assert.strictEqual(writer.endSync(), -1); +} + +async function testNoReason() { + const { writer, broadcast: bc } = broadcast({ budget: 1 }); + bc.push(); + writer.writeSync('ab'); + const write = writer.write('c'); + const end = writer.end(); + bc.cancel(); + const error = writer.signal.reason; + assert.strictEqual(error.name, 'TypeError'); + assert.strictEqual(error.code, 'ERR_INVALID_STATE'); + await assert.rejects(write, (e) => e === error); + await assert.rejects(end, (e) => e === error); + await assert.rejects(writer.end(), (e) => e === error); +} + +// Only buffered data, no pending write. +async function testBufferedOnly() { + const { writer, broadcast: bc } = broadcast(); + bc.push(); + writer.writeSync('ab'); + const end = writer.end(); + const reason = new Error('cancelled'); + bc.cancel(reason); + await assert.rejects(end, reason); +} + +// Every consumer has read all of the data, but has not read the end yet: +// all of it was delivered, so end() resolves with the byte count. +async function testAllDelivered() { + const { writer, broadcast: bc } = broadcast(); + const it = bc.push()[Symbol.asyncIterator](); + writer.writeSync('ab'); + const end = writer.end(); + assert.strictEqual((await it.next()).done, false); + bc.cancel(new Error('cancelled')); + assert.strictEqual(await end, 2); + // Later calls report that the writer was stopped. + await assert.rejects(writer.end(), { message: 'cancelled' }); +} + +Promise.all([ + testReason(), + testNoReason(), + testBufferedOnly(), + testAllDelivered(), +]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-broadcast-cancel-writes.js b/test/parallel/test-stream-iter-broadcast-cancel-writes.js index a17ce33315da..14543e9a238b 100644 --- a/test/parallel/test-stream-iter-broadcast-cancel-writes.js +++ b/test/parallel/test-stream-iter-broadcast-cancel-writes.js @@ -74,7 +74,8 @@ async function testStopLastAndNoPromotion() { assert.strictEqual((await read).done, true); await assert.rejects(write, { name: 'TypeError' }); assert.strictEqual(await drain, false); - assert.strictEqual(await end, 4); + // The pending write was not delivered: end() rejects as it does. + await assert.rejects(end, writer.signal.reason); assert.strictEqual((await holding.next()).done, true); } diff --git a/test/parallel/test-stream-iter-broadcast-cancelled-push.js b/test/parallel/test-stream-iter-broadcast-cancelled-push.js index c7078a506057..97f09bca0cc3 100644 --- a/test/parallel/test-stream-iter-broadcast-cancelled-push.js +++ b/test/parallel/test-stream-iter-broadcast-cancelled-push.js @@ -44,9 +44,10 @@ async function testCancelDiscardsBuffer() { writer.writeSync('abcd'); assert.strictEqual(writer.canWrite, false); bc.cancel(); - // The writer was closed with the bytes written. + // The writer was closed and stopped: end() rejects with the stop reason. assert.strictEqual(writer.canWrite, null); - assert.strictEqual(await writer.end(), 4); + await assert.rejects(writer.end(), writer.signal.reason); + assert.strictEqual(writer.endSync(), -1); for await (const batch of bc.push()) { assert.fail(`unexpected ${batch}`); } diff --git a/test/parallel/test-stream-iter-broadcast-end-no-consumers.js b/test/parallel/test-stream-iter-broadcast-end-no-consumers.js new file mode 100644 index 000000000000..1ac1ad05eb37 --- /dev/null +++ b/test/parallel/test-stream-iter-broadcast-end-no-consumers.js @@ -0,0 +1,98 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// end() on a broadcast writer with no consumers completes at once only if no +// write is pending. Otherwise the writer is closing, and end() resolves once +// no write is pending and every consumer registered while it is closing, +// including consumers that attach after end() was called, has read past the +// end or detached. + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { broadcast, text } = require('stream/iter'); + +function track(promise) { + const state = { settled: false, value: undefined }; + promise.then(common.mustCall((value) => { + state.settled = true; + state.value = value; + })); + return state; +} + +// No write pending: end() resolves at once, and a later consumer reads the +// buffered data and the end. +async function testNoPendingWrite() { + const { writer, broadcast: bc } = broadcast({ budget: 4 }); + writer.writeSync('12345678'); + assert.strictEqual(await writer.end(), 8); + assert.strictEqual(await text(bc.push()), '12345678'); +} + +// A write is pending: end() and the write wait for a consumer, which drains +// them once it attaches. +async function testPendingWriteLateConsumer() { + const { writer, broadcast: bc } = broadcast({ budget: 4 }); + writer.writeSync('12345678'); + const write = track(writer.write('abcd')); + const end = track(writer.end()); + assert.strictEqual(writer.endSync(), -1); + await setImmediate(); + assert.strictEqual(write.settled, false); + assert.strictEqual(end.settled, false); + + assert.strictEqual(await text(bc.push()), '12345678abcd'); + await setImmediate(); + assert.strictEqual(write.settled, true); + assert.strictEqual(end.settled, true); + assert.strictEqual(end.value, 12); +} + +// end() waits for every consumer registered while closing. +async function testWaitsForEveryLateConsumer() { + const { writer, broadcast: bc } = broadcast({ budget: 4 }); + writer.writeSync('12345678'); + const write = writer.write('abcd'); + const end = track(writer.end()); + const fast = bc.push(); + const slow = bc.push()[Symbol.asyncIterator](); + const first = await slow.next(); + assert.strictEqual(first.done, false); + assert.strictEqual(await text(fast), '12345678abcd'); + await write; + await setImmediate(); + assert.strictEqual(end.settled, false); + const second = await slow.next(); + assert.strictEqual(second.done, false); + await setImmediate(); + assert.strictEqual(end.settled, false); + // Detaching counts as done. + await slow.return(); + await setImmediate(); + assert.strictEqual(end.settled, true); + assert.strictEqual(end.value, 12); +} + +// A consumer that attaches and detaches before reading does not drain the +// pending write: end() keeps waiting. +async function testDetachBeforeReading() { + const { writer, broadcast: bc } = broadcast({ budget: 4 }); + writer.writeSync('12345678'); + const write = track(writer.write('abcd')); + const end = track(writer.end()); + await bc.push()[Symbol.asyncIterator]().return(); + await setImmediate(); + assert.strictEqual(write.settled, false); + assert.strictEqual(end.settled, false); + assert.strictEqual(await text(bc.push()), '12345678abcd'); + await setImmediate(); + assert.strictEqual(end.settled, true); +} + +(async () => { + await testNoPendingWrite(); + await testPendingWriteLateConsumer(); + await testWaitsForEveryLateConsumer(); + await testDetachBeforeReading(); +})().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-broadcast-fail-buffered.js b/test/parallel/test-stream-iter-broadcast-fail-buffered.js new file mode 100644 index 000000000000..df34ca3d533f --- /dev/null +++ b/test/parallel/test-stream-iter-broadcast-fail-buffered.js @@ -0,0 +1,101 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// After a broadcast() writer is failed (without cancelling the broadcast), +// each consumer reads the entries still buffered for it, then rejects with +// the error. A consumer waiting for data rejects at once. Consumers added +// later do the same while the data is still buffered. + +const common = require('../common'); +const assert = require('assert'); +const { broadcast } = require('stream/iter'); + +const decoder = new TextDecoder(); + +async function read(iterator) { + try { + const result = await iterator.next(); + return result.done ? 'done' : decoder.decode(result.value[0]); + } catch (error) { + return `error: ${error.message}`; + } +} + +async function testBufferedThenError() { + const { writer, broadcast: channel } = broadcast(); + const c1 = channel.push()[Symbol.asyncIterator](); + const c2 = channel.push()[Symbol.asyncIterator](); + writer.writeSync('a'); + writer.writeSync('b'); + assert.strictEqual(await read(c2), 'a'); + writer.fail(new Error('failed')); + // The consumers are detached once they have read the error. + assert.strictEqual(channel.consumerCount, 2); + + // Added after fail(): reads from the oldest buffered entry. + const late = channel.push()[Symbol.asyncIterator](); + assert.strictEqual(channel.consumerCount, 3); + + assert.strictEqual(await read(c1), 'a'); + assert.strictEqual(await read(c1), 'b'); + assert.strictEqual(await read(c1), 'error: failed'); + assert.strictEqual(await read(c1), 'error: failed'); + assert.strictEqual(await read(c2), 'b'); + assert.strictEqual(await read(c2), 'error: failed'); + assert.strictEqual(await read(late), 'a'); + assert.strictEqual(await read(late), 'b'); + assert.strictEqual(await read(late), 'error: failed'); + assert.strictEqual(channel.consumerCount, 0); + + // Once no consumer holds the data, a new consumer only sees the error. + assert.strictEqual(await read(channel.push()[Symbol.asyncIterator]()), + 'error: failed'); +} + +async function testWaitingConsumerRejects() { + const { writer, broadcast: channel } = broadcast(); + const waiting = channel.push()[Symbol.asyncIterator](); + const reading = channel.push()[Symbol.asyncIterator](); + writer.writeSync('a'); + assert.strictEqual(await read(waiting), 'a'); + const pending = [read(waiting), read(waiting)]; + writer.fail(new Error('failed')); + // The waiting consumer had nothing left to read: it is detached. + assert.strictEqual(channel.consumerCount, 1); + assert.deepStrictEqual(await Promise.all(pending), + ['error: failed', 'error: failed']); + assert.strictEqual(await read(reading), 'a'); + assert.strictEqual(await read(reading), 'error: failed'); +} + +// A consumer that stops after fail() releases the buffered data. +async function testReturnAfterFail() { + const { writer, broadcast: channel } = broadcast(); + const consumer = channel.push()[Symbol.asyncIterator](); + writer.writeSync('a'); + writer.fail(new Error('failed')); + await consumer.return(); + assert.strictEqual(channel.consumerCount, 0); + assert.strictEqual(await read(consumer), 'done'); +} + +// Aborting the factory signal later cancels the broadcast: consumers that +// have not read their data reject with the abort reason. +async function testSignalAfterFail() { + const controller = new AbortController(); + const { writer, broadcast: channel } = broadcast({ + signal: controller.signal, + }); + const consumer = channel.push()[Symbol.asyncIterator](); + writer.writeSync('a'); + writer.fail(new Error('failed')); + controller.abort(new Error('aborted')); + assert.strictEqual(await read(consumer), 'error: aborted'); +} + +Promise.all([ + testBufferedThenError(), + testWaitingConsumerRejects(), + testReturnAfterFail(), + testSignalAfterFail(), +]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-broadcast-ondrain-true.js b/test/parallel/test-stream-iter-broadcast-ondrain-true.js new file mode 100644 index 000000000000..50025305fd81 --- /dev/null +++ b/test/parallel/test-stream-iter-broadcast-ondrain-true.js @@ -0,0 +1,62 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// A broadcast writer's ondrain() resolves with true once the slowest +// consumer frees budget, pending writes are written as budget frees, and +// consumers of a closing writer that have read everything see the end. + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { broadcast, ondrain, text } = require('stream/iter'); + +async function testDrainTrue() { + const { writer, broadcast: bc } = broadcast({ budget: 2 }); + const fast = bc.push()[Symbol.asyncIterator](); + const slow = bc.push()[Symbol.asyncIterator](); + writer.writeSync('abc'); + assert.strictEqual(writer.canWrite, false); + let drained; + const drain = ondrain(writer).then((value) => { drained = value; }); + await fast.next(); + await setImmediate(); + // The slowest consumer still holds the budget. + assert.strictEqual(drained, undefined); + await slow.next(); + await drain; + assert.strictEqual(drained, true); + assert.strictEqual(writer.canWrite, true); +} + +async function testPendingWritePromoted() { + const { writer, broadcast: bc } = broadcast({ budget: 1 }); + const it = bc.push()[Symbol.asyncIterator](); + writer.writeSync('a'); + let written = false; + const write = writer.write('b').then(() => { written = true; }); + await setImmediate(); + assert.strictEqual(written, false); + await it.next(); + await write; + assert.strictEqual(written, true); + assert.deepStrictEqual([...(await it.next()).value[0]], [98]); +} + +// Each consumer of a closing writer gets the end once it has read all of +// the data, without waiting for the other consumers. +async function testClosingEnd() { + const { writer, broadcast: bc } = broadcast(); + const first = bc.push(); + const second = bc.push(); + writer.writeSync('hi'); + const end = writer.end(); + assert.strictEqual(await text(first), 'hi'); + assert.strictEqual(await text(second), 'hi'); + assert.strictEqual(await end, 2); +} + +Promise.all([ + testDrainTrue(), + testPendingWritePromoted(), + testClosingEnd(), +]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-broadcast-signal-abort.js b/test/parallel/test-stream-iter-broadcast-signal-abort.js index 0603a860a223..4c16c66ac362 100644 --- a/test/parallel/test-stream-iter-broadcast-signal-abort.js +++ b/test/parallel/test-stream-iter-broadcast-signal-abort.js @@ -76,9 +76,11 @@ async function testAbortAfterCancelHasNoEffect() { const { writer, broadcast: bc } = broadcast({ signal: ac.signal }); bc.cancel(); ac.abort(new Error('ignored')); - // The writer was closed by cancel(). + // The writer was closed by cancel(): end() rejects with the reason it + // stopped, not the abort reason. assert.strictEqual(writer.canWrite, null); - assert.strictEqual(await writer.end(), 0); + await assert.rejects(writer.end(), writer.signal.reason); + assert.strictEqual(writer.signal.reason.code, 'ERR_INVALID_STATE'); const result = await bc.push()[Symbol.asyncIterator]().next(); assert.strictEqual(result.done, true); assert.strictEqual(result.value, undefined); diff --git a/test/parallel/test-stream-iter-cancel-keep-error.js b/test/parallel/test-stream-iter-cancel-keep-error.js new file mode 100644 index 000000000000..ca14afa60c1e --- /dev/null +++ b/test/parallel/test-stream-iter-cancel-keep-error.js @@ -0,0 +1,110 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// A cancel() without a reason (or undefined, or Symbol.dispose) after the +// broadcast writer failed, or after the share's source errored, does not turn +// the error into a clean end: consumers read the data still buffered for +// them, then reject with the stored error, and consumers created after the +// cancel() reject with it too. Consumers that keep the error stay registered +// until their pulls reject. + +const common = require('../common'); +const assert = require('assert'); +const { broadcast, share, shareSync } = require('stream/iter'); + +const decoder = new TextDecoder(); + +const cancels = { + 'cancel()': (target) => target.cancel(), + 'cancel(undefined)': (target) => target.cancel(undefined), + 'Symbol.dispose': (target) => target[Symbol.dispose](), +}; + +async function testBroadcast(name, cancel) { + const { writer, broadcast: bc } = broadcast(); + const consumer = bc.push()[Symbol.asyncIterator](); + const transformed = bc.push((chunks) => chunks)[Symbol.asyncIterator](); + writer.writeSync('buffered'); + const error = new Error('failed'); + writer.fail(error); + cancel(bc); + assert.strictEqual(bc.consumerCount, 2, name); + + for (const iterator of [consumer, transformed]) { + const first = await iterator.next(); + assert.strictEqual(decoder.decode(first.value[0]), 'buffered', name); + await assert.rejects(iterator.next(), error, name); + } + assert.strictEqual(bc.consumerCount, 0, name); + + const late = bc.push(common.mustNotCall())[Symbol.asyncIterator](); + await assert.rejects(late.next(), error, name); + await assert.rejects(bc.push()[Symbol.asyncIterator]().next(), error, name); +} + +async function testShare(name, cancel) { + const error = new Error('source failed'); + async function* source() { + yield 'buffered'; + throw error; + } + const sh = share(source()); + const fast = sh.pull()[Symbol.asyncIterator](); + const slow = sh.pull()[Symbol.asyncIterator](); + const first = await fast.next(); + assert.strictEqual(decoder.decode(first.value[0]), 'buffered', name); + await assert.rejects(fast.next(), error, name); + cancel(sh); + assert.strictEqual(sh.consumerCount, 1, name); + + const buffered = await slow.next(); + assert.strictEqual(decoder.decode(buffered.value[0]), 'buffered', name); + await assert.rejects(slow.next(), error, name); + assert.strictEqual(sh.consumerCount, 0, name); + + const late = sh.pull(common.mustNotCall())[Symbol.asyncIterator](); + await assert.rejects(late.next(), error, name); + await assert.rejects(sh.pull()[Symbol.asyncIterator]().next(), error, name); +} + +function testShareSync(name, cancel) { + const error = new Error('source failed'); + function* source() { + yield 'a'; + throw error; + } + const sh = shareSync(source()); + const first = sh.pull()[Symbol.iterator](); + const second = sh.pull()[Symbol.iterator](); + first.next(); + assert.throws(() => first.next(), error, name); + cancel(sh); + // The data buffered for the consumer is read before the error. + assert.strictEqual(second.next().done, false, name); + assert.throws(() => second.next(), error, name); + + const late = sh.pull(common.mustNotCall())[Symbol.iterator](); + assert.throws(() => late.next(), error, name); + assert.throws(() => sh.pull()[Symbol.iterator]().next(), error, name); +} + +// A cancel() with a reason replaces the stored error. +async function testReasonReplacesError() { + const { writer, broadcast: bc } = broadcast(); + const consumer = bc.push()[Symbol.asyncIterator](); + writer.writeSync('buffered'); + writer.fail(new Error('failed')); + const reason = new Error('cancelled'); + bc.cancel(reason); + await assert.rejects(consumer.next(), reason); + await assert.rejects(bc.push()[Symbol.asyncIterator]().next(), reason); +} + +(async () => { + for (const [name, cancel] of Object.entries(cancels)) { + await testBroadcast(name, cancel); + await testShare(name, cancel); + testShareSync(name, cancel); + } + await testReasonReplacesError(); +})().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-end-reads-before-drain.js b/test/parallel/test-stream-iter-end-reads-before-drain.js new file mode 100644 index 000000000000..31f48cdc705c --- /dev/null +++ b/test/parallel/test-stream-iter-end-reads-before-drain.js @@ -0,0 +1,31 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// end() settles the pending reads that can report the end before it tells +// the drain waiters that no more data can be written. + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { broadcast, ondrain } = require('stream/iter'); + +async function test(useEndSync) { + const log = []; + const { writer, broadcast: bc } = broadcast({ budget: 1 }); + const fast = bc.push()[Symbol.asyncIterator](); + bc.push(); // A consumer that does not read keeps the budget used. + writer.writeSync('a'); + await fast.next(); + const read = fast.next().then((result) => log.push(`read ${result.done}`)); + const drain = ondrain(writer).then((value) => log.push(`drain ${value}`)); + await setImmediate(); + if (useEndSync) { + assert.strictEqual(writer.endSync(), -1); + } else { + writer.end(); + } + await Promise.all([read, drain]); + assert.deepStrictEqual(log, ['read true', 'drain false']); +} + +Promise.all([test(false), test(true)]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-pipe-cancelled-broadcast.js b/test/parallel/test-stream-iter-pipe-cancelled-broadcast.js new file mode 100644 index 000000000000..6690cf2dafdc --- /dev/null +++ b/test/parallel/test-stream-iter-pipe-cancelled-broadcast.js @@ -0,0 +1,40 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// A pipe into a broadcast writer closed by Broadcast.cancel() reports the +// reason the writer stopped (the cancel reason, or the TypeError that +// writer.signal aborted with), the same for pipeTo() and pipeToSync(), with +// and without data. + +const common = require('../common'); +const assert = require('assert'); +const { broadcast, pipeTo, pipeToSync } = require('stream/iter'); + +async function test() { + for (const reason of [new Error('cancelled'), undefined]) { + for (const source of [['y'], []]) { + const a = broadcast(); + a.broadcast.cancel(reason); + const expected = a.writer.signal.reason; + if (reason !== undefined) assert.strictEqual(expected, reason); + await assert.rejects(pipeTo(source, a.writer), (e) => e === expected); + + const b = broadcast(); + b.broadcast.cancel(reason); + const expectedSync = b.writer.signal.reason; + assert.throws(() => pipeToSync(source, b.writer), + (e) => e === expectedSync); + } + } + + // write() and writev() reject with it too. + const { writer, broadcast: bc } = broadcast(); + const reason = new Error('cancelled'); + bc.cancel(reason); + await assert.rejects(writer.write('a'), reason); + await assert.rejects(writer.writev(['a', 'b']), reason); + assert.strictEqual(writer.writeSync('a'), false); + assert.strictEqual(writer.writevSync(['a']), false); +} + +test().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-sharesync-buffered-before-error.js b/test/parallel/test-stream-iter-sharesync-buffered-before-error.js new file mode 100644 index 000000000000..1dab99d889ec --- /dev/null +++ b/test/parallel/test-stream-iter-sharesync-buffered-before-error.js @@ -0,0 +1,48 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// A SyncShare consumer reads the data buffered for it before it throws the +// source's error, as the consumers of an async share do. + +require('../common'); +const assert = require('assert'); +const { shareSync } = require('stream/iter'); + +const decoder = new TextDecoder(); +const error = new Error('source failed'); +function* source() { + yield 'a'; + yield 'b'; + throw error; +} + +function read(it) { + const log = []; + for (;;) { + let result; + try { + result = it.next(); + } catch (e) { + assert.strictEqual(e, error); + log.push('error'); + return log; + } + if (result.done) return log; + log.push(decoder.decode(result.value[0])); + } +} + +const sh = shareSync(source()); +const first = sh.pull()[Symbol.iterator](); +const second = sh.pull()[Symbol.iterator](); +assert.deepStrictEqual(read(first), ['a', 'b', 'error']); +assert.deepStrictEqual(read(second), ['a', 'b', 'error']); +assert.strictEqual(sh.consumerCount, 0); +assert.throws(() => second.next(), error); + +// With transforms too. +const sh2 = shareSync(source()); +const plain = sh2.pull()[Symbol.iterator](); +const transformed = sh2.pull((chunks) => chunks)[Symbol.iterator](); +assert.deepStrictEqual(read(plain), ['a', 'b', 'error']); +assert.deepStrictEqual(read(transformed), ['a', 'b', 'error']); From 976b38c1a7dc80b5f13e7eabf4204fe262060cc4 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 18:59:07 +0000 Subject: [PATCH 21/26] stream: settle pending next() on stream/iter merge() return() Calling return() on a merge() iterator while a next() is pending now resolves the pending call as done right away, and does not wait for the sources' return(). Previously it could hang until a source suspended at an await settled. Concurrent next() calls on a merge() iterator are settled in order, and after an abort the pending and later calls reject with the reason. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 9 + lib/internal/streams/iter/consumers.js | 190 ++++++++++++------ .../test-stream-iter-concurrent-next.js | 101 ++++++++++ .../test-stream-iter-consumers-merge.js | 6 +- .../parallel/test-stream-iter-merge-return.js | 168 ++++++++++++++++ 5 files changed, 413 insertions(+), 61 deletions(-) create mode 100644 test/parallel/test-stream-iter-concurrent-next.js create mode 100644 test/parallel/test-stream-iter-merge-return.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index f3443d8cbeb4..a7da1db97553 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -1562,6 +1562,15 @@ calls `return()` on the other sources but does not wait for it to settle: an async generator source that is suspended in an `await` only runs its cleanup once that `await` completes. +If the iterator's `return()` or `throw()` is called while a `next()` call is +pending, the pending call fulfills with `{ done: true, value: undefined }` at +once, and `merge()` calls `return()` on the sources without waiting for it +to settle. + +Calls to `next()` are settled in order. If `signal` aborts while `next()` +calls are pending, they all reject with `signal.reason`, as do later calls, +unless the merge had already finished. + ```mjs import { from, merge, text } from 'node:stream/iter'; diff --git a/lib/internal/streams/iter/consumers.js b/lib/internal/streams/iter/consumers.js index a06752acbc0a..ade16b684b40 100644 --- a/lib/internal/streams/iter/consumers.js +++ b/lib/internal/streams/iter/consumers.js @@ -60,11 +60,16 @@ const { const { IterResult, + PendingRequest, kNullOnceOption, + kResolvedPromise, concatBytes, getProtocolMethod, + newPendingPromise, raceSignal, recordChunk, + takeReject, + takeResolve, validateRecordedChunks, yieldAbortable, } = require('internal/streams/iter/utils'); @@ -503,78 +508,136 @@ MergeEntry.prototype = ObjectFreeze({ __proto__: null }); * @returns {AsyncIterable} */ /** - * The iterator of merge() of a single source without a signal: what an - * async generator doing `for await (const batch of source) yield batch;` - * gives, without its layer for every batch. Calls to next() are passed to - * the source's iterator, from from(), which queues them as an async - * generator does. return() and throw() wait for the last next() before - * closing the source, as the generator would queue them, and later calls - * wait for them in turn. The source is opened by the first next(). + * The iterator of merge(). Calls to next() are passed to the iterator of the + * merged sources, created by `open()` on the first next(), which settles them + * in order: the iterator of the source from from() for a single source, or + * an async generator. return() and throw() are passed to it once no next() is + * pending, and later calls wait for them. + * + * While a next() is pending, return() or throw() stops the merge at once, as + * pull() does: the pending calls resolve with `{ done: true, value: undefined + * }`, `interrupt()` lets the merge close the sources, and the iterator is + * closed without waiting for it. The later results of the pending calls, and + * any error from closing the iterator, are ignored. */ -class MergeSourceIterator { - #source; +class MergeIterator { + #open; + #interrupt; + #signal; #iterator = null; - // The last next() of the source's iterator, and the promise of return() - // or throw() once one is called. - #last = null; + // The settling functions of the pending next() calls, in order. + #pending = new RingBuffer(); + // The promise of return() or throw() once one is called. #closing = null; - - constructor(source) { - this.#source = source; + // Whether a next() call has rejected because `signal` aborted: every + // pending and later next() call then rejects with its reason. + #aborted = false; + + constructor(open, interrupt, signal) { + this.#open = open; + this.#interrupt = interrupt; + this.#signal = signal; } next() { if (this.#closing !== null) { return PromisePrototypeThen(this.#closing, doneResult, doneResult); } + if (this.#aborted) return PromiseReject(this.#signal.reason); + let next; try { - this.#iterator ??= this.#source[SymbolAsyncIterator](); - const next = PromiseResolve(this.#iterator.next()); - this.#last = next; - return next; + this.#iterator ??= this.#open(); + next = PromiseResolve(this.#iterator.next()); } catch (error) { this.#closing = PromiseReject(error); markPromiseAsHandled(this.#closing); return this.#closing; } + const promise = newPendingPromise(); + this.#pending.push(new PendingRequest(takeResolve(), takeReject())); + PromisePrototypeThen(next, this.#onResult, this.#onError); + return promise; } + // Once stopped, #pending is empty, and the results are ignored. + #onResult = (result) => { + if (this.#pending.length > 0) this.#pending.shift().resolve(result); + }; + + #onError = (error) => { + if (this.#pending.length === 0) return; + this.#pending.shift().reject(error); + const signal = this.#signal; + if (signal !== undefined && signal.aborted && error === signal.reason) { + // The merge stopped for the abort: the calls queued after this one + // reject with the reason too, rather than report the end. + this.#aborted = true; + while (this.#pending.length > 0) this.#pending.shift().reject(error); + } + }; + return(value) { - return this.#close(() => new IterResult(true, value), false); + if (this.#closing !== null) { + const settle = () => new IterResult(true, value); + return PromisePrototypeThen(this.#closing, settle, settle); + } + if (this.#iterator === null || this.#pending.length > 0) { + this.#stop(); + return PromiseResolve(new IterResult(true, value)); + } + return this.#close(this.#iterator.return, value); } throw(error) { - return this.#close(() => { throw error; }, true); - } - - // Close the source once the last next() has settled, if it was opened, - // then settle with `settle()`. Errors closing it are ignored if `quiet`, - // as for await ignores them when its body throws. - #close(settle, quiet) { if (this.#closing !== null) { + const settle = () => { throw error; }; return PromisePrototypeThen(this.#closing, settle, settle); } - const iterator = this.#iterator; - if (iterator === null) { - this.#closing = PromiseResolve(); - return PromisePrototypeThen(this.#closing, settle); + if (this.#iterator === null || this.#pending.length > 0) { + this.#stop(); + return PromiseReject(error); + } + return this.#close(this.#iterator.throw, error); + } + + // Pass return() or throw() on: later calls wait for it. + #close(method, value) { + let closing; + try { + closing = PromiseResolve( + FunctionPrototypeCall(method, this.#iterator, value)); + } catch (error) { + closing = PromiseReject(error); } - const close = () => { - const closed = PromiseResolve(iterator.return?.()); - return quiet ? PromisePrototypeThen(closed, undefined, () => {}) : closed; - }; - const closing = PromisePrototypeThen(this.#last ?? PromiseResolve(), - close, close); this.#closing = closing; markPromiseAsHandled(closing); - return PromisePrototypeThen(closing, settle); + return closing; + } + + // Stop before the iterator is opened, or while a next() is pending. + #stop() { + this.#closing = kResolvedPromise; + const iterator = this.#iterator; + if (iterator === null) return; + while (this.#pending.length > 0) { + this.#pending.shift().resolve(new IterResult(true, undefined)); + } + this.#interrupt?.(); + let closed; + try { + closed = iterator.return?.(); + } catch { + // Ignored, see above. + return; + } + markPromiseAsHandled(PromiseResolve(closed)); } [SymbolAsyncIterator]() { return this; } } -ObjectSetPrototypeOf(MergeSourceIterator.prototype, null); +ObjectSetPrototypeOf(MergeIterator.prototype, null); function doneResult() { return new IterResult(true, undefined); @@ -599,33 +662,24 @@ function merge(...args) { // Normalize each source via from() const normalized = ArrayPrototypeMap(sources, (source) => from(source)); - if (normalized.length === 1) { - // A single source is read without an async generator layer for every - // batch (see MergeSourceIterator). With a signal, the source is read through - // yieldAbortable(), which rejects a pending read when the signal aborts - // (also before the first read), closes the source, and then ends. An - // async iterable is made abortable before from(), so that an abort - // closes it even while from() is reading it. - const { signal } = options; + const { signal } = options; + if (normalized.length === 1 && signal === undefined) { + // A single source without a signal is read without an async generator + // layer for every batch. return { __proto__: null, [SymbolAsyncIterator]() { - if (signal === undefined) { - return new MergeSourceIterator(normalized[0]); - } - const source = isAsyncIterable(sources[0]) ? - from(yieldAbortable(sources[0], signal)) : - yieldAbortable(normalized[0], signal); - return source[SymbolAsyncIterator](); + return new MergeIterator( + () => normalized[0][SymbolAsyncIterator]()); }, }; } - return { + // The async generator reading several sources, given the MergeIterator's + // `control`. + const merged = { __proto__: null, - async *[SymbolAsyncIterator]() { - const { signal } = options; - + async *read(control) { signal?.throwIfAborted(); if (normalized.length === 0) return; @@ -641,6 +695,16 @@ function merge(...args) { let onAbort; let stopped = false; + // Stop the merge while the consumer's next() is pending (see + // MergeIterator): the sources are closed, and the pending next() ends. + control.interrupt = () => { + control.interrupted = true; + if (waitResolve) { + waitResolve(); + waitResolve = null; + } + }; + if (signal) { onAbort = () => { if (waitResolve) { @@ -693,6 +757,7 @@ function merge(...args) { let primaryError = kNoMergeError; try { while (activeCount > 0 || ready.length > 0) { + if (control.interrupted) return; signal?.throwIfAborted(); // Drain ready queue synchronously @@ -739,6 +804,15 @@ function merge(...args) { } }, }; + + return { + __proto__: null, + [SymbolAsyncIterator]() { + const control = { __proto__: null, interrupted: false, interrupt: null }; + return new MergeIterator(() => merged.read(control), + () => control.interrupt?.(), signal); + }, + }; } async function cleanupIterators(iterators, primaryError, pendingPulls) { diff --git a/test/parallel/test-stream-iter-concurrent-next.js b/test/parallel/test-stream-iter-concurrent-next.js new file mode 100644 index 000000000000..84a2edbc7f65 --- /dev/null +++ b/test/parallel/test-stream-iter-concurrent-next.js @@ -0,0 +1,101 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// Concurrent next() calls on merge() and on transform pipelines are settled +// in order, with no batch delivered twice. return() resolves every pending +// call with the end, and an abort rejects every pending call, and the later +// ones, with the reason. + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { broadcast, merge, pull, push, share } = require('stream/iter'); + +const decoder = new TextDecoder(); +const label = (result) => + (result.done ? 'done' : result.value.map((c) => decoder.decode(c)).join('')); +const settle = (promise) => promise.then(label, (error) => `error ${error.message}`); +function never() { + return (async function*() { + yield* []; + await new Promise(() => {}); + })(); +} + +async function testOrder() { + async function* a() { yield 'a1'; await setImmediate(); yield 'a2'; } + + async function* b() { await setImmediate(); yield 'b1'; } + + const merged = merge(a(), b())[Symbol.asyncIterator](); + const results = await Promise.all([1, 2, 3, 4].map(() => merged.next())); + assert.deepStrictEqual(results.map(label).sort(), + ['a1', 'a2', 'b1', 'done']); + assert.strictEqual(label(results[3]), 'done'); + + const stateful = { async *transform(src) { yield* src; } }; + for (const transform of [(c) => c, stateful]) { + const it = pull(a(), transform)[Symbol.asyncIterator](); + const all = await Promise.all([1, 2, 3].map(() => it.next())); + assert.deepStrictEqual(all.map(label), ['a1', 'a2', 'done']); + } + + const { writer, readable } = push((c) => c); + const it = readable[Symbol.asyncIterator](); + const pending = [it.next(), it.next(), it.next()]; + writer.writeSync('x'); + await setImmediate(); + writer.writeSync('y'); + await setImmediate(); + writer.endSync(); + assert.deepStrictEqual((await Promise.all(pending)).map(label), + ['x', 'y', 'done']); +} + +// Each factory returns an iterator given a signal. +const factories = { + 'pull': (signal) => pull(never(), (c) => c, { signal }), + 'merge': (signal) => merge(never(), ['x'], { signal }), + 'push': (signal) => push((c) => c, { signal }).readable, + 'broadcast': (signal) => broadcast().broadcast.push((c) => c, { signal }), + 'share': (signal) => share(never()).pull((c) => c, { signal }), +}; + +async function testReturnAndAbort() { + for (const [name, create] of Object.entries(factories)) { + let it = create(new AbortController().signal)[Symbol.asyncIterator](); + if (name === 'merge') await it.next(); + let pending = [it.next(), it.next(), it.next()]; + await setImmediate(); + assert.deepStrictEqual(await Promise.all([...pending, it.return()].map(settle)), + ['done', 'done', 'done', 'done'], name); + assert.strictEqual(await settle(it.next()), 'done', name); + + const ac = new AbortController(); + it = create(ac.signal)[Symbol.asyncIterator](); + if (name === 'merge') await it.next(); + pending = [it.next(), it.next(), it.next()]; + await setImmediate(); + ac.abort(new Error('aborted')); + assert.deepStrictEqual(await Promise.all(pending.map(settle)), + ['error aborted', 'error aborted', 'error aborted'], + name); + assert.strictEqual(await settle(it.next()), 'error aborted', name); + } +} + +// A merge that has finished reports the end even if its signal aborts later. +async function testMergeFinishedThenAborted() { + const ac = new AbortController(); + const it = merge(['x'], { signal: ac.signal })[Symbol.asyncIterator](); + assert.strictEqual(await settle(it.next()), 'x'); + assert.strictEqual(await settle(it.next()), 'done'); + ac.abort(new Error('aborted')); + assert.strictEqual(await settle(it.next()), 'done'); +} + +Promise.all([ + testOrder(), + testReturnAndAbort(), + testMergeFinishedThenAborted(), +]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-consumers-merge.js b/test/parallel/test-stream-iter-consumers-merge.js index 9e69d5f7fcb9..6da1d6ea6df3 100644 --- a/test/parallel/test-stream-iter-consumers-merge.js +++ b/test/parallel/test-stream-iter-consumers-merge.js @@ -464,7 +464,7 @@ async function testMergeMultiSourceBreakWithCleanupError() { // merge() of a single source behaves as an async generator reading it: // an abort rejects the pending read, closes the source and ends the // iteration; an abort before the first read does not open the source; -// return() is queued behind pending reads. +// return() with reads pending ends them at once and closes the source. async function testMergeSingleSourceProtocol() { const log = []; function source(name, values, { hang = false } = {}) { @@ -525,8 +525,8 @@ async function testMergeSingleSourceProtocol() { assert.deepStrictEqual(log, [ 'a 1: AbortError', 'a 2: done', 'b iterator', 'b next 0', 'b 1: 1', 'b next 1', 'b return', - 'b 2: AbortError', 'b 3: done', - 'c iterator', 'c next 0', 'c next 1', 'c 0: 1', 'c 1: 120', 'c return', + 'b 2: AbortError', 'b 3: AbortError', + 'c iterator', 'c next 0', 'c return', 'c 0: done', 'c 1: done', 'c 2: done', 'c 3: done', 'd return: done', ]); diff --git a/test/parallel/test-stream-iter-merge-return.js b/test/parallel/test-stream-iter-merge-return.js new file mode 100644 index 000000000000..d1f39a081cd4 --- /dev/null +++ b/test/parallel/test-stream-iter-merge-return.js @@ -0,0 +1,168 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// return() or throw() on a merge() iterator while a next() is pending +// fulfills the pending next() with { done: true, value: undefined } at once, +// and calls return() on the sources without waiting for it to settle, also +// for a source suspended in an await. + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { from, merge } = require('stream/iter'); + +const done = { done: true, value: undefined }; + +// An async generator that never finishes an await: return() called on it +// while suspended there does not settle. +function hanging(log, name) { + return { + // eslint-disable-next-line require-yield + async *[Symbol.asyncIterator]() { + try { + log.push(`${name} started`); + await new Promise(() => {}); + } finally { + log.push(`${name} finally`); + } + }, + }; +} + +// A source whose return() never settles, and records being called. +function neverReturning(log, name) { + return { + [Symbol.asyncIterator]() { + return { + next() { return new Promise(() => {}); }, + return() { + log.push(`${name} return`); + return new Promise(() => {}); + }, + }; + }, + }; +} + +const variants = { + 'one source': (log) => [neverReturning(log, 'a')], + 'one source with a signal': (log) => [ + neverReturning(log, 'a'), { signal: new AbortController().signal }], + 'two sources': (log) => [neverReturning(log, 'a'), neverReturning(log, 'b')], + 'two sources with a signal': (log) => [ + neverReturning(log, 'a'), neverReturning(log, 'b'), + { signal: new AbortController().signal }], + 'generator sources': (log) => [hanging(log, 'a'), hanging(log, 'b')], + 'one generator source': (log) => [hanging(log, 'a')], +}; + +async function testReturnWithPendingNext() { + for (const name in variants) { + const log = []; + const iterator = merge(...variants[name](log))[Symbol.asyncIterator](); + const pending = iterator.next(); + await setImmediate(); + const returned = iterator.return('value'); + assert.deepStrictEqual({ ...await pending }, done, name); + assert.deepStrictEqual({ ...await returned }, + { done: true, value: 'value' }, name); + assert.deepStrictEqual({ ...await iterator.next() }, done, name); + // The sources' return() was called (sources that are not generators + // record it). + for (const entry of log) { + assert.match(entry, /^[ab] (started|return)$/, name); + } + if (!name.includes('generator')) { + assert.ok(log.includes('a return'), name); + } + } +} + +async function testThrowWithPendingNext() { + for (const name in variants) { + const log = []; + const iterator = merge(...variants[name](log))[Symbol.asyncIterator](); + const pending = iterator.next(); + await setImmediate(); + const error = new Error('thrown'); + const thrown = iterator.throw(error); + assert.deepStrictEqual({ ...await pending }, done, name); + await assert.rejects(thrown, error, name); + assert.deepStrictEqual({ ...await iterator.next() }, done, name); + } +} + +// Several pending next() calls all end. +async function testSeveralPendingNexts() { + const log = []; + const iterator = merge(neverReturning(log, 'a'), from('x'))[ + Symbol.asyncIterator](); + const first = await iterator.next(); + assert.strictEqual(first.done, false); + const pending = [iterator.next(), iterator.next()]; + await setImmediate(); + await iterator.return(); + for (const result of await Promise.all(pending)) { + assert.deepStrictEqual({ ...result }, done); + } + assert.deepStrictEqual(log, ['a return']); +} + +// A source that settles after the merge has stopped is ignored. +async function testLateSourceResultIgnored() { + const { promise, resolve } = Promise.withResolvers(); + let returns = 0; + const source = { + [Symbol.asyncIterator]() { + return { + next: () => promise, + return() { + returns++; + return Promise.resolve({ done: true }); + }, + }; + }, + }; + for (const sources of [[source], [source, neverReturning([], 'b')]]) { + const iterator = merge(...sources)[Symbol.asyncIterator](); + const pending = iterator.next(); + await setImmediate(); + await iterator.return(); + assert.deepStrictEqual({ ...await pending }, done); + } + assert.strictEqual(returns, 2); + resolve({ done: false, value: [new Uint8Array(1)] }); + await setImmediate(); +} + +// Without a pending next(), return() still waits for the sources' return(). +async function testReturnWithoutPendingNext() { + let closed = false; + const source = { + [Symbol.asyncIterator]() { + return { + next: () => Promise.resolve({ done: false, value: [new Uint8Array(1)] }), + async return() { + await setImmediate(); + closed = true; + return { done: true }; + }, + }; + }, + }; + for (const sources of [[source], [source, from('x')]]) { + closed = false; + const iterator = merge(...sources)[Symbol.asyncIterator](); + await iterator.next(); + await iterator.return(); + assert.strictEqual(closed, true); + } +} + +Promise.all([ + testReturnWithPendingNext(), + testThrowWithPendingNext(), + testSeveralPendingNexts(), + testLateSourceResultIgnored(), + testReturnWithoutPendingNext(), +]).then(common.mustCall()); From f32f5745001b21cfa1eda6e27837755f373cfec3 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 18:59:07 +0000 Subject: [PATCH 22/26] stream: reject promises from stream/iter toStreamable A promise returned by a toStreamable method, even one that is also iterable, is now rejected with ERR_INVALID_ARG_TYPE wherever a value is normalized: in from() and fromSync() at the top level, nested values, and transform output. Previously a nested one was awaited. Use toAsyncStreamable for asynchronous conversion. Also correct the fromSync() documentation, which said that toAsyncStreamable is ignored. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 12 +- lib/internal/streams/iter/from.js | 29 +++- .../test-stream-iter-tostreamable-promise.js | 125 ++++++++++++++++++ ...est-stream-iter-transform-normalization.js | 7 +- 4 files changed, 161 insertions(+), 12 deletions(-) create mode 100644 test/parallel/test-stream-iter-tostreamable-promise.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index a7da1db97553..a56542fc63fb 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -765,8 +765,11 @@ added: Synchronous version of [`from()`][]. Returns a sync iterable. Cannot accept async iterables or promises. Objects implementing `Symbol.for('Stream.toStreamable')` are converted via that protocol (takes -precedence over `Symbol.iterator`). The `toAsyncStreamable` protocol is -ignored entirely. +precedence over `Symbol.iterator`). The `toAsyncStreamable` protocol is not +used: an object that implements only `Symbol.for('Stream.toAsyncStreamable')` +is rejected with a `TypeError`, and an object that also implements +`Symbol.for('Stream.toStreamable')` or `Symbol.iterator` is converted through +those. ```mjs import { fromSync, textSync } from 'node:stream/iter'; @@ -2711,7 +2714,10 @@ text(stream).then(console.log); // 'hello world' The value must be a function that synchronously converts the object into a streamable value. When the object is passed to `fromSync()`, this method is called to produce the actual data. It must synchronously return a streamable -value: a string, `Uint8Array`, or `Iterable`. +value: a string, `Uint8Array`, or `Iterable`. It must not return a promise: +[`from()`][] rejects a promise returned by this method with a `TypeError`, +including for a nested value or the output of a transform. Use +`Stream.toAsyncStreamable` to convert an object asynchronously. ```mjs import { fromSync, textSync } from 'node:stream/iter'; diff --git a/lib/internal/streams/iter/from.js b/lib/internal/streams/iter/from.js index 023cc4d526a6..2ce335a2f0d0 100644 --- a/lib/internal/streams/iter/from.js +++ b/lib/internal/streams/iter/from.js @@ -94,6 +94,26 @@ function nextStreamableDepth(depth, value) { // are already available are not held back until the wait completes. const kFlushBatch = Symbol('kFlushBatch'); +/** + * Call a toStreamable method. It converts synchronously, so a promise it + * returns, even one that is also iterable, is rejected: asynchronous + * conversion uses toAsyncStreamable. + * @param {Function} method + * @param {any} value + * @returns {any} + */ +function callToStreamable(method, value) { + const result = FunctionPrototypeCall(method, value); + if (isPromise(result)) { + throw new ERR_INVALID_ARG_TYPE( + 'value', + ['string', 'ArrayBuffer', 'ArrayBufferView', 'Iterable', 'toStreamable'], + result, + ); + } + return result; +} + function createNormalizationContext() { return ObjectSetPrototypeOf({ cancelled: false, @@ -351,7 +371,7 @@ function* normalizeSyncValue(value, depth = 0) { const streamableMethod = getProtocolMethod(value, toStreamable); if (streamableMethod !== undefined) { const nextDepth = nextStreamableDepth(depth, value); - const result = FunctionPrototypeCall(streamableMethod, value); + const result = callToStreamable(streamableMethod, value); yield* normalizeSyncValue(result, nextDepth); return; } @@ -783,7 +803,7 @@ async function* normalizeAsyncValue( const streamableMethod = getProtocolMethod(value, toStreamable); if (streamableMethod !== undefined) { const nextDepth = nextStreamableDepth(depth, value); - const result = FunctionPrototypeCall(streamableMethod, value); + const result = callToStreamable(streamableMethod, value); yield* normalizeAsyncValue( result, allowNestedAsyncStreamables, context, emitFlush, nextDepth); return; @@ -1863,12 +1883,11 @@ function fromSyncWithDepth(input, depth) { } // Check toStreamable protocol (takes precedence over iteration protocols). - // toAsyncStreamable is ignored entirely in fromSync. const streamableMethod = getProtocolMethod(input, toStreamable); if (streamableMethod !== undefined) { const nextDepth = nextStreamableDepth(depth, input); return fromSyncWithDepth( - FunctionPrototypeCall(streamableMethod, input), nextDepth); + callToStreamable(streamableMethod, input), nextDepth); } // Fast path: Uint8Array[] - yield in bounded sub-batches. @@ -2046,7 +2065,7 @@ function fromWithDepth(input, depth) { if (streamableMethod !== undefined) { const nextDepth = nextStreamableDepth(depth, input); return fromWithDepth( - FunctionPrototypeCall(streamableMethod, input), nextDepth); + callToStreamable(streamableMethod, input), nextDepth); } // Fast path: validated source already yields valid Uint8Array[] batches diff --git a/test/parallel/test-stream-iter-tostreamable-promise.js b/test/parallel/test-stream-iter-tostreamable-promise.js new file mode 100644 index 000000000000..b52b6b2dcbbb --- /dev/null +++ b/test/parallel/test-stream-iter-tostreamable-promise.js @@ -0,0 +1,125 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// A promise returned by a Stream.toStreamable method is rejected with a +// TypeError, at the top level of from() and also for a nested value, the +// value of an async source, and the output of a transform. A promise +// returned by Stream.toAsyncStreamable is waited for. + +const common = require('../common'); +const assert = require('assert'); +const { + Broadcast, + Share, + bytes, + from, + fromSync, + merge, + pull, + text, + textSync, + toAsyncStreamable, + toStreamable, +} = require('stream/iter'); + +const typeError = { name: 'TypeError', code: 'ERR_INVALID_ARG_TYPE' }; + +function promising() { + return { [toStreamable]() { return Promise.resolve('hello'); } }; +} + +function asyncPromising() { + return { [toAsyncStreamable]() { return Promise.resolve('hello'); } }; +} + +async function testFrom() { + // At the top level, from() throws. + assert.throws(() => from(promising()), typeError); + await assert.rejects(text(from([promising()])), typeError); + await assert.rejects(text(from(['a', [promising()]])), typeError); + await assert.rejects(text(from((function*() { yield promising(); })())), + typeError); + await assert.rejects( + text(from((async function*() { yield promising(); })())), typeError); + await assert.rejects( + text(from((async function*() { yield ['a', promising()]; })())), + typeError); + // Through a toStreamable or toAsyncStreamable conversion. + await assert.rejects( + text(from([{ [toStreamable]() { return [promising()]; } }])), typeError); + await assert.rejects( + text(from({ [toAsyncStreamable]() { return [promising()]; } })), + typeError); +} + +async function testTransformOutput() { + const transforms = { + 'stateless': () => promising(), + 'async stateless': async () => promising(), + 'stateless nested': () => ['a', promising()], + 'stateful': { + async *transform(source) { + for await (const batch of source) { + if (batch !== null) yield promising(); + } + }, + }, + }; + for (const name in transforms) { + await assert.rejects(text(pull(from('x'), transforms[name])), typeError, + name); + } +} + +async function testOtherConsumers() { + await assert.rejects(bytes(merge(from([promising()]), from('x'))), + typeError); + const { broadcast } = Broadcast.from([promising()]); + await assert.rejects(text(broadcast.push()), typeError); + const share = Share.from([promising()]); + await assert.rejects(text(share.pull()), typeError); +} + +// toAsyncStreamable may return a promise, also when nested. +async function testToAsyncStreamablePromise() { + assert.strictEqual(await text(from(asyncPromising())), 'hello'); + assert.strictEqual( + await text(from((async function*() { yield [asyncPromising(), '!']; })())), + 'hello!'); + assert.strictEqual( + await text(pull(from('x'), (b) => (b === null ? null : [asyncPromising()]))), + 'hello'); +} + +// A toStreamable method returning a value that is not a promise is still +// accepted when nested. +async function testToStreamableValue() { + const value = { [toStreamable]() { return ['hel', 'lo']; } }; + assert.strictEqual(await text(from([value])), 'hello'); + assert.strictEqual( + await text(pull(from('x'), (b) => (b === null ? null : value))), 'hello'); +} + +// A promise is rejected even if it is also iterable, at the top level and +// nested, for from() and fromSync(). +async function testIterablePromise() { + const iterablePromise = () => { + const promise = Promise.resolve('z'); + promise[Symbol.iterator] = function*() { yield 'it'; }; + return promise; + }; + const value = () => ({ [toStreamable]: iterablePromise }); + assert.throws(() => from(value()), typeError); + await assert.rejects(text(from([value()])), typeError); + assert.throws(() => textSync(fromSync(value())), typeError); + assert.throws(() => textSync(fromSync([value()])), typeError); +} + +Promise.all([ + testFrom(), + testIterablePromise(), + testTransformOutput(), + testOtherConsumers(), + testToAsyncStreamablePromise(), + testToStreamableValue(), +]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-transform-normalization.js b/test/parallel/test-stream-iter-transform-normalization.js index 0d0b3615d537..dd6e94455f10 100644 --- a/test/parallel/test-stream-iter-transform-normalization.js +++ b/test/parallel/test-stream-iter-transform-normalization.js @@ -158,8 +158,6 @@ const asyncValues = { ['x', (async function*() { yield 'y'; yield Promise.resolve('z'); })()], 'async generator': () => (async function*() { yield 'x'; yield ['y', Promise.resolve('z')]; })(), - 'toStreamable returning a promise': () => - ({ [toStreamable]() { return Promise.resolve('xyz'); } }), 'promise': () => Promise.resolve(['x', 'y', 'z']), '100 async conversions': () => [chain(100, toAsyncStreamable), 'yz'], }; @@ -170,8 +168,6 @@ const asyncOnlyValues = { 'nested promise': asyncValues['nested promise'], 'nested async generator': asyncValues['nested async generator'], 'promise in a generator': asyncValues['promise in a generator'], - 'toStreamable returning a promise': - asyncValues['toStreamable returning a promise'], 'promise': () => Promise.resolve('xyz'), 'async generator': asyncValues['async generator'], }; @@ -185,6 +181,9 @@ const invalidValues = { 'toStreamable returning null': () => ({ [toStreamable]() { return null; } }), 'toStreamable returning undefined': () => ({ [toStreamable]() {} }), 'non-callable toStreamable': () => ({ [toStreamable]: 'xyz' }), + // toStreamable converts synchronously, also in async pipelines. + 'toStreamable returning a promise': () => + ({ [toStreamable]() { return Promise.resolve('xyz'); } }), }; async function testAsyncValues() { From 0f283feadeab3fe3c95327bff580e45c968247c6 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 19:33:47 +0000 Subject: [PATCH 23/26] stream: settle pending next() on stream/iter return() Calling return() on a pull() pipeline's iterator or a from() iterator while next() is pending now resolves the pending calls with done at once, instead of rejecting them with an AbortError, and closes the upstream iterators without waiting for them. Results that arrive later are discarded. A return() with no next() pending still waits for the upstream return(). push() readables and broadcast and share consumers with transforms use the same steps, so return() never sends the flush signal to their transforms, and neither does cancel() with no reason. A share consumer's return() resolves a pending next() at once and detaches it, and an upstream pull still in flight is buffered for later consumers. This also fixes a share consumer without transforms whose next() could hang after return(). throw() on push, broadcast and share consumers closes the consumer and rejects with its argument. Broadcast and Share cancel(reason) tear down a consumer's transforms as an abort does. Pipelines close their stateful transforms outermost first, and shareSync().pull() validates its transforms before registering a consumer. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 73 +++- lib/internal/streams/iter/broadcast.js | 21 +- lib/internal/streams/iter/from.js | 237 ++++++++++-- lib/internal/streams/iter/pull.js | 248 +++++++++++-- lib/internal/streams/iter/push.js | 6 +- lib/internal/streams/iter/share.js | 308 +++++++++++----- lib/internal/streams/iter/utils.js | 14 +- .../test-stream-iter-abort-pending-read.js | 5 +- .../test-stream-iter-cancel-no-flush.js | 172 +++++++++ ...st-stream-iter-cancel-reason-transforms.js | 77 ++++ .../test-stream-iter-consumer-throw.js | 74 ++++ test/parallel/test-stream-iter-from-async.js | 27 +- test/parallel/test-stream-iter-pull-async.js | 4 +- .../test-stream-iter-pull-close-order.js | 84 +++++ ...stream-iter-pull-transform-error-closes.js | 76 ++++ .../test-stream-iter-pullsync-early-return.js | 24 ++ ...ream-iter-push-signal-pending-transform.js | 32 ++ .../test-stream-iter-return-after-finish.js | 42 +++ .../test-stream-iter-return-no-flush.js | 148 ++++++++ .../test-stream-iter-return-pending.js | 345 ++++++++++++++++++ .../test-stream-iter-share-coverage.js | 5 +- .../test-stream-iter-share-return-pending.js | 162 ++++++++ ...t-stream-iter-sharesync-pull-validation.js | 20 + 23 files changed, 2032 insertions(+), 172 deletions(-) create mode 100644 test/parallel/test-stream-iter-cancel-no-flush.js create mode 100644 test/parallel/test-stream-iter-cancel-reason-transforms.js create mode 100644 test/parallel/test-stream-iter-consumer-throw.js create mode 100644 test/parallel/test-stream-iter-pull-close-order.js create mode 100644 test/parallel/test-stream-iter-pull-transform-error-closes.js create mode 100644 test/parallel/test-stream-iter-pullsync-early-return.js create mode 100644 test/parallel/test-stream-iter-push-signal-pending-transform.js create mode 100644 test/parallel/test-stream-iter-return-after-finish.js create mode 100644 test/parallel/test-stream-iter-return-no-flush.js create mode 100644 test/parallel/test-stream-iter-return-pending.js create mode 100644 test/parallel/test-stream-iter-share-return-pending.js create mode 100644 test/parallel/test-stream-iter-sharesync-pull-validation.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index a56542fc63fb..b8096922f6f1 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -191,6 +191,9 @@ transform of the pipeline. Transforms passed to [`pullSync()`][] receive no The flush signal (`null`) is sent after the source ends, giving transforms a chance to emit trailing data (e.g., compression footers). +It is not sent to the transforms of a consumer of a [`broadcast()`][] or +[`share()`][] that is cancelled without a reason: the consumer ends as if its +iterator's `return()` had been called. ```js // Stateless: uppercase transform @@ -730,6 +733,15 @@ The readable of a [`push()`][] stream without transforms, the iterables returned by [`fromReadable()`][], and the results of `from()` itself already yield normalized batches, so `from()` returns them unchanged. +Calls to the iterator's `next()` and `throw()` are handled in order: a call +made while an earlier one is pending (for example, while a promise in `input` +is awaited) waits for it. `return()` does not wait: every `next()` call still +pending fulfills with `{ done: true, value: undefined }` at once, `return()` +fulfills at once, and the iterator of `input` (and of any nested iterable being +read) is closed by calling its `return()` without waiting for it to settle. +Results that arrive later are discarded, and later `next()` calls fulfill with +`{ done: true, value: undefined }`. + ```mjs import { Buffer } from 'node:buffer'; import { from, text } from 'node:stream/iter'; @@ -936,6 +948,17 @@ When `signal` aborts, the pending read (or the next one) rejects with `pull()` still returns an iterable; reading from it rejects with `signal.reason` without reading from `source`. +If the iterator's `return()` is called while a read is pending, the +transforms' `signal` is aborted, the pending read (and any read queued after +it) fulfills with `{ done: true, value: undefined }` at once, as does +`return()`, and the iterators of the stateful transforms and then the +source's are closed, outermost first, by calling their `return()` without +waiting for it to settle. The same order is used when `signal` aborts while a +read is pending. A result that +arrives later is discarded, and later reads fulfill with +`{ done: true, value: undefined }`. No transform receives the flush signal +(`null`) once `return()` has been called, even if the source ends afterwards. + ```mjs import { from, pull, text } from 'node:stream/iter'; @@ -1079,6 +1102,17 @@ Zero-length chunks are accepted without being buffered: they are not delivered to the consumer, and `writeSync()` and `write()` report success for them even when backpressure is active. +Calling `throw(error)` on the readable's iterator stops the consumer: a pending +read rejects with `error`, the writer's pending and later writes reject with +`error`, `throw()` rejects with `error`, and later reads fulfill with +`{ done: true, value: undefined }`. + +When `readable` has transforms, its iterator's `return()` stops them as +[`pull()`][]'s `return()` does: their `signal` is aborted, a pending read +fulfills with `{ done: true, value: undefined }` at once, later reads report +the end, and no transform receives the flush signal (`null`). The writer is +then cancelled, as when a consumer without transforms stops reading. + ## Duplex channels ### `duplex([options])` @@ -1744,8 +1778,13 @@ run().catch(console.error); * `reason` {any} Cancel the broadcast. If `reason` is provided and is not `undefined`, all -consumers reject with that exact reason. If it is omitted or `undefined`, -consumers complete normally. +consumers reject with that exact reason. A consumer with transforms is then +stopped as when its `signal` aborts: the transforms' `signal` aborts with +`reason`, the stateful transforms' iterators are closed, and its pending and +later reads reject with `reason`. If it is omitted or `undefined`, +consumers complete normally, as if their iterator's `return()` had been +called: a pending read fulfills with `{ done: true, value: undefined }`, and +no transform receives the flush signal (`null`). Cancelling also closes the paired writer: afterwards its `canWrite` is `null`. This lets a [`Broadcast.from()`][] pump stop pulling from its source. Writes @@ -1789,6 +1828,17 @@ The number of active consumers. Create a new consumer. Optional transforms are applied to this consumer's view of the data. +Calling `return()` on the consumer's iterator detaches it at once, so it no +longer counts in `consumerCount` or for backpressure, even while a read is +pending: that read, and any read queued after it, fulfills with +`{ done: true, value: undefined }` at once. With transforms, the pipeline is +stopped as by [`pull()`][]'s `return()`: no transform receives the flush +signal (`null`). + +Calling `throw(error)` on the consumer's iterator stops the consumer as +`return()` does, and then rejects with `error`. Later reads fulfill with +`{ done: true, value: undefined }`. + #### `broadcast[Symbol.dispose]()` Alias for `broadcast.cancel()`. @@ -1951,8 +2001,9 @@ Create a {Share} from an existing source. * `reason` {any} Cancel the share. If `reason` is provided and is not `undefined`, all consumers -reject with that exact reason. If it is omitted or `undefined`, consumers -complete normally. +reject with that exact reason; a consumer with transforms is stopped as for +[`broadcast.cancel()`][]. If it is omitted or `undefined`, consumers complete +normally. Consumers created with `share.pull()` after cancelling are not registered: their first read rejects with `reason` if one was provided, or with the error @@ -1978,6 +2029,20 @@ The number of active consumers. Create a new consumer of the shared source. +Calling `return()` on the consumer's iterator detaches it at once, so it no +longer counts in `consumerCount` or for backpressure, even while a read is +pending: that read, and any read queued after it, fulfills with +`{ done: true, value: undefined }` at once. With transforms, the pipeline is +stopped as by [`pull()`][]'s `return()`: no transform receives the flush +signal (`null`). If the read was waiting for the source, that read of the +source still completes: its result is buffered as any other, for the other +consumers and for consumers that attach later (unless the share has been +cancelled by then), and an error it reports is stored. + +Calling `throw(error)` on the consumer's iterator stops the consumer as +`return()` does, and then rejects with `error`. Later reads fulfill with +`{ done: true, value: undefined }`. + #### `share[Symbol.dispose]()` Alias for `share.cancel()`. diff --git a/lib/internal/streams/iter/broadcast.js b/lib/internal/streams/iter/broadcast.js index fef168dfeebe..0a1f62b10933 100644 --- a/lib/internal/streams/iter/broadcast.js +++ b/lib/internal/streams/iter/broadcast.js @@ -53,6 +53,7 @@ const { } = require('internal/streams/iter/from'); const { + kSetConsumerStop, pullWithConsumerCleanup, } = require('internal/streams/iter/pull'); @@ -228,8 +229,8 @@ class BroadcastImpl { return() { return kDone; }, - throw() { - return kDone; + throw(error) { + return PromiseReject(error); }, }, null); }, @@ -248,6 +249,9 @@ class BroadcastImpl { pending: new RingBuffer(1), detached: false, error: kNoBroadcastError, + // Set by a pipeline of transforms reading the consumer (see + // kSetConsumerStop). + stop: null, }, null); this.#consumers.add(state); @@ -279,6 +283,9 @@ class BroadcastImpl { return { __proto__: null, + [kSetConsumerStop](stop) { + state.stop = stop; + }, [SymbolAsyncIterator]() { return ObjectSetPrototypeOf({ next() { @@ -338,9 +345,10 @@ class BroadcastImpl { return kDone; }, - throw() { + // Stops the consumer as return() does, then rejects with `error`. + throw(error) { detach(); - return kDone; + return PromiseReject(error); }, }, null); }, @@ -386,6 +394,11 @@ class BroadcastImpl { } else { this.#resolvePendingDone(consumer); } + // Its transforms are not flushed, and with a reason they are torn + // down as by a signal abort: see kSetConsumerStop. + const stop = consumer.stop; + consumer.stop = null; + stop?.(reason); consumer.detached = true; } this.#consumers.clear(); diff --git a/lib/internal/streams/iter/from.js b/lib/internal/streams/iter/from.js index 2ce335a2f0d0..48bd94409b1c 100644 --- a/lib/internal/streams/iter/from.js +++ b/lib/internal/streams/iter/from.js @@ -46,8 +46,11 @@ const { toAsyncStreamable, } = require('internal/streams/iter/types'); +const { RingBuffer } = require('internal/streams/iter/ringbuffer'); + const { IterResult, + PendingRequest, kActive, kDone, kResolvedPromise, @@ -208,6 +211,9 @@ const kReadFailed = Symbol('kReadFailed'); // createAsyncSourceNormalizer(): see kRead in yieldNormalizationAbortable(). const kSetReadHandlers = Symbol('kSetReadHandlers'); const kRead = Symbol('kRead'); +// What createAsyncSourceNormalizer()'s steps of reading a batch give while a +// kRead is pending, which settles the promise of next() in turn. +const kPendingRead = Symbol('kPendingRead'); // The result kReadUncancellable gives once the source is done. const kDoneSourceResult = ObjectFreeze({ __proto__: null, value: undefined, done: true }); @@ -260,14 +266,69 @@ function createNormalizationIterator(createIterator) { [kValidatedSource]: true, }, null); } + return createInterruptibleIterator(iterator, context); +} + +/** + * The iterator of from() for an iterator that queues its calls as an async + * generator does (normalizeAsyncStreamableResult()). Calls are passed to it, + * except return() while a next() is pending: as for the source normalizers + * (see interrupt() in createAsyncSourceNormalizer()), the pending calls then + * report the end at once, and the iterator is closed without waiting for it, + * errors closing it ignored. The normalization is cancelled, which releases + * the read the iterator is waiting for, and the later results of the + * pending calls are ignored. + * @param {object} iterator + * @param {object} context + * @returns {object} + */ +function createInterruptibleIterator(iterator, context) { + // The settling functions of the pending next() calls, in order. + const pending = new RingBuffer(); + let interrupted = false; + + function onResult(result) { + if (pending.length > 0) pending.shift().resolve(result); + } + + function onError(error) { + if (pending.length > 0) pending.shift().reject(error); + } + return ObjectSetPrototypeOf({ next(value) { - return FunctionPrototypeCall(iterator.next, iterator, value); + if (interrupted) return PromiseResolve(new IterResult(true, undefined)); + let next; + try { + next = PromiseResolve( + FunctionPrototypeCall(iterator.next, iterator, value)); + } catch (error) { + return PromiseReject(error); + } + const promise = newPendingPromise(); + pending.push(new PendingRequest(takeResolve(), takeReject())); + PromisePrototypeThen(next, onResult, onError); + return promise; }, return(value) { cancelNormalization( context, lazyDOMException('Aborted', 'AbortError')); - return FunctionPrototypeCall(iterator.return, iterator, value); + if (interrupted || pending.length === 0) { + return FunctionPrototypeCall(iterator.return, iterator, value); + } + interrupted = true; + while (pending.length > 0) { + pending.shift().resolve(new IterResult(true, undefined)); + } + let closed; + try { + closed = FunctionPrototypeCall(iterator.return, iterator); + } catch { + // Ignored, see above. + return PromiseResolve(new IterResult(true, value)); + } + markPromiseAsHandled(PromiseResolve(closed)); + return PromiseResolve(new IterResult(true, value)); }, throw(error) { cancelNormalization(context, error, true); @@ -961,6 +1022,8 @@ async function* normalizeAsyncSourceValue(value, context, * and an error normalizing a value closes the source first; * - return() closes the value being normalized and the source, propagating * errors from closing them, and throw() closes them ignoring such errors. + * Unlike an async generator, return() while a next() is pending does not + * wait for it: see interrupt(). * @param {AsyncIterable} source * @param {object} context * @returns {object} An object with next(), return() and throw(). @@ -984,12 +1047,15 @@ function createAsyncSourceNormalizer(source, context) { let uncancellable = false; let releasableReads = false; let readReleased = false; - // Whether the source is read with kRead, and the settling functions of - // the read's promise while it is pending. + // Whether the source is read with kRead. A next() then has a promise of + // its own (see doNext()), and these are its settling functions while it + // is pending. let readable = false; let resolveRead = null; let rejectRead = null; - const { run, settled } = createOperationQueue(); + // Whether return() has interrupted a pending next(): see interrupt(). + let interrupted = false; + const { run, settled, flush } = createOperationQueue(); function finish(result) { settled(); @@ -1008,6 +1074,7 @@ function createAsyncSourceNormalizer(source, context) { } function onBodyError(error) { + if (interrupted) return kPendingRead; // Like for await when its body throws: close the source, keep the error. valueBatches = null; boundedBatches = null; @@ -1052,6 +1119,7 @@ function createAsyncSourceNormalizer(source, context) { } function onValueResult(result) { + if (interrupted) return kPendingRead; if (result.done) { valueBatches = null; return pullSource(); @@ -1118,29 +1186,69 @@ function createAsyncSourceNormalizer(source, context) { } // The kRead handlers: the result is handled in the reaction to the - // source's result, and settles the read's promise. + // source's result, and settles the promise of next(). Once return() has + // interrupted next(), they are ignored. function onRead(result) { - const resolve = resolveRead; - const reject = rejectRead; - resolveRead = rejectRead = null; + if (resolveRead === null) return; let settledWith; try { settledWith = onSourceResult(result); } catch (error) { - reject(error); + rejectNext(error); return; } - resolve(settledWith); + continueNext(settledWith); } function onReadError(error) { - const reject = rejectRead; - resolveRead = rejectRead = null; + if (rejectRead === null) return; state = kDone; settled(); + rejectNext(error); + } + + // Settle the promise of next() with what the steps of reading a batch give: + // a result; kPendingRead while a kRead is pending, which settles it in + // turn; or a promise for either. + function continueNext(settledWith) { + if (resolveRead === null) return; + // Results are IterResults; testing for one is cheaper than isPromise(). + if (settledWith instanceof IterResult) { + const resolve = resolveRead; + resolveRead = rejectRead = null; + resolve(settledWith); + } else if (settledWith !== kPendingRead) { + PromisePrototypeThen(settledWith, continueNext, rejectNext); + } + } + + function rejectNext(error) { + const reject = rejectRead; + if (reject === null) return; + resolveRead = rejectRead = null; reject(error); } + // return() while a next() with a promise of its own is pending: as for a + // pull() pipeline, the pending call and those queued after it report the + // end at once, and the value being normalized and the source are closed + // without waiting, errors closing them ignored. The normalization has been + // cancelled, which releases a pending read of the source (see kRead), and + // the later results of the steps of next() are ignored. + function interrupt() { + interrupted = true; + state = kDone; + const resolve = resolveRead; + resolveRead = rejectRead = null; + boundedBatches = null; + const pending = valueBatches; + valueBatches = null; + if (pending !== null) markPromiseAsHandled(pending.return()); + markPromiseAsHandled(iterator.return()); + resolve(new IterResult(true, undefined)); + flush(); + } + function pullSource() { if (uncancellable) { if (releasableReads) return readReleasable(); @@ -1148,13 +1256,10 @@ function createAsyncSourceNormalizer(source, context) { onUncancellableResult, onUncancellableError); } if (readable) { - // One promise for the read, which a cancellation rejects, instead of - // next()'s promise and a reaction to it. - const promise = newPendingPromise(); - resolveRead = takeResolve(); - rejectRead = takeReject(); + // The read settles the promise of next(), which a cancellation + // rejects, instead of a promise of its own and a reaction to it. iterator[kRead](); - return promise; + return kPendingRead; } return PromisePrototypeThen(iterator.next(), onSourceResult, fail); } @@ -1190,6 +1295,23 @@ function createAsyncSourceNormalizer(source, context) { } state = kActive; } + if (readable && !uncancellable) { + // A promise of its own for next(), which the steps of reading a batch + // settle, so that return() can settle it at once. + const promise = newPendingPromise(); + resolveRead = takeResolve(); + rejectRead = takeReject(); + let settledWith; + try { + settledWith = boundedBatches !== null || valueBatches !== null ? + pullValue() : pullSource(); + } catch (error) { + rejectNext(error); + return promise; + } + continueNext(settledWith); + return promise; + } if (boundedBatches !== null || valueBatches !== null) { return PromiseResolve(pullValue()); } @@ -1239,7 +1361,13 @@ function createAsyncSourceNormalizer(source, context) { return ObjectSetPrototypeOf({ next() { return run(doNext); }, - return(value) { return run(doReturn, value); }, + return(value) { + if (resolveRead !== null) { + interrupt(); + return PromiseResolve(new IterResult(true, value)); + } + return run(doReturn, value); + }, throw(error) { return run(doThrow, error); }, [kNextUncancellable](releasable = false) { uncancellable = true; @@ -1510,7 +1638,8 @@ class SyncSourceReader { * 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 the source is closed as for an error in - * the body of a for...of loop. + * the body of a for...of loop. As for the async source normalizer, return() + * while a next() is pending does not wait for it: see interrupt(). * @param {Iterable} source * @param {object} context * @returns {object} An object with next(), return() and throw(). @@ -1520,7 +1649,13 @@ function createSyncSourceNormalizer(source, context) { let done = false; // A normalizeAsyncSourceValue() generator for the value being normalized. let valueBatches = null; - const { run, settled, idle } = createOperationQueue(); + // The settling functions of the promise of a next() that is pending, as + // a value is normalized asynchronously. + let resolveNext = null; + let rejectNext = null; + // Whether return() has interrupted a pending next(): see interrupt(). + let interrupted = false; + const { run, settled, idle, flush } = createOperationQueue(); // Results are often produced synchronously. Once one is, the next call // runs at once, as for the async source normalizer; calls queued while @@ -1549,6 +1684,7 @@ function createSyncSourceNormalizer(source, context) { } function onValueResult(result) { + if (interrupted) return; if (result.done) { valueBatches = null; return produce(); @@ -1557,6 +1693,7 @@ function createSyncSourceNormalizer(source, context) { } function onValueError(error) { + if (interrupted) return; valueBatches = null; throwIntoReader(error); return fail(error); @@ -1588,11 +1725,57 @@ function createSyncSourceNormalizer(source, context) { function doNext() { if (done) return PromiseResolve(finish(new IterResult(true, undefined))); + let produced; try { - return PromiseResolve(produce()); + produced = produce(); } catch (error) { return PromiseReject(error); } + // produce() gives a promise when, and only when, a value is being + // normalized asynchronously: a promise of its own then, so that return() + // can settle it at once. + if (valueBatches === null) return PromiseResolve(produced); + const promise = newPendingPromise(); + resolveNext = takeResolve(); + rejectNext = takeReject(); + PromisePrototypeThen(produced, onNextResult, onNextError); + return promise; + } + + function onNextResult(result) { + const resolve = resolveNext; + if (resolve === null) return; // Interrupted. + resolveNext = rejectNext = null; + resolve(result); + } + + function onNextError(error) { + const reject = rejectNext; + if (reject === null) return; // Interrupted. + resolveNext = rejectNext = null; + reject(error); + } + + // return() while a next() is pending: as for a pull() pipeline, the + // pending call and those queued after it report the end at once, and the + // value being normalized and the source are closed without waiting, + // errors closing them ignored. The normalization has been cancelled, and + // the later results of normalizing the value are ignored. + function interrupt() { + interrupted = true; + done = true; + const resolve = resolveNext; + resolveNext = rejectNext = null; + const pending = valueBatches; + valueBatches = null; + if (pending !== null) markPromiseAsHandled(pending.return()); + try { + reader.return(); + } catch { + // Ignored, see above. + } + resolve(new IterResult(true, undefined)); + flush(); } function doReturn(value) { @@ -1673,7 +1856,13 @@ function createSyncSourceNormalizer(source, context) { return ObjectSetPrototypeOf({ next() { return run(doNext); }, - return(value) { return run(doReturn, value); }, + return(value) { + if (resolveNext !== null) { + interrupt(); + return PromiseResolve(new IterResult(true, value)); + } + return run(doReturn, value); + }, throw(error) { return run(doThrow, error); }, [kNextSyncBatch]: nextSyncBatch, }, null); diff --git a/lib/internal/streams/iter/pull.js b/lib/internal/streams/iter/pull.js index eae4f8cdef9d..6060757c253a 100644 --- a/lib/internal/streams/iter/pull.js +++ b/lib/internal/streams/iter/pull.js @@ -237,7 +237,7 @@ async function normalizeTransformValueAsync(result) { * @param {Array} run - Array of stateless transform functions * @yields {Uint8Array[]} */ -function* applyFusedStatelessSyncTransforms(source, run) { +function* applyFusedStatelessSyncTransforms(source, run, stopState) { for (const chunks of source) { let current = chunks; for (let i = 0; i < run.length; i++) { @@ -248,6 +248,8 @@ function* applyFusedStatelessSyncTransforms(source, run) { } if (current !== null) yield current; } + // A stopped pipeline is not flushed (see pullSyncWithConsumerStop()). + if (stopState !== undefined && stopState.stopped) return; // Flush each transform after all upstream data, including data emitted by // earlier flushes, has been processed by that transform. let pending = []; @@ -271,14 +273,15 @@ function* applyFusedStatelessSyncTransforms(source, run) { * Apply a single stateful sync transform to a source. * @yields {Uint8Array[]} */ -function* withFlushSync(source) { +function* withFlushSync(source, stopState) { yield* source; + if (stopState !== undefined && stopState.stopped) return; yield null; } -function* applyStatefulSyncTransform(source, transform, receiver) { +function* applyStatefulSyncTransform(source, transform, receiver, stopState) { const output = FunctionPrototypeCall( - transform, receiver, withFlushSync(source)); + transform, receiver, withFlushSync(source, stopState)); for (const item of output) { const batch = normalizeTransformOutputSync(item); if (batch !== null) yield batch; @@ -287,9 +290,13 @@ function* applyStatefulSyncTransform(source, transform, receiver) { /** * Create a sync pipeline from source through transforms. + * @param {Iterable} source + * @param {Array} transforms + * @param {{ stopped: boolean }} [stopState] - Once `stopped` is set, the end + * of the source does not flush the transforms. * @yields {Uint8Array[]} */ -function* createSyncPipeline(source, transforms) { +function* createSyncPipeline(source, transforms, stopState) { let current = source; // Apply transforms - fuse consecutive stateless transforms into a single @@ -300,17 +307,19 @@ function* createSyncPipeline(source, transforms) { const transform = transforms[i]; if (isTransformObject(transform)) { if (statelessRun.length > 0) { - current = applyFusedStatelessSyncTransforms(current, statelessRun); + current = applyFusedStatelessSyncTransforms(current, statelessRun, + stopState); statelessRun = []; } current = applyStatefulSyncTransform( - current, transform.transform, transform.receiver); + current, transform.transform, transform.receiver, stopState); } else { ArrayPrototypePush(statelessRun, transform); } } if (statelessRun.length > 0) { - current = applyFusedStatelessSyncTransforms(current, statelessRun); + current = applyFusedStatelessSyncTransforms(current, statelessRun, + stopState); } yield* current; @@ -562,6 +571,13 @@ function applyFusedStatelessAsyncTransforms(source, run, abort) { } if (result.done) { sourceDone = true; + // A pipeline that has been aborted (its consumer stopped, its signal + // aborted or it failed) does not flush its transforms: the source + // can still end after the abort, as a pending read is released. + if (abort.aborted) { + state = kDone; + return finish(new IterResult(true, undefined)); + } delegate = flushFusedStatelessAsyncTransforms(run, runOptions); return pullDelegate(); } @@ -675,11 +691,13 @@ function applyFusedStatelessAsyncTransforms(source, run, abort) { * read for every batch. Reads are passed to * the source's iterator, with one reaction each; once it is done, null is * yielded once, as the flush signal. return() and throw() are passed on as - * yield* does. + * yield* does. Once `abort` has aborted, the end of the source is passed on + * without the flush signal (see applyFusedStatelessAsyncTransforms()). * @param {AsyncIterable} source + * @param {PipelineAbort} abort - The pipeline's abort state * @returns {AsyncIterator} */ -function createFlushSource(source) { +function createFlushSource(source, abort) { let iterator = null; // Whether the source is done, and the flush signal yielded; then the // source is ended. @@ -695,6 +713,10 @@ function createFlushSource(source) { } if (result.done) { sourceDone = true; + if (abort.aborted) { + done = true; + return new IterResult(true, undefined); + } return new IterResult(false, null); } return new IterResult(false, result.value); @@ -759,6 +781,40 @@ function createFlushSource(source) { }, null); } +/** + * The source of a validated stateful transform (e.g. compression), which + * handles the end of its source itself, without the flush signal: reads are + * passed to the source's iterator, but once `abort` has aborted (for example + * by a return() while a read is pending), the end of the source is reported + * as the abort, so that the transform stops without finishing its output. + * @param {AsyncIterable} source + * @param {PipelineAbort} abort - The pipeline's abort state + * @returns {AsyncIterator} + */ +function createValidatedSource(source, abort) { + let iterator = null; + + function onResult(result) { + if (abort.aborted && result?.done === true) throw abort.reason; + return result; + } + + return ObjectSetPrototypeOf({ + next() { + iterator ??= source[SymbolAsyncIterator](); + return PromisePrototypeThen(PromiseResolve(iterator.next()), onResult); + }, + return(value) { + const it = iterator; + if (it === null || it.return == null) { + return PromiseResolve(new IterResult(true, value)); + } + return FunctionPrototypeCall(it.return, it, value); + }, + [SymbolAsyncIterator]() { return this; }, + }, null); +} + // Iterate the output of a stateful transform as for await does, for outputs // that are not async iterables: see createStatefulTransformIterator(). async function* yieldStatefulOutput(output) { @@ -774,8 +830,8 @@ async function* yieldStatefulOutput(output) { * `for await (const item of output)` over the transform's output would * yield, written out by hand, as it runs for every batch. The transform is * called on the first next(), with createFlushSource(source), or with - * `source` itself for a validated transform (e.g. compression), whose - * output needs no normalization. An output that is not an async iterable + * createValidatedSource(source) for a validated transform (e.g. + * compression), whose output needs no normalization. An output that is not an async iterable * is read by the async generator instead (yieldStatefulOutput()). * @param {AsyncIterable} source * @param {Function} transform @@ -848,7 +904,8 @@ function createStatefulTransformIterator( try { const output = FunctionPrototypeCall( transform, receiver, - validated ? source : createFlushSource(source), options); + validated ? createValidatedSource(source, abort) : + createFlushSource(source, abort), options); if (output != null && typeof output[SymbolAsyncIterator] === 'function') { iterator = output[SymbolAsyncIterator](); @@ -997,9 +1054,12 @@ function hasTransformObject(transforms) { * @param {AsyncIterable} normalized * @param {Array} transforms * @param {PipelineAbort} abort - The pipeline's abort state + * @param {Array} statefulLayers - The layers of the stateful transforms are + * added to it, innermost first * @returns {AsyncIterable} */ -function createAsyncTransformLayers(normalized, transforms, abort) { +function createAsyncTransformLayers(normalized, transforms, abort, + statefulLayers) { // Apply transforms - fuse consecutive stateless transforms into a single // layer to avoid unnecessary async ticks. // @@ -1023,6 +1083,7 @@ function createAsyncTransformLayers(normalized, transforms, abort) { current = createStatefulTransformIterator( current, transform.transform, transform.receiver, opts, abort, transform[kValidatedTransform] === true); + ArrayPrototypePush(statefulLayers, current); } else { ArrayPrototypePush(statelessRun, transform); } @@ -1054,7 +1115,10 @@ function createAsyncTransformLayers(normalized, transforms, abort) { * aborted. * When `signal` aborts, the pull that observes it and every later pull reject * with its reason, and the transforms are closed. When the consumer stops, - * later pulls report the end. + * later pulls report the end. When it calls return() while a pull is + * pending, that pull and those queued after it report the end at once, as + * does return(), and the source and the transforms are closed without + * waiting (see interrupt()). * * A pending pull can only be rejected at once if it is a promise of its own, * one more for every batch. Without a signal, pipeTo() never stops the @@ -1075,6 +1139,9 @@ function createAsyncPipeline(source, transforms, signal, let pipelineSource; let iterator; let nextMethod; + // The layers of the stateful transforms, innermost first (see + // closeTransforms()). + const statefulLayers = []; // The settling functions of the pending pull, if any. The operation queue // runs one pull at a time. let resolvePull = null; @@ -1086,6 +1153,7 @@ function createAsyncPipeline(source, transforms, signal, const self = ObjectSetPrototypeOf({ next() { return operations.run(doNext); }, return(value) { + if (resolvePull !== null) return interrupt(value); stop(lazyDOMException('Aborted', 'AbortError')); return operations.run(doReturn, value); }, @@ -1115,21 +1183,20 @@ function createAsyncPipeline(source, transforms, signal, // the source or a transform is called, so these wait for a microtask, for // that call to return. A result of the transforms that comes later is // ignored. - function abortPipeline(reason, closeTransforms) { + function abortPipeline(reason, withTransforms) { state = kDone; removeSignalListener(); abort.abort(reason); const reject = rejectPull; resolvePull = rejectPull = null; PromisePrototypeThen(kResolvedPromise, () => { + // Outermost first: the transforms, then the source. + if (withTransforms) closeTransforms(true); pipelineSource.close(); if (reject !== null) { operations.settled(); reject(reason); } - if (closeTransforms) { - markPromiseAsHandled(closeAsyncIterator(iterator, true)); - } }); } @@ -1154,6 +1221,46 @@ function createAsyncPipeline(source, transforms, signal, } } + // return() while a pull is pending: abort the pipeline, so that the + // transforms see their signal aborted, settle the pending pull and those + // queued after it with the end at once, and close the source and the + // transforms without waiting for them, ignoring errors closing them. As in + // abortPipeline(), they are closed a microtask later, and a result of the + // transforms that comes later is ignored. + function interrupt(value) { + const resolve = resolvePull; + resolvePull = rejectPull = null; + state = kDone; + removeSignalListener(); + abort.abort(lazyDOMException('Aborted', 'AbortError')); + PromisePrototypeThen(kResolvedPromise, closeUpstream); + resolve(new IterResult(true, undefined)); + operations.flush(); + return PromiseResolve(new IterResult(true, value)); + } + + // Close the transforms and then the source, outermost first, without + // waiting. + function closeUpstream() { + closeTransforms(false); + pipelineSource.close(); + } + + // Close the transforms' iterators without waiting, outermost first: the + // outermost layer, then the layer of each stateful transform, whether or + // not the layers outside it would close it. Closing a layer again does + // nothing. + function closeTransforms(quiet) { + if (iterator === pipelineSource) return; + markPromiseAsHandled(closeAsyncIterator(iterator, quiet)); + for (let i = statefulLayers.length - 1; i >= 0; i--) { + const layer = statefulLayers[i]; + if (layer !== iterator) { + markPromiseAsHandled(closeAsyncIterator(layer, quiet)); + } + } + } + // The end of the pipeline, for an error: what an async generator would do // in its `catch` block, then `finally`. function failed(error) { @@ -1266,7 +1373,8 @@ function createAsyncPipeline(source, transforms, signal, iterator = pipelineSource; } else { iterator = createAsyncTransformLayers( - pipelineSource, transforms, abort)[SymbolAsyncIterator](); + pipelineSource, transforms, abort, + statefulLayers)[SymbolAsyncIterator](); } nextMethod = iterator.next; } catch (error) { @@ -1363,6 +1471,16 @@ function createAsyncPipeline(source, transforms, signal, */ function pullSync(source, ...transforms) { const normalized = fromSync(source); + snapshotSyncTransforms(transforms); + return { + __proto__: null, + *[SymbolIterator]() { + yield* createSyncPipeline(normalized, transforms); + }, + }; +} + +function snapshotSyncTransforms(transforms) { for (let i = 0; i < transforms.length; i++) { const transform = snapshotTransform(transforms[i]); if (transform === undefined) { @@ -1372,10 +1490,42 @@ function pullSync(source, ...transforms) { } transforms[i] = transform; } +} + +// The method of a broadcast or share consumer that a pipeline reading it +// calls with a function stopping the pipeline: see pullWithConsumerCleanup(). +const kSetConsumerStop = Symbol('kSetConsumerStop'); + +/** + * pullSync() for a consumer of a sync share: if the share is cancelled + * without a reason, the consumer's pipelines are closed, as by return(), and + * the transforms are not flushed (see kSetConsumerStop). + * @param {Iterable} source - The consumer + * @param {Array} transforms + * @returns {Iterable} + */ +function pullSyncWithConsumerStop(source, transforms) { + const normalized = fromSync(source); + snapshotSyncTransforms(transforms); + const stopState = { __proto__: null, stopped: false }; + const iterators = []; + source[kSetConsumerStop](() => { + stopState.stopped = true; + for (let i = 0; i < iterators.length; i++) { + try { + iterators[i].return(); + } catch { + // A pipeline that is running (the share was cancelled by one of its + // transforms) ends when it next reads the consumer, without a flush. + } + } + }); return { __proto__: null, - *[SymbolIterator]() { - yield* createSyncPipeline(normalized, transforms); + [SymbolIterator]() { + const iterator = createSyncPipeline(normalized, transforms, stopState); + ArrayPrototypePush(iterators, iterator); + return iterator; }, }; } @@ -1411,6 +1561,14 @@ function pull(source, ...args) { // Keep ownership of a bonded consumer outside the transform pipeline so it can // be detached even when the pipeline never starts or terminates early. +// +// A broadcast or share consumer has a [kSetConsumerStop](stop) method: the +// consumer calls `stop` when a cancel() without a reason ends it, and the +// pipeline then stops as when its return() is called, so that no transform +// is flushed: its transforms' signal aborts, a pending next() resolves with +// the end at once, and later next() calls report the end. A cancel() with a +// reason calls `stop(reason)`: the pipeline is then torn down as when its +// signal aborts, and the pending and later next() calls reject with it. function pullWithConsumerCleanup(source, transforms, signal) { const sourceIterator = source[SymbolAsyncIterator](); const pipelineSource = { @@ -1458,12 +1616,46 @@ function pullWithConsumerCleanup(source, transforms, signal) { if (signal.aborted) abortHandler(); } + // The pipelines created, whether the consumer has been stopped, and the + // reason it was cancelled with, if any. + const iterators = []; + let stopped = false; + let hasCancelReason = false; + let cancelReason; + if (typeof source[kSetConsumerStop] === 'function') { + source[kSetConsumerStop]((reason) => { + stopped = true; + // The consumer has been detached already. + sourceClosed = true; + if (abortHandler !== undefined) { + signal.removeEventListener('abort', abortHandler); + } + // A cancel with a reason stops the pipelines as a signal abort does: + // their transforms' signal aborts with the reason, the stateful + // transforms are closed, and the pending and later pulls reject with + // it. Without a reason, they stop as by return(). + if (reason !== undefined) { + hasCancelReason = true; + cancelReason = reason; + } + for (let i = 0; i < iterators.length; i++) { + markPromiseAsHandled(hasCancelReason ? + iterators[i].throw(reason) : iterators[i].return()); + } + }); + } + return { __proto__: null, [SymbolAsyncIterator]() { const iterator = pipeline[SymbolAsyncIterator](); + ArrayPrototypePush(iterators, iterator); return ObjectSetPrototypeOf({ next(value) { + if (stopped) { + if (hasCancelReason) return PromiseReject(cancelReason); + return PromiseResolve(new IterResult(true, undefined)); + } return PromisePrototypeThen( iterator.next(value), (result) => { @@ -1476,8 +1668,13 @@ function pullWithConsumerCleanup(source, transforms, signal) { }); }, return(value) { + // The pipeline is stopped first, as pull()'s return() stops it: + // its transforms' signal aborts, a pending next() resolves with + // the end at once and no transform is flushed. Then the writer is + // cancelled, or the cursor detached. + const result = iterator.return(value); closeSource('return', value); - return iterator.return(value); + return result; }, throw(error) { closeSource('throw', error); @@ -1577,7 +1774,7 @@ function pipeToSync(source, ...args) { } } catch (error) { if (!options.preventFail) { - failWriterQuietly(writer, error); + failOpenWriterQuietly(writer, error); } throw error; } @@ -1972,9 +2169,12 @@ async function pipeTo(source, ...args) { } module.exports = { + kSetConsumerStop, pipeTo, pipeToSync, pull, pullSync, + pullSyncWithConsumerStop, pullWithConsumerCleanup, + snapshotSyncTransforms, }; diff --git a/lib/internal/streams/iter/push.js b/lib/internal/streams/iter/push.js index f715b7602e25..c9cbc3b71465 100644 --- a/lib/internal/streams/iter/push.js +++ b/lib/internal/streams/iter/push.js @@ -479,12 +479,10 @@ class PushQueue { // =========================================================================== async read() { - if (this.#consumerState === 'returned') { + // After the consumer's return() or throw(), reads report the end. + if (this.#consumerState !== 'active') { return new IterResult(true, undefined); } - if (this.#consumerState === 'thrown') { - throw this.#consumerError; - } // If there's data in the buffer, return it immediately if (this.#slots.length > 0) { diff --git a/lib/internal/streams/iter/share.js b/lib/internal/streams/iter/share.js index 6c1363556e55..13b1ba6b63d4 100644 --- a/lib/internal/streams/iter/share.js +++ b/lib/internal/streams/iter/share.js @@ -33,12 +33,15 @@ const { } = require('internal/streams/iter/from'); const { - pullSync: pullSyncWithTransforms, + kSetConsumerStop, + pullSyncWithConsumerStop, pullWithConsumerCleanup, + snapshotSyncTransforms, } = require('internal/streams/iter/pull'); const { IterResult, + PendingRequest, kMultiConsumerDefaultBudget, createEntry, getProtocolMethod, @@ -48,7 +51,9 @@ const { splitBatchEntry, validateBatchEntry, validateBudget, + newPendingPromise, newResolveOnlyPromise, + takeReject, takeResolve, } = require('internal/streams/iter/utils'); const { @@ -80,15 +85,6 @@ const kNoShareError = Symbol('kNoShareError'); const kPull = Symbol('kPull'); const kSetFactorySignal = Symbol('kSetFactorySignal'); -// Clear `pending` from the pendingNext of the consumer `state` when it -// settles, unless a next() has been queued behind it. -function clearPendingNext(state, pending) { - const onSettled = () => { - if (state.pendingNext === pending) state.pendingNext = null; - }; - PromisePrototypeThen(pending, onSettled, onSettled); -} - class ShareImpl { #source; #options; @@ -110,6 +106,10 @@ class ShareImpl { #pullDone = null; #resolvePull = null; #pullDiscard = false; + // The afterPull() functions of the consumers whose next() waits for the + // read (see #waitForRead()), called once it completes, in order: cheaper + // than a reaction to #pullDone for each. + #pullCallbacks = null; #cancelError = kNoShareError; // Whether cancel() was called without a reason after the source errored: // the consumers still read their buffered data, then reject with the error. @@ -184,8 +184,8 @@ class ShareImpl { return() { return PromiseResolve(new IterResult(true, undefined)); }, - throw() { - return PromiseResolve(new IterResult(true, undefined)); + throw(error) { + return PromiseReject(error); }, }, null); }, @@ -199,16 +199,23 @@ class ShareImpl { reject: null, detached: false, error: kNoShareError, - // Set by #readAsync() for next(): the read waits for the source. - waiting: false, - // Created by #readAfterPull() on first use. + // Set by a pipeline of transforms reading the consumer (see + // kSetConsumerStop). + stop: null, + // Created by #waitForRead() on first use. afterPull: undefined, - // The read #readAfterPull() returned, while it is pending. - waitingRead: null, // The last pending next() of the consumer, if it is waiting for the // source: the next one waits for it, as next() calls of an async // generator do. pendingNext: null, + // The settling functions of the first pending next() call, those of + // the calls after it (see #addRequest()), and the handlers of their + // reads, created on first use. + headResolve: null, + headReject: null, + requests: null, + onReadResult: undefined, + onReadError: undefined, }, null); this.#consumers.add(state); @@ -224,46 +231,55 @@ class ShareImpl { return { __proto__: null, + [kSetConsumerStop](stop) { + state.stop = stop; + }, [SymbolAsyncIterator]() { - // A read that finds data, or the end, settles at once; one that - // waits for the source becomes pendingNext. + // Read the consumer's next batch, or the end, if it can be read + // now: returns kPull if it waits for the source. + const readNow = () => { + let result = self.#tryRead(state); + // A sync source can be read at once, when there is room. + while (result === kPull && + self.#bufferedBytes < self.#options.budget && + self.#pullSync()) { + result = self.#tryRead(state); + } + return result; + }; + // A read queued behind a pending next(). const read = () => { let result; try { - result = self.#tryRead(state); - // A sync source can be read at once, when there is room. - while (result === kPull && - self.#bufferedBytes < self.#options.budget && - self.#pullSync()) { - result = self.#tryRead(state); - } + result = readNow(); } catch (error) { return PromiseReject(error); } if (result !== kPull) return PromiseResolve(result); - return self.#readAsync(state); + return self.#readAsyncLoop(state); }; - const clearPending = (pending) => clearPendingNext(state, pending); return ObjectSetPrototypeOf({ next() { - let next; if (state.pendingNext !== null) { - next = PromisePrototypeThen(state.pendingNext, read, read); - } else { - state.waiting = false; - next = read(); - // Settled at once: nothing for a later next() to wait for. - if (!state.waiting) return next; + return self.#trackRead( + state, PromisePrototypeThen(state.pendingNext, read, read)); + } + // A read that finds data, or the end, settles at once; one that + // waits for the source becomes pendingNext. + let result; + try { + result = readNow(); + } catch (error) { + return PromiseReject(error); } - state.pendingNext = next; - markPromiseAsHandled(next); - // A read waiting for a pull of the source clears pendingNext - // itself (see #readAfterPull()). - if (next !== state.waitingRead) clearPending(next); - return next; + if (result !== kPull) return PromiseResolve(result); + return self.#waitForRead(state); }, + // A pending next() resolves with the end at once, without waiting + // for the source. A pull of the source that it was waiting for + // still completes, for the other consumers. async return() { state.detached = true; state.resolve = null; @@ -271,17 +287,20 @@ class ShareImpl { if (self.#deleteConsumer(state)) { self.#tryTrimBuffer(); } + self.#endReads(state); return new IterResult(true, undefined); }, - async throw() { + // Stops the consumer as return() does, then rejects with `error`. + async throw(error) { state.detached = true; state.resolve = null; state.reject = null; if (self.#deleteConsumer(state)) { self.#tryTrimBuffer(); } - return new IterResult(true, undefined); + self.#endReads(state); + throw error; }, }, null); }, @@ -303,6 +322,10 @@ class ShareImpl { return; } + // The consumers waiting for the read report the cancellation once + // they have been detached, below. + const callbacks = this.#pullCallbacks; + this.#pullCallbacks = null; if (this.#resolvePull !== null) this.#finishPull(); try { @@ -331,6 +354,11 @@ class ShareImpl { consumer.reject = null; } consumer.detached = true; + // Its transforms are not flushed, and with a reason they are torn + // down as by a signal abort: see kSetConsumerStop. + const stop = consumer.stop; + consumer.stop = null; + stop?.(reason); } this.#consumers.clear(); this.#buffer.clear(); @@ -341,6 +369,9 @@ class ShareImpl { this.#pullWaiters[i](); } this.#pullWaiters = []; + if (callbacks !== null) { + for (let i = 0; i < callbacks.length; i++) callbacks[i](); + } } [SymbolDispose]() { @@ -390,21 +421,130 @@ class ShareImpl { return kPull; } + // A next() that waits for the source, or for an earlier next() that does, + // gets a promise of its own, settled with the result of `read`, so that + // return() can settle it at once (see #endReads()). The reads settle in + // order, as each waits for the previous one. + #trackRead(state, read) { + const promise = this.#addRequest(state); + PromisePrototypeThen(read, state.onReadResult, state.onReadError); + return promise; + } + + // Add a pending next() to those of the consumer `state`, and return its + // promise. The first pending call is kept in `state` itself, and those + // queued behind it in `state.requests`. + #addRequest(state) { + const promise = newPendingPromise(); + const resolve = takeResolve(); + const reject = takeReject(); + if (state.headResolve === null) { + // The handlers are created by a method of their own, so that no + // context is allocated for them on every call (see afterPull). + if (state.onReadResult === undefined) this.#createReadHandlers(state); + state.headResolve = resolve; + state.headReject = reject; + } else { + state.requests ??= new RingBuffer(1); + state.requests.push(new PendingRequest(resolve, reject)); + } + state.pendingNext = promise; + markPromiseAsHandled(promise); + return promise; + } + + // The handlers settling the first pending next() of the consumer `state` + // with the result of its read: the next one, if any, becomes the first. + #createReadHandlers(state) { + const shift = () => { + const requests = state.requests; + if (requests !== null && requests.length > 0) { + const next = requests.shift(); + state.headResolve = next.resolve; + state.headReject = next.reject; + } else { + state.headResolve = null; + state.headReject = null; + state.pendingNext = null; + } + }; + state.onReadResult = (result) => { + const resolve = state.headResolve; + // Settled by return() already. + if (resolve === null) return; + shift(); + resolve(result); + }; + state.onReadError = (error) => { + const reject = state.headReject; + if (reject === null) return; + shift(); + reject(error); + }; + } + + // Resolve the pending next() calls of a consumer that has stopped with the + // end: the results of their reads are discarded. + #endReads(state) { + state.pendingNext = null; + const resolve = state.headResolve; + if (resolve === null) return; + state.headResolve = null; + state.headReject = null; + resolve(new IterResult(true, undefined)); + const requests = state.requests; + if (requests === null) return; + while (requests.length > 0) { + requests.shift().resolve(new IterResult(true, undefined)); + } + } + + // A next() of the consumer `state`, with none pending, that waits for the + // source: its promise is settled once the source has been read, without + // a promise of its own for the read in the common case (see afterPull). + #waitForRead(state) { + const promise = this.#addRequest(state); + if (this.#bufferedBytes < this.#options.budget && + !this.#sourceExhausted && !this.#cancelled) { + // afterPull() is created by a method of its own: if it were created + // here, V8 would allocate the context it captures on every call, even + // when it already exists. It is called when the read completes, which + // is at once if reading the source throws. + state.afterPull ??= this.#createAfterPull(state); + ArrayPrototypePush(this.#pullCallbacks ??= [], state.afterPull); + this.#pullFromSource(false); + } else { + PromisePrototypeThen(this.#readAsyncLoop(state), state.onReadResult, + state.onReadError); + } + return promise; + } + + // Once the source has been read, with room in the buffer: settle the + // pending next() with the consumer's batch, or read the source again. + #createAfterPull(state) { + return () => { + let result; + try { + result = this.#tryRead(state); + } catch (error) { + state.onReadError(error); + return; + } + if (result === kPull) { + PromisePrototypeThen(this.#readAsyncLoop(state), state.onReadResult, + state.onReadError); + return; + } + state.onReadResult(result); + }; + } + // Read the consumer's next batch once the source has been read. Loops // until it gets data, the source is exhausted, or the consumer is // detached: multiple consumers may be woken after a single pull, and // those that find no data at their cursor must pull again rather than // terminate prematurely. - #readAsync(state) { - state.waiting = true; - if (this.#bufferedBytes < this.#options.budget) { - const read = this.#readAfterPull(state); - state.waitingRead = read; - return read; - } - return this.#readAsyncLoop(state); - } - async #readAsyncLoop(state) { for (;;) { // Need to pull from source - check buffer limit @@ -440,45 +580,6 @@ class ShareImpl { } } - // The common case of #readAsyncLoop(), without an async function: there - // is room in the buffer, so read the source and then the consumer's batch. - // When the read settles with the result afterPull() returns, it is no - // longer pending: clear it from pendingNext, unless a next() has been - // queued behind it, without a reaction of its own. - #readAfterPull(state) { - // afterPull() is created by a method of its own: if it were created - // here, V8 would allocate the context it captures on every call, even - // when it already exists. - state.afterPull ??= this.#createAfterPull(state); - return PromisePrototypeThen(this.#pullFromSource(false), state.afterPull); - } - - #createAfterPull(state) { - return () => { - let result; - try { - result = this.#tryRead(state); - } catch (error) { - this.#clearWaitingRead(state); - throw error; - } - if (result === kPull) { - // Still pending: clear it when it settles. - const read = state.waitingRead; - state.waitingRead = null; - if (state.pendingNext === read) clearPendingNext(state, read); - return this.#readAsyncLoop(state); - } - this.#clearWaitingRead(state); - return result; - }; - } - - #clearWaitingRead(state) { - if (state.pendingNext === state.waitingRead) state.pendingNext = null; - state.waitingRead = null; - } - // Read a batch of the source synchronously, if it can be read so (a sync // source normalized by from()) and no read of it is pending. Returns // whether the source was read: a batch buffered, or its end or error @@ -655,6 +756,11 @@ class ShareImpl { } this.#pullWaiters = []; resolve(); + const callbacks = this.#pullCallbacks; + if (callbacks !== null) { + this.#pullCallbacks = null; + for (let i = 0; i < callbacks.length; i++) callbacks[i](); + } } #bufferBatch(batch) { @@ -775,6 +881,10 @@ class SyncShareImpl { } pull(...transforms) { + // The transforms are validated first, as share.pull() does: also for a + // cancelled share, and before a consumer is registered. + snapshotSyncTransforms(transforms); + // A consumer of a cancelled share is not registered, reads no buffered // data and does not call any of the transforms. if (this.#cancelled) { @@ -784,7 +894,7 @@ class SyncShareImpl { const rawConsumer = this.#createRawConsumer(); if (transforms.length > 0) { - return pullSyncWithTransforms(rawConsumer, ...transforms); + return pullSyncWithConsumerStop(rawConsumer, transforms); } return rawConsumer; } @@ -818,6 +928,9 @@ class SyncShareImpl { cursor: this.#bufferStart, detached: false, error: kNoShareError, + // Set by a pipeline of transforms reading the consumer (see + // kSetConsumerStop). + stop: null, }, null); this.#consumers.add(state); @@ -833,6 +946,9 @@ class SyncShareImpl { return { __proto__: null, + [kSetConsumerStop](stop) { + state.stop = stop; + }, [SymbolIterator]() { return ObjectSetPrototypeOf({ next() { @@ -986,6 +1102,12 @@ class SyncShareImpl { for (const consumer of this.#consumers) { if (hasReason) consumer.error = reason; consumer.detached = true; + if (!hasReason) { + // Its transforms are not flushed: see kSetConsumerStop. + const stop = consumer.stop; + consumer.stop = null; + stop?.(); + } } this.#consumers.clear(); } diff --git a/lib/internal/streams/iter/utils.js b/lib/internal/streams/iter/utils.js index b0e0890e8d78..f65a0003d879 100644 --- a/lib/internal/streams/iter/utils.js +++ b/lib/internal/streams/iter/utils.js @@ -659,7 +659,8 @@ class QueuedOperation { * 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, idle: Function }} + * @returns {{ run: Function, settled: Function, idle: Function, + * flush: Function }} */ function createOperationQueue() { let busy = false; @@ -700,6 +701,17 @@ function createOperationQueue() { idle() { return !busy && (queue === null || queue.length === 0); }, + // Settle the running operation and run the queued ones now, in order, + // for an iterator that has just stopped: each must then call settled() + // before it returns, as operations do once the iterator is done. + flush() { + busy = false; + while (queue !== null && queue.length !== 0) { + const { method, arg, resolve, reject } = queue.shift(); + busy = true; + PromisePrototypeThen(method(arg), resolve, reject); + } + }, }; } diff --git a/test/parallel/test-stream-iter-abort-pending-read.js b/test/parallel/test-stream-iter-abort-pending-read.js index 87a051a17df1..0dcc5db8855f 100644 --- a/test/parallel/test-stream-iter-abort-pending-read.js +++ b/test/parallel/test-stream-iter-abort-pending-read.js @@ -72,7 +72,8 @@ async function testPull(transforms) { }); } -// pull() without a signal, stopped with return() while a pull is pending. +// pull() without a signal, stopped with return() while a pull is pending: +// the pending pull reports the end. async function testPullReturn() { const { source, log, release } = pendingSource(); const it = pull(from(source), (c) => c)[Symbol.asyncIterator](); @@ -80,7 +81,7 @@ async function testPullReturn() { const pending = it.next(); await tick(); const returned = it.return(); - await assert.rejects(pending, { name: 'AbortError' }); + assert.deepStrictEqual({ ...await pending }, { done: true, value: undefined }); await returned; assert.deepStrictEqual(log, ['next', 'next', 'return']); release(); diff --git a/test/parallel/test-stream-iter-cancel-no-flush.js b/test/parallel/test-stream-iter-cancel-no-flush.js new file mode 100644 index 000000000000..1dd4911ad1fd --- /dev/null +++ b/test/parallel/test-stream-iter-cancel-no-flush.js @@ -0,0 +1,172 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// A cancel() without a reason (or Symbol.dispose) of a Broadcast, Share or +// SyncShare ends its consumers as their return() would: their transforms are +// not flushed (they never receive null), a pending next() fulfills with the +// end, the transforms' signal aborts, and later next() calls report the end. + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { broadcast, share, shareSync } = require('stream/iter'); + +const decoder = new TextDecoder(); + +function assertDone(result, message) { + assert.deepStrictEqual({ ...result }, { done: true, value: undefined }, + message); +} + +function recordingTransforms() { + const log = { statelessFlush: 0, statefulFlush: 0, signals: [] }; + const stateless = (chunks, options) => { + if (options !== undefined) log.signals.push(options.signal); + if (chunks === null) log.statelessFlush++; + return chunks; + }; + const stateful = { + async *transform(source, { signal }) { + log.signals.push(signal); + for await (const chunks of source) { + if (chunks === null) { + log.statefulFlush++; + yield 'flushed'; + } else { + yield chunks; + } + } + }, + }; + const statefulSync = { + *transform(source) { + for (const chunks of source) { + if (chunks === null) { + log.statefulFlush++; + yield 'flushed'; + } else { + yield chunks; + } + } + }, + }; + return { log, transforms: [stateless, stateful], statefulSync }; +} + +const asyncCases = { + broadcast(transforms) { + const { writer, broadcast: bc } = broadcast(); + writer.writeSync('a'); + return { target: bc, consumer: bc.push(...transforms) }; + }, + share(transforms) { + async function* source() { + yield 'a'; + await new Promise(() => {}); + } + const sh = share(source()); + return { target: sh, consumer: sh.pull(...transforms) }; + }, +}; + +const cancels = { + 'cancel()': (target) => target.cancel(), + 'Symbol.dispose': (target) => target[Symbol.dispose](), +}; + +async function testPendingNext(name, create, cancel) { + const { log, transforms } = recordingTransforms(); + const { target, consumer } = create(transforms); + const iterator = consumer[Symbol.asyncIterator](); + const first = await iterator.next(); + assert.strictEqual(decoder.decode(first.value[0]), 'a', name); + const pending = iterator.next(); + await setImmediate(); + cancel(target); + assert.strictEqual(target.consumerCount, 0, name); + assertDone(await pending, name); + assertDone(await iterator.next(), name); + await setImmediate(); + assert.strictEqual(log.statelessFlush, 0, name); + assert.strictEqual(log.statefulFlush, 0, name); + for (const signal of log.signals) assert.strictEqual(signal.aborted, true); +} + +async function testIdle(name, create, cancel) { + const { log, transforms } = recordingTransforms(); + const { target, consumer } = create(transforms); + const iterator = consumer[Symbol.asyncIterator](); + const first = await iterator.next(); + assert.strictEqual(first.done, false, name); + cancel(target); + assertDone(await iterator.next(), name); + await setImmediate(); + assert.strictEqual(log.statelessFlush, 0, name); + assert.strictEqual(log.statefulFlush, 0, name); +} + +// Cancelled before the consumer was read: the transforms are not called. +async function testNotStarted(name, create, cancel) { + const { target, consumer } = create([common.mustNotCall()]); + cancel(target); + assertDone(await consumer[Symbol.asyncIterator]().next(), name); +} + +// Consumers created after the cancel() call no transform. +async function testCreatedAfter(name, create, cancel) { + const { target } = create([]); + cancel(target); + const consumer = name.startsWith('broadcast') ? + target.push(common.mustNotCall()) : target.pull(common.mustNotCall()); + assertDone(await consumer[Symbol.asyncIterator]().next(), name); +} + +function testShareSync() { + for (const [name, cancel] of Object.entries(cancels)) { + const { log, transforms: [stateless], statefulSync } = + recordingTransforms(); + const sh = shareSync(['a', 'b']); + const iterator = sh.pull(stateless, statefulSync)[Symbol.iterator](); + const first = iterator.next(); + assert.strictEqual(decoder.decode(first.value[0]), 'a', name); + cancel(sh); + assertDone(iterator.next(), name); + assertDone(iterator.next(), name); + assert.strictEqual(log.statelessFlush, 0, name); + assert.strictEqual(log.statefulFlush, 0, name); + + // Not read before the cancel, and created after it. + const sh2 = shareSync(['a']); + const notStarted = sh2.pull(common.mustNotCall()); + cancel(sh2); + assertDone(notStarted[Symbol.iterator]().next(), name); + assertDone(sh2.pull(common.mustNotCall())[Symbol.iterator]().next(), name); + } + + // Cancelled by a transform while the pipeline is running: it ends without + // the flush signal. + const log = { flush: 0 }; + const sh = shareSync(['a', 'b']); + const iterator = sh.pull((chunks) => { + if (chunks === null) log.flush++; + else sh.cancel(); + return chunks; + })[Symbol.iterator](); + const first = iterator.next(); + assert.strictEqual(decoder.decode(first.value[0]), 'a'); + assertDone(iterator.next()); + assert.strictEqual(log.flush, 0); +} + +(async () => { + for (const [kind, create] of Object.entries(asyncCases)) { + for (const [cancelName, cancel] of Object.entries(cancels)) { + const name = `${kind} ${cancelName}`; + await testPendingNext(name, create, cancel); + await testIdle(name, create, cancel); + await testNotStarted(name, create, cancel); + await testCreatedAfter(name, create, cancel); + } + } + testShareSync(); +})().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-cancel-reason-transforms.js b/test/parallel/test-stream-iter-cancel-reason-transforms.js new file mode 100644 index 000000000000..28f1f6c91352 --- /dev/null +++ b/test/parallel/test-stream-iter-cancel-reason-transforms.js @@ -0,0 +1,77 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// Broadcast.cancel(reason) and Share.cancel(reason) stop a consumer with +// transforms as an abort of its signal does: the transforms' signal aborts +// with the reason, the stateful transforms are closed, and the pending and +// later reads reject with the reason, whether or not a read is pending. + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { broadcast, share } = require('stream/iter'); + +function never() { + return (async function*() { yield* []; await new Promise(() => {}); })(); +} + +async function check(name, create) { + for (const withPending of [true, false]) { + let signal; + let closed = false; + const stateful = { + async *transform(src, options) { + signal = options.signal; + try { + for await (const batch of src) yield batch; + } finally { + closed = true; + } + }, + }; + const { consumer, cancel, start } = create(stateful); + const it = consumer[Symbol.asyncIterator](); + let pending; + if (withPending) { + pending = it.next(); + } else { + start(); + await it.next(); + } + await setImmediate(); + const reason = new Error('cancelled'); + cancel(reason); + if (pending) await assert.rejects(pending, reason, name); + await assert.rejects(it.next(), reason, name); + await setImmediate(); + assert.strictEqual(signal.reason, reason, name); + assert.strictEqual(closed, true, name); + } +} + +async function test() { + await check('broadcast', (stateful) => { + const { writer, broadcast: bc } = broadcast(); + return { + consumer: bc.push(stateful, (c) => c), + cancel: (reason) => bc.cancel(reason), + start: () => writer.writeSync('a'), + }; + }); + await check('share', (stateful) => { + let started = false; + const sh = share({ + async *[Symbol.asyncIterator]() { + if (started) yield 'a'; + yield* never(); + }, + }); + return { + consumer: sh.pull(stateful, (c) => c), + cancel: (reason) => sh.cancel(reason), + start: () => { started = true; }, + }; + }); +} + +test().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-consumer-throw.js b/test/parallel/test-stream-iter-consumer-throw.js new file mode 100644 index 000000000000..6c27287fa60a --- /dev/null +++ b/test/parallel/test-stream-iter-consumer-throw.js @@ -0,0 +1,74 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// throw(error) on the iterators of push(), pull(), Broadcast.push(), +// Share.pull() and merge() stops them as return() does and rejects with +// the error. Later next() calls report the end. + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { broadcast, merge, pull, push, share } = require('stream/iter'); + +const factories = { + 'push': () => push().readable, + 'push with transforms': () => push((c) => c).readable, + 'pull': () => pull(push().readable, (c) => c), + 'broadcast': () => broadcast().broadcast.push(), + 'broadcast with transforms': () => broadcast().broadcast.push((c) => c), + 'share': () => share(push().readable).pull(), + 'share with transforms': () => share(push().readable).pull((c) => c), + 'merge': () => merge(push().readable), +}; + +async function testThrow() { + for (const [name, create] of Object.entries(factories)) { + for (const withPending of [false, true]) { + const it = create()[Symbol.asyncIterator](); + let pending; + if (withPending) { + pending = it.next(); + pending.catch(() => {}); + await setImmediate(); + } + const error = new Error('thrown'); + await assert.rejects(it.throw(error), (e) => e === error, name); + if (pending !== undefined) { + // A pending next() is settled. + await pending.then( + (result) => assert.strictEqual(result.done, true, name), + (e) => assert.strictEqual(e, error, name)); + } + assert.strictEqual((await it.next()).done, true, name); + } + } +} + +// Consumers of a cancelled broadcast or share are not registered, and their +// throw() rejects with the error too. +async function testCancelled() { + const { broadcast: bc } = broadcast(); + bc.cancel(); + const sh = share(push().readable); + sh.cancel(); + for (const consumer of [bc.push(), sh.pull()]) { + const error = new Error('thrown'); + await assert.rejects(consumer[Symbol.asyncIterator]().throw(error), + (e) => e === error); + } +} + +// A push() writer sees the thrown error. +async function testPushWriter() { + const { writer, readable } = push(); + const error = new Error('thrown'); + await assert.rejects(readable[Symbol.asyncIterator]().throw(error), error); + await assert.rejects(writer.write('a'), error); + assert.strictEqual(writer.signal.reason, error); +} + +Promise.all([ + testThrow(), + testCancelled(), + testPushWriter(), +]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-from-async.js b/test/parallel/test-stream-iter-from-async.js index a6bd4a486921..0354d16d9311 100644 --- a/test/parallel/test-stream-iter-from-async.js +++ b/test/parallel/test-stream-iter-from-async.js @@ -401,9 +401,9 @@ async function testFromReturnCancelsPendingPromises() { const read = iterator.next(); await setImmediate(); - const rejected = assert.rejects(read, { name: 'AbortError' }); const closed = iterator.return(); - const [, result] = await Promise.all([rejected, closed]); + const [readResult, result] = await Promise.all([read, closed]); + assert.deepStrictEqual({ ...readResult }, { done: true, value: undefined }); assert.strictEqual(result.done, true); deferred.resolve('late value'); } @@ -449,9 +449,9 @@ async function testFromReturnClosesPendingNestedIterator() { const read = iterator.next(); await fixture.started; - const rejected = assert.rejects(read, { name: 'AbortError' }); const closed = iterator.return(); - await Promise.all([rejected, closed]); + const [readResult] = await Promise.all([read, closed]); + assert.deepStrictEqual({ ...readResult }, { done: true, value: undefined }); assert.strictEqual(fixture.wasReturned(), true); fixture.resolve({ done: true }); } @@ -478,8 +478,8 @@ async function testFromCancellationHandlesCleanupRejection() { const read = iterator.next(); await fixture.started; - const rejected = assert.rejects(read, { name: 'AbortError' }); - await Promise.all([rejected, iterator.return()]); + const [readResult] = await Promise.all([read, iterator.return()]); + assert.deepStrictEqual({ ...readResult }, { done: true, value: undefined }); await setImmediate(); assert.strictEqual(fixture.wasReturned(), true); fixture.resolve({ done: true }); @@ -858,7 +858,9 @@ async function testFromSyncSourceReturnAndThrow() { async function testFromSyncSourceCallOrder() { // A next() made synchronously after another that finished synchronously - // runs at once, before a return() made after it. + // runs at once, before a return() made after it. It is still pending, + // normalizing 'a' asynchronously, when return() is called, and so return() + // settles it with the end at once and closes the source. let log = []; let iterator = from(createLoggedSyncSource(log, [ [Uint8Array.of(1)], 'a', [Uint8Array.of(2)], @@ -868,12 +870,13 @@ async function testFromSyncSourceCallOrder() { await settle(log, `result ${i}`, results[i]); } assert.deepStrictEqual(log, [ - 'iterator', 'next 0', 'next 1', 'result 0: 1', 'result 1: 1', 'return', + 'iterator', 'next 0', 'next 1', 'return', 'result 0: 1', 'result 1: done', 'result 2: done', ]); - // A call made while a value is normalized asynchronously is queued - // behind it, and so a return() made then cancels it. + // A next() made while a value is normalized asynchronously is queued + // behind it, and a return() made then does not wait: the pending calls + // report the end at once. log = []; iterator = from(createLoggedSyncSource(log, [ [Uint8Array.of(1)], Promise.resolve(Uint8Array.of(2)), [Uint8Array.of(3)], @@ -884,8 +887,8 @@ async function testFromSyncSourceCallOrder() { await settle(log, `result ${i}`, results[i]); } assert.deepStrictEqual(log, [ - 'iterator', 'next 0', 'next 1', 'result 0: 1', 'return', - 'result 1: AbortError', 'result 2: done', 'result 3: done', + 'iterator', 'next 0', 'next 1', 'return', 'result 0: 1', + 'result 1: done', 'result 2: done', 'result 3: done', ]); // A next() made synchronously after another reads the source at once. diff --git a/test/parallel/test-stream-iter-pull-async.js b/test/parallel/test-stream-iter-pull-async.js index 53480cb653df..abe84c40efa2 100644 --- a/test/parallel/test-stream-iter-pull-async.js +++ b/test/parallel/test-stream-iter-pull-async.js @@ -306,7 +306,7 @@ async function testPullReturnWhileSourceNextPending() { }; const iter = pull(source)[Symbol.asyncIterator](); - const next = assert.rejects(iter.next(), { name: 'AbortError' }); + const next = iter.next(); await nextStarted; const timeout = {}; @@ -317,7 +317,7 @@ async function testPullReturnWhileSourceNextPending() { assert.notStrictEqual(result, timeout); assert.deepStrictEqual({ ...result }, { value: undefined, done: true }); - await next; + assert.deepStrictEqual({ ...await next }, { value: undefined, done: true }); } async function testTransformedConsumerReturnBeforeNext() { diff --git a/test/parallel/test-stream-iter-pull-close-order.js b/test/parallel/test-stream-iter-pull-close-order.js new file mode 100644 index 000000000000..0b0fc5014ab8 --- /dev/null +++ b/test/parallel/test-stream-iter-pull-close-order.js @@ -0,0 +1,84 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// When pull()'s iterator is returned, or its signal aborts, while a pull is +// pending, the iterators of the stateful transforms and then the source's +// are closed, outermost first, each of them even if the layer outside it +// does not close it. + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { pull, push } = require('stream/iter'); + +function create(log, signal) { + const source = { + [Symbol.asyncIterator]() { + return { + next: () => new Promise(() => {}), + return: async () => { log.push('source'); return { done: true }; }, + }; + }, + }; + // A transform whose iterator does not close its input. + const transform = (name) => ({ + transform(input) { + const it = input[Symbol.asyncIterator](); + return { + [Symbol.asyncIterator]() { return this; }, + next: () => it.next(), + return: async () => { log.push(name); return { done: true }; }, + }; + }, + }); + const args = [source, transform('inner'), (c) => c, transform('outer')]; + if (signal) args.push({ signal }); + return pull(...args)[Symbol.asyncIterator](); +} + +async function testReturn() { + const log = []; + const it = create(log); + const pending = it.next(); + await setImmediate(); + await it.return(); + assert.strictEqual((await pending).done, true); + await setImmediate(); + assert.deepStrictEqual(log, ['outer', 'inner', 'source']); +} + +async function testAbort() { + const log = []; + const ac = new AbortController(); + const it = create(log, ac.signal); + const pending = it.next(); + await setImmediate(); + const reason = new Error('aborted'); + ac.abort(reason); + await assert.rejects(pending, reason); + await setImmediate(); + assert.deepStrictEqual(log, ['outer', 'inner', 'source']); +} + +// A stateful transform upstream of a stateless one that never settles is +// closed too, when push()'s signal aborts. +async function testPushAbort() { + const ac = new AbortController(); + let finished = false; + const { writer, readable } = push( + { async *transform(src) { try { yield* src; } finally { finished = true; } } }, + () => new Promise(() => {}), + { signal: ac.signal }); + const it = readable[Symbol.asyncIterator](); + writer.writeSync('a'); + const pending = it.next(); + await setImmediate(); + const reason = new Error('aborted'); + ac.abort(reason); + await assert.rejects(pending, reason); + await setImmediate(); + assert.strictEqual(finished, true); +} + +Promise.all([testReturn(), testAbort(), testPushAbort()]) + .then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-pull-transform-error-closes.js b/test/parallel/test-stream-iter-pull-transform-error-closes.js new file mode 100644 index 000000000000..f73fa8bf45e6 --- /dev/null +++ b/test/parallel/test-stream-iter-pull-transform-error-closes.js @@ -0,0 +1,76 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// A transform that throws in pull() or pullSync() closes the source and the +// stateful transforms upstream of it. + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { pull, pullSync, push, text, textSync } = require('stream/iter'); + +const fail = () => { throw new Error('transform failed'); }; + +async function testPushSource() { + const { writer, readable } = push({ budget: 1 }); + writer.writeSync('a'); + await assert.rejects(text(pull(readable, fail)), { message: 'transform failed' }); + // The source was closed: the writer was cancelled. + assert.strictEqual(writer.signal.aborted, true); + assert.strictEqual(writer.canWrite, null); +} + +async function testAsync() { + const log = []; + async function* source() { + try { + yield 'a'; + yield 'b'; + } finally { + log.push('source'); + } + } + const stateful = { + async *transform(input) { + try { + for await (const batch of input) yield batch; + } finally { + log.push('stateful'); + } + }, + }; + await assert.rejects(text(pull(source(), stateful, fail)), + { message: 'transform failed' }); + await setImmediate(); + assert.deepStrictEqual(log.sort(), ['source', 'stateful']); +} + +function testSync() { + const log = []; + function* source() { + try { + yield 'a'; + yield 'b'; + } finally { + log.push('source'); + } + } + const stateful = { + *transform(input) { + try { + yield* input; + } finally { + log.push('stateful'); + } + }, + }; + assert.throws(() => textSync(pullSync(source(), stateful, fail)), + { message: 'transform failed' }); + assert.deepStrictEqual(log, ['source', 'stateful']); +} + +Promise.all([ + testPushSource(), + testAsync(), + testSync(), +]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-pullsync-early-return.js b/test/parallel/test-stream-iter-pullsync-early-return.js new file mode 100644 index 000000000000..bf4e9c8c724a --- /dev/null +++ b/test/parallel/test-stream-iter-pullsync-early-return.js @@ -0,0 +1,24 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// return() on a pullSync() or SyncShare.pull() iterator before its first +// next() finishes it without calling the transforms or reading the source. + +const common = require('../common'); +const assert = require('assert'); +const { pullSync, shareSync } = require('stream/iter'); + +const source = { + [Symbol.iterator]: common.mustNotCall(), +}; +const stateful = { transform: common.mustNotCall() }; + +for (const iterable of [ + pullSync(source, stateful, common.mustNotCall()), + shareSync(source).pull(stateful), +]) { + const it = iterable[Symbol.iterator](); + assert.deepStrictEqual({ ...it.return() }, { done: true, value: undefined }); + assert.strictEqual(it.next().done, true); + assert.strictEqual(it.next().done, true); +} diff --git a/test/parallel/test-stream-iter-push-signal-pending-transform.js b/test/parallel/test-stream-iter-push-signal-pending-transform.js new file mode 100644 index 000000000000..075233c3a29f --- /dev/null +++ b/test/parallel/test-stream-iter-push-signal-pending-transform.js @@ -0,0 +1,32 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// An abort of push()'s signal settles a pull waiting inside a transform: +// it rejects with the reason, as for pull(), Broadcast.push() and +// Share.pull(). + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { push } = require('stream/iter'); + +async function test() { + const ac = new AbortController(); + const { writer, readable } = push( + async (chunks) => { + await new Promise(() => {}); + return chunks; + }, + { signal: ac.signal }); + const it = readable[Symbol.asyncIterator](); + writer.writeSync('a'); + const pending = it.next(); + await setImmediate(); + const reason = new Error('aborted'); + ac.abort(reason); + await assert.rejects(pending, reason); + await assert.rejects(it.next(), reason); + assert.strictEqual(writer.signal.reason, reason); +} + +test().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-return-after-finish.js b/test/parallel/test-stream-iter-return-after-finish.js new file mode 100644 index 000000000000..4cdae7d196e8 --- /dev/null +++ b/test/parallel/test-stream-iter-return-after-finish.js @@ -0,0 +1,42 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// return() on a pipeline that has already finished normally does not abort +// the transforms' signal. + +const common = require('../common'); +const assert = require('assert'); +const { broadcast, pull, push, share } = require('stream/iter'); + +async function check(name, iterable, getSignal) { + const it = iterable[Symbol.asyncIterator](); + while (!(await it.next()).done); + await it.return(); + assert.strictEqual(getSignal().aborted, false, name); +} + +async function test() { + let signal; + const stateless = (chunks, options) => { signal = options.signal; return chunks; }; + const stateful = { + async *transform(src, options) { signal = options.signal; yield* src; }, + }; + for (const transform of [stateless, stateful]) { + await check('pull', pull(['a'], transform), () => signal); + + const { writer, readable } = push(transform); + writer.writeSync('a'); + writer.endSync(); + await check('push', readable, () => signal); + + const { writer: bw, broadcast: bc } = broadcast(); + const consumer = bc.push(transform); + bw.writeSync('a'); + bw.endSync(); + await check('broadcast', consumer, () => signal); + + await check('share', share(['a']).pull(transform), () => signal); + } +} + +test().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-return-no-flush.js b/test/parallel/test-stream-iter-return-no-flush.js new file mode 100644 index 000000000000..3edf5f541079 --- /dev/null +++ b/test/parallel/test-stream-iter-return-no-flush.js @@ -0,0 +1,148 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// return() on the iterator of a push() readable with transforms, of a +// Broadcast push() consumer with transforms or of a Share pull() consumer +// with transforms tears the pipeline down as pull()'s return() does: the +// transforms' signal aborts, a pending next() fulfills with the end at once, +// later next() calls report the end, and no transform receives the flush +// signal (null). Then the writer is cancelled, or the cursor detached. + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { broadcast, pull, push, share } = require('stream/iter'); + +function assertDone(result, message) { + assert.deepStrictEqual({ ...result }, { done: true, value: undefined }, + message); +} + +// An async source whose next() never settles. +function neverSource() { + return { + [Symbol.asyncIterator]() { + return { + next() { return new Promise(() => {}); }, + async return() { return { done: true }; }, + }; + }, + }; +} + +// A stateless and a stateful transform recording the flush signal and the +// signal they were given. +function recordingTransforms() { + const log = { statelessFlush: 0, statefulFlush: 0, signals: [] }; + const stateless = (chunks, { signal }) => { + log.signals.push(signal); + if (chunks === null) log.statelessFlush++; + return chunks; + }; + const stateful = { + async *transform(source, { signal }) { + log.signals.push(signal); + for await (const chunks of source) { + if (chunks === null) { + log.statefulFlush++; + yield 'flushed'; + } else { + yield chunks; + } + } + }, + }; + return { log, transforms: [stateless, stateful] }; +} + +const cases = { + 'push()'(transforms) { + const { writer, readable } = push(...transforms); + return { readable, writer, count: () => 0 }; + }, + 'Broadcast push()'(transforms) { + // The writer is not cancelled: only the consumer stops. + const { broadcast: bc } = broadcast(); + return { + readable: bc.push(...transforms), + count: () => bc.consumerCount, + }; + }, + 'Share pull()'(transforms) { + const sh = share(neverSource()); + return { + readable: sh.pull(...transforms), + count: () => sh.consumerCount, + }; + }, + 'pull()'(transforms) { + return { readable: pull(neverSource(), ...transforms), count: () => 0 }; + }, +}; + +async function testPendingReturn(name, create) { + const { log, transforms } = recordingTransforms(); + const { readable, writer, count } = create(transforms); + const iterator = readable[Symbol.asyncIterator](); + const pending = iterator.next(); + await setImmediate(); + assert.ok(log.signals.length > 0, name); + + const returned = iterator.return(); + // The cursor is detached, or the writer cancelled, at once. + assert.strictEqual(count(), 0, name); + if (writer !== undefined) assert.strictEqual(writer.canWrite, null, name); + assertDone(await pending, name); + assertDone(await returned, name); + assertDone(await iterator.next(), name); + await setImmediate(); + for (const signal of log.signals) assert.strictEqual(signal.aborted, true); + assert.strictEqual(log.statelessFlush, 0, name); + assert.strictEqual(log.statefulFlush, 0, name); + if (writer !== undefined) { + assert.strictEqual(writer.signal.aborted, true, name); + await assert.rejects(writer.write('x'), { name: 'TypeError' }); + } +} + +async function testIdleReturn(name, create) { + const { log, transforms } = recordingTransforms(); + const { readable, writer, count } = create(transforms); + if (writer !== undefined) writer.writeSync('a'); + const iterator = readable[Symbol.asyncIterator](); + if (writer !== undefined) { + const first = await iterator.next(); + assert.strictEqual(first.done, false, name); + } + assertDone(await iterator.return(), name); + assert.strictEqual(count(), 0, name); + assertDone(await iterator.next(), name); + await setImmediate(); + assert.strictEqual(log.statelessFlush, 0, name); + assert.strictEqual(log.statefulFlush, 0, name); +} + +// A push() readable whose writer has data and an end pending: return() +// still reports the end without flushing the transforms. +async function testReturnWithBufferedData() { + const { log, transforms } = recordingTransforms(); + const { writer, readable } = push(...transforms); + const iterator = readable[Symbol.asyncIterator](); + const pending = iterator.next(); + await setImmediate(); + const returned = iterator.return(); + writer.writeSync('late'); + assertDone(await pending); + assertDone(await returned); + await setImmediate(); + assert.strictEqual(log.statelessFlush, 0); + assert.strictEqual(log.statefulFlush, 0); +} + +(async () => { + for (const [name, create] of Object.entries(cases)) { + await testPendingReturn(name, create); + await testIdleReturn(name, create); + } + await testReturnWithBufferedData(); +})().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-return-pending.js b/test/parallel/test-stream-iter-return-pending.js new file mode 100644 index 000000000000..9841e25a7b1c --- /dev/null +++ b/test/parallel/test-stream-iter-return-pending.js @@ -0,0 +1,345 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// return() on the iterator of a pull() pipeline or of from() while next() +// calls are pending: the pending calls fulfill with +// { done: true, value: undefined } at once, return() fulfills at once, the +// upstream iterators are closed without waiting for their return(), results +// that come later are ignored, and later next() calls report the end. + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { from, fromSync, pull, pullSync } = require('stream/iter'); + +const done = { done: true, value: undefined }; +const toAsyncStreamable = Symbol.for('Stream.toAsyncStreamable'); + +// An async source whose next() calls stay pending until release(), and +// whose return() never settles (or rejects, with `failReturn`). +function pendingSource(log, { failReturn = false } = {}) { + const releases = []; + return { + source: { + [Symbol.asyncIterator]() { + log.push('iterator'); + return { + next() { + log.push('next'); + return new Promise((resolve) => { + releases.push(() => { + resolve({ done: false, value: [new Uint8Array([1])] }); + }); + }); + }, + return() { + log.push('return'); + if (failReturn) return Promise.reject(new Error('return failed')); + return new Promise(() => {}); + }, + }; + }, + }, + release() { + for (const release of releases.splice(0)) release(); + }, + }; +} + +// Check that `iterable` behaves as above once `pendingCalls` next() calls +// are pending. `check()` checks what upstream saw after return(). +async function checkReturnWithPending(name, iterable, release, check, + pendingCalls = 1) { + const iterator = iterable[Symbol.asyncIterator](); + const settled = []; + const pending = []; + for (let i = 0; i < pendingCalls; i++) { + pending.push(iterator.next().then((result) => { + settled.push(i); + return result; + })); + } + await setImmediate(); + assert.deepStrictEqual(settled, [], name); + + const returned = iterator.return('value'); + // Everything settles at once, without waiting for upstream. + const results = await Promise.all([...pending, returned]); + for (let i = 0; i < pendingCalls; i++) { + assert.deepStrictEqual({ ...results[i] }, done, `${name}: next ${i}`); + } + assert.deepStrictEqual({ ...results[pendingCalls] }, + { done: true, value: 'value' }, name); + assert.deepStrictEqual(settled, Array.from({ length: pendingCalls }, + (_, i) => i), name); + await setImmediate(); + check(); + + // Later results are ignored. + release(); + await setImmediate(); + assert.deepStrictEqual({ ...await iterator.next() }, done, name); + assert.deepStrictEqual({ ...await iterator.return() }, done, name); +} + +// A stateful transform that records its cleanup. +function statefulTransform(log) { + return { + async *transform(source) { + try { + for await (const batch of source) yield batch; + } finally { + log.push('finally'); + } + }, + }; +} + +const pipelines = { + 'pull()': () => [], + 'pull() with a stateless transform': () => [(batch) => batch], + 'pull() with two stateless transforms': () => [(b) => b, (b) => b], + 'pull() with a signal': () => [{ signal: new AbortController().signal }], + 'pull() with a stateless transform and a signal': () => [ + (batch) => batch, { signal: new AbortController().signal }], + 'pull() with a stateful transform': (log) => [statefulTransform(log)], +}; + +async function testPull() { + for (const name in pipelines) { + for (const pendingCalls of [1, 3]) { + for (const failReturn of [false, true]) { + const log = []; + const { source, release } = pendingSource(log, { failReturn }); + const label = `${name}, ${pendingCalls} pending, ` + + `failReturn: ${failReturn}`; + await checkReturnWithPending( + label, pull(source, ...pipelines[name](log)), release, + common.mustCall(() => { + // The source is closed once, while its next() is pending. + assert.strictEqual(log.filter((e) => e === 'next').length, 1, + label); + assert.strictEqual(log.filter((e) => e === 'return').length, 1, + label); + }), pendingCalls); + } + } + } +} + +// The transforms' signal is still aborted by return(), at once, with an +// AbortError. +async function testPullTransformSignal() { + // A stateless transform, which gets the signal with the first batch. + let signal; + let reads = 0; + const source = { + [Symbol.asyncIterator]() { + return { + next() { + if (reads++ === 0) { + return Promise.resolve({ done: false, value: [new Uint8Array(1)] }); + } + return new Promise(() => {}); + }, + }; + }, + }; + const stateless = (batch, options) => { + signal = options.signal; + return batch; + }; + const stateful = { + async *transform(source, options) { + signal = options.signal; + for await (const batch of source) yield batch; + }, + }; + for (const transform of [stateless, stateful]) { + reads = 0; + signal = undefined; + const iterator = pull(source, transform)[Symbol.asyncIterator](); + await iterator.next(); + const pending = iterator.next(); + await setImmediate(); + assert.strictEqual(signal.aborted, false); + const returned = iterator.return(); + assert.strictEqual(signal.aborted, true); + assert.strictEqual(signal.reason.name, 'AbortError'); + assert.deepStrictEqual({ ...await pending }, done); + await returned; + } +} + +// from() sources whose iterator has a next() pending: reading the source, +// or normalizing a value asynchronously. +const fromSources = { + 'async iterable': (log) => { + const { source, release } = pendingSource(log); + return { input: source, release }; + }, + 'async iterable, failing return()': (log) => { + const { source, release } = pendingSource(log, { failReturn: true }); + return { input: source, release }; + }, + 'async iterable yielding a pending promise': (log) => { + const deferred = Promise.withResolvers(); + return { + input: { + [Symbol.asyncIterator]() { + let first = true; + return { + next() { + log.push('next'); + if (!first) return new Promise(() => {}); + first = false; + return Promise.resolve({ done: false, value: deferred.promise }); + }, + return() { + log.push('return'); + return new Promise(() => {}); + }, + }; + }, + }, + release: () => deferred.resolve('late'), + }; + }, + 'async iterable yielding a pending async iterable': (log) => { + const nested = pendingSource(log); + return { + input: (async function*() { + try { + yield nested.source; + } finally { + log.push('outer finally'); + } + })(), + release: nested.release, + }; + }, + 'sync iterable yielding a pending promise': (log) => { + const deferred = Promise.withResolvers(); + return { + input: { + [Symbol.iterator]() { + return { + next() { + log.push('next'); + return { done: false, value: deferred.promise }; + }, + return() { + log.push('return'); + return { done: true }; + }, + }; + }, + }, + release: () => deferred.resolve('late'), + }; + }, + 'toAsyncStreamable with a pending promise': (log) => { + const deferred = Promise.withResolvers(); + return { + input: { + [toAsyncStreamable]() { + log.push('next'); + return deferred.promise; + }, + }, + release: () => deferred.resolve('late'), + }; + }, + 'toAsyncStreamable with a pending async iterable': (log) => { + const { source, release } = pendingSource(log); + return { + input: { [toAsyncStreamable]() { return source; } }, + release, + }; + }, +}; + +async function testFrom() { + for (const name in fromSources) { + for (const pendingCalls of [1, 3]) { + const log = []; + const { input, release } = fromSources[name](log); + const label = `from(): ${name}, ${pendingCalls} pending`; + const check = common.mustCall(() => { + if (log.includes('iterator')) { + // The source was read once, and closed once. + assert.strictEqual(log.filter((e) => e === 'next').length, 1, + label); + assert.strictEqual(log.filter((e) => e === 'return').length, 1, + label); + } + }); + await checkReturnWithPending(label, from(input), release, check, + pendingCalls); + } + } +} + +// pull() of a from() source, with no transform: the pipeline is the from() +// iterator. +async function testPullOfFrom() { + for (const name in fromSources) { + const log = []; + const { input, release } = fromSources[name](log); + await checkReturnWithPending(`pull(from()): ${name}`, + pull(from(input), (batch) => batch), + release, () => {}); + } +} + +// return() while no next() is pending still waits for upstream's return(), +// and propagates its errors, as before. +async function testReturnWithoutPending() { + const error = new Error('return failed'); + const makeSource = () => ({ + [Symbol.asyncIterator]() { + return { + next() { + return Promise.resolve({ done: false, value: [new Uint8Array(1)] }); + }, + return() { return Promise.reject(error); }, + }; + }, + }); + for (const iterable of [from(makeSource()), + pull(makeSource(), (batch) => batch)]) { + const iterator = iterable[Symbol.asyncIterator](); + await iterator.next(); + await assert.rejects(iterator.return(), error); + } +} + +// pullSync() and fromSync() have no pending calls: return() closes the +// source at once, as before. +function testSync() { + const log = []; + const source = { + [Symbol.iterator]() { + return { + next() { return { done: false, value: [new Uint8Array(1)] }; }, + return() { log.push('return'); return { done: true }; }, + }; + }, + }; + for (const iterable of [fromSync(source), pullSync(source, (b) => b)]) { + const iterator = iterable[Symbol.iterator](); + assert.strictEqual(iterator.next().done, false); + assert.strictEqual(iterator.return().done, true); + assert.strictEqual(iterator.next().done, true); + } + assert.deepStrictEqual(log, ['return', 'return']); +} + +(async () => { + await testPull(); + await testPullTransformSignal(); + await testFrom(); + await testPullOfFrom(); + await testReturnWithoutPending(); + testSync(); +})().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-share-coverage.js b/test/parallel/test-stream-iter-share-coverage.js index 73827f2d40fd..ebdcf06d84cc 100644 --- a/test/parallel/test-stream-iter-share-coverage.js +++ b/test/parallel/test-stream-iter-share-coverage.js @@ -72,9 +72,10 @@ async function testAsyncIteratorThrow() { const iter = consumer[Symbol.asyncIterator](); const first = await iter.next(); assert.strictEqual(first.done, false); - const result = await iter.throw(new Error('test-throw')); - assert.strictEqual(result.done, true); + const error = new Error('test-throw'); + await assert.rejects(iter.throw(error), error); assert.strictEqual(shared.consumerCount, 0); + assert.strictEqual((await iter.next()).done, true); } // Sync consumer iterator throw() diff --git a/test/parallel/test-stream-iter-share-return-pending.js b/test/parallel/test-stream-iter-share-return-pending.js new file mode 100644 index 000000000000..321191e2cfff --- /dev/null +++ b/test/parallel/test-stream-iter-share-return-pending.js @@ -0,0 +1,162 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// return() on a Share or Broadcast consumer while next() is pending: the +// pending next() and those queued after it fulfill with the end at once, +// later next() calls report the end, and the cursor is detached at once. A +// pull of the source that a Share consumer was waiting for still completes: +// its result is buffered for the other consumers, and for consumers that +// attach later, even when no consumer remains, unless the share has been +// cancelled by then. An error it reports is stored. + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { broadcast, share, text } = require('stream/iter'); + +function assertDone(result, message) { + assert.deepStrictEqual({ ...result }, { done: true, value: undefined }, + message); +} + +// An async source whose reads wait until settle() is called. +function controlledSource() { + const reads = []; + return { + reads, + source: { + [Symbol.asyncIterator]() { + return { + next() { + const { promise, resolve, reject } = Promise.withResolvers(); + reads.push({ resolve, reject }); + return promise; + }, + async return() { return { done: true }; }, + }; + }, + }, + }; +} + +function settle(reads, value) { + reads.shift().resolve(value === undefined ? + { done: true, value: undefined } : + { done: false, value: [new TextEncoder().encode(value)] }); +} + +// Share pull() without transforms, with a source that never settles. +async function testShareReturnPending() { + const { reads, source } = controlledSource(); + const sh = share(source); + const iterator = sh.pull()[Symbol.asyncIterator](); + const first = iterator.next(); + const second = iterator.next(); + await setImmediate(); + assert.strictEqual(reads.length, 1); + assert.strictEqual(sh.consumerCount, 1); + const returned = iterator.return(); + assert.strictEqual(sh.consumerCount, 0); + assertDone(await first); + assertDone(await second); + assertDone(await returned); + assertDone(await iterator.next()); +} + +// The upstream pull completes for the other consumer. +async function testShareInFlightForOthers() { + const { reads, source } = controlledSource(); + const sh = share(source); + const leaving = sh.pull()[Symbol.asyncIterator](); + const staying = sh.pull()[Symbol.asyncIterator](); + const leavingNext = leaving.next(); + const stayingNext = staying.next(); + await setImmediate(); + assert.strictEqual(reads.length, 1); + await leaving.return(); + assertDone(await leavingNext); + assert.strictEqual(sh.consumerCount, 1); + settle(reads, 'a'); + const result = await stayingNext; + assert.strictEqual(new TextDecoder().decode(result.value[0]), 'a'); + const end = staying.next(); + await setImmediate(); + settle(reads); + assertDone(await end); +} + +// No consumer remains when the upstream pull completes: its result is still +// buffered, for consumers that attach later. +async function testShareInFlightKeptForLateConsumers() { + const { reads, source } = controlledSource(); + const sh = share(source); + const iterator = sh.pull()[Symbol.asyncIterator](); + const pending = iterator.next(); + await setImmediate(); + await iterator.return(); + assertDone(await pending); + assert.strictEqual(sh.consumerCount, 0); + settle(reads, 'kept'); + await setImmediate(); + const late = sh.pull(); + const read = text(late); + await setImmediate(); + settle(reads); + assert.strictEqual(await read, 'kept'); +} + +// The share is cancelled before the upstream pull completes: its result is +// discarded. +async function testShareInFlightDiscardedAfterCancel() { + const { reads, source } = controlledSource(); + const sh = share(source); + const iterator = sh.pull()[Symbol.asyncIterator](); + const pending = iterator.next(); + await setImmediate(); + await iterator.return(); + assertDone(await pending); + sh.cancel(); + settle(reads, 'dropped'); + await setImmediate(); + assertDone(await sh.pull()[Symbol.asyncIterator]().next()); +} + +// An error from the upstream pull is stored. +async function testShareInFlightErrorStored() { + const { reads, source } = controlledSource(); + const sh = share(source); + const iterator = sh.pull()[Symbol.asyncIterator](); + const pending = iterator.next(); + await setImmediate(); + await iterator.return(); + assertDone(await pending); + const error = new Error('upstream'); + reads.shift().reject(error); + await setImmediate(); + await assert.rejects(sh.pull()[Symbol.asyncIterator]().next(), error); +} + +// Broadcast push() without transforms. +async function testBroadcastReturnPending() { + const { writer, broadcast: bc } = broadcast(); + const iterator = bc.push()[Symbol.asyncIterator](); + const first = iterator.next(); + const second = iterator.next(); + const returned = iterator.return(); + assert.strictEqual(bc.consumerCount, 0); + assertDone(await first); + assertDone(await second); + assertDone(await returned); + assertDone(await iterator.next()); + // The writer stays open for other consumers. + assert.strictEqual(writer.canWrite, true); +} + +(async () => { + await testShareReturnPending(); + await testShareInFlightForOthers(); + await testShareInFlightKeptForLateConsumers(); + await testShareInFlightDiscardedAfterCancel(); + await testShareInFlightErrorStored(); + await testBroadcastReturnPending(); +})().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-sharesync-pull-validation.js b/test/parallel/test-stream-iter-sharesync-pull-validation.js new file mode 100644 index 000000000000..a707ab5e4ef0 --- /dev/null +++ b/test/parallel/test-stream-iter-sharesync-pull-validation.js @@ -0,0 +1,20 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// SyncShare.pull() validates its transforms first: also when the share is +// cancelled, and without registering a consumer. + +require('../common'); +const assert = require('assert'); +const { shareSync } = require('stream/iter'); + +const invalid = { code: 'ERR_INVALID_ARG_TYPE' }; + +const cancelled = shareSync(['a']); +cancelled.cancel(); +assert.throws(() => cancelled.pull(42), invalid); +assert.throws(() => cancelled.pull((c) => c, {}), invalid); + +const sh = shareSync(['a']); +assert.throws(() => sh.pull(42), invalid); +assert.strictEqual(sh.consumerCount, 0); From 87ab9b80c3e76f7e7503bc12bd42c635278cb9f3 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 19:33:48 +0000 Subject: [PATCH 24/26] stream: check an aborted signal first in stream/iter multi-consumers merge(), broadcastFrom(), Broadcast.from(), share() and shareSync() now convert their options and check for an already aborted signal before converting any input. merge() returns an iterator that rejects with the abort reason, and broadcastFrom() and share() return an already cancelled object, without normalizing the input. An already aborted pull(), merge(), broadcast or share consumer keeps rejecting until return() or throw() is called, which then reports done. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 24 ++++- lib/internal/streams/iter/broadcast.js | 28 ++--- lib/internal/streams/iter/consumers.js | 6 +- lib/internal/streams/iter/pull.js | 16 +-- lib/internal/streams/iter/share.js | 28 ++--- lib/internal/streams/iter/utils.js | 36 +++++++ ...est-stream-iter-aborted-iterable-return.js | 102 ++++++++++++++++++ .../test-stream-iter-consumers-merge.js | 7 +- .../test-stream-iter-merge-aborted-signal.js | 91 ++++++++++++++++ ...ream-iter-multi-consumer-aborted-signal.js | 74 +++++++++++++ 10 files changed, 369 insertions(+), 43 deletions(-) create mode 100644 test/parallel/test-stream-iter-aborted-iterable-return.js create mode 100644 test/parallel/test-stream-iter-merge-aborted-signal.js create mode 100644 test/parallel/test-stream-iter-multi-consumer-aborted-signal.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index b8096922f6f1..349c492faa2a 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -946,7 +946,11 @@ until the returned iterable is consumed. Transforms are applied in order. When `signal` aborts, the pending read (or the next one) rejects with `signal.reason`, and so does every later read. If `signal` is already aborted, `pull()` still returns an iterable; reading from it rejects with -`signal.reason` without reading from `source`. +`signal.reason` without reading from `source`. Once the iterator's `return()` +or `throw()` has been called, reads fulfill with +`{ done: true, value: undefined }` instead. The same applies to the consumers +that [`broadcast.push()`][] and [`share.pull()`][] create with a `signal` that +is already aborted. If the iterator's `return()` is called while a read is pending, the transforms' `signal` is aborted, the pending read (and any read queued after @@ -1594,6 +1598,11 @@ Merge multiple async iterables by yielding batches in temporal order (whichever source produces data first). All sources are consumed concurrently, with at most one pending `next()` call per source. +If `signal` is already aborted when `merge()` is called, no source is +converted or read, so `merge()` does not throw for an invalid source: every +`next()` call on the returned iterable rejects with `signal.reason` until the +iterator's `return()` or `throw()` is called, as for [`pull()`][]. + If a source fails, the returned iterable rejects with its error. `merge()` calls `return()` on the other sources but does not wait for it to settle: an async generator source that is suspended in an `await` only runs its cleanup @@ -1880,6 +1889,12 @@ consumers make room in the buffer. Cancelling the broadcast (including by aborting `options.signal`) stops reading the source and closes it. If reading the source fails, the consumers reject with the error. +`options` are converted before `input` is normalized. If `options.signal` is +already aborted, the returned broadcast is already cancelled with +`signal.reason`, and `input` is not normalized, so an invalid `input` does not +throw: every consumer rejects with `signal.reason`. The same applies to +[`Broadcast.from()`][], whose writer is then already failed. + ```mjs import { broadcastFrom, text } from 'node:stream/iter'; @@ -1927,6 +1942,11 @@ If `source` implements `Symbol.for('Stream.shareProtocol')`, that method is called with `options`, before they are validated, and its result is returned; it must be an object. +Otherwise, `options` are converted before `source` is normalized. If +`options.signal` is already aborted, the returned share is already cancelled +with `signal.reason`, and `source` is not normalized, so an invalid `source` +does not throw: every consumer rejects with `signal.reason`. + A consumer created with `share.pull()` starts reading at the oldest entry still in the buffer. Entries are released once every consumer has read them. When every consumer has detached, the buffered data is kept for consumers that @@ -2833,6 +2853,7 @@ console.log(textSync(stream)); // 'hello world' [`arrayBuffer()`]: #arraybuffersource-options [`broadcast()`]: #broadcastoptions [`broadcast.cancel()`]: #broadcastcancelreason +[`broadcast.push()`]: #broadcastpushtransforms-options [`bytes()`]: #bytessource-options [`channel.abort()`]: #channelabortreason [`dump()`]: #drainsource-options @@ -2850,6 +2871,7 @@ console.log(textSync(stream)); // 'hello world' [`pullSync()`]: #pullsyncsource-transforms [`push()`]: #pushtransforms-options [`share()`]: #sharesource-options +[`share.pull()`]: #sharepulltransforms-options [`stream.Readable`]: stream.md#class-streamreadable [`stream.Writable`]: stream.md#class-streamwritable [`stream.writer`]: quic.md#streamwriter diff --git a/lib/internal/streams/iter/broadcast.js b/lib/internal/streams/iter/broadcast.js index 0a1f62b10933..6d014d52a1f5 100644 --- a/lib/internal/streams/iter/broadcast.js +++ b/lib/internal/streams/iter/broadcast.js @@ -65,6 +65,7 @@ const { kNullOnceOption, kResolvedPromise, convertChunks, + createAbortedIterable, createEntry, snapshotByteView, getProtocolMethod, @@ -191,15 +192,7 @@ class BroadcastImpl { // Avoid registering a consumer that the pre-aborted pipeline will never // read or detach. - if (signal?.aborted) { - return { - __proto__: null, - // eslint-disable-next-line require-yield - async *[SymbolAsyncIterator]() { - throw signal.reason; - }, - }; - } + if (signal?.aborted) return createAbortedIterable(signal.reason); const rawConsumer = this.#createRawConsumer(); @@ -1155,6 +1148,15 @@ function callBroadcastProtocol(protocol, input, options) { * @returns {{ writer: Writer, broadcast: Broadcast }} */ function createBroadcastFrom(input, options) { + options = converters.BroadcastOptions(options, { + __proto__: null, + context: 'options', + }); + const { signal } = options; + // Already aborted: broadcast() cancels the broadcast with the abort reason, + // and fails its writer. The input is not normalized. + if (signal?.aborted) return broadcast(options); + const source = from(input); if (!isAsyncIterable(source) && !isSyncIterable(source)) { @@ -1162,16 +1164,8 @@ function createBroadcastFrom(input, options) { 'input', ['Broadcastable', 'AsyncIterable', 'Iterable'], input); } - options = converters.BroadcastOptions(options, { - __proto__: null, - context: 'options', - }); const result = broadcast(options); - const { signal } = options; const controller = new AbortController(); - if (signal?.aborted) { - abortSignal(controller.signal, signal.reason); - } const onCancel = (reason) => { if (!controller.signal.aborted) { abortSignal(controller.signal, reason); diff --git a/lib/internal/streams/iter/consumers.js b/lib/internal/streams/iter/consumers.js index ade16b684b40..18e7a5aca9f9 100644 --- a/lib/internal/streams/iter/consumers.js +++ b/lib/internal/streams/iter/consumers.js @@ -64,6 +64,7 @@ const { kNullOnceOption, kResolvedPromise, concatBytes, + createAbortedIterable, getProtocolMethod, newPendingPromise, raceSignal, @@ -658,11 +659,14 @@ function merge(...args) { __proto__: null, context: 'options', }); + const { signal } = options; + + // Already aborted: no source is normalized, nor read. + if (signal?.aborted) return createAbortedIterable(signal.reason); // Normalize each source via from() const normalized = ArrayPrototypeMap(sources, (source) => from(source)); - const { signal } = options; if (normalized.length === 1 && signal === undefined) { // A single source without a signal is read without an async generator // layer for every batch. diff --git a/lib/internal/streams/iter/pull.js b/lib/internal/streams/iter/pull.js index 6060757c253a..d5c0870ebfaa 100644 --- a/lib/internal/streams/iter/pull.js +++ b/lib/internal/streams/iter/pull.js @@ -64,6 +64,7 @@ const { kStart, callWithByteView, checkFixedBatchChunk, + createAbortedIterable, createBatchEntry, createOperationQueue, fixedBatchToEntry, @@ -1148,16 +1149,21 @@ function createAsyncPipeline(source, transforms, signal, let rejectPull = null; // See stop(). let closeWithoutWaiting = false; + // Whether the consumer has called return() or throw(): later pulls report + // the end, even once `signal` has aborted. + let consumerStopped = false; const operations = createOperationQueue(); const self = ObjectSetPrototypeOf({ next() { return operations.run(doNext); }, return(value) { + consumerStopped = true; if (resolvePull !== null) return interrupt(value); stop(lazyDOMException('Aborted', 'AbortError')); return operations.run(doReturn, value); }, throw(error) { + consumerStopped = true; stop(error); return operations.run(doThrow, error); }, @@ -1350,7 +1356,7 @@ function createAsyncPipeline(source, transforms, signal, } function doNext() { - if (signalAborted) { + if (signalAborted && !consumerStopped) { operations.settled(); return PromiseReject(signal.reason); } @@ -1597,13 +1603,7 @@ function pullWithConsumerCleanup(source, transforms, signal) { if (signal?.aborted) { closeSource('throw', signal.reason); - return { - __proto__: null, - // eslint-disable-next-line require-yield - async *[SymbolAsyncIterator]() { - throw signal.reason; - }, - }; + return createAbortedIterable(signal.reason); } const pipeline = signal === undefined ? diff --git a/lib/internal/streams/iter/share.js b/lib/internal/streams/iter/share.js index 13b1ba6b63d4..b11bfc3e21ca 100644 --- a/lib/internal/streams/iter/share.js +++ b/lib/internal/streams/iter/share.js @@ -43,6 +43,7 @@ const { IterResult, PendingRequest, kMultiConsumerDefaultBudget, + createAbortedIterable, createEntry, getProtocolMethod, getMinCursor, @@ -151,15 +152,7 @@ class ShareImpl { // Avoid registering a consumer that the pre-aborted pipeline will never // read or detach. - if (signal?.aborted) { - return { - __proto__: null, - // eslint-disable-next-line require-yield - async *[SymbolAsyncIterator]() { - throw signal.reason; - }, - }; - } + if (signal?.aborted) return createAbortedIterable(signal.reason); const rawConsumer = this.#createRawConsumer(); @@ -1239,8 +1232,6 @@ function share(source, options) { if (protocol !== undefined) { return callShareProtocol(protocol, source, options, 'shareProtocol'); } - // Normalize source via from() - accepts strings, ArrayBuffers, protocols, etc. - const normalized = from(source); options = converters.ShareOptions(options, { __proto__: null, context: 'options', @@ -1259,6 +1250,16 @@ function share(source, options) { signal, }; + // Already aborted: the share is cancelled with the abort reason, and the + // source is not normalized. + if (signal?.aborted) { + const cancelled = new ShareImpl(undefined, opts); + cancelled.cancel(signal.reason); + return cancelled; + } + + // Normalize source via from() - accepts strings, ArrayBuffers, protocols, etc. + const normalized = from(source); const shareImpl = new ShareImpl(normalized, opts); if (signal) { @@ -1275,8 +1276,6 @@ function shareSync(source, options) { if (protocol !== undefined) { return callShareProtocol(protocol, source, options, 'shareSyncProtocol'); } - // Normalize source via fromSync() - accepts strings, ArrayBuffers, protocols, etc. - const normalized = fromSync(source); options = converters.ShareSyncOptions(options, { __proto__: null, context: 'options', @@ -1302,6 +1301,9 @@ function shareSync(source, options) { backpressure, }; + // Normalize source via fromSync() - accepts strings, ArrayBuffers, protocols, etc. + // As for share(), the options are converted first. + const normalized = fromSync(source); return new SyncShareImpl(normalized, opts); } diff --git a/lib/internal/streams/iter/utils.js b/lib/internal/streams/iter/utils.js index f65a0003d879..056ff524e0e0 100644 --- a/lib/internal/streams/iter/utils.js +++ b/lib/internal/streams/iter/utils.js @@ -198,6 +198,41 @@ function onSignalAbort(signal, handler) { } } +/** + * The async iterable returned for a signal that has already aborted (by + * pull(), merge(), and the consumers of a broadcast or share): its iterators + * reject every next() call with `reason` until return() or throw() is + * called. return() then resolves with the end, throw() rejects with the + * value passed to it, and later next() calls report the end. + * @param {any} reason + * @returns {AsyncIterable} + */ +function createAbortedIterable(reason) { + return { + __proto__: null, + [SymbolAsyncIterator]() { + let stopped = false; + return ObjectSetPrototypeOf({ + next() { + if (stopped) return PromiseResolve(new IterResult(true, undefined)); + return PromiseReject(reason); + }, + return(value) { + stopped = true; + return PromiseResolve(new IterResult(true, value)); + }, + throw(error) { + stopped = true; + return PromiseReject(error); + }, + [SymbolAsyncIterator]() { + return this; + }, + }, null); + }, + }; +} + /** * The abort state of a pipeline: what the AbortController of a pipeline in * the specification holds, without creating an AbortController unless its @@ -1178,6 +1213,7 @@ module.exports = { takeResolve, callWithByteView, concatBytes, + createAbortedIterable, createOperationQueue, convertChunks, checkFixedBatchChunk, diff --git a/test/parallel/test-stream-iter-aborted-iterable-return.js b/test/parallel/test-stream-iter-aborted-iterable-return.js new file mode 100644 index 000000000000..d7747e5bedb7 --- /dev/null +++ b/test/parallel/test-stream-iter-aborted-iterable-return.js @@ -0,0 +1,102 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// The iterable returned for a signal that has already aborted rejects every +// next() call with the abort reason until return() or throw() is called: +// return() then resolves with the end, throw() rejects with its argument, +// and later next() calls report the end. Also from()'s iterator: a throw() +// waiting behind a pending next() when return() is called rejects, and a +// second return() does not close the input again. + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { broadcast, from, merge, pull, share } = require('stream/iter'); + +const factories = { + 'pull': (signal) => pull(['a'], (c) => c, { signal }), + 'pull without transforms': (signal) => pull(['a'], { signal }), + 'merge': (signal) => merge(['a'], { signal }), + 'broadcast': (signal) => broadcast().broadcast.push({ signal }), + 'broadcast with transforms': (signal) => + broadcast().broadcast.push((c) => c, { signal }), + 'share': (signal) => share(['a']).pull({ signal }), + 'share with transforms': (signal) => share(['a']).pull((c) => c, { signal }), +}; + +async function testAborted() { + const reason = new Error('aborted'); + const signal = AbortSignal.abort(reason); + for (const [name, create] of Object.entries(factories)) { + let it = create(signal)[Symbol.asyncIterator](); + await assert.rejects(it.next(), reason, name); + await assert.rejects(it.next(), reason, name); + assert.deepStrictEqual({ ...await it.return('v') }, + { done: true, value: 'v' }, name); + assert.strictEqual((await it.next()).done, true, name); + + it = create(signal)[Symbol.asyncIterator](); + const error = new Error('thrown'); + await assert.rejects(it.throw(error), error, name); + assert.strictEqual((await it.next()).done, true, name); + } +} + +async function testFromQueuedThrow() { + let closes = 0; + let release; + const gate = new Promise((resolve) => { release = resolve; }); + const source = { + [Symbol.asyncIterator]() { + return { + next: () => gate.then(() => ({ done: false, value: 'a' })), + return: async () => { closes++; return { done: true }; }, + }; + }, + }; + // A nested promise keeps next() pending. + const it = from({ async *[Symbol.asyncIterator]() { yield gate; } })[ + Symbol.asyncIterator](); + const pending = it.next(); + await setImmediate(); + const error = new Error('thrown'); + const thrown = it.throw(error); + const returned = it.return(); + assert.strictEqual((await pending).done, true); + await assert.rejects(thrown, error); + assert.strictEqual((await returned).done, true); + assert.strictEqual((await it.return()).done, true); + assert.strictEqual((await it.next()).done, true); + release(); + + const it2 = from(source)[Symbol.asyncIterator](); + release(); + await it2.next(); + await it2.return(); + await it2.return(); + assert.strictEqual(closes, 1); +} + +// throw() rejects with its argument, not with an error closing the input. +async function testFromThrowCloseError() { + const source = { + [Symbol.asyncIterator]() { + return { + next: async () => ({ done: false, value: 'a' }), + return: async () => { throw new Error('close failed'); }, + }; + }, + }; + const it = from(source)[Symbol.asyncIterator](); + await it.next(); + const error = new Error('thrown'); + await assert.rejects(it.throw(error), error); + const second = new Error('second'); + await assert.rejects(it.throw(second), second); +} + +Promise.all([ + testAborted(), + testFromQueuedThrow(), + testFromThrowCloseError(), +]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-consumers-merge.js b/test/parallel/test-stream-iter-consumers-merge.js index 6da1d6ea6df3..8cfc76a5453b 100644 --- a/test/parallel/test-stream-iter-consumers-merge.js +++ b/test/parallel/test-stream-iter-consumers-merge.js @@ -463,8 +463,9 @@ async function testMergeMultiSourceBreakWithCleanupError() { // merge() of a single source behaves as an async generator reading it: // an abort rejects the pending read, closes the source and ends the -// iteration; an abort before the first read does not open the source; -// return() with reads pending ends them at once and closes the source. +// iteration; with a signal already aborted, every read rejects and the +// source is not opened; return() with reads pending ends them at once and +// closes the source. async function testMergeSingleSourceProtocol() { const log = []; function source(name, values, { hang = false } = {}) { @@ -523,7 +524,7 @@ async function testMergeSingleSourceProtocol() { await assert.rejects(it.throw(new Error('thrown')), { message: 'thrown' }); assert.deepStrictEqual(log, [ - 'a 1: AbortError', 'a 2: done', + 'a 1: AbortError', 'a 2: AbortError', 'b iterator', 'b next 0', 'b 1: 1', 'b next 1', 'b return', 'b 2: AbortError', 'b 3: AbortError', 'c iterator', 'c next 0', 'c return', 'c 0: done', 'c 1: done', diff --git a/test/parallel/test-stream-iter-merge-aborted-signal.js b/test/parallel/test-stream-iter-merge-aborted-signal.js new file mode 100644 index 000000000000..1bb529026d36 --- /dev/null +++ b/test/parallel/test-stream-iter-merge-aborted-signal.js @@ -0,0 +1,91 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// merge() with a signal that has already aborted checks it before any +// source is normalized: invalid sources throw nothing, no source is +// converted or opened, and every next() rejects with the abort reason. + +const common = require('../common'); +const assert = require('assert'); +const { from, merge } = require('stream/iter'); + +const toStreamable = Symbol.for('Stream.toStreamable'); +const toAsyncStreamable = Symbol.for('Stream.toAsyncStreamable'); + +async function testInvalidSourceNotNormalized() { + const reason = new Error('aborted'); + const signal = AbortSignal.abort(reason); + // Without the early check, from(42) would throw ERR_INVALID_ARG_TYPE. + const merged = merge(from('a'), 42, { signal }); + const iterator = merged[Symbol.asyncIterator](); + for (let i = 0; i < 3; i++) { + await assert.rejects(iterator.next(), (error) => error === reason); + } + // A new iterator rejects too. + await assert.rejects(merged[Symbol.asyncIterator]().next(), + (error) => error === reason); +} + +async function testNoSourceTouched() { + const signal = AbortSignal.abort(); + const touched = common.mustNotCall('source touched'); + const sources = [ + { [Symbol.asyncIterator]: touched }, + { [Symbol.iterator]: touched }, + { [toStreamable]: touched }, + { [toAsyncStreamable]: touched }, + ]; + for (const count of [1, 2, 4]) { + const iterator = merge(...sources.slice(0, count), { signal })[ + Symbol.asyncIterator](); + await assert.rejects(iterator.next(), { name: 'AbortError' }); + await assert.rejects(iterator.next(), { name: 'AbortError' }); + } + // No sources at all. + await assert.rejects( + merge({ signal })[Symbol.asyncIterator]().next(), { name: 'AbortError' }); +} + +async function testForAwait() { + const signal = AbortSignal.abort(); + await assert.rejects(async () => { + // eslint-disable-next-line no-unused-vars + for await (const _ of merge(from('a'), from('b'), { signal })) { + assert.fail('no batch'); + } + }, { name: 'AbortError' }); +} + +async function testReturnAndThrow() { + const signal = AbortSignal.abort(); + const iterator = merge(from('a'), { signal })[Symbol.asyncIterator](); + assert.deepStrictEqual({ ...await iterator.return('v') }, + { done: true, value: 'v' }); + const error = new Error('thrown'); + await assert.rejects(iterator.throw(error), error); + assert.deepStrictEqual({ ...await iterator.next() }, + { done: true, value: undefined }); +} + +// Without an aborted signal, sources are still normalized eagerly. +function testNotAbortedStillValidates() { + assert.throws(() => merge(from('a'), 42), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws( + () => merge(from('a'), 42, { signal: new AbortController().signal }), + { code: 'ERR_INVALID_ARG_TYPE' }); +} + +// Invalid options still throw before the signal is looked at. +function testInvalidOptions() { + assert.throws(() => merge(from('a'), { signal: 'nope' }), + { code: 'ERR_INVALID_ARG_TYPE' }); +} + +(async () => { + await testInvalidSourceNotNormalized(); + await testNoSourceTouched(); + await testForAwait(); + await testReturnAndThrow(); + testNotAbortedStillValidates(); + testInvalidOptions(); +})().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-multi-consumer-aborted-signal.js b/test/parallel/test-stream-iter-multi-consumer-aborted-signal.js new file mode 100644 index 000000000000..5523709959bc --- /dev/null +++ b/test/parallel/test-stream-iter-multi-consumer-aborted-signal.js @@ -0,0 +1,74 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// broadcastFrom(), Broadcast.from() and share() convert their options and +// check for an already aborted signal before converting their input: with an +// aborted signal they return a cancelled Broadcast or Share without +// normalizing the input (so an invalid input does not throw), and its +// consumers reject with the abort reason. shareSync() converts its options +// before its input too. + +const common = require('../common'); +const assert = require('assert'); +const { + Broadcast, + broadcastFrom, + share, + shareSync, +} = require('stream/iter'); + +// An input whose conversion would be observable. +const touched = { + get [Symbol.asyncIterator]() { return common.mustNotCall()(); }, + get [Symbol.iterator]() { return common.mustNotCall()(); }, + [Symbol.for('Stream.toAsyncStreamable')]: common.mustNotCall(), + [Symbol.for('Stream.toStreamable')]: common.mustNotCall(), +}; + +(async () => { + for (const input of [42, touched]) { + const reason = new Error('aborted'); + const signal = AbortSignal.abort(reason); + + const bc = broadcastFrom(input, { signal }); + assert.strictEqual(bc.consumerCount, 0); + await assert.rejects(bc.push()[Symbol.asyncIterator]().next(), reason); + await assert.rejects( + bc.push(common.mustNotCall())[Symbol.asyncIterator]().next(), reason); + + const { writer, broadcast: fromBc } = Broadcast.from(input, { signal }); + await assert.rejects(fromBc.push()[Symbol.asyncIterator]().next(), reason); + assert.strictEqual(writer.signal.reason, reason); + await assert.rejects(writer.write('x'), reason); + + const sh = share(input, { signal }); + assert.strictEqual(sh.consumerCount, 0); + await assert.rejects(sh.pull()[Symbol.asyncIterator]().next(), reason); + await assert.rejects( + sh.pull(common.mustNotCall())[Symbol.asyncIterator]().next(), reason); + } + + // The options are still validated. + const signal = AbortSignal.abort(); + assert.throws(() => broadcastFrom(42, { signal, budget: 0 }), + { code: 'ERR_OUT_OF_RANGE' }); + assert.throws(() => share(42, { signal, budget: 0 }), + { code: 'ERR_OUT_OF_RANGE' }); + assert.throws(() => broadcastFrom(42, { signal, backpressure: 'bad' }), + { code: 'ERR_INVALID_ARG_VALUE' }); + + // Invalid options are reported before an invalid input. + assert.throws(() => broadcastFrom(42, { backpressure: 'bad' }), + { code: 'ERR_INVALID_ARG_VALUE' }); + assert.throws(() => share(42, { backpressure: 'bad' }), + { code: 'ERR_INVALID_ARG_VALUE' }); + assert.throws(() => shareSync(42, { backpressure: 'bad' }), + { code: 'ERR_INVALID_ARG_VALUE' }); + assert.throws(() => shareSync(42, { budget: 0 }), + { code: 'ERR_OUT_OF_RANGE' }); + + // Without an aborted signal, an invalid input still throws. + assert.throws(() => broadcastFrom(42), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => share(42), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => shareSync(42), { code: 'ERR_INVALID_ARG_TYPE' }); +})().then(common.mustCall()); From 133e8bb49db505a956bd69f99a09dd70118369b1 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 21:43:42 +0000 Subject: [PATCH 25/26] stream: queue stream/iter throw() behind pending next() throw() on the iterators of push(), pull(), Broadcast.push(), Share.pull(), merge() and from() handled a pending next() in two different ways: push readables and pipelines rejected it with the thrown value, and broadcast and share consumers resolved it with the end. Per the Iterable Streams specification, throw() is now served in order: it waits until the next() calls made before it have settled, which settle as they would have, then stops the iterator as return() would and rejects with its argument. Calls made while it waits report the end, and a return() made meanwhile still stops the iterator at once. As throw() is handled as return(), the writer of a push() stream whose consumer throws is cancelled without an error, as for return(): its writes reject with ERR_INVALID_STATE, its signal aborts with that error, and ondrain() resolves with false. After return() or throw(), later reads of a broadcast or share consumer report the end, even once the source has failed. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/stream_iter.md | 83 ++-- lib/internal/streams/iter/broadcast.js | 29 +- lib/internal/streams/iter/consumers.js | 66 +++- lib/internal/streams/iter/from.js | 38 +- lib/internal/streams/iter/pull.js | 145 ++++--- lib/internal/streams/iter/push.js | 65 ++-- lib/internal/streams/iter/share.js | 54 ++- lib/internal/streams/iter/utils.js | 102 +++++ .../test-stream-iter-abort-pending-read.js | 13 +- .../test-stream-iter-consumer-throw.js | 59 ++- .../parallel/test-stream-iter-merge-return.js | 20 +- test/parallel/test-stream-iter-push-writer.js | 48 +-- .../test-stream-iter-reason-propagation.js | 8 +- .../parallel/test-stream-iter-throw-queued.js | 355 ++++++++++++++++++ .../test-stream-iter-writer-signal.js | 7 +- 15 files changed, 885 insertions(+), 207 deletions(-) create mode 100644 test/parallel/test-stream-iter-throw-queued.js diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index 349c492faa2a..21794f4b6c6a 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -573,8 +573,10 @@ The writers created by [`push()`][], [`broadcast()`][], and [`duplex()`][] have it. Their signal aborts: * when the consumer stops reading (for example, it breaks out of a - `for await` loop, or its iterator's `throw()` is called). The reason is the - error that later writes reject with. + `for await` loop, or its iterator's `return()` or `throw()` is called). The + reason is the error that later writes reject with: an `ERR_INVALID_STATE` + `TypeError` when the consumer stopped with `return()` or `throw()`, or the + error of a transform that threw. * when `writer.fail()` is called, including by an aborted `signal` option of `push()`, `broadcast()`, or `duplex()`. The reason is the `fail()` reason: if `fail()` was called with no argument, the `AbortError` {DOMException} @@ -736,12 +738,20 @@ yield normalized batches, so `from()` returns them unchanged. Calls to the iterator's `next()` and `throw()` are handled in order: a call made while an earlier one is pending (for example, while a promise in `input` is awaited) waits for it. `return()` does not wait: every `next()` call still -pending fulfills with `{ done: true, value: undefined }` at once, `return()` -fulfills at once, and the iterator of `input` (and of any nested iterable being -read) is closed by calling its `return()` without waiting for it to settle. -Results that arrive later are discarded, and later `next()` calls fulfill with +pending fulfills with `{ done: true, value: undefined }` at once, every +`throw()` call still waiting rejects with its argument, `return()` fulfills at +once, and the iterator of `input` (and of any nested iterable being read) is +closed by calling its `return()` without waiting for it to settle. Results +that arrive later are discarded, and later `next()` calls fulfill with `{ done: true, value: undefined }`. +A `throw(error)` call therefore waits until the `next()` calls made before it +have settled: they fulfill or reject as they would have, not with `error`. +It then closes the iterator of `input` as `return()` would, ignoring an error +from closing it, and rejects with `error`. If the pending `next()` never +settles, for example because `input` never produces another value, neither +does `throw()`: call `return()` to stop reading at once. + ```mjs import { Buffer } from 'node:buffer'; import { from, text } from 'node:stream/iter'; @@ -947,7 +957,7 @@ When `signal` aborts, the pending read (or the next one) rejects with `signal.reason`, and so does every later read. If `signal` is already aborted, `pull()` still returns an iterable; reading from it rejects with `signal.reason` without reading from `source`. Once the iterator's `return()` -or `throw()` has been called, reads fulfill with +has been called, or a `throw()` has run (see below), reads fulfill with `{ done: true, value: undefined }` instead. The same applies to the consumers that [`broadcast.push()`][] and [`share.pull()`][] create with a `signal` that is already aborted. @@ -963,6 +973,17 @@ arrives later is discarded, and later reads fulfill with `{ done: true, value: undefined }`. No transform receives the flush signal (`null`) once `return()` has been called, even if the source ends afterwards. +The iterator's `throw(error)` is handled in order with `next()`, as for +[`from()`][]: it waits until the reads made before it have settled, which +fulfill or reject as they would have, not with `error`. It then stops the +pipeline as a `return()` made at that time would (the transforms' `signal` +aborts with an `AbortError` {DOMException}, and the transforms and the source +are closed, errors from closing them ignored), and rejects with `error`. Later +reads fulfill with `{ done: true, value: undefined }`. A `return()` made while +a `throw()` waits stops the pipeline at once: the pending reads fulfill with +`{ done: true, value: undefined }`, and the `throw()` rejects with its +argument. + ```mjs import { from, pull, text } from 'node:stream/iter'; @@ -1106,10 +1127,16 @@ Zero-length chunks are accepted without being buffered: they are not delivered to the consumer, and `writeSync()` and `write()` report success for them even when backpressure is active. -Calling `throw(error)` on the readable's iterator stops the consumer: a pending -read rejects with `error`, the writer's pending and later writes reject with -`error`, `throw()` rejects with `error`, and later reads fulfill with -`{ done: true, value: undefined }`. +Calling `throw(error)` on the readable's iterator waits until the reads made +before it have settled: they get the data written, the end, or the writer's +error, as they would have. It then stops the consumer as `return()` does, and +rejects with `error`. The writer sees the consumer stop as after `return()`, +not `error`: its pending and later writes reject with an `ERR_INVALID_STATE` +`TypeError`, `writer.signal` aborts with that error, and drain waiters resolve +with `false`. Later reads fulfill with `{ done: true, value: undefined }`. With +no read pending, `throw()` acts at once; a `return()` made while it waits +settles the pending reads with `{ done: true, value: undefined }`, and the +`throw()` then rejects with `error`. When `readable` has transforms, its iterator's `return()` stops them as [`pull()`][]'s `return()` does: their `signal` is aborted, a pending read @@ -1608,10 +1635,16 @@ calls `return()` on the other sources but does not wait for it to settle: an async generator source that is suspended in an `await` only runs its cleanup once that `await` completes. -If the iterator's `return()` or `throw()` is called while a `next()` call is -pending, the pending call fulfills with `{ done: true, value: undefined }` at -once, and `merge()` calls `return()` on the sources without waiting for it -to settle. +If the iterator's `return()` is called while a `next()` call is pending, the +pending call fulfills with `{ done: true, value: undefined }` at once, and +`merge()` calls `return()` on the sources without waiting for it to settle. + +The iterator's `throw(error)` waits until the `next()` calls made before it +have settled, as they would have, not with `error`. It then stops the merge +as a `return()` made at that time would, and rejects with `error`. Later +`next()` calls fulfill with `{ done: true, value: undefined }`. A `return()` +made while a `throw()` waits stops the merge at once, and the `throw()` then +rejects with its argument. Calls to `next()` are settled in order. If `signal` aborts while `next()` calls are pending, they all reject with `signal.reason`, as do later calls, @@ -1844,9 +1877,13 @@ pending: that read, and any read queued after it, fulfills with stopped as by [`pull()`][]'s `return()`: no transform receives the flush signal (`null`). -Calling `throw(error)` on the consumer's iterator stops the consumer as -`return()` does, and then rejects with `error`. Later reads fulfill with -`{ done: true, value: undefined }`. +Calling `throw(error)` on the consumer's iterator waits until the reads made +before it have settled: they get their data, the end, or their own error, as +they would have. It then stops the consumer as `return()` does, and rejects +with `error`. Later reads fulfill with `{ done: true, value: undefined }`. +With no read pending, `throw()` acts at once. A `return()` made while it +waits detaches the consumer at once, and the `throw()` then rejects with +`error`. #### `broadcast[Symbol.dispose]()` @@ -2059,9 +2096,13 @@ source still completes: its result is buffered as any other, for the other consumers and for consumers that attach later (unless the share has been cancelled by then), and an error it reports is stored. -Calling `throw(error)` on the consumer's iterator stops the consumer as -`return()` does, and then rejects with `error`. Later reads fulfill with -`{ done: true, value: undefined }`. +Calling `throw(error)` on the consumer's iterator waits until the reads made +before it have settled: they get their data, the end, or their own error, as +they would have. It then stops the consumer as `return()` does, and rejects +with `error`. Later reads fulfill with `{ done: true, value: undefined }`. +With no read pending, `throw()` acts at once. A `return()` made while it +waits detaches the consumer at once, and the `throw()` then rejects with +`error`. #### `share[Symbol.dispose]()` diff --git a/lib/internal/streams/iter/broadcast.js b/lib/internal/streams/iter/broadcast.js index 6d014d52a1f5..bd6bb345c724 100644 --- a/lib/internal/streams/iter/broadcast.js +++ b/lib/internal/streams/iter/broadcast.js @@ -61,6 +61,7 @@ const { IterResult, PendingRequest, PendingWrite, + QueuedThrow, kMultiConsumerDefaultBudget, kNullOnceOption, kResolvedPromise, @@ -245,6 +246,10 @@ class BroadcastImpl { // Set by a pipeline of transforms reading the consumer (see // kSetConsumerStop). stop: null, + // The promise of the last next() call that had to wait, and the + // throw() waiting for it, if any (see QueuedThrow). + lastNext: null, + queuedThrow: null, }, null); this.#consumers.add(state); @@ -274,6 +279,13 @@ class BroadcastImpl { self.#notifyEndDrained(); } + // throw() once no read is pending: stop as return() does. + function stopForThrow(error) { + detach(); + state.error = kNoBroadcastError; + return PromiseReject(error); + } + return { __proto__: null, [kSetConsumerStop](stop) { @@ -282,6 +294,7 @@ class BroadcastImpl { [SymbolAsyncIterator]() { return ObjectSetPrototypeOf({ next() { + if (state.queuedThrow?.waiting) return state.queuedThrow.next(); if (state.detached) { if (state.error !== kNoBroadcastError) { return PromiseReject(state.error); @@ -321,6 +334,7 @@ class BroadcastImpl { const resolve = takeResolve(); const reject = takeReject(); state.pending.push(new PendingRequest(resolve, reject)); + state.lastNext = promise; return promise; } @@ -329,19 +343,28 @@ class BroadcastImpl { const reject = takeReject(); state.resolve = resolve; state.reject = reject; + state.lastNext = promise; self.#waiters.push(state); return promise; }, + // Later reads report the end, even if the writer had failed. return() { detach(); + state.error = kNoBroadcastError; + state.queuedThrow?.abandon(); return kDone; }, - // Stops the consumer as return() does, then rejects with `error`. + // Once the pending next() calls have settled, stops the consumer + // as return() does, then rejects with `error`. throw(error) { - detach(); - return PromiseReject(error); + if (state.queuedThrow?.waiting || state.resolve !== null || + state.pending.length > 0) { + state.queuedThrow ??= new QueuedThrow(stopForThrow); + return state.queuedThrow.throw(error, state.lastNext); + } + return stopForThrow(error); }, }, null); }, diff --git a/lib/internal/streams/iter/consumers.js b/lib/internal/streams/iter/consumers.js index 18e7a5aca9f9..ef1caff2cba0 100644 --- a/lib/internal/streams/iter/consumers.js +++ b/lib/internal/streams/iter/consumers.js @@ -512,14 +512,19 @@ MergeEntry.prototype = ObjectFreeze({ __proto__: null }); * The iterator of merge(). Calls to next() are passed to the iterator of the * merged sources, created by `open()` on the first next(), which settles them * in order: the iterator of the source from from() for a single source, or - * an async generator. return() and throw() are passed to it once no next() is - * pending, and later calls wait for them. + * an async generator. return() is passed to it once no next() is pending, + * and later calls wait for it. * - * While a next() is pending, return() or throw() stops the merge at once, as - * pull() does: the pending calls resolve with `{ done: true, value: undefined - * }`, `interrupt()` lets the merge close the sources, and the iterator is - * closed without waiting for it. The later results of the pending calls, and - * any error from closing the iterator, are ignored. + * While a next() is pending, return() stops the merge at once, as pull() + * does: the pending calls resolve with `{ done: true, value: undefined }`, + * `interrupt()` lets the merge close the sources, and the iterator is closed + * without waiting for it. The later results of the pending calls, and any + * error from closing the iterator, are ignored. + * + * throw() waits until the pending next() calls have settled, and then stops + * the merge as a return() made then would, ignoring errors from closing it, + * and rejects with its argument. A return() made while it waits stops the + * merge at once, and the throw() then rejects with its argument. */ class MergeIterator { #open; @@ -530,6 +535,9 @@ class MergeIterator { #pending = new RingBuffer(); // The promise of return() or throw() once one is called. #closing = null; + // While a throw() waits for the pending next() calls, the function + // resolving #closing. + #resolveThrow = null; // Whether a next() call has rejected because `signal` aborted: every // pending and later next() call then rejects with its reason. #aborted = false; @@ -562,7 +570,9 @@ class MergeIterator { // Once stopped, #pending is empty, and the results are ignored. #onResult = (result) => { - if (this.#pending.length > 0) this.#pending.shift().resolve(result); + if (this.#pending.length === 0) return; + this.#pending.shift().resolve(result); + if (this.#pending.length === 0) this.#idle(); }; #onError = (error) => { @@ -575,14 +585,29 @@ class MergeIterator { this.#aborted = true; while (this.#pending.length > 0) this.#pending.shift().reject(error); } + if (this.#pending.length === 0) this.#idle(); }; + // The pending calls have settled: a throw() waiting for them closes the + // iterator, as a return() made now would. + #idle() { + const resolve = this.#resolveThrow; + if (resolve === null) return; + this.#resolveThrow = null; + resolve(this.#close(this.#iterator.return)); + } + return(value) { + if (this.#pending.length > 0) { + // Pending, possibly with a throw() waiting. + this.#stop(); + return PromiseResolve(new IterResult(true, value)); + } if (this.#closing !== null) { const settle = () => new IterResult(true, value); return PromisePrototypeThen(this.#closing, settle, settle); } - if (this.#iterator === null || this.#pending.length > 0) { + if (this.#iterator === null) { this.#stop(); return PromiseResolve(new IterResult(true, value)); } @@ -590,15 +615,25 @@ class MergeIterator { } throw(error) { + const settle = () => { throw error; }; if (this.#closing !== null) { - const settle = () => { throw error; }; return PromisePrototypeThen(this.#closing, settle, settle); } - if (this.#iterator === null || this.#pending.length > 0) { + if (this.#iterator === null) { this.#stop(); return PromiseReject(error); } - return this.#close(this.#iterator.throw, error); + if (this.#pending.length === 0) { + return PromisePrototypeThen( + this.#close(this.#iterator.return), settle, settle); + } + // Wait for the pending calls (see #idle()). Later calls wait for the + // throw(). + const closing = newPendingPromise(); + this.#resolveThrow = takeResolve(); + takeReject(); + this.#closing = closing; + return PromisePrototypeThen(closing, settle, settle); } // Pass return() or throw() on: later calls wait for it. @@ -615,8 +650,13 @@ class MergeIterator { return closing; } - // Stop before the iterator is opened, or while a next() is pending. + // Stop before the iterator is opened, or while a next() is pending. A + // throw() waiting for the pending calls then rejects without closing the + // iterator again. #stop() { + const resolveThrow = this.#resolveThrow; + this.#resolveThrow = null; + resolveThrow?.(); this.#closing = kResolvedPromise; const iterator = this.#iterator; if (iterator === null) return; diff --git a/lib/internal/streams/iter/from.js b/lib/internal/streams/iter/from.js index 48bd94409b1c..b2ff45f8c23a 100644 --- a/lib/internal/streams/iter/from.js +++ b/lib/internal/streams/iter/from.js @@ -51,6 +51,7 @@ const { RingBuffer } = require('internal/streams/iter/ringbuffer'); const { IterResult, PendingRequest, + QueuedThrow, kActive, kDone, kResolvedPromise, @@ -230,8 +231,9 @@ function createNormalizationIterator(createIterator) { context, lazyDOMException('Aborted', 'AbortError')); return FunctionPrototypeCall(iterator.return, iterator, value); }, + // Queued after the pending calls: the normalizer cancels the + // normalization once it runs (see doThrow()). throw(error) { - cancelNormalization(context, error, true); return FunctionPrototypeCall(iterator.throw, iterator, error); }, [kNextUncancellable](releasable) { @@ -253,8 +255,9 @@ function createNormalizationIterator(createIterator) { context, lazyDOMException('Aborted', 'AbortError')); return FunctionPrototypeCall(iterator.return, iterator, value); }, + // Queued after the pending calls: the normalizer cancels the + // normalization once it runs (see doThrow()). throw(error) { - cancelNormalization(context, error, true); return FunctionPrototypeCall(iterator.throw, iterator, error); }, [kNextSyncBatch]() { @@ -283,9 +286,20 @@ function createNormalizationIterator(createIterator) { * @returns {object} */ function createInterruptibleIterator(iterator, context) { - // The settling functions of the pending next() calls, in order. + // The settling functions of the pending next() calls, in order, and the + // promise of the last one. const pending = new RingBuffer(); + let lastNext = null; let interrupted = false; + // A throw() waiting for the pending calls, if any: see QueuedThrow. + let queuedThrow = null; + + // throw() once no earlier call is pending: cancel the normalization, and + // pass it on, which closes the source. + function stopForThrow(error) { + cancelNormalization(context, error, true); + return FunctionPrototypeCall(iterator.throw, iterator, error); + } function onResult(result) { if (pending.length > 0) pending.shift().resolve(result); @@ -297,6 +311,7 @@ function createInterruptibleIterator(iterator, context) { return ObjectSetPrototypeOf({ next(value) { + if (queuedThrow?.waiting) return queuedThrow.next(); if (interrupted) return PromiseResolve(new IterResult(true, undefined)); let next; try { @@ -307,6 +322,7 @@ function createInterruptibleIterator(iterator, context) { } const promise = newPendingPromise(); pending.push(new PendingRequest(takeResolve(), takeReject())); + lastNext = promise; PromisePrototypeThen(next, onResult, onError); return promise; }, @@ -314,12 +330,15 @@ function createInterruptibleIterator(iterator, context) { cancelNormalization( context, lazyDOMException('Aborted', 'AbortError')); if (interrupted || pending.length === 0) { + queuedThrow?.abandon(); return FunctionPrototypeCall(iterator.return, iterator, value); } interrupted = true; while (pending.length > 0) { pending.shift().resolve(new IterResult(true, undefined)); } + // A throw() waiting for them rejects with its argument. + queuedThrow?.abandon(); let closed; try { closed = FunctionPrototypeCall(iterator.return, iterator); @@ -330,9 +349,14 @@ function createInterruptibleIterator(iterator, context) { markPromiseAsHandled(PromiseResolve(closed)); return PromiseResolve(new IterResult(true, value)); }, + // Waits for the pending next() calls, as the iterator would, but + // without passing later calls on before the throw() has run. throw(error) { - cancelNormalization(context, error, true); - return FunctionPrototypeCall(iterator.throw, iterator, error); + if (queuedThrow?.waiting || pending.length > 0) { + queuedThrow ??= new QueuedThrow(stopForThrow); + return queuedThrow.throw(error, lastNext); + } + return stopForThrow(error); }, [SymbolAsyncIterator]() { return this; @@ -1344,7 +1368,9 @@ function createAsyncSourceNormalizer(source, context) { return PromisePrototypeThen(closed, () => finish(result), fail); } + // Once the calls before it have settled, as the specification requires. function doThrow(error) { + cancelNormalization(context, error, true); if (state !== kActive) { state = kDone; settled(); @@ -1808,7 +1834,9 @@ function createSyncSourceNormalizer(source, context) { }); } + // Once the calls before it have settled, as the specification requires. function doThrow(error) { + cancelNormalization(context, error, true); if (done) { settled(); return PromiseReject(error); diff --git a/lib/internal/streams/iter/pull.js b/lib/internal/streams/iter/pull.js index d5c0870ebfaa..f1c615322d0c 100644 --- a/lib/internal/streams/iter/pull.js +++ b/lib/internal/streams/iter/pull.js @@ -984,12 +984,6 @@ class PipelineSource { return this; } - // Whether the source is read with kNextUncancellable (known once it has - // been read). - get uncancellable() { - return this.#uncancellable && this.#iterator !== null; - } - next() { if (this.#abort.aborted) return PromiseReject(this.#abort.reason); if (this.#closed) return PromiseResolve(new IterResult(true, undefined)); @@ -1097,6 +1091,17 @@ function createAsyncTransformLayers(normalized, transforms, abort, return current; } +// Methods of a pull() pipeline's iterator for pullWithConsumerCleanup(): one +// tears the pipeline down as an abort of its signal does, for a cancel() of +// the consumer with a reason, and one sets a function that throw() calls +// once it runs, when no earlier call is pending. +const kAbortPipeline = Symbol('kAbortPipeline'); +const kSetThrowHook = Symbol('kSetThrowHook'); + +// A method of a push readable's iterator: stop reading as return() does, but +// error the writer with the given reason (see DuplexChannel abort()). +const kCancelConsumer = Symbol('kCancelConsumer'); + /** * The iterator of a pull() pipeline, also used by pipeTo() for transforms: an * async iterator doing what an async generator would, written out by hand to @@ -1119,7 +1124,9 @@ function createAsyncTransformLayers(normalized, transforms, abort, * later pulls report the end. When it calls return() while a pull is * pending, that pull and those queued after it report the end at once, as * does return(), and the source and the transforms are closed without - * waiting (see interrupt()). + * waiting (see interrupt()). throw() is queued as next() is: once the calls + * before it have settled, it stops the pipeline as return() would then, + * and rejects with its argument. * * A pending pull can only be rejected at once if it is a promise of its own, * one more for every batch. Without a signal, pipeTo() never stops the @@ -1147,11 +1154,11 @@ function createAsyncPipeline(source, transforms, signal, // runs one pull at a time. let resolvePull = null; let rejectPull = null; - // See stop(). - let closeWithoutWaiting = false; - // Whether the consumer has called return() or throw(): later pulls report - // the end, even once `signal` has aborted. + // Whether the consumer has called return(), or a throw() has run: later + // pulls report the end, even once `signal` has aborted. let consumerStopped = false; + // See kSetThrowHook. + let throwHook = null; const operations = createOperationQueue(); const self = ObjectSetPrototypeOf({ @@ -1159,13 +1166,19 @@ function createAsyncPipeline(source, transforms, signal, return(value) { consumerStopped = true; if (resolvePull !== null) return interrupt(value); - stop(lazyDOMException('Aborted', 'AbortError')); + stop(); return operations.run(doReturn, value); }, - throw(error) { - consumerStopped = true; - stop(error); - return operations.run(doThrow, error); + throw(error) { return operations.run(doThrow, error); }, + [kAbortPipeline](reason) { + if (state !== kActive) { + state = kDone; + return; + } + abortPipeline(reason, true); + }, + [kSetThrowHook](hook) { + throwHook = hook; }, [SymbolAsyncIterator]() { return this; }, }, null); @@ -1206,25 +1219,12 @@ function createAsyncPipeline(source, transforms, signal, }); } - // The consumer stops early: abort the pipeline at once, so that the - // transforms see their signal aborted before they are closed and a pending - // pull rejects; doReturn() or doThrow() then closes the transforms. - function stop(reason) { + // The consumer stops early, with no pull pending (see interrupt()): abort + // the pipeline at once, so that the transforms see their signal aborted + // before doReturn() or doThrow() closes them. + function stop() { if (state !== kActive) return; - if (rejectPull !== null) { - abortPipeline(reason, false); - state = kActive; - // The pending pull is waiting for a read of the source that is now - // ignored, and with uncancellable reads nothing settles that read - // early: closing the transforms would wait for it, as a transform - // layer's return() waits for its pending next(). The transforms are - // all stateless then (see PipelineSource), so nothing but stream/iter - // code waits for them, and doReturn() / doThrow() close them without - // waiting. The source has already been closed. - closeWithoutWaiting = pipelineSource.uncancellable; - } else { - abort.abort(reason); - } + abort.abort(lazyDOMException('Aborted', 'AbortError')); } // return() while a pull is pending: abort the pipeline, so that the @@ -1427,11 +1427,6 @@ function createAsyncPipeline(source, transforms, signal, } state = kDone; removeSignalListener(); - if (closeWithoutWaiting) { - markPromiseAsHandled(closeAsyncIterator(iterator, false)); - operations.settled(); - return PromiseResolve(result); - } return PromisePrototypeThen( closeAsyncIterator(iterator, false), () => { operations.settled(); @@ -1442,24 +1437,28 @@ function createAsyncPipeline(source, transforms, signal, }); } + // throw() once the calls before it have settled: stop as return() would + // then, ignoring errors closing the transforms and the source, and reject + // with `error`. function doThrow(error) { + consumerStopped = true; + const hook = throwHook; + throwHook = null; if (state !== kActive) { state = kDone; + hook?.(); operations.settled(); return PromiseReject(error); } + stop(); state = kDone; removeSignalListener(); - if (closeWithoutWaiting) { - markPromiseAsHandled(closeAsyncIterator(iterator, true)); + const closed = closeAsyncIterator(iterator, true); + hook?.(); + return PromisePrototypeThen(closed, () => { operations.settled(); - return PromiseReject(error); - } - return PromisePrototypeThen( - closeAsyncIterator(iterator, true), () => { - operations.settled(); - throw error; - }); + throw error; + }); } return self; @@ -1565,6 +1564,10 @@ function pull(source, ...args) { }; } +function rethrow(error) { + throw error; +} + // Keep ownership of a bonded consumer outside the transform pipeline so it can // be detached even when the pipeline never starts or terminates early. // @@ -1586,15 +1589,23 @@ function pullWithConsumerCleanup(source, transforms, signal) { let sourceClosed = false; let abortHandler; - function closeSource(method, value) { + // Stop the consumer: as by its return(), or, given an `error`, for an + // error of the pipeline or an abort, which errors a push() writer with it + // (kCancelConsumer). The consumer's own throw() is not used: it would wait + // for its pending reads. + function closeSource(withError, error) { if (sourceClosed) return; sourceClosed = true; if (abortHandler !== undefined) { signal.removeEventListener('abort', abortHandler); } - const close = sourceIterator[method] ?? sourceIterator.return; + if (withError && typeof sourceIterator[kCancelConsumer] === 'function') { + sourceIterator[kCancelConsumer](error); + return; + } + const close = sourceIterator.return; if (typeof close === 'function') { - const result = FunctionPrototypeCall(close, sourceIterator, value); + const result = FunctionPrototypeCall(close, sourceIterator); const cleanup = PromisePrototypeThen( PromiseResolve(result), undefined, undefined); markPromiseAsHandled(cleanup); @@ -1602,7 +1613,7 @@ function pullWithConsumerCleanup(source, transforms, signal) { } if (signal?.aborted) { - closeSource('throw', signal.reason); + closeSource(true, signal.reason); return createAbortedIterable(signal.reason); } @@ -1611,11 +1622,15 @@ function pullWithConsumerCleanup(source, transforms, signal) { pull(pipelineSource, ...transforms, { __proto__: null, signal }); if (signal !== undefined) { - abortHandler = () => closeSource('throw', signal.reason); + abortHandler = () => closeSource(true, signal.reason); signal.addEventListener('abort', abortHandler, kNullOnceOption); if (signal.aborted) abortHandler(); } + function closeSourceForThrow() { + closeSource(false); + } + // The pipelines created, whether the consumer has been stopped, and the // reason it was cancelled with, if any. const iterators = []; @@ -1639,8 +1654,11 @@ function pullWithConsumerCleanup(source, transforms, signal) { cancelReason = reason; } for (let i = 0; i < iterators.length; i++) { - markPromiseAsHandled(hasCancelReason ? - iterators[i].throw(reason) : iterators[i].return()); + if (hasCancelReason) { + iterators[i][kAbortPipeline](reason); + } else { + markPromiseAsHandled(iterators[i].return()); + } } }); } @@ -1650,6 +1668,8 @@ function pullWithConsumerCleanup(source, transforms, signal) { [SymbolAsyncIterator]() { const iterator = pipeline[SymbolAsyncIterator](); ArrayPrototypePush(iterators, iterator); + // The consumer is stopped when the pipeline's throw() runs. + iterator[kSetThrowHook](closeSourceForThrow); return ObjectSetPrototypeOf({ next(value) { if (stopped) { @@ -1659,11 +1679,11 @@ function pullWithConsumerCleanup(source, transforms, signal) { return PromisePrototypeThen( iterator.next(value), (result) => { - if (result.done) closeSource('return'); + if (result.done) closeSource(false); return result; }, (error) => { - closeSource('throw', error); + closeSource(true, error); throw error; }); }, @@ -1673,12 +1693,16 @@ function pullWithConsumerCleanup(source, transforms, signal) { // the end at once and no transform is flushed. Then the writer is // cancelled, or the cursor detached. const result = iterator.return(value); - closeSource('return', value); + closeSource(false); return result; }, + // Waits for the pending next() calls, as pull()'s throw() does, and + // then stops the pipeline and the consumer as return() does. It + // settles a reaction later, as next() does, so that the calls settle + // in order. throw(error) { - closeSource('throw', error); - return iterator.throw(error); + return PromisePrototypeThen(iterator.throw(error), undefined, + rethrow); }, [SymbolAsyncIterator]() { return this; @@ -2169,6 +2193,7 @@ async function pipeTo(source, ...args) { } module.exports = { + kCancelConsumer, kSetConsumerStop, pipeTo, pipeToSync, diff --git a/lib/internal/streams/iter/push.js b/lib/internal/streams/iter/push.js index c9cbc3b71465..59e72f344738 100644 --- a/lib/internal/streams/iter/push.js +++ b/lib/internal/streams/iter/push.js @@ -13,7 +13,6 @@ const { PromiseResolve, PromiseWithResolvers, SafeWeakSet, - Symbol, SymbolAsyncDispose, SymbolAsyncIterator, SymbolDispose, @@ -36,6 +35,7 @@ const { IterResult, PendingRequest, PendingWrite, + QueuedThrow, kNullOnceOption, kPushDefaultBudget, kResolvedPromise, @@ -58,6 +58,7 @@ const { } = require('internal/streams/iter/webidl'); const { + kCancelConsumer, pullWithConsumerCleanup, } = require('internal/streams/iter/pull'); @@ -67,10 +68,6 @@ const { const consumerReturnErrors = new SafeWeakSet(); -// A method of a push readable's iterator: stop reading as return() does, but -// error the writer with the given reason (see DuplexChannel abort()). -const kCancelConsumer = Symbol('kCancelConsumer'); - function isConsumerReturnError(error) { return consumerReturnErrors.has(error); } @@ -116,12 +113,10 @@ class PushQueue { #pendingDrains = []; /** Writer state: 'open' | 'closing' | 'closed' | 'errored' */ #writerState = 'open'; - /** Consumer state: 'active' | 'returned' | 'thrown' */ + /** Consumer state: 'active' | 'returned' */ #consumerState = 'active'; /** Error that closed the writer */ #writerError; - /** Error supplied by the consumer */ - #consumerError; /** Total bytes written */ #bytesWritten = 0; /** Pending end promise (resolves when consumer drains past end sentinel) */ @@ -290,7 +285,6 @@ class PushQueue { throw this.#writerError; } if (this.#consumerState !== 'active') { - if (this.#consumerState === 'thrown') throw this.#consumerError; throw new ERR_INVALID_STATE.TypeError('Stream closed by consumer'); } @@ -478,6 +472,11 @@ class PushQueue { // Consumer Methods // =========================================================================== + // Whether a read is waiting for data. + get hasPendingReads() { + return this.#pendingReads.length > 0; + } + async read() { // After the consumer's return() or throw(), reads report the end. if (this.#consumerState !== 'active') { @@ -535,17 +534,6 @@ class PushQueue { if (stopped) this.#stop(error); } - consumerThrow(error) { - if (this.#consumerState !== 'active') return; - this.#consumerState = 'thrown'; - this.#consumerError = error; - this.#rejectPendingReads(error); - const stopped = this.#terminateWriterFromConsumer(error); - // Reject pending drains - the consumer errored - this.#rejectPendingDrains(error); - if (stopped) this.#stop(error); - } - // =========================================================================== // Private Methods // =========================================================================== @@ -629,9 +617,6 @@ class PushQueue { if (this.#consumerState === 'returned') { const pending = this.#pendingReads.shift(); pending.resolve(new IterResult(true, undefined)); - } else if (this.#consumerState === 'thrown') { - const pending = this.#pendingReads.shift(); - pending.reject(this.#consumerError); } else if (this.#slots.length > 0) { const pending = this.#pendingReads.shift(); try { @@ -861,7 +846,22 @@ class PushWriter { // Readable Implementation // ============================================================================= +async function readNext(queue) { + return queue.read(); +} + +// throw() once no read is pending: the consumer stops as by return(), which +// cancels the writer without an error, and the throw() rejects. +function stopForThrow(queue, error) { + queue.consumerReturn(); + return PromiseReject(error); +} + function createReadable(queue) { + // The promise of the last next() call (reads settle in order), and the + // throw() waiting for it, if any: see QueuedThrow. + let lastNext = null; + let queuedThrow = null; return { __proto__: null, // The batches read are validated already: from() and pipeTo() can read @@ -869,16 +869,25 @@ function createReadable(queue) { [kValidatedSource]: true, [SymbolAsyncIterator]() { return ObjectSetPrototypeOf({ - async next() { - return queue.read(); + next() { + if (queuedThrow?.waiting) return queuedThrow.next(); + lastNext = readNext(queue); + return lastNext; }, + // A throw() waiting for the pending reads, which this settles, + // then rejects with its argument. async return(value) { queue.consumerReturn(); return new IterResult(true, value); }, - async throw(error) { - queue.consumerThrow(error); - throw error; + // Waits for the pending reads, then stops as return() does. + throw(error) { + if (queuedThrow?.waiting || queue.hasPendingReads) { + queuedThrow ??= new QueuedThrow( + (error) => stopForThrow(queue, error)); + return queuedThrow.throw(error, lastNext); + } + return stopForThrow(queue, error); }, [kCancelConsumer](reason) { queue.consumerCancel(reason); diff --git a/lib/internal/streams/iter/share.js b/lib/internal/streams/iter/share.js index b11bfc3e21ca..1e6deb788885 100644 --- a/lib/internal/streams/iter/share.js +++ b/lib/internal/streams/iter/share.js @@ -42,6 +42,7 @@ const { const { IterResult, PendingRequest, + QueuedThrow, kMultiConsumerDefaultBudget, createAbortedIterable, createEntry, @@ -209,6 +210,8 @@ class ShareImpl { requests: null, onReadResult: undefined, onReadError: undefined, + // A throw() waiting for pendingNext, if any (see QueuedThrow). + queuedThrow: null, }, null); this.#consumers.add(state); @@ -222,6 +225,26 @@ class ShareImpl { } const self = this; + // A pending next() resolves with the end at once, without waiting for + // the source. A pull of the source that it was waiting for still + // completes, for the other consumers. + function detach() { + state.detached = true; + state.resolve = null; + state.reject = null; + if (self.#deleteConsumer(state)) { + self.#tryTrimBuffer(); + } + self.#endReads(state); + } + + // throw() once no read is pending: stop as return() does. + function stopForThrow(error) { + detach(); + state.error = kNoShareError; + return PromiseReject(error); + } + return { __proto__: null, [kSetConsumerStop](stop) { @@ -254,6 +277,7 @@ class ShareImpl { return ObjectSetPrototypeOf({ next() { + if (state.queuedThrow?.waiting) return state.queuedThrow.next(); if (state.pendingNext !== null) { return self.#trackRead( state, PromisePrototypeThen(state.pendingNext, read, read)); @@ -270,30 +294,22 @@ class ShareImpl { return self.#waitForRead(state); }, - // A pending next() resolves with the end at once, without waiting - // for the source. A pull of the source that it was waiting for - // still completes, for the other consumers. + // Later reads report the end, even if the source had failed. async return() { - state.detached = true; - state.resolve = null; - state.reject = null; - if (self.#deleteConsumer(state)) { - self.#tryTrimBuffer(); - } - self.#endReads(state); + detach(); + state.error = kNoShareError; + state.queuedThrow?.abandon(); return new IterResult(true, undefined); }, - // Stops the consumer as return() does, then rejects with `error`. - async throw(error) { - state.detached = true; - state.resolve = null; - state.reject = null; - if (self.#deleteConsumer(state)) { - self.#tryTrimBuffer(); + // Once the pending next() calls have settled, stops the consumer + // as return() does, then rejects with `error`. + throw(error) { + if (state.queuedThrow?.waiting || state.pendingNext !== null) { + state.queuedThrow ??= new QueuedThrow(stopForThrow); + return state.queuedThrow.throw(error, state.pendingNext); } - self.#endReads(state); - throw error; + return stopForThrow(error); }, }, null); }, diff --git a/lib/internal/streams/iter/utils.js b/lib/internal/streams/iter/utils.js index 056ff524e0e0..70a55e392104 100644 --- a/lib/internal/streams/iter/utils.js +++ b/lib/internal/streams/iter/utils.js @@ -750,6 +750,107 @@ function createOperationQueue() { }; } +// A next() or throw() call made while a throw() of a consumer waits: see +// QueuedThrow. +class QueuedCall { + constructor(isThrow, error, resolve, reject) { + this.isThrow = isThrow; + this.error = error; + this.resolve = resolve; + this.reject = reject; + } +} + +/** + * Serves throw() in order for an iterator whose next() calls settle in the + * order they are made, and which settles a throw() made with no next() + * pending at once (the iterators of push(), Broadcast.push(), + * Share.pull() and some from() iterators). As the specification requires, + * a throw() made while a next() is pending waits until that call, and so + * every earlier one, has settled: the pending calls settle as they would + * have, not with the thrown error. The throw() is then handled by + * `stop(error)`, which stops the iterator as return() does and returns the + * promise of the throw(). The calls made while it waits wait behind it, and + * settle once it has: next() with the end, throw() rejecting with its + * argument. A return() while it waits calls abandon(). + */ +class QueuedThrow { + #stop; + // The calls waiting, the first a throw(), or null if none is. + #calls = null; + + constructor(stop) { + this.#stop = stop; + } + + // Whether a throw() is waiting: later calls then go through this. + get waiting() { + return this.#calls !== null; + } + + // throw(error) while a next() is pending, `last` being the promise of the + // last next() call, or while a throw() is waiting. + throw(error, last) { + const promise = newPendingPromise(); + const call = new QueuedCall(true, error, takeResolve(), takeReject()); + if (this.#calls === null) { + this.#calls = new RingBuffer(1); + PromisePrototypeThen(last, this.#onSettled, this.#onSettled); + } + this.#calls.push(call); + return promise; + } + + // next() while a throw() is waiting. + next() { + const promise = newPendingPromise(); + this.#calls.push(new QueuedCall(false, undefined, takeResolve(), + takeReject())); + return promise; + } + + // return() while a throw() is waiting: the waiting calls settle at once. + abandon() { + const calls = this.#calls; + if (calls === null) return; + this.#calls = null; + settleQueuedCalls(calls); + } + + #onSettled = () => { + const calls = this.#calls; + if (calls === null) return; // Abandoned. + this.#calls = null; + const first = calls.shift(); + let result; + try { + result = this.#stop(first.error); + } catch (error) { + result = PromiseReject(error); + } + // The calls after it settle once it has. + PromisePrototypeThen(result, (value) => { + first.resolve(value); + settleQueuedCalls(calls); + }, (error) => { + first.reject(error); + settleQueuedCalls(calls); + }); + }; +} +ObjectSetPrototypeOf(QueuedThrow.prototype, null); + +function settleQueuedCalls(calls) { + while (calls.length > 0) { + const call = calls.shift(); + if (call.isThrow) { + call.reject(call.error); + } else { + call.resolve(new IterResult(true, undefined)); + } + } +} + /** * Validate an explicit `budget` option. The spec only requires the default * budget to be at least 16384 bytes; any positive explicit budget is valid. @@ -1203,6 +1304,7 @@ module.exports = { PendingRequest, PendingWrite, PipelineAbort, + QueuedThrow, kMultiConsumerDefaultBudget, kNullOnceOption, kPushDefaultBudget, diff --git a/test/parallel/test-stream-iter-abort-pending-read.js b/test/parallel/test-stream-iter-abort-pending-read.js index 0dcc5db8855f..2ca7a322ea32 100644 --- a/test/parallel/test-stream-iter-abort-pending-read.js +++ b/test/parallel/test-stream-iter-abort-pending-read.js @@ -90,7 +90,8 @@ async function testPullReturn() { assert.deepStrictEqual(log, ['next', 'next', 'return']); } -// The same, stopped with throw(). +// throw() while a pull is pending waits for it: the pull settles with the +// source's batch, and the source is then closed. async function testPullThrow() { const { source, log, release } = pendingSource(); const it = pull(from(source), (c) => c)[Symbol.asyncIterator](); @@ -99,12 +100,12 @@ async function testPullThrow() { await tick(); const error = new Error('thrown'); const thrown = it.throw(error); - await assert.rejects(pending, error); - await assert.rejects(thrown, error); - assert.deepStrictEqual(log, ['next', 'next', 'return']); - release(); - await tick(); await tick(); + assert.deepStrictEqual(log, ['next', 'next']); + release(); + assert.deepStrictEqual({ ...await pending }, + { done: false, value: [new Uint8Array([2])] }); + await assert.rejects(thrown, error); assert.deepStrictEqual(log, ['next', 'next', 'return']); } diff --git a/test/parallel/test-stream-iter-consumer-throw.js b/test/parallel/test-stream-iter-consumer-throw.js index 6c27287fa60a..adba509d82eb 100644 --- a/test/parallel/test-stream-iter-consumer-throw.js +++ b/test/parallel/test-stream-iter-consumer-throw.js @@ -3,42 +3,62 @@ // throw(error) on the iterators of push(), pull(), Broadcast.push(), // Share.pull() and merge() stops them as return() does and rejects with -// the error. Later next() calls report the end. +// the error, once a pending next() has settled. Later next() calls report +// the end. const common = require('../common'); const assert = require('assert'); const { setImmediate } = require('timers/promises'); const { broadcast, merge, pull, push, share } = require('stream/iter'); +// Each gives an iterable and its writer, which ends it. +function withPush(create) { + return () => { + const { writer, readable } = push(); + return { iterable: create(readable), writer }; + }; +} + const factories = { - 'push': () => push().readable, - 'push with transforms': () => push((c) => c).readable, - 'pull': () => pull(push().readable, (c) => c), - 'broadcast': () => broadcast().broadcast.push(), - 'broadcast with transforms': () => broadcast().broadcast.push((c) => c), - 'share': () => share(push().readable).pull(), - 'share with transforms': () => share(push().readable).pull((c) => c), - 'merge': () => merge(push().readable), + 'push': () => push(), + 'push with transforms': () => push((c) => c), + 'pull': withPush((readable) => pull(readable, (c) => c)), + 'broadcast': () => { + const { writer, broadcast: bc } = broadcast(); + return { iterable: bc.push(), writer }; + }, + 'broadcast with transforms': () => { + const { writer, broadcast: bc } = broadcast(); + return { iterable: bc.push((c) => c), writer }; + }, + 'share': withPush((readable) => share(readable).pull()), + 'share with transforms': withPush((readable) => share(readable).pull((c) => c)), + 'merge': withPush((readable) => merge(readable)), }; async function testThrow() { for (const [name, create] of Object.entries(factories)) { for (const withPending of [false, true]) { - const it = create()[Symbol.asyncIterator](); + const { iterable, readable, writer } = create(); + const it = (iterable ?? readable)[Symbol.asyncIterator](); let pending; if (withPending) { pending = it.next(); - pending.catch(() => {}); await setImmediate(); } const error = new Error('thrown'); - await assert.rejects(it.throw(error), (e) => e === error, name); + const thrown = it.throw(error); if (pending !== undefined) { - // A pending next() is settled. - await pending.then( - (result) => assert.strictEqual(result.done, true, name), - (e) => assert.strictEqual(e, error, name)); + // throw() waits for the pending next(), which settles as it would + // have: with the end, once the writer ends. + let settled = false; + thrown.catch(() => { settled = true; }); + await setImmediate(); + assert.strictEqual(settled, false, name); + writer.endSync(); + assert.strictEqual((await pending).done, true, name); } + await assert.rejects(thrown, (e) => e === error, name); assert.strictEqual((await it.next()).done, true, name); } } @@ -58,13 +78,14 @@ async function testCancelled() { } } -// A push() writer sees the thrown error. +// A push() writer sees the consumer stop as by return(), not the thrown +// error. async function testPushWriter() { const { writer, readable } = push(); const error = new Error('thrown'); await assert.rejects(readable[Symbol.asyncIterator]().throw(error), error); - await assert.rejects(writer.write('a'), error); - assert.strictEqual(writer.signal.reason, error); + await assert.rejects(writer.write('a'), { code: 'ERR_INVALID_STATE' }); + assert.strictEqual(writer.signal.reason.code, 'ERR_INVALID_STATE'); } Promise.all([ diff --git a/test/parallel/test-stream-iter-merge-return.js b/test/parallel/test-stream-iter-merge-return.js index d1f39a081cd4..7ea7e965fd48 100644 --- a/test/parallel/test-stream-iter-merge-return.js +++ b/test/parallel/test-stream-iter-merge-return.js @@ -1,10 +1,12 @@ // Flags: --experimental-stream-iter 'use strict'; -// return() or throw() on a merge() iterator while a next() is pending -// fulfills the pending next() with { done: true, value: undefined } at once, -// and calls return() on the sources without waiting for it to settle, also -// for a source suspended in an await. +// return() on a merge() iterator while a next() is pending fulfills the +// pending next() with { done: true, value: undefined } at once, and calls +// return() on the sources without waiting for it to settle, also for a +// source suspended in an await. throw() waits for the pending next(), so a +// return() made while it waits does the same, and the throw() then rejects +// with its argument. const common = require('../common'); const assert = require('assert'); @@ -86,8 +88,18 @@ async function testThrowWithPendingNext() { await setImmediate(); const error = new Error('thrown'); const thrown = iterator.throw(error); + let settled = false; + for (const promise of [pending, thrown]) { + Promise.allSettled([promise]).then(common.mustCall(() => { + settled = true; + })); + } + await setImmediate(); + assert.strictEqual(settled, false, name); + const returned = iterator.return(); assert.deepStrictEqual({ ...await pending }, done, name); await assert.rejects(thrown, error, name); + assert.deepStrictEqual({ ...await returned }, done, name); assert.deepStrictEqual({ ...await iterator.next() }, done, name); } } diff --git a/test/parallel/test-stream-iter-push-writer.js b/test/parallel/test-stream-iter-push-writer.js index 976a89dd1411..2ce882730223 100644 --- a/test/parallel/test-stream-iter-push-writer.js +++ b/test/parallel/test-stream-iter-push-writer.js @@ -182,7 +182,7 @@ async function testOndrainResolvesFalseOnConsumerBreak() { await pendingWrite.catch(() => {}); // Ignore write rejection } -async function testOndrainRejectsOnConsumerThrow() { +async function testOndrainResolvesFalseOnConsumerThrow() { const kChunk = new Uint8Array(16384); const { writer, readable } = push({ budget: 16384 }); @@ -197,18 +197,19 @@ async function testOndrainRejectsOnConsumerThrow() { const drainPromise = ondrain(writer); // Consumer throws via iterator.throw() before draining enough - // to clear backpressure. The drain should reject. + // to clear backpressure. It stops as by return(): the drain resolves + // with false, and the pending write rejects. const iter = readable[Symbol.asyncIterator](); const err = new Error('consumer error'); - const drainRejects = assert.rejects(drainPromise, (e) => e === err); - const pendingWriteRejects = pendingWrite.catch(() => {}); + const pendingWriteRejects = assert.rejects(pendingWrite, + { code: 'ERR_INVALID_STATE' }); await assert.rejects( () => iter.throw(err), (e) => e === err, ); - await drainRejects; - await pendingWriteRejects; // Ignore write rejection + assert.strictEqual(await drainPromise, false); + await pendingWriteRejects; } async function testWritev() { @@ -402,7 +403,7 @@ async function testOndrainWaitsForDrain() { writer.endSync(); } -// Consumer throw causes subsequent writes to reject with consumer's error +// Consumer throw causes subsequent writes to reject, as after return() async function testConsumerThrowRejectsWrites() { const kChunk = new Uint8Array(16384); const { writer, readable } = push({ budget: 16384 }); @@ -415,10 +416,11 @@ async function testConsumerThrowRejectsWrites() { (e) => e === err, ); - // Subsequent async writes should reject with the consumer's error + // Subsequent async writes reject as after return(), not with the + // consumer's error await assert.rejects( () => writer.write('x'), - { message: 'consumer boom' }, + { code: 'ERR_INVALID_STATE', name: 'TypeError' }, ); } @@ -499,9 +501,10 @@ async function testEndRejectsAfterConsumerReturn() { assert.strictEqual((await iter.next()).done, true); } -// iterator.throw() rejects a pending read with the thrown error -async function testConsumerThrowRejectsPendingRead() { - const { readable } = push(); +// iterator.throw() waits for a pending read, which gets the data written, +// and then rejects with the thrown error +async function testConsumerThrowWaitsForPendingRead() { + const { writer, readable } = push(); const iter = readable[Symbol.asyncIterator](); const readPromise = iter.next(); @@ -509,16 +512,13 @@ async function testConsumerThrowRejectsPendingRead() { await setImmediate(); const err = new Error('consumer read boom'); - const readRejects = assert.rejects( - () => readPromise, - (e) => e === err, - ); - await assert.rejects( - () => iter.throw(err), - (e) => e === err, - ); - - await readRejects; + const thrown = iter.throw(err); + writer.writeSync('a'); + const result = await readPromise; + assert.strictEqual(result.done, false); + assert.deepStrictEqual(result.value, [new TextEncoder().encode('a')]); + await assert.rejects(thrown, (e) => e === err); + assert.strictEqual(writer.canWrite, null); } // end() drains writes that were already pending, then waits for EOF to be read. @@ -716,7 +716,7 @@ Promise.all([ testWriteWithPreAbortedSignal(), testCancelledWriteRemovedFromQueue(), testOndrainResolvesFalseOnConsumerBreak(), - testOndrainRejectsOnConsumerThrow(), + testOndrainResolvesFalseOnConsumerThrow(), testWritev(), testWritevSync(), testWritevSyncInvalidChunkDoesNotQueue(), @@ -741,7 +741,7 @@ Promise.all([ testFailRejectsPendingReadWithFalsyReason(), testConsumerReturnResolvesPendingRead(), testEndRejectsAfterConsumerReturn(), - testConsumerThrowRejectsPendingRead(), + testConsumerThrowWaitsForPendingRead(), testEndDrainsPendingWrites(), testEndWaitsForEofPull(), testEndIdempotentWhenClosed(), diff --git a/test/parallel/test-stream-iter-reason-propagation.js b/test/parallel/test-stream-iter-reason-propagation.js index 5c815c0d76ac..8e9d2d73f353 100644 --- a/test/parallel/test-stream-iter-reason-propagation.js +++ b/test/parallel/test-stream-iter-reason-propagation.js @@ -228,7 +228,9 @@ async function testTransformReasons() { await rejectsWith(next, null); } -async function testIteratorThrowReasonReachesTransforms() { +// throw() rejects with its argument, even undefined. It stops the pipeline +// as return() does, so the transforms' signal aborts with an AbortError. +async function testIteratorThrowReason() { const reason = undefined; let observedReason; const transformed = pull(from('data'), (batch, { signal }) => { @@ -241,7 +243,7 @@ async function testIteratorThrowReasonReachesTransforms() { await iterator.next(); await rejectsWith(iterator.throw(reason), reason); - assert.strictEqual(observedReason, reason); + assert.strictEqual(observedReason.name, 'AbortError'); } async function testErroredWriterPrecedesOperationSignal() { @@ -281,7 +283,7 @@ Promise.all([ testExplicitUndefinedCancellation(), testPendingWriteAbortReasons(), testTransformReasons(), - testIteratorThrowReasonReachesTransforms(), + testIteratorThrowReason(), testErroredWriterPrecedesOperationSignal(), testCompletedBroadcastConsumerStaysCompleted(), ]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-throw-queued.js b/test/parallel/test-stream-iter-throw-queued.js new file mode 100644 index 000000000000..b19df44e00e5 --- /dev/null +++ b/test/parallel/test-stream-iter-throw-queued.js @@ -0,0 +1,355 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// throw(error) on the iterators of push(), pull(), Broadcast.push(), +// Share.pull(), merge() and from() is served in order: it waits until the +// next() calls made before it have settled, and those settle as they would +// have (with data, the end, or their own error). It then stops the iterator +// as return() would, and rejects with `error`. The calls made while it +// waits wait behind it: next() then reports the end, and throw() rejects +// with its own argument. A return() made while it waits settles the +// pending calls with the end at once, and the throw() rejects with +// `error`. With no call pending, throw() acts at once. + +const common = require('../common'); +const assert = require('assert'); +const { setImmediate } = require('timers/promises'); +const { + broadcast, duplex, from, merge, ondrain, pull, push, share, +} = require('stream/iter'); + +const done = { done: true, value: undefined }; +const bytesA = [new TextEncoder().encode('a')]; + +async function recordSettled(log, name, promise) { + await Promise.allSettled([promise]); + log.push(name); +} + +// Records the order in which promises settle. +function recorder() { + const log = []; + return { + log, + track(name, promise) { + recordSettled(log, name, promise); + return promise; + }, + }; +} + +// Each gives the iterator under test and the push() writer it reads from. +function fromPush(create) { + return () => { + const { writer, readable } = push(); + return { iterable: create(readable), writer }; + }; +} + +const statefulIdentity = { + async *transform(source) { + for await (const batch of source) { + if (batch !== null) yield batch; + } + }, +}; + +const factories = { + 'push': fromPush((readable) => readable), + 'push with transforms': () => { + const { writer, readable } = push((c) => c); + return { iterable: readable, writer }; + }, + 'pull': fromPush((readable) => pull(readable, (c) => c)), + 'pull with a stateful transform': fromPush( + (readable) => pull(readable, statefulIdentity)), + 'pull with a signal': fromPush( + (readable) => pull(readable, { signal: new AbortController().signal })), + 'broadcast': () => { + const { writer, broadcast: bc } = broadcast(); + return { iterable: bc.push(), writer }; + }, + 'broadcast with transforms': () => { + const { writer, broadcast: bc } = broadcast(); + return { iterable: bc.push((c) => c), writer }; + }, + 'share': fromPush((readable) => share(readable).pull()), + 'share with transforms': fromPush( + (readable) => share(readable).pull((c) => c)), + 'merge': fromPush((readable) => merge(readable)), + 'merge of two sources': fromPush( + (readable) => merge(readable, from([]))), + 'from() of an async generator': fromPush((readable) => from( + (async function*() { for await (const batch of readable) yield batch; })())), + 'from() of a toAsyncStreamable promise': fromPush((readable) => from({ + [Symbol.for('Stream.toAsyncStreamable')]() { + return Promise.resolve(readable); + }, + })), +}; + +// The pending next() gets the data written after throw() was called, then +// throw() rejects, and the calls made after it settle in order. +async function testPendingNextGetsData() { + for (const [name, create] of Object.entries(factories)) { + const { iterable, writer } = create(); + const it = iterable[Symbol.asyncIterator](); + const { log, track } = recorder(); + const pending = track('next', it.next()); + await setImmediate(); + const error = new Error('thrown'); + const thrown = track('throw', it.throw(error)); + const after = track('next after', it.next()); + const error2 = new Error('thrown again'); + const thrown2 = track('throw after', it.throw(error2)); + await setImmediate(); + assert.deepStrictEqual(log, [], name); + writer.writeSync('a'); + assert.deepStrictEqual({ ...await pending }, + { done: false, value: bytesA }, name); + await assert.rejects(thrown, (e) => e === error, name); + assert.deepStrictEqual({ ...await after }, done, name); + await assert.rejects(thrown2, (e) => e === error2, name); + assert.deepStrictEqual( + log, ['next', 'throw', 'next after', 'throw after'], name); + assert.deepStrictEqual({ ...await it.next() }, done, name); + } +} + +// The pending next() settles with the end, or with its own error, not with +// the thrown error. +async function testPendingNextSettlesNormally() { + for (const [name, create] of Object.entries(factories)) { + for (const how of ['end', 'fail']) { + const { iterable, writer } = create(); + const it = iterable[Symbol.asyncIterator](); + const pending = it.next(); + await setImmediate(); + const error = new Error('thrown'); + const thrown = it.throw(error); + const failure = new Error('failed'); + if (how === 'end') { + writer.endSync(); + assert.deepStrictEqual({ ...await pending }, done, name); + } else { + writer.fail(failure); + await assert.rejects(pending, (e) => e === failure, name); + } + await assert.rejects(thrown, (e) => e === error, name); + assert.deepStrictEqual({ ...await it.next() }, done, name); + } + } +} + +// return() while a throw() waits: the pending next() reports the end at +// once, and the throw() rejects with its argument. +async function testReturnWhileThrowWaits() { + for (const [name, create] of Object.entries(factories)) { + const { iterable } = create(); + const it = iterable[Symbol.asyncIterator](); + const { log, track } = recorder(); + const pending = track('next', it.next()); + await setImmediate(); + const error = new Error('thrown'); + const thrown = track('throw', it.throw(error)); + const after = track('next after', it.next()); + await setImmediate(); + const returned = it.return(); + assert.deepStrictEqual({ ...await pending }, done, name); + await assert.rejects(thrown, (e) => e === error, name); + assert.deepStrictEqual({ ...await after }, done, name); + assert.strictEqual((await returned).done, true, name); + assert.deepStrictEqual(log, ['next', 'throw', 'next after'], name); + assert.deepStrictEqual({ ...await it.next() }, done, name); + } +} + +// With no call pending, throw() rejects at once, without waiting for data. +async function testNoPendingCall() { + for (const [name, create] of Object.entries(factories)) { + for (const started of [false, true]) { + const { iterable, writer } = create(); + const it = iterable[Symbol.asyncIterator](); + if (started) { + writer.writeSync('a'); + assert.deepStrictEqual({ ...await it.next() }, + { done: false, value: bytesA }, name); + } + const error = new Error('thrown'); + await assert.rejects(it.throw(error), (e) => e === error, name); + assert.deepStrictEqual({ ...await it.next() }, done, name); + } + } +} + +// from() of a sync iterable whose value is a promise: throw() waits for it. +async function testFromNestedPromise() { + const { promise, resolve } = Promise.withResolvers(); + const it = from([promise])[Symbol.asyncIterator](); + const pending = it.next(); + await setImmediate(); + const error = new Error('thrown'); + const thrown = it.throw(error); + let settled = false; + thrown.catch(() => { settled = true; }); + await setImmediate(); + assert.strictEqual(settled, false); + resolve('a'); + assert.deepStrictEqual({ ...await pending }, { done: false, value: bytesA }); + await assert.rejects(thrown, (e) => e === error); + assert.deepStrictEqual({ ...await it.next() }, done); +} + +// The upstream is closed once throw() runs, not before. +async function testUpstreamClosedOnceThrowRuns() { + const log = []; + let release; + const source = { + [Symbol.asyncIterator]() { + return { + next() { + log.push('next'); + return new Promise((resolve) => { + release = () => resolve({ done: false, value: bytesA }); + }); + }, + return() { + log.push('return'); + return Promise.resolve(done); + }, + }; + }, + }; + for (const create of [ + () => from(source), + () => pull(source, (c) => c), + () => merge(source), + ]) { + log.length = 0; + const it = create()[Symbol.asyncIterator](); + const pending = it.next(); + await setImmediate(); + const error = new Error('thrown'); + const thrown = it.throw(error); + await setImmediate(); + assert.deepStrictEqual(log, ['next']); + release(); + assert.deepStrictEqual({ ...await pending }, + { done: false, value: bytesA }); + await assert.rejects(thrown, (e) => e === error); + assert.deepStrictEqual(log, ['next', 'return']); + } +} + +// The transforms' signal aborts once throw() runs, as for return(). +async function testTransformSignal() { + const { writer, readable } = push(); + let signal; + const it = pull(readable, (batch, options) => { + signal = options.signal; + return batch; + })[Symbol.asyncIterator](); + writer.writeSync('a'); + await it.next(); + const pending = it.next(); + await setImmediate(); + const error = new Error('thrown'); + const thrown = it.throw(error); + await setImmediate(); + assert.strictEqual(signal.aborted, false); + writer.writeSync('a'); + await pending; + await assert.rejects(thrown, (e) => e === error); + assert.strictEqual(signal.aborted, true); + assert.strictEqual(signal.reason.name, 'AbortError'); +} + +// A broadcast or share consumer is detached once throw() runs. +async function testConsumerDetached() { + const { writer, broadcast: bc } = broadcast(); + const it = bc.push()[Symbol.asyncIterator](); + const pending = it.next(); + await setImmediate(); + const thrown = it.throw(new Error('thrown')); + await setImmediate(); + assert.strictEqual(bc.consumerCount, 1); + writer.writeSync('a'); + await pending; + await assert.rejects(thrown, { message: 'thrown' }); + assert.strictEqual(bc.consumerCount, 0); + + const sh = share(from('a')); + const consumer = sh.pull()[Symbol.asyncIterator](); + await consumer.next(); + assert.strictEqual(sh.consumerCount, 1); + await assert.rejects(consumer.throw(new Error('thrown')), + { message: 'thrown' }); + assert.strictEqual(sh.consumerCount, 0); +} + +// A push() writer whose consumer threw is stopped as when the consumer +// returns: writes reject and writer.signal aborts with the same error as +// after return(), drain waiters resolve with false, and the other end of a +// duplex channel closes cleanly. +async function testPushWriter() { + for (const withTransforms of [false, true]) { + const { writer, readable } = withTransforms ? + push((c) => c, { budget: 1 }) : push({ budget: 1 }); + writer.writeSync('ab'); + const drain = ondrain(writer); + const it = readable[Symbol.asyncIterator](); + const error = new Error('thrown'); + await assert.rejects(it.throw(error), (e) => e === error); + assert.strictEqual(await drain, false); + assert.strictEqual(writer.canWrite, null); + await assert.rejects(writer.write('a'), + { code: 'ERR_INVALID_STATE', name: 'TypeError' }); + assert.strictEqual(writer.signal.aborted, true); + assert.strictEqual(writer.signal.reason.code, 'ERR_INVALID_STATE'); + } + + const [a, b] = duplex(); + await assert.rejects(b.readable[Symbol.asyncIterator]().throw( + new Error('thrown')), { message: 'thrown' }); + await a.close(); +} + +// After a failure, return() makes later reads of a broadcast or share +// consumer report the end, as throw() does. +async function testReturnAfterFailureReportsEnd() { + const error = new Error('boom'); + { + const { writer, broadcast: bc } = broadcast(); + const it = bc.push()[Symbol.asyncIterator](); + writer.fail(error); + await assert.rejects(it.next(), error); + await assert.rejects(it.next(), error); + assert.deepStrictEqual({ ...await it.return() }, done); + assert.deepStrictEqual({ ...await it.next() }, done); + } + { + async function* source() { + yield bytesA; + throw error; + } + const it = share(source()).pull()[Symbol.asyncIterator](); + await it.next(); + await assert.rejects(it.next(), error); + await assert.rejects(it.next(), error); + assert.deepStrictEqual({ ...await it.return() }, done); + assert.deepStrictEqual({ ...await it.next() }, done); + } +} + +(async () => { + await testPendingNextGetsData(); + await testPendingNextSettlesNormally(); + await testReturnWhileThrowWaits(); + await testNoPendingCall(); + await testFromNestedPromise(); + await testUpstreamClosedOnceThrowRuns(); + await testTransformSignal(); + await testConsumerDetached(); + await testPushWriter(); + await testReturnAfterFailureReportsEnd(); +})().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-writer-signal.js b/test/parallel/test-stream-iter-writer-signal.js index 921a8b7365c8..f266dbd71ce4 100644 --- a/test/parallel/test-stream-iter-writer-signal.js +++ b/test/parallel/test-stream-iter-writer-signal.js @@ -132,7 +132,8 @@ function assertAbortError(reason) { assert.strictEqual(signal.aborted, true); })().then(common.mustCall()); -// Consumer throw() aborts the signal with the thrown error. +// Consumer throw() stops the consumer as return() does: the signal aborts +// with the same reason as for return(), not with the thrown error. (async () => { const { writer, readable } = push(); const signal = writer.signal; @@ -140,7 +141,9 @@ function assertAbortError(reason) { const iterator = readable[Symbol.asyncIterator](); await assert.rejects(iterator.throw(error), error); assert.strictEqual(signal.aborted, true); - assert.strictEqual(signal.reason, error); + assert.notStrictEqual(signal.reason, error); + assert.strictEqual(signal.reason.code, 'ERR_INVALID_STATE'); + assert.strictEqual(signal.reason.name, 'TypeError'); })().then(common.mustCall()); // The consumer stopping after the writer already failed keeps the reason. From 5e64229b343f52df31cf4309777b72e22ecda35b Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 29 Nov 2026 21:43:42 +0000 Subject: [PATCH 26/26] quic: follow the stream/iter drain protocol in stream writers The drainable protocol method of a QUIC stream writer returned null when the writer had capacity, and end() waited for pending drain waiters instead of settling them. Per the Iterable Streams drainable protocol, it now returns null only once canWrite is null, a promise resolved with true while there is capacity, and otherwise a promise that resolves with true once there is, with false if the writer is ended first, and rejects if it fails or the peer stops sending. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/quic.md | 29 +++-- lib/internal/streams/iter/writer.js | 49 ++++++-- ...test-quic-stream-writer-drain-protocol.mjs | 112 ++++++++++++++++++ 3 files changed, 171 insertions(+), 19 deletions(-) create mode 100644 test/parallel/test-quic-stream-writer-drain-protocol.mjs diff --git a/doc/api/quic.md b/doc/api/quic.md index 7a2af0aa6087..1559cb465d35 100644 --- a/doc/api/quic.md +++ b/doc/api/quic.md @@ -325,9 +325,9 @@ There are two ways to write data to a stream: (`write()`, `writev()`, `end()`). The asynchronous `write()` and `writev()` methods use the stream/iter strict backpressure policy: when the write buffer is full, they reject with `ERR_INVALID_STATE` instead of waiting for capacity. - If a drain is already pending, `end()` waits for it before closing. Check - `writer.canWrite` before writing. To wait for capacity, use `ondrain()` from - `node:stream/iter`, then retry the write. The stream's `onblocked` callback + If a write is waiting for capacity, `end()` waits for it before closing. + Check `writer.canWrite` before writing. To wait for capacity, use + `ondrain()` from `node:stream/iter`, then retry the write. The stream's `onblocked` callback reports that transport flow control has blocked progress, but does not signal that writer capacity is available again. `writeSync()` returns `false` when the write buffer is full; the caller @@ -2512,8 +2512,8 @@ The Writer has the following methods: `ERR_INVALID_STATE` when the stream is flow-controlled rather than waiting for capacity. * `endSync()` — Synchronous close. Returns total bytes or `-1`. -* `end([options])` — Async close. If a drain is already pending, waits for it - before closing. +* `end([options])` — Async close. If a write is waiting for capacity, waits + for it before closing. Pending `ondrain()` promises resolve with `false`. * `fail(reason)` — Errors the stream (sends `RESET_STREAM` to peer). Later writes and `end()` reject with `reason`, or with an `AbortError` {DOMException} if `reason` is omitted or `undefined`. @@ -2525,18 +2525,23 @@ The Writer has the following methods: See [`stream.destroy()`][] for a full-stream abort that also resets the readable side via `STOP_SENDING`. * `canWrite` — `true` if writes will be accepted, `false` if at capacity, - or `null` if closed/errored. When `writeSync()` returns `false`, use - `ondrain()` from `node:stream/iter` to wait before retrying. If `ondrain()` - returns `null`, no drain wait is available and the write should not be - retried. + or `null` if closing, closed or errored. When `writeSync()` returns + `false`, use `ondrain()` from `node:stream/iter` to wait before retrying. + +The Writer implements the drainable protocol used by `ondrain()`, as the +writers of `node:stream/iter` do. `ondrain(writer)` returns `null` when +`writer.canWrite` is `null`: no drain wait is available and the write should +not be retried. Otherwise it returns a promise that resolves with `true` +once the stream has capacity (at once if it has capacity already), resolves +with `false` if the writer is ended first, and rejects if the writer fails +first, by `fail()` or because the peer sent `STOP_SENDING`. ```mjs import { ondrain } from 'node:stream/iter'; while (!writer.writeSync(chunk)) { - const drain = ondrain(writer); - if (drain === null) break; - await drain; + // Null once the writer is closed or errored, false once it is ended. + if (!await ondrain(writer)) break; } ``` diff --git a/lib/internal/streams/iter/writer.js b/lib/internal/streams/iter/writer.js index e8b234d6bf55..1583e4f5d7e5 100644 --- a/lib/internal/streams/iter/writer.js +++ b/lib/internal/streams/iter/writer.js @@ -55,10 +55,34 @@ function getWriter(obj) { let errored = false; let error = null; let totalBytesWritten = 0; + // The wakeup of a write waiting for capacity. let drainWakeup = null; + // The promise of the drainable protocol while the writer has no capacity: + // see notifyDrainWaiters() and rejectDrainWaiters(). + let drainWaiters = null; let pendingWrite = null; let pendingEnd = null; + // As for a push() writer: the drain waiters resolve with true once there + // is capacity, and with false once the writer stops accepting data + // without failing (end()). + function notifyDrainWaiters(canWrite) { + if (drainWaiters === null) return; + const { resolve } = drainWaiters; + drainWaiters = null; + resolve(canWrite); + } + + // The writer failed: the drain waiters reject. Nothing may be waiting for + // the promise, so the rejection is marked as handled. + function rejectDrainWaiters(reason) { + if (drainWaiters === null) return; + const { promise, reject } = drainWaiters; + drainWaiters = null; + markPromiseAsHandled(promise); + reject(reason); + } + function raceWithSignal(promise, signal) { if (signal === undefined) return promise; signal.throwIfAborted(); @@ -93,6 +117,9 @@ function getWriter(obj) { drainWakeup.resolve(true); drainWakeup = null; } + if (!closed && !ending && !errored && writeDesiredSize() > 0) { + notifyDrainWaiters(true); + } }); setStopSendingCallback((reason) => { @@ -104,6 +131,7 @@ function getWriter(obj) { drainWakeup.reject(error); drainWakeup = null; } + rejectDrainWaiters(error); } }); @@ -253,12 +281,13 @@ function getWriter(obj) { // If we're already closed, just return the total bytes written. if (closed) return totalBytesWritten; - // Accepted writes and existing drain waiters must settle before ending. + // Accepted writes must settle before ending. if (ending || pendingWrite !== null || drainWakeup !== null) return -1; // Fantastic, we can end synchronously! endWrite(); closed = true; + notifyDrainWaiters(false); return totalBytesWritten; } @@ -298,6 +327,8 @@ function getWriter(obj) { if (pendingEnd === null) { ending = true; + // The writer is closing: no more data can be written. + notifyDrainWaiters(false); pendingEnd = finishEnd(); } return raceWithSignal(pendingEnd, signal); @@ -335,6 +366,7 @@ function getWriter(obj) { drainWakeup.reject(error); drainWakeup = null; } + rejectDrainWaiters(error); } const writer = { @@ -352,13 +384,16 @@ function getWriter(obj) { endSync, end, fail, + // As for a push() writer: null once canWrite is null (the writer is + // closing, closed or errored), a promise resolved with true while there + // is capacity, and otherwise a promise that resolves with true once + // there is, with false if the writer is ended first, and rejects if it + // fails first. [drainableProtocol]() { - if (closed || ending || errored) return null; - // If a drain is already pending, return the existing promise. - if (drainWakeup != null) return drainWakeup.promise; - if (writeDesiredSize() > 0) return null; - drainWakeup = PromiseWithResolvers(); - return drainWakeup.promise; + if (closed || ending || errored || writeEnded()) return null; + if (writeDesiredSize() > 0) return PromiseResolve(true); + drainWaiters ??= PromiseWithResolvers(); + return drainWaiters.promise; }, [SymbolAsyncDispose]() { if (ending) return pendingEnd; diff --git a/test/parallel/test-quic-stream-writer-drain-protocol.mjs b/test/parallel/test-quic-stream-writer-drain-protocol.mjs new file mode 100644 index 000000000000..b9a75f343951 --- /dev/null +++ b/test/parallel/test-quic-stream-writer-drain-protocol.mjs @@ -0,0 +1,112 @@ +// Flags: --experimental-quic --experimental-stream-iter --no-warnings + +// Test: the drainable protocol of a QUIC stream writer, through ondrain(), +// behaves as for a push() writer: +// - with capacity, it returns a promise resolved with true; +// - without capacity, it returns a promise that resolves with true once +// the stream has capacity again, with false if end() is called first, +// and rejects if the writer fails first; +// - once the writer is closing, closed or errored (canWrite is null), it +// returns null. + +import { hasQuic, skip, mustCall } from '../common/index.mjs'; +import assert from 'node:assert'; + +if (!hasQuic) { + skip('QUIC is not enabled'); +} + +const { listen, connect } = await import('../common/quic.mjs'); +const { bytes, ondrain } = await import('stream/iter'); + +const budget = 1024; +const chunk = new Uint8Array(budget); + +const serverEndpoint = await listen(mustCall((serverSession) => { + // The server reads every stream, so that the client streams drain. + serverSession.onstream = (stream) => { + bytes(stream).catch(() => {}); + stream.closed.catch(() => {}); + }; +})); + +const clientSession = await connect(serverEndpoint.address); +await clientSession.opened; + +function createWriter() { + const stream = clientSession.createBidirectionalStream({ budget }); + stream.closed.catch(() => {}); + return { stream, writer: stream.writer }; +} + +// Write until the writer has no capacity. Returns the bytes written. +function fill(writer) { + let written = 0; + while (writer.canWrite) { + assert.strictEqual(writer.writeSync(chunk), true); + written += chunk.byteLength; + } + assert.strictEqual(writer.canWrite, false); + return written; +} + +// With capacity: a promise resolved with true. +{ + const { writer } = createWriter(); + assert.strictEqual(writer.canWrite, true); + const drain = ondrain(writer); + assert.ok(drain instanceof Promise); + assert.strictEqual(await drain, true); + await writer.end(); +} + +// Without capacity: resolves with true once the stream has capacity again. +{ + const { writer } = createWriter(); + fill(writer); + const drain = ondrain(writer); + assert.ok(drain instanceof Promise); + assert.strictEqual(await drain, true); + assert.strictEqual(writer.canWrite, true); + await writer.end(); +} + +// end() while waiting: resolves with false, and the writer then returns +// null. end() itself completes once the data is sent. +{ + const { writer } = createWriter(); + const written = fill(writer); + const drain = ondrain(writer); + assert.ok(drain instanceof Promise); + const ended = writer.end(); + assert.strictEqual(ondrain(writer), null); + assert.strictEqual(await drain, false); + assert.strictEqual(await ended, written); + assert.strictEqual(ondrain(writer), null); +} + +// fail() while waiting: rejects with the reason, and the writer then +// returns null. +{ + const { writer } = createWriter(); + fill(writer); + const drain = ondrain(writer); + assert.ok(drain instanceof Promise); + const reason = new Error('failed'); + writer.fail(reason); + await assert.rejects(drain, (error) => error === reason); + assert.strictEqual(writer.canWrite, null); + assert.strictEqual(ondrain(writer), null); +} + +// endSync() with capacity: the writer then returns null. +{ + const { writer } = createWriter(); + writer.writeSync('x'); + assert.strictEqual(writer.endSync(), 1); + assert.strictEqual(writer.canWrite, null); + assert.strictEqual(ondrain(writer), null); +} + +await clientSession.close(); +await serverEndpoint.close();