diff --git a/doc/api/fs.md b/doc/api/fs.md index 186ab76c0989..7262ceb43164 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 @@ -1127,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..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,9 +2512,11 @@ 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`. 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 @@ -2523,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/doc/api/stream_iter.md b/doc/api/stream_iter.md index 03c14e21afa3..21794f4b6c6a 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 @@ -133,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: @@ -148,6 +176,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 @@ -159,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 @@ -425,8 +460,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. @@ -480,7 +518,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()` @@ -508,7 +549,83 @@ 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` + + + +* {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 `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} + 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 + 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]()` @@ -518,7 +635,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. @@ -528,7 +645,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. @@ -536,7 +653,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. @@ -546,7 +664,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. @@ -599,7 +718,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. @@ -607,12 +727,31 @@ Objects implementing `Symbol.for('Stream.toAsyncStreamable')` or `Symbol.for('Stream.toStreamable')` are converted via those protocols. The `toAsyncStreamable` protocol takes precedence over `toStreamable`, which takes precedence over the iteration protocols (`Symbol.asyncIterator`, -`Symbol.iterator`). +`Symbol.iterator`). A value that needs more than 100 of these conversions one +after the other (for example, an object whose conversion returns the object +itself) is rejected with a `RangeError` whose code is `ERR_INVALID_ARG_VALUE`. 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, 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'; @@ -648,8 +787,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'; @@ -697,6 +839,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'; @@ -765,6 +916,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. 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()`. + +`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])` @@ -1267,7 +1552,8 @@ added: - v24.20.0 --> -* `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` @@ -1339,11 +1625,31 @@ 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 once that `await` completes. +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, +unless the merge had already finished. + ```mjs import { from, merge, text } from 'node:stream/iter'; @@ -1446,6 +1752,21 @@ 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`), +and every consumer rejects with the reason. + ```mjs import { broadcast, text } from 'node:stream/iter'; @@ -1498,12 +1819,40 @@ 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. - -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. +Cancel the broadcast. If `reason` is provided and is not `undefined`, all +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 +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, 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` @@ -1521,6 +1870,21 @@ 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 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]()` Alias for `broadcast.cancel()`. @@ -1541,6 +1905,55 @@ 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. + +`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'; + +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])`