mirror of
https://github.com/nodejs/node.git
synced 2026-11-27 17:52:27 -05:00
stream: add stream/iter Implementation
Experimental implementation of https://stream-iter.jasnell.me/ Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-By: Claude/Opus 4.6 PR-URL: https://github.com/nodejs/node/pull/62066 Reviewed-By: Robert Nagy <ronagy@icloud.com> Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
1 parent
9289ad5cbb
commit
ae7c6a7767
27 files changed
+9421
-299
No files matched your search
@@ -1277,6 +1277,16 @@ added:
|
||||
|
||||
Enable experimental support for storage inspection
|
||||
|
||||
### `--experimental-stream-iter`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
Enable the experimental [`node:stream/iter`][] module.
|
||||
|
||||
### `--experimental-test-coverage`
|
||||
|
||||
<!-- YAML
|
||||
@@ -3612,6 +3622,7 @@ one is included in the list below.
|
||||
* `--experimental-require-module`
|
||||
* `--experimental-shadow-realm`
|
||||
* `--experimental-specifier-resolution`
|
||||
* `--experimental-stream-iter`
|
||||
* `--experimental-test-isolation`
|
||||
* `--experimental-top-level-await`
|
||||
* `--experimental-vm-modules`
|
||||
@@ -4251,6 +4262,7 @@ node --stack-trace-limit=12 -p -e "Error.stackTraceLimit" # prints 12
|
||||
[`import` specifier]: esm.md#import-specifiers
|
||||
[`net.getDefaultAutoSelectFamilyAttemptTimeout()`]: net.md#netgetdefaultautoselectfamilyattempttimeout
|
||||
[`node:sqlite`]: sqlite.md
|
||||
[`node:stream/iter`]: stream_iter.md
|
||||
[`process.setUncaughtExceptionCaptureCallback()`]: process.md#processsetuncaughtexceptioncapturecallbackfn
|
||||
[`tls.DEFAULT_MAX_VERSION`]: tls.md#tlsdefault_max_version
|
||||
[`tls.DEFAULT_MIN_VERSION`]: tls.md#tlsdefault_min_version
|
||||
|
||||
+268
@@ -377,6 +377,154 @@ added: v10.0.0
|
||||
|
||||
* Type: {number} The numeric file descriptor managed by the {FileHandle} object.
|
||||
|
||||
#### `filehandle.pull([...transforms][, options])`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
* `...transforms` {Function|Object} Optional transforms to apply via
|
||||
[`stream/iter pull()`][].
|
||||
* `options` {Object}
|
||||
* `signal` {AbortSignal}
|
||||
* `autoClose` {boolean} Close the file handle when the stream ends.
|
||||
**Default:** `false`.
|
||||
* `start` {number} Byte offset to begin reading from. When specified,
|
||||
reads use explicit positioning (`pread` semantics). **Default:** current
|
||||
file position.
|
||||
* `limit` {number} Maximum number of bytes to read before ending the
|
||||
iterator. Reads stop when `limit` bytes have been delivered or EOF is
|
||||
reached, whichever comes first. **Default:** read until EOF.
|
||||
* `chunkSize` {number} Size in bytes of the buffer allocated for each
|
||||
read operation. **Default:** `131072` (128 KB).
|
||||
* Returns: {AsyncIterable\<Uint8Array\[]>}
|
||||
|
||||
Return the file contents as an async iterable using the
|
||||
[`node:stream/iter`][] pull model. Reads are performed in `chunkSize`-byte
|
||||
chunks (default 128 KB). If transforms are provided, they are applied
|
||||
via [`stream/iter pull()`][].
|
||||
|
||||
The file handle is locked while the iterable is being consumed and unlocked
|
||||
when iteration completes, an error occurs, or the consumer breaks.
|
||||
|
||||
This function is only available when the `--experimental-stream-iter` flag is
|
||||
enabled.
|
||||
|
||||
```mjs
|
||||
import { open } from 'node:fs/promises';
|
||||
import { text } from 'node:stream/iter';
|
||||
import { compressGzip } from 'node:zlib/iter';
|
||||
|
||||
const fh = await open('input.txt', 'r');
|
||||
|
||||
// Read as text
|
||||
console.log(await text(fh.pull({ autoClose: true })));
|
||||
|
||||
// Read 1 KB starting at byte 100
|
||||
const fh2 = await open('input.txt', 'r');
|
||||
console.log(await text(fh2.pull({ start: 100, limit: 1024, autoClose: true })));
|
||||
|
||||
// Read with compression
|
||||
const fh3 = await open('input.txt', 'r');
|
||||
const compressed = fh3.pull(compressGzip(), { autoClose: true });
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { open } = require('node:fs/promises');
|
||||
const { text } = require('node:stream/iter');
|
||||
const { compressGzip } = require('node:zlib/iter');
|
||||
|
||||
async function run() {
|
||||
const fh = await open('input.txt', 'r');
|
||||
|
||||
// Read as text
|
||||
console.log(await text(fh.pull({ autoClose: true })));
|
||||
|
||||
// Read 1 KB starting at byte 100
|
||||
const fh2 = await open('input.txt', 'r');
|
||||
console.log(await text(fh2.pull({ start: 100, limit: 1024, autoClose: true })));
|
||||
|
||||
// Read with compression
|
||||
const fh3 = await open('input.txt', 'r');
|
||||
const compressed = fh3.pull(compressGzip(), { autoClose: true });
|
||||
}
|
||||
|
||||
run().catch(console.error);
|
||||
```
|
||||
|
||||
#### `filehandle.pullSync([...transforms][, options])`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
* `...transforms` {Function|Object} Optional transforms to apply via
|
||||
[`stream/iter pullSync()`][].
|
||||
* `options` {Object}
|
||||
* `autoClose` {boolean} Close the file handle when the stream ends.
|
||||
**Default:** `false`.
|
||||
* `start` {number} Byte offset to begin reading from. When specified,
|
||||
reads use explicit positioning. **Default:** current file position.
|
||||
* `limit` {number} Maximum number of bytes to read before ending the
|
||||
iterator. **Default:** read until EOF.
|
||||
* `chunkSize` {number} Size in bytes of the buffer allocated for each
|
||||
read operation. **Default:** `131072` (128 KB).
|
||||
* Returns: {Iterable\<Uint8Array\[]>}
|
||||
|
||||
Synchronous counterpart of [`filehandle.pull()`][]. Returns a sync iterable
|
||||
that reads the file using synchronous I/O on the main thread. Reads are
|
||||
performed in `chunkSize`-byte chunks (default 128 KB).
|
||||
|
||||
The file handle is locked while the iterable is being consumed. Unlike the
|
||||
async `pull()`, this method does not support `AbortSignal` since all
|
||||
operations are synchronous.
|
||||
|
||||
This function is only available when the `--experimental-stream-iter` flag is
|
||||
enabled.
|
||||
|
||||
```mjs
|
||||
import { open } from 'node:fs/promises';
|
||||
import { textSync, pipeToSync } from 'node:stream/iter';
|
||||
import { compressGzipSync, decompressGzipSync } from 'node:zlib/iter';
|
||||
|
||||
const fh = await open('input.txt', 'r');
|
||||
|
||||
// Read as text (sync)
|
||||
console.log(textSync(fh.pullSync({ autoClose: true })));
|
||||
|
||||
// Sync compress pipeline: file -> gzip -> file
|
||||
const src = await open('input.txt', 'r');
|
||||
const dst = await open('output.gz', 'w');
|
||||
pipeToSync(src.pullSync(compressGzipSync(), { autoClose: true }), dst.writer({ autoClose: true }));
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { open } = require('node:fs/promises');
|
||||
const { textSync, pipeToSync } = require('node:stream/iter');
|
||||
const { compressGzipSync, decompressGzipSync } = require('node:zlib/iter');
|
||||
|
||||
async function run() {
|
||||
const fh = await open('input.txt', 'r');
|
||||
|
||||
// Read as text (sync)
|
||||
console.log(textSync(fh.pullSync({ autoClose: true })));
|
||||
|
||||
// Sync compress pipeline: file -> gzip -> file
|
||||
const src = await open('input.txt', 'r');
|
||||
const dst = await open('output.gz', 'w');
|
||||
pipeToSync(
|
||||
src.pullSync(compressGzipSync(), { autoClose: true }),
|
||||
dst.writer({ autoClose: true }),
|
||||
);
|
||||
}
|
||||
|
||||
run().catch(console.error);
|
||||
```
|
||||
|
||||
#### `filehandle.read(buffer, offset, length, position)`
|
||||
|
||||
<!-- YAML
|
||||
@@ -859,6 +1007,121 @@ On Linux, positional writes don't work when the file is opened in append mode.
|
||||
The kernel ignores the position argument and always appends the data to
|
||||
the end of the file.
|
||||
|
||||
#### `filehandle.writer([options])`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
* `options` {Object}
|
||||
* `autoClose` {boolean} Close the file handle when the writer ends or
|
||||
fails. **Default:** `false`.
|
||||
* `start` {number} Byte offset to start writing at. When specified,
|
||||
writes use explicit positioning. **Default:** current file position.
|
||||
* `limit` {number} Maximum number of bytes the writer will accept.
|
||||
Async writes (`write()`, `writev()`) that would exceed the limit reject
|
||||
with `ERR_OUT_OF_RANGE`. Sync writes (`writeSync()`, `writevSync()`)
|
||||
return `false`. **Default:** no limit.
|
||||
* `chunkSize` {number} Maximum chunk size in bytes for synchronous write
|
||||
operations. Writes larger than this threshold fall back to async I/O.
|
||||
Set this to match the reader's `chunkSize` for optimal `pipeTo()`
|
||||
performance. **Default:** `131072` (128 KB).
|
||||
* Returns: {Object}
|
||||
* `write(chunk[, options])` {Function} Returns {Promise\<void>}.
|
||||
Accepts `Uint8Array`, `Buffer`, or string (UTF-8 encoded).
|
||||
* `chunk` {Buffer|TypedArray|DataView|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\<void>}. Uses
|
||||
scatter/gather I/O via a single `writev()` syscall. Accepts mixed
|
||||
`Uint8Array`/string arrays.
|
||||
* `chunks` {Array\<Buffer|TypedArray|DataView|string>}
|
||||
* `options` {Object}
|
||||
* `signal` {AbortSignal} If the signal is already aborted, the write
|
||||
rejects with `AbortError` without performing I/O.
|
||||
* `writeSync(chunk)` {Function} Returns {boolean}. Attempts a synchronous
|
||||
write. Returns `true` if the write succeeded, `false` if the caller
|
||||
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}
|
||||
* `writevSync(chunks)` {Function} Returns {boolean}. Synchronous batch
|
||||
write. Same fallback semantics as `writeSync()`.
|
||||
* `chunks` {Array\<Buffer|TypedArray|DataView|string>}
|
||||
* `end([options])` {Function} Returns {Promise\<number>} total bytes
|
||||
written. Idempotent: returns `totalBytesWritten` if already closed,
|
||||
returns the pending promise if already closing. Rejects if the writer
|
||||
is in an errored state.
|
||||
* `options` {Object}
|
||||
* `signal` {AbortSignal} If the signal is already aborted, `end()`
|
||||
rejects with `AbortError` and the writer remains open.
|
||||
* `endSync()` {Function} Returns {number|number} total bytes written on
|
||||
success, `-1` if the writer is errored or an async operation is in
|
||||
flight. Idempotent when already closed.
|
||||
* `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.
|
||||
|
||||
Return a [`node:stream/iter`][] writer backed by this file handle.
|
||||
|
||||
The writer supports both `Symbol.asyncDispose` and `Symbol.dispose`:
|
||||
|
||||
* `await using w = fh.writer()` — if the writer is still open (no `end()`
|
||||
called), `asyncDispose` calls `fail()`. If `end()` is pending, it waits
|
||||
for it to complete.
|
||||
* `using w = fh.writer()` — calls `fail()` unconditionally.
|
||||
|
||||
The `writeSync()` and `writevSync()` methods enable the try-sync fast path
|
||||
used by [`stream/iter pipeTo()`][]. When the reader's chunk size matches the
|
||||
writer's `chunkSize`, all writes in a `pipeTo()` pipeline complete
|
||||
synchronously with zero promise overhead.
|
||||
|
||||
This function is only available when the `--experimental-stream-iter` flag is
|
||||
enabled.
|
||||
|
||||
```mjs
|
||||
import { open } from 'node:fs/promises';
|
||||
import { from, pipeTo } from 'node:stream/iter';
|
||||
import { compressGzip } from 'node:zlib/iter';
|
||||
|
||||
// Async pipeline
|
||||
const fh = await open('output.gz', 'w');
|
||||
await pipeTo(from('Hello!'), compressGzip(), fh.writer({ autoClose: true }));
|
||||
|
||||
// Sync pipeline with limit
|
||||
const src = await open('input.txt', 'r');
|
||||
const dst = await open('output.txt', 'w');
|
||||
const w = dst.writer({ limit: 1024 * 1024 }); // Max 1 MB
|
||||
await pipeTo(src.pull({ autoClose: true }), w);
|
||||
await w.end();
|
||||
await dst.close();
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { open } = require('node:fs/promises');
|
||||
const { from, pipeTo } = require('node:stream/iter');
|
||||
const { compressGzip } = require('node:zlib/iter');
|
||||
|
||||
async function run() {
|
||||
// Async pipeline
|
||||
const fh = await open('output.gz', 'w');
|
||||
await pipeTo(from('Hello!'), compressGzip(), fh.writer({ autoClose: true }));
|
||||
|
||||
// Sync pipeline with limit
|
||||
const src = await open('input.txt', 'r');
|
||||
const dst = await open('output.txt', 'w');
|
||||
const w = dst.writer({ limit: 1024 * 1024 }); // Max 1 MB
|
||||
await pipeTo(src.pull({ autoClose: true }), w);
|
||||
await w.end();
|
||||
await dst.close();
|
||||
}
|
||||
|
||||
run().catch(console.error);
|
||||
```
|
||||
|
||||
#### `filehandle[Symbol.asyncDispose]()`
|
||||
|
||||
<!-- YAML
|
||||
@@ -8737,6 +9000,7 @@ the file contents.
|
||||
[`event ports`]: https://illumos.org/man/port_create
|
||||
[`filehandle.createReadStream()`]: #filehandlecreatereadstreamoptions
|
||||
[`filehandle.createWriteStream()`]: #filehandlecreatewritestreamoptions
|
||||
[`filehandle.pull()`]: #filehandlepulltransforms-options
|
||||
[`filehandle.writeFile()`]: #filehandlewritefiledata-options
|
||||
[`fs.access()`]: #fsaccesspath-mode-callback
|
||||
[`fs.accessSync()`]: #fsaccesssyncpath-mode
|
||||
@@ -8787,6 +9051,10 @@ the file contents.
|
||||
[`inotify(7)`]: https://man7.org/linux/man-pages/man7/inotify.7.html
|
||||
[`kqueue(2)`]: https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
|
||||
[`minimatch`]: https://github.com/isaacs/minimatch
|
||||
[`node:stream/iter`]: stream_iter.md
|
||||
[`stream/iter pipeTo()`]: stream_iter.md#pipetosource-transforms-writer
|
||||
[`stream/iter pull()`]: stream_iter.md#pullsource-transforms-options
|
||||
[`stream/iter pullSync()`]: stream_iter.md#pullsyncsource-transforms
|
||||
[`util.promisify()`]: util.md#utilpromisifyoriginal
|
||||
[bigints]: https://tc39.github.io/proposal-bigint
|
||||
[caveats]: #caveats
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
* [Modules: Packages](packages.md)
|
||||
* [Modules: TypeScript](typescript.md)
|
||||
* [Net](net.md)
|
||||
* [Iterable Streams API](stream_iter.md)
|
||||
* [OS](os.md)
|
||||
* [Path](path.md)
|
||||
* [Performance hooks](perf_hooks.md)
|
||||
@@ -69,6 +70,7 @@
|
||||
* [Web Streams API](webstreams.md)
|
||||
* [Worker threads](worker_threads.md)
|
||||
* [Zlib](zlib.md)
|
||||
* [Zlib Iterable Compression](zlib_iter.md)
|
||||
|
||||
<hr class="line"/>
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,254 @@
|
||||
# Iterable Compression
|
||||
|
||||
<!--introduced_in=REPLACEME-->
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
<!-- source_link=lib/zlib/iter.js -->
|
||||
|
||||
The `node:zlib/iter` module provides compression and decompression transforms
|
||||
for use with the [`node:stream/iter`][] iterable streams API.
|
||||
|
||||
This module is available only when the `--experimental-stream-iter` CLI flag
|
||||
is enabled.
|
||||
|
||||
Each algorithm has both an async variant (stateful async generator, for use
|
||||
with [`pull()`][] and [`pipeTo()`][]) and a sync variant (stateful sync
|
||||
generator, for use with `pullSync()` and `pipeToSync()`).
|
||||
|
||||
The async transforms run compression on the libuv threadpool, overlapping
|
||||
I/O with JavaScript execution. The sync transforms run compression directly
|
||||
on the main thread.
|
||||
|
||||
> Note: The defaults for these transforms are tuned for streaming throughput,
|
||||
> and differ from the defaults in `node:zlib`. In particular, gzip/deflate
|
||||
> default to level 4 (not 6) and memLevel 9 (not 8), and Brotli defaults to
|
||||
> quality 6 (not 11). These choices match common HTTP server configurations
|
||||
> and provide significantly faster compression with only a small reduction in
|
||||
> compression ratio. All defaults can be overridden via options.
|
||||
|
||||
```mjs
|
||||
import { from, pull, bytes, text } from 'node:stream/iter';
|
||||
import { compressGzip, decompressGzip } from 'node:zlib/iter';
|
||||
|
||||
// Async round-trip
|
||||
const compressed = await bytes(pull(from('hello'), compressGzip()));
|
||||
const original = await text(pull(from(compressed), decompressGzip()));
|
||||
console.log(original); // 'hello'
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { from, pull, bytes, text } = require('node:stream/iter');
|
||||
const { compressGzip, decompressGzip } = require('node:zlib/iter');
|
||||
|
||||
async function run() {
|
||||
const compressed = await bytes(pull(from('hello'), compressGzip()));
|
||||
const original = await text(pull(from(compressed), decompressGzip()));
|
||||
console.log(original); // 'hello'
|
||||
}
|
||||
|
||||
run().catch(console.error);
|
||||
```
|
||||
|
||||
```mjs
|
||||
import { fromSync, pullSync, textSync } from 'node:stream/iter';
|
||||
import { compressGzipSync, decompressGzipSync } from 'node:zlib/iter';
|
||||
|
||||
// Sync round-trip
|
||||
const compressed = pullSync(fromSync('hello'), compressGzipSync());
|
||||
const original = textSync(pullSync(compressed, decompressGzipSync()));
|
||||
console.log(original); // 'hello'
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { fromSync, pullSync, textSync } = require('node:stream/iter');
|
||||
const { compressGzipSync, decompressGzipSync } = require('node:zlib/iter');
|
||||
|
||||
const compressed = pullSync(fromSync('hello'), compressGzipSync());
|
||||
const original = textSync(pullSync(compressed, decompressGzipSync()));
|
||||
console.log(original); // 'hello'
|
||||
```
|
||||
|
||||
## `compressBrotli([options])`
|
||||
|
||||
## `compressBrotliSync([options])`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
* `options` {Object}
|
||||
* `chunkSize` {number} Output buffer size. **Default:** `65536` (64 KB).
|
||||
* `params` {Object} Key-value object where keys and values are
|
||||
`zlib.constants` entries. The most important compressor parameters are:
|
||||
* `BROTLI_PARAM_MODE` -- `BROTLI_MODE_GENERIC` (default),
|
||||
`BROTLI_MODE_TEXT`, or `BROTLI_MODE_FONT`.
|
||||
* `BROTLI_PARAM_QUALITY` -- ranges from `BROTLI_MIN_QUALITY` to
|
||||
`BROTLI_MAX_QUALITY`. **Default:** `6` (not `BROTLI_DEFAULT_QUALITY`
|
||||
which is 11). Quality 6 is appropriate for streaming; quality 11 is
|
||||
intended for offline/build-time compression.
|
||||
* `BROTLI_PARAM_SIZE_HINT` -- expected input size. **Default:** `0`
|
||||
(unknown).
|
||||
* `BROTLI_PARAM_LGWIN` -- window size (log2). **Default:** `20` (1 MB).
|
||||
The Brotli library default is 22 (4 MB); the reduced default saves
|
||||
memory without significant compression impact for streaming workloads.
|
||||
* `BROTLI_PARAM_LGBLOCK` -- input block size (log2).
|
||||
See the [Brotli compressor options][] in the zlib documentation for the
|
||||
full list.
|
||||
* `dictionary` {Buffer|TypedArray|DataView}
|
||||
* Returns: {Object} A stateful transform.
|
||||
|
||||
Create a Brotli compression transform. Output is compatible with
|
||||
`zlib.brotliDecompress()` and `decompressBrotli()`/`decompressBrotliSync()`.
|
||||
|
||||
## `compressDeflate([options])`
|
||||
|
||||
## `compressDeflateSync([options])`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
* `options` {Object}
|
||||
* `chunkSize` {number} Output buffer size. **Default:** `65536` (64 KB).
|
||||
* `level` {number} Compression level (`0`-`9`). **Default:** `4`.
|
||||
* `windowBits` {number} **Default:** `Z_DEFAULT_WINDOWBITS` (15).
|
||||
* `memLevel` {number} **Default:** `9`.
|
||||
* `strategy` {number} **Default:** `Z_DEFAULT_STRATEGY`.
|
||||
* `dictionary` {Buffer|TypedArray|DataView}
|
||||
* Returns: {Object} A stateful transform.
|
||||
|
||||
Create a deflate compression transform. Output is compatible with
|
||||
`zlib.inflate()` and `decompressDeflate()`/`decompressDeflateSync()`.
|
||||
|
||||
## `compressGzip([options])`
|
||||
|
||||
## `compressGzipSync([options])`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
* `options` {Object}
|
||||
* `chunkSize` {number} Output buffer size. **Default:** `65536` (64 KB).
|
||||
* `level` {number} Compression level (`0`-`9`). **Default:** `4`.
|
||||
* `windowBits` {number} **Default:** `Z_DEFAULT_WINDOWBITS` (15).
|
||||
* `memLevel` {number} **Default:** `9`.
|
||||
* `strategy` {number} **Default:** `Z_DEFAULT_STRATEGY`.
|
||||
* `dictionary` {Buffer|TypedArray|DataView}
|
||||
* Returns: {Object} A stateful transform.
|
||||
|
||||
Create a gzip compression transform. Output is compatible with `zlib.gunzip()`
|
||||
and `decompressGzip()`/`decompressGzipSync()`.
|
||||
|
||||
## `compressZstd([options])`
|
||||
|
||||
## `compressZstdSync([options])`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
* `options` {Object}
|
||||
* `chunkSize` {number} Output buffer size. **Default:** `65536` (64 KB).
|
||||
* `params` {Object} Key-value object where keys and values are
|
||||
`zlib.constants` entries. The most important compressor parameters are:
|
||||
* `ZSTD_c_compressionLevel` -- **Default:** `ZSTD_CLEVEL_DEFAULT` (3).
|
||||
* `ZSTD_c_checksumFlag` -- generate a checksum. **Default:** `0`.
|
||||
* `ZSTD_c_strategy` -- compression strategy. Values include
|
||||
`ZSTD_fast`, `ZSTD_dfast`, `ZSTD_greedy`, `ZSTD_lazy`,
|
||||
`ZSTD_lazy2`, `ZSTD_btlazy2`, `ZSTD_btopt`, `ZSTD_btultra`,
|
||||
`ZSTD_btultra2`.
|
||||
See the [Zstd compressor options][] in the zlib documentation for the
|
||||
full list.
|
||||
* `pledgedSrcSize` {number} Expected uncompressed size (optional hint).
|
||||
* `dictionary` {Buffer|TypedArray|DataView}
|
||||
* Returns: {Object} A stateful transform.
|
||||
|
||||
Create a Zstandard compression transform. Output is compatible with
|
||||
`zlib.zstdDecompress()` and `decompressZstd()`/`decompressZstdSync()`.
|
||||
|
||||
## `decompressBrotli([options])`
|
||||
|
||||
## `decompressBrotliSync([options])`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
* `options` {Object}
|
||||
* `chunkSize` {number} Output buffer size. **Default:** `65536` (64 KB).
|
||||
* `params` {Object} Key-value object where keys and values are
|
||||
`zlib.constants` entries. Available decompressor parameters:
|
||||
* `BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION` -- boolean
|
||||
flag affecting internal memory allocation.
|
||||
* `BROTLI_DECODER_PARAM_LARGE_WINDOW` -- boolean flag enabling "Large
|
||||
Window Brotli" mode (not compatible with [RFC 7932][]).
|
||||
See the [Brotli decompressor options][] in the zlib documentation for
|
||||
details.
|
||||
* `dictionary` {Buffer|TypedArray|DataView}
|
||||
* Returns: {Object} A stateful transform.
|
||||
|
||||
Create a Brotli decompression transform.
|
||||
|
||||
## `decompressDeflate([options])`
|
||||
|
||||
## `decompressDeflateSync([options])`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
* `options` {Object}
|
||||
* `chunkSize` {number} Output buffer size. **Default:** `65536` (64 KB).
|
||||
* `windowBits` {number} **Default:** `Z_DEFAULT_WINDOWBITS` (15).
|
||||
* `dictionary` {Buffer|TypedArray|DataView}
|
||||
* Returns: {Object} A stateful transform.
|
||||
|
||||
Create a deflate decompression transform.
|
||||
|
||||
## `decompressGzip([options])`
|
||||
|
||||
## `decompressGzipSync([options])`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
* `options` {Object}
|
||||
* `chunkSize` {number} Output buffer size. **Default:** `65536` (64 KB).
|
||||
* `windowBits` {number} **Default:** `Z_DEFAULT_WINDOWBITS` (15).
|
||||
* `dictionary` {Buffer|TypedArray|DataView}
|
||||
* Returns: {Object} A stateful transform.
|
||||
|
||||
Create a gzip decompression transform.
|
||||
|
||||
## `decompressZstd([options])`
|
||||
|
||||
## `decompressZstdSync([options])`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
* `options` {Object}
|
||||
* `chunkSize` {number} Output buffer size. **Default:** `65536` (64 KB).
|
||||
* `params` {Object} Key-value object where keys and values are
|
||||
`zlib.constants` entries. Available decompressor parameters:
|
||||
* `ZSTD_d_windowLogMax` -- maximum window size (log2) the decompressor
|
||||
will allocate. Limits memory usage against malicious input.
|
||||
See the [Zstd decompressor options][] in the zlib documentation for
|
||||
details.
|
||||
* `dictionary` {Buffer|TypedArray|DataView}
|
||||
* Returns: {Object} A stateful transform.
|
||||
|
||||
Create a Zstandard decompression transform.
|
||||
|
||||
[Brotli compressor options]: zlib.md#compressor-options
|
||||
[Brotli decompressor options]: zlib.md#decompressor-options
|
||||
[RFC 7932]: https://www.rfc-editor.org/rfc/rfc7932
|
||||
[Zstd compressor options]: zlib.md#compressor-options-1
|
||||
[Zstd decompressor options]: zlib.md#decompressor-options-1
|
||||
[`node:stream/iter`]: stream_iter.md
|
||||
[`pipeTo()`]: stream_iter.md#pipetosource-transforms-writer-options
|
||||
[`pull()`]: stream_iter.md#pullsource-transforms-options
|
||||
@@ -720,6 +720,11 @@ top-level awaits, and print their location to help users find them.
|
||||
.It Fl -experimental-quic
|
||||
Enable experimental support for the QUIC protocol.
|
||||
.
|
||||
.It Fl -experimental-stream-iter
|
||||
Enable the experimental
|
||||
.Sy node:stream/iter
|
||||
module.
|
||||
.
|
||||
.It Fl -experimental-sea-config
|
||||
Use this flag to generate a blob that can be injected into the Node.js
|
||||
binary to produce a single executable application. See the documentation
|
||||
|
||||
@@ -131,7 +131,7 @@ const schemelessBlockList = new SafeSet([
|
||||
'test/reporters',
|
||||
]);
|
||||
// Modules that will only be enabled at run time.
|
||||
const experimentalModuleList = new SafeSet(['sqlite', 'quic']);
|
||||
const experimentalModuleList = new SafeSet(['sqlite', 'quic', 'stream/iter', 'zlib/iter']);
|
||||
|
||||
// Set up process.binding() and process._linkedBinding().
|
||||
{
|
||||
|
||||
@@ -16,6 +16,9 @@ const {
|
||||
SafePromisePrototypeFinally,
|
||||
Symbol,
|
||||
SymbolAsyncDispose,
|
||||
SymbolAsyncIterator,
|
||||
SymbolDispose,
|
||||
SymbolIterator,
|
||||
Uint8Array,
|
||||
uncurryThis,
|
||||
} = primordials;
|
||||
@@ -43,6 +46,8 @@ const {
|
||||
ERR_INVALID_ARG_VALUE,
|
||||
ERR_INVALID_STATE,
|
||||
ERR_METHOD_NOT_IMPLEMENTED,
|
||||
ERR_OPERATION_FAILED,
|
||||
ERR_OUT_OF_RANGE,
|
||||
},
|
||||
} = require('internal/errors');
|
||||
const { isArrayBufferView } = require('internal/util/types');
|
||||
@@ -65,6 +70,7 @@ const {
|
||||
stringToFlags,
|
||||
stringToSymlinkType,
|
||||
toUnixTimestamp,
|
||||
handleErrorFromBinding: handleSyncErrorFromBinding,
|
||||
validateBufferArray,
|
||||
validateCpOptions,
|
||||
validateOffsetLengthRead,
|
||||
@@ -96,6 +102,7 @@ const {
|
||||
isWindows,
|
||||
isMacOS,
|
||||
} = require('internal/util');
|
||||
const { getOptionValue } = require('internal/options');
|
||||
const EventEmitter = require('events');
|
||||
const { StringDecoder } = require('string_decoder');
|
||||
const { kFSWatchStart, watch } = require('internal/fs/watchers');
|
||||
@@ -115,6 +122,7 @@ const kCloseReject = Symbol('kCloseReject');
|
||||
const kRef = Symbol('kRef');
|
||||
const kUnref = Symbol('kUnref');
|
||||
const kLocked = Symbol('kLocked');
|
||||
const kCloseSync = Symbol('kCloseSync');
|
||||
|
||||
const { kUsePromises } = binding;
|
||||
const { Interface } = require('internal/readline/interface');
|
||||
@@ -142,6 +150,24 @@ const lazyReadableStream = getLazy(() =>
|
||||
require('internal/webstreams/readablestream').ReadableStream,
|
||||
);
|
||||
|
||||
// Lazy loaded to avoid circular dependency with new streams.
|
||||
let newStreamsPull;
|
||||
let newStreamsPullSync;
|
||||
let newStreamsParsePullArgs;
|
||||
let newStreamsToUint8Array;
|
||||
let newStreamsConvertChunks;
|
||||
function lazyNewStreams() {
|
||||
if (newStreamsPull === undefined) {
|
||||
const pullModule = require('internal/streams/iter/pull');
|
||||
newStreamsPull = pullModule.pull;
|
||||
newStreamsPullSync = pullModule.pullSync;
|
||||
const utils = require('internal/streams/iter/utils');
|
||||
newStreamsParsePullArgs = utils.parsePullArgs;
|
||||
newStreamsToUint8Array = utils.toUint8Array;
|
||||
newStreamsConvertChunks = utils.convertChunks;
|
||||
}
|
||||
}
|
||||
|
||||
// By the time the C++ land creates an error for a promise rejection (likely from a
|
||||
// libuv callback), there is already no JS frames on the stack. So we need to
|
||||
// wait until V8 resumes execution back to JS land before we have enough information
|
||||
@@ -269,6 +295,16 @@ class FileHandle extends EventEmitter {
|
||||
return this[kClosePromise];
|
||||
};
|
||||
|
||||
[kCloseSync]() {
|
||||
if (this[kFd] === -1) return;
|
||||
if (this[kClosePromise]) {
|
||||
throw new ERR_INVALID_STATE('The FileHandle is closing');
|
||||
}
|
||||
this[kFd] = -1;
|
||||
this[kHandle].closeSync();
|
||||
this.emit('close');
|
||||
}
|
||||
|
||||
async [SymbolAsyncDispose]() {
|
||||
await this.close();
|
||||
}
|
||||
@@ -424,6 +460,612 @@ class FileHandle extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
if (getOptionValue('--experimental-stream-iter')) {
|
||||
const kNullPrototo = { __proto__: null };
|
||||
const kDefaultChunkSize = 131072;
|
||||
const kNone = -1;
|
||||
/**
|
||||
* Return the file contents as an AsyncIterable<Uint8Array[]> using the
|
||||
* new streams pull model. Optional transforms and options (including
|
||||
* AbortSignal) may be provided as trailing arguments, mirroring the
|
||||
* Stream.pull() signature.
|
||||
* @param {...(Function|object)} args - Optional transforms and/or options
|
||||
* @returns {AsyncIterable<Uint8Array[]>}
|
||||
*/
|
||||
FileHandle.prototype.pull = function pull(...args) {
|
||||
if (this[kFd] === kNone)
|
||||
throw new ERR_INVALID_STATE('The FileHandle is closed');
|
||||
if (this[kClosePromise])
|
||||
throw new ERR_INVALID_STATE('The FileHandle is closing');
|
||||
if (this[kLocked])
|
||||
throw new ERR_INVALID_STATE('The FileHandle is locked');
|
||||
|
||||
lazyNewStreams();
|
||||
const { transforms, options = kNullPrototo } = newStreamsParsePullArgs(args);
|
||||
|
||||
const {
|
||||
autoClose = false,
|
||||
chunkSize: readSize = kDefaultChunkSize,
|
||||
signal,
|
||||
} = options;
|
||||
let {
|
||||
start: pos = kNone,
|
||||
limit: remaining = kNone,
|
||||
} = options;
|
||||
|
||||
const handle = this;
|
||||
const fd = this[kFd];
|
||||
|
||||
validateBoolean(autoClose, 'options.autoClose');
|
||||
|
||||
if (pos !== kNone) {
|
||||
validateInteger(pos, 'options.start', 0);
|
||||
}
|
||||
if (remaining !== kNone) {
|
||||
validateInteger(remaining, 'options.limit', 1);
|
||||
}
|
||||
if (readSize !== undefined) {
|
||||
validateInteger(readSize, 'options.chunkSize', 1);
|
||||
}
|
||||
if (signal !== undefined) {
|
||||
validateAbortSignal(signal, 'options.signal');
|
||||
}
|
||||
|
||||
this[kLocked] = true;
|
||||
|
||||
const source = {
|
||||
__proto__: null,
|
||||
async *[SymbolAsyncIterator]() {
|
||||
handle[kRef]();
|
||||
try {
|
||||
if (signal) {
|
||||
// Signal-aware path
|
||||
while (remaining !== 0) {
|
||||
if (signal.aborted) {
|
||||
throw signal.reason ??
|
||||
lazyDOMException('The operation was aborted',
|
||||
'AbortError');
|
||||
}
|
||||
const toRead = remaining > 0 ?
|
||||
MathMin(readSize, remaining) : readSize;
|
||||
const buf = Buffer.allocUnsafe(toRead);
|
||||
let bytesRead;
|
||||
try {
|
||||
bytesRead =
|
||||
(await binding.read(fd, buf, 0,
|
||||
toRead, pos, kUsePromises)) || 0;
|
||||
} catch (err) {
|
||||
ErrorCaptureStackTrace(err, handleErrorFromBinding);
|
||||
throw err;
|
||||
}
|
||||
if (bytesRead === 0) break;
|
||||
if (pos >= 0) pos += bytesRead;
|
||||
if (remaining > 0) remaining -= bytesRead;
|
||||
yield [bytesRead < toRead ? buf.subarray(0, bytesRead) : buf];
|
||||
}
|
||||
} else {
|
||||
// Fast path - no signal check per iteration
|
||||
while (remaining !== 0) {
|
||||
const toRead = remaining > 0 ?
|
||||
MathMin(readSize, remaining) : readSize;
|
||||
const buf = Buffer.allocUnsafe(toRead);
|
||||
let bytesRead;
|
||||
try {
|
||||
bytesRead =
|
||||
(await binding.read(fd, buf, 0,
|
||||
toRead, pos, kUsePromises)) || 0;
|
||||
} catch (err) {
|
||||
ErrorCaptureStackTrace(err, handleErrorFromBinding);
|
||||
throw err;
|
||||
}
|
||||
if (bytesRead === 0) break;
|
||||
if (pos >= 0) pos += bytesRead;
|
||||
if (remaining > 0) remaining -= bytesRead;
|
||||
yield [bytesRead < toRead ? buf.subarray(0, bytesRead) : buf];
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
handle[kLocked] = false;
|
||||
handle[kUnref]();
|
||||
if (autoClose) {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// If transforms provided, wrap with pull pipeline
|
||||
if (transforms.length > 0) {
|
||||
const pullArgs = [...transforms];
|
||||
if (options) {
|
||||
ArrayPrototypePush(pullArgs, options);
|
||||
}
|
||||
return newStreamsPull(source, ...pullArgs);
|
||||
}
|
||||
return source;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the file contents as an Iterable<Uint8Array[]> using synchronous
|
||||
* reads. Optional transforms and options may be provided as trailing
|
||||
* arguments, mirroring the Stream.pullSync() signature.
|
||||
* @param {...(Function|object)} args - Optional transforms and/or options
|
||||
* @returns {Iterable<Uint8Array[]>}
|
||||
*/
|
||||
FileHandle.prototype.pullSync = function pullSync(...args) {
|
||||
if (this[kFd] === kNone)
|
||||
throw new ERR_INVALID_STATE('The FileHandle is closed');
|
||||
if (this[kClosePromise])
|
||||
throw new ERR_INVALID_STATE('The FileHandle is closing');
|
||||
if (this[kLocked])
|
||||
throw new ERR_INVALID_STATE('The FileHandle is locked');
|
||||
|
||||
lazyNewStreams();
|
||||
const { transforms, options = kNullPrototo } = newStreamsParsePullArgs(args);
|
||||
|
||||
const {
|
||||
autoClose = false,
|
||||
chunkSize: readSize = kDefaultChunkSize,
|
||||
} = options;
|
||||
let {
|
||||
start: pos = kNone,
|
||||
limit: remaining = kNone,
|
||||
} = options;
|
||||
|
||||
const handle = this;
|
||||
const fd = this[kFd];
|
||||
|
||||
validateBoolean(autoClose, 'options.autoClose');
|
||||
|
||||
if (pos !== kNone) {
|
||||
validateInteger(pos, 'options.start', 0);
|
||||
}
|
||||
if (remaining !== kNone) {
|
||||
validateInteger(remaining, 'options.limit', 1);
|
||||
}
|
||||
if (readSize !== undefined) {
|
||||
validateInteger(readSize, 'options.chunkSize', 1);
|
||||
}
|
||||
|
||||
this[kLocked] = true;
|
||||
|
||||
handle[kRef]();
|
||||
|
||||
function cleanup() {
|
||||
handle[kLocked] = false;
|
||||
handle[kUnref]();
|
||||
if (autoClose) {
|
||||
handle[kCloseSync]();
|
||||
}
|
||||
}
|
||||
|
||||
const source = {
|
||||
__proto__: null,
|
||||
[SymbolIterator]() {
|
||||
let done = false;
|
||||
return {
|
||||
__proto__: null,
|
||||
next() {
|
||||
if (done || remaining === 0) {
|
||||
if (!done) {
|
||||
done = true;
|
||||
cleanup();
|
||||
}
|
||||
return { value: undefined, done: true };
|
||||
}
|
||||
const toRead = remaining > 0 ?
|
||||
MathMin(readSize, remaining) : readSize;
|
||||
const buf = Buffer.allocUnsafe(toRead);
|
||||
let bytesRead;
|
||||
try {
|
||||
bytesRead = binding.read(fd, buf, 0, toRead, pos) || 0;
|
||||
} catch (err) {
|
||||
done = true;
|
||||
cleanup();
|
||||
throw err;
|
||||
}
|
||||
if (bytesRead === 0) {
|
||||
done = true;
|
||||
cleanup();
|
||||
return { value: undefined, done: true };
|
||||
}
|
||||
if (pos >= 0) pos += bytesRead;
|
||||
if (remaining > 0) remaining -= bytesRead;
|
||||
const chunk = bytesRead < toRead ?
|
||||
buf.subarray(0, bytesRead) : buf;
|
||||
return { value: [chunk], done: false };
|
||||
},
|
||||
return() {
|
||||
if (!done) {
|
||||
done = true;
|
||||
cleanup();
|
||||
}
|
||||
return { value: undefined, done: true };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
if (transforms.length > 0) {
|
||||
return newStreamsPullSync(source, ...transforms);
|
||||
}
|
||||
return source;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return a new-streams Writer backed by this file handle.
|
||||
* The writer uses direct binding.writeBuffer / binding.writeBuffers
|
||||
* calls, bypassing the FileHandle.write() validation chain.
|
||||
*
|
||||
* Supports writev() for batch writes (single syscall per batch).
|
||||
* Handles EAGAIN with retry (up to 5 attempts), matching WriteStream.
|
||||
* @param {{
|
||||
* autoClose?: boolean;
|
||||
* start?: number;
|
||||
* }} [options]
|
||||
* @returns {{ write, writev, end, fail }}
|
||||
*/
|
||||
FileHandle.prototype.writer = function writer(options = kNullPrototo) {
|
||||
if (this[kFd] === kNone)
|
||||
throw new ERR_INVALID_STATE('The FileHandle is closed');
|
||||
if (this[kClosePromise])
|
||||
throw new ERR_INVALID_STATE('The FileHandle is closing');
|
||||
if (this[kLocked])
|
||||
throw new ERR_INVALID_STATE('The FileHandle is locked');
|
||||
|
||||
lazyNewStreams();
|
||||
|
||||
validateObject(options, 'options');
|
||||
const {
|
||||
autoClose = false,
|
||||
chunkSize: syncWriteThreshold = kDefaultChunkSize,
|
||||
} = options;
|
||||
let {
|
||||
start: pos = kNone,
|
||||
limit: bytesRemaining = kNone,
|
||||
} = options;
|
||||
|
||||
const handle = this;
|
||||
const fd = this[kFd];
|
||||
let totalBytesWritten = 0;
|
||||
let closed = false;
|
||||
let closing = false;
|
||||
let pendingEndPromise = null;
|
||||
let error = null;
|
||||
let asyncPending = false;
|
||||
|
||||
validateBoolean(autoClose, 'options.autoClose');
|
||||
|
||||
if (pos !== kNone) {
|
||||
validateInteger(pos, 'options.start', 0);
|
||||
}
|
||||
if (bytesRemaining !== kNone) {
|
||||
validateInteger(bytesRemaining, 'options.limit', 1);
|
||||
}
|
||||
if (syncWriteThreshold !== undefined) {
|
||||
validateInteger(syncWriteThreshold, 'options.chunkSize', 1);
|
||||
}
|
||||
|
||||
this[kLocked] = true;
|
||||
handle[kRef]();
|
||||
|
||||
// Write a single buffer with EAGAIN retry (up to 5 retries).
|
||||
async function writeAll(buf, offset, length, position, signal) {
|
||||
asyncPending = true;
|
||||
try {
|
||||
let retries = 0;
|
||||
while (length > 0) {
|
||||
const bytesWritten = (await PromisePrototypeThen(
|
||||
binding.writeBuffer(fd, buf, offset, length, position,
|
||||
kUsePromises),
|
||||
undefined,
|
||||
handleErrorFromBinding,
|
||||
)) || 0;
|
||||
|
||||
signal?.throwIfAborted();
|
||||
|
||||
if (bytesWritten === 0) {
|
||||
if (++retries > 5) {
|
||||
throw new ERR_OPERATION_FAILED('write failed after retries');
|
||||
}
|
||||
} else {
|
||||
retries = 0;
|
||||
}
|
||||
|
||||
totalBytesWritten += bytesWritten;
|
||||
offset += bytesWritten;
|
||||
length -= bytesWritten;
|
||||
if (position >= 0) position += bytesWritten;
|
||||
}
|
||||
} finally {
|
||||
asyncPending = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Writev with EAGAIN retry. On partial write, concatenates remaining
|
||||
// buffers and falls back to writeAll (same approach as WriteStream).
|
||||
async function writevAll(buffers, position, signal) {
|
||||
asyncPending = true;
|
||||
try {
|
||||
let totalSize = 0;
|
||||
for (let i = 0; i < buffers.length; i++) {
|
||||
totalSize += buffers[i].byteLength;
|
||||
}
|
||||
|
||||
let retries = 0;
|
||||
while (totalSize > 0) {
|
||||
const bytesWritten = (await PromisePrototypeThen(
|
||||
binding.writeBuffers(fd, buffers, position, kUsePromises),
|
||||
undefined,
|
||||
handleErrorFromBinding,
|
||||
)) || 0;
|
||||
|
||||
signal?.throwIfAborted();
|
||||
|
||||
if (bytesWritten === 0) {
|
||||
if (++retries > 5) {
|
||||
throw new ERR_OPERATION_FAILED('writev failed after retries');
|
||||
}
|
||||
} else {
|
||||
retries = 0;
|
||||
}
|
||||
|
||||
totalBytesWritten += bytesWritten;
|
||||
totalSize -= bytesWritten;
|
||||
if (position >= 0) position += bytesWritten;
|
||||
|
||||
if (totalSize > 0) {
|
||||
// Partial write - concatenate remaining and use writeAll.
|
||||
const remaining = Buffer.concat(buffers);
|
||||
const wrote = bytesWritten;
|
||||
// writeAll is already inside asyncPending = true, but
|
||||
// writeAll sets it again - that's fine (idempotent).
|
||||
await writeAll(remaining, wrote, remaining.length - wrote,
|
||||
position, signal);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
asyncPending = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Synchronous write with EAGAIN retry. Throws on I/O error.
|
||||
// Used by writeSync for the full write, and by writevSync for
|
||||
// completing a partial writev.
|
||||
function writeSyncAll(buf, offset, length, position) {
|
||||
let retries = 0;
|
||||
while (length > 0) {
|
||||
const ctx = {};
|
||||
const bytesWritten = binding.writeBuffer(
|
||||
fd, buf, offset, length, position, undefined, ctx) || 0;
|
||||
if (ctx.errno !== undefined) {
|
||||
handleSyncErrorFromBinding(ctx);
|
||||
}
|
||||
if (bytesWritten === 0) {
|
||||
if (++retries > 5) {
|
||||
throw new ERR_OPERATION_FAILED('write failed after retries');
|
||||
}
|
||||
} else {
|
||||
retries = 0;
|
||||
}
|
||||
totalBytesWritten += bytesWritten;
|
||||
offset += bytesWritten;
|
||||
length -= bytesWritten;
|
||||
if (position >= 0) position += bytesWritten;
|
||||
}
|
||||
}
|
||||
|
||||
async function cleanup() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
handle[kLocked] = false;
|
||||
handle[kUnref]();
|
||||
if (autoClose) {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
__proto__: null,
|
||||
write(chunk, options = kNullPrototo) {
|
||||
if (error) {
|
||||
return PromiseReject(error);
|
||||
}
|
||||
if (closed) {
|
||||
return PromiseReject(
|
||||
new ERR_INVALID_STATE.TypeError('The writer is closed'));
|
||||
}
|
||||
validateObject(options, 'options');
|
||||
const {
|
||||
signal,
|
||||
} = options;
|
||||
if (signal !== undefined) {
|
||||
validateAbortSignal(signal, 'options.signal');
|
||||
if (signal.aborted) {
|
||||
return PromiseReject(signal.reason);
|
||||
}
|
||||
}
|
||||
chunk = newStreamsToUint8Array(chunk);
|
||||
if (bytesRemaining >= 0 && chunk.byteLength > bytesRemaining) {
|
||||
return PromiseReject(
|
||||
new ERR_OUT_OF_RANGE('write', `<= ${bytesRemaining} bytes`,
|
||||
chunk.byteLength));
|
||||
}
|
||||
if (bytesRemaining > 0) bytesRemaining -= chunk.byteLength;
|
||||
const position = pos;
|
||||
if (pos >= 0) pos += chunk.byteLength;
|
||||
return writeAll(chunk, 0, chunk.byteLength, position, signal);
|
||||
},
|
||||
|
||||
writev(chunks, options = kNullPrototo) {
|
||||
if (error) {
|
||||
return PromiseReject(error);
|
||||
}
|
||||
if (closed) {
|
||||
return PromiseReject(
|
||||
new ERR_INVALID_STATE.TypeError('The writer is closed'));
|
||||
}
|
||||
validateObject(options, 'options');
|
||||
const {
|
||||
signal,
|
||||
} = options;
|
||||
if (signal !== undefined) {
|
||||
validateAbortSignal(signal, 'options.signal');
|
||||
if (signal?.aborted) {
|
||||
return PromiseReject(signal.reason);
|
||||
}
|
||||
}
|
||||
chunks = newStreamsConvertChunks(chunks);
|
||||
let totalSize = 0;
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
totalSize += chunks[i].byteLength;
|
||||
}
|
||||
if (bytesRemaining >= 0 && totalSize > bytesRemaining) {
|
||||
return PromiseReject(
|
||||
new ERR_OUT_OF_RANGE('writev', `<= ${bytesRemaining} bytes`,
|
||||
totalSize));
|
||||
}
|
||||
if (bytesRemaining > 0) bytesRemaining -= totalSize;
|
||||
const position = pos;
|
||||
if (pos >= 0) pos += totalSize;
|
||||
return writevAll(chunks, position, signal);
|
||||
},
|
||||
|
||||
writeSync(chunk) {
|
||||
if (error || closed || asyncPending) return false;
|
||||
chunk = newStreamsToUint8Array(chunk);
|
||||
const length = chunk.byteLength;
|
||||
if (length > syncWriteThreshold) return false;
|
||||
if (length === 0) return true;
|
||||
if (bytesRemaining >= 0 && length > bytesRemaining) return false;
|
||||
const position = pos;
|
||||
// First attempt - if this fails with zero bytes written,
|
||||
// return false so pipeTo can fall back to async write().
|
||||
const ctx = {};
|
||||
const bytesWritten = binding.writeBuffer(
|
||||
fd, chunk, 0, length, position, undefined, ctx) || 0;
|
||||
if (ctx.errno !== undefined) return false;
|
||||
totalBytesWritten += bytesWritten;
|
||||
if (position >= 0) {
|
||||
pos = position + bytesWritten;
|
||||
}
|
||||
if (bytesWritten === length) {
|
||||
if (bytesRemaining > 0) bytesRemaining -= length;
|
||||
return true;
|
||||
}
|
||||
// Partial write - bytes are on disk. Must complete or throw.
|
||||
// Cannot return false here because pipeTo would re-send the
|
||||
// full chunk, causing duplicate data on disk.
|
||||
writeSyncAll(chunk, bytesWritten, length - bytesWritten,
|
||||
position >= 0 ? position + bytesWritten : -1);
|
||||
if (bytesRemaining > 0) bytesRemaining -= length;
|
||||
return true;
|
||||
},
|
||||
|
||||
writevSync(chunks) {
|
||||
if (error || closed || asyncPending) return false;
|
||||
chunks = newStreamsConvertChunks(chunks);
|
||||
let totalSize = 0;
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
totalSize += chunks[i].byteLength;
|
||||
}
|
||||
if (totalSize > syncWriteThreshold) return false;
|
||||
if (totalSize === 0) return true;
|
||||
if (bytesRemaining >= 0 && totalSize > bytesRemaining) return false;
|
||||
const position = pos;
|
||||
// writeBuffers throws on error (zero bytes written) - safe
|
||||
// to catch and return false for async fallback.
|
||||
let bytesWritten;
|
||||
try {
|
||||
bytesWritten = binding.writeBuffers(fd, chunks, position) || 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
totalBytesWritten += bytesWritten;
|
||||
if (position >= 0) {
|
||||
pos = position + bytesWritten;
|
||||
}
|
||||
if (bytesWritten === totalSize) {
|
||||
if (bytesRemaining > 0) bytesRemaining -= totalSize;
|
||||
return true;
|
||||
}
|
||||
// Partial writev - bytes are on disk. Must complete or throw.
|
||||
const rest = Buffer.concat(chunks);
|
||||
writeSyncAll(rest, bytesWritten,
|
||||
rest.byteLength - bytesWritten,
|
||||
position >= 0 ? position + bytesWritten : -1);
|
||||
if (bytesRemaining > 0) bytesRemaining -= totalSize;
|
||||
return true;
|
||||
},
|
||||
|
||||
end(options = kNullPrototo) {
|
||||
if (error) {
|
||||
return PromiseReject(error);
|
||||
}
|
||||
if (closed) {
|
||||
return PromiseResolve(totalBytesWritten);
|
||||
}
|
||||
if (closing) {
|
||||
return pendingEndPromise;
|
||||
}
|
||||
validateObject(options, 'options');
|
||||
const {
|
||||
signal,
|
||||
} = options;
|
||||
if (signal !== undefined) {
|
||||
validateAbortSignal(signal, 'options.signal');
|
||||
if (signal.aborted) {
|
||||
return PromiseReject(signal.reason);
|
||||
}
|
||||
}
|
||||
closing = true;
|
||||
pendingEndPromise = PromisePrototypeThen(
|
||||
cleanup(), () => totalBytesWritten);
|
||||
return pendingEndPromise;
|
||||
},
|
||||
|
||||
endSync() {
|
||||
if (error) return -1;
|
||||
if (closed) return totalBytesWritten;
|
||||
if (asyncPending) return -1;
|
||||
closed = true;
|
||||
handle[kLocked] = false;
|
||||
handle[kUnref]();
|
||||
if (autoClose) {
|
||||
handle[kCloseSync]();
|
||||
}
|
||||
return totalBytesWritten;
|
||||
},
|
||||
|
||||
fail(reason) {
|
||||
if (closed || error) return;
|
||||
error = reason ?? new ERR_INVALID_STATE('Failed');
|
||||
closed = true;
|
||||
handle[kLocked] = false;
|
||||
handle[kUnref]();
|
||||
if (autoClose) {
|
||||
handle[kCloseSync]();
|
||||
}
|
||||
},
|
||||
|
||||
[SymbolAsyncDispose]() {
|
||||
if (closing) {
|
||||
return pendingEndPromise ?? PromiseResolve();
|
||||
}
|
||||
if (!closed && !error) {
|
||||
this.fail();
|
||||
}
|
||||
return PromiseResolve();
|
||||
},
|
||||
|
||||
[SymbolDispose]() {
|
||||
this.fail();
|
||||
},
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
async function handleFdClose(fileOpPromise, closeFunc) {
|
||||
return PromisePrototypeThen(
|
||||
fileOpPromise,
|
||||
|
||||
@@ -115,6 +115,7 @@ function prepareExecution(options) {
|
||||
setupNavigator();
|
||||
setupWarningHandler();
|
||||
setupSQLite();
|
||||
setupStreamIter();
|
||||
setupQuic();
|
||||
setupWebStorage();
|
||||
setupWebsocket();
|
||||
@@ -392,6 +393,16 @@ function initializeConfigFileSupport() {
|
||||
}
|
||||
}
|
||||
|
||||
function setupStreamIter() {
|
||||
if (!getOptionValue('--experimental-stream-iter')) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { BuiltinModule } = require('internal/bootstrap/realm');
|
||||
BuiltinModule.allowRequireByUsers('stream/iter');
|
||||
BuiltinModule.allowRequireByUsers('zlib/iter');
|
||||
}
|
||||
|
||||
function setupQuic() {
|
||||
if (!getOptionValue('--experimental-quic')) {
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,762 @@
|
||||
'use strict';
|
||||
|
||||
// New Streams API - Broadcast
|
||||
//
|
||||
// Push-model multi-consumer streaming. A single writer can push data to
|
||||
// multiple consumers. Each consumer has an independent cursor into a
|
||||
// shared buffer.
|
||||
|
||||
const {
|
||||
ArrayIsArray,
|
||||
ArrayPrototypePush,
|
||||
MathMax,
|
||||
PromisePrototypeThen,
|
||||
PromiseReject,
|
||||
PromiseResolve,
|
||||
PromiseWithResolvers,
|
||||
SafeSet,
|
||||
Symbol,
|
||||
SymbolAsyncDispose,
|
||||
SymbolAsyncIterator,
|
||||
SymbolDispose,
|
||||
TypedArrayPrototypeGetByteLength,
|
||||
} = primordials;
|
||||
|
||||
const { lazyDOMException } = require('internal/util');
|
||||
|
||||
const {
|
||||
codes: {
|
||||
ERR_INVALID_ARG_TYPE,
|
||||
ERR_INVALID_RETURN_VALUE,
|
||||
ERR_INVALID_STATE,
|
||||
},
|
||||
} = require('internal/errors');
|
||||
const {
|
||||
validateAbortSignal,
|
||||
validateInteger,
|
||||
validateObject,
|
||||
} = require('internal/validators');
|
||||
|
||||
const {
|
||||
broadcastProtocol,
|
||||
drainableProtocol,
|
||||
} = require('internal/streams/iter/types');
|
||||
|
||||
const {
|
||||
isAsyncIterable,
|
||||
isSyncIterable,
|
||||
} = require('internal/streams/iter/from');
|
||||
|
||||
const {
|
||||
pull: pullWithTransforms,
|
||||
} = require('internal/streams/iter/pull');
|
||||
|
||||
const {
|
||||
kMultiConsumerDefaultHWM,
|
||||
kResolvedPromise,
|
||||
clampHWM,
|
||||
convertChunks,
|
||||
getMinCursor,
|
||||
hasProtocol,
|
||||
onSignalAbort,
|
||||
parsePullArgs,
|
||||
wrapError,
|
||||
toUint8Array,
|
||||
validateBackpressure,
|
||||
} = require('internal/streams/iter/utils');
|
||||
|
||||
const {
|
||||
RingBuffer,
|
||||
} = require('internal/streams/iter/ringbuffer');
|
||||
|
||||
const kCancelWriter = Symbol('kCancelWriter');
|
||||
const kWrite = Symbol('kWrite');
|
||||
const kEnd = Symbol('kEnd');
|
||||
const kAbort = Symbol('kAbort');
|
||||
const kGetDesiredSize = Symbol('kGetDesiredSize');
|
||||
const kCanWrite = Symbol('kCanWrite');
|
||||
const kOnBufferDrained = Symbol('kOnBufferDrained');
|
||||
|
||||
// =============================================================================
|
||||
// Broadcast Implementation
|
||||
// =============================================================================
|
||||
|
||||
class BroadcastImpl {
|
||||
#buffer = new RingBuffer();
|
||||
#bufferStart = 0;
|
||||
#consumers = new SafeSet();
|
||||
#waiters = []; // Consumers with pending resolve (subset of #consumers)
|
||||
#ended = false;
|
||||
#error = null;
|
||||
#cancelled = false;
|
||||
#options;
|
||||
#writer = null;
|
||||
#cachedMinCursor = 0;
|
||||
#minCursorDirty = false;
|
||||
|
||||
constructor(options) {
|
||||
this.#options = options;
|
||||
this[kOnBufferDrained] = null;
|
||||
}
|
||||
|
||||
setWriter(writer) {
|
||||
this.#writer = writer;
|
||||
}
|
||||
|
||||
get backpressurePolicy() {
|
||||
return this.#options.backpressure;
|
||||
}
|
||||
|
||||
get highWaterMark() {
|
||||
return this.#options.highWaterMark;
|
||||
}
|
||||
|
||||
get consumerCount() {
|
||||
return this.#consumers.size;
|
||||
}
|
||||
|
||||
get bufferSize() {
|
||||
return this.#buffer.length;
|
||||
}
|
||||
|
||||
push(...args) {
|
||||
const { transforms, options } = parsePullArgs(args);
|
||||
const rawConsumer = this.#createRawConsumer();
|
||||
|
||||
// When transforms are present, delegate to pull() which creates its
|
||||
// own internal AbortController that follows the external signal.
|
||||
// When no transforms, return rawConsumer directly (controller elided
|
||||
// per PULL-02 optimization -- no transforms means no signal recipient).
|
||||
if (transforms.length > 0) {
|
||||
const pullArgs = [...transforms];
|
||||
if (options?.signal) {
|
||||
ArrayPrototypePush(pullArgs,
|
||||
{ __proto__: null, signal: options.signal });
|
||||
}
|
||||
return pullWithTransforms(rawConsumer, ...pullArgs);
|
||||
}
|
||||
return rawConsumer;
|
||||
}
|
||||
|
||||
#createRawConsumer() {
|
||||
const state = {
|
||||
__proto__: null,
|
||||
// Start at the oldest buffered entry so late-joining consumers
|
||||
// can read data already in the buffer.
|
||||
cursor: this.#bufferStart,
|
||||
resolve: null,
|
||||
reject: null,
|
||||
detached: false,
|
||||
};
|
||||
|
||||
this.#consumers.add(state);
|
||||
// New consumer starts at buffer start; recalculate min cursor
|
||||
// since this consumer may now be the slowest.
|
||||
if (this.#consumers.size === 1) {
|
||||
this.#cachedMinCursor = state.cursor;
|
||||
this.#minCursorDirty = false;
|
||||
} else {
|
||||
this.#minCursorDirty = true;
|
||||
}
|
||||
const self = this;
|
||||
|
||||
const kDone = PromiseResolve(
|
||||
{ __proto__: null, done: true, value: undefined });
|
||||
|
||||
function detach() {
|
||||
state.detached = true;
|
||||
state.resolve = null;
|
||||
state.reject = null;
|
||||
self.#consumers.delete(state);
|
||||
self.#minCursorDirty = true;
|
||||
self.#tryTrimBuffer();
|
||||
}
|
||||
|
||||
return {
|
||||
__proto__: null,
|
||||
[SymbolAsyncIterator]() {
|
||||
return {
|
||||
__proto__: null,
|
||||
next() {
|
||||
if (state.detached) {
|
||||
if (self.#error) return PromiseReject(self.#error);
|
||||
return kDone;
|
||||
}
|
||||
|
||||
const bufferIndex = state.cursor - self.#bufferStart;
|
||||
if (bufferIndex < self.#buffer.length) {
|
||||
const chunk = self.#buffer.get(bufferIndex);
|
||||
// If this consumer was at the min cursor, mark dirty
|
||||
if (state.cursor <= self.#cachedMinCursor) {
|
||||
self.#minCursorDirty = true;
|
||||
}
|
||||
state.cursor++;
|
||||
self.#tryTrimBuffer();
|
||||
return PromiseResolve(
|
||||
{ __proto__: null, done: false, value: chunk });
|
||||
}
|
||||
|
||||
if (self.#error) {
|
||||
state.detached = true;
|
||||
self.#consumers.delete(state);
|
||||
return PromiseReject(self.#error);
|
||||
}
|
||||
|
||||
if (self.#ended || self.#cancelled) {
|
||||
detach();
|
||||
return kDone;
|
||||
}
|
||||
|
||||
const { promise, resolve, reject } = PromiseWithResolvers();
|
||||
state.resolve = resolve;
|
||||
state.reject = reject;
|
||||
ArrayPrototypePush(self.#waiters, state);
|
||||
return promise;
|
||||
},
|
||||
|
||||
return() {
|
||||
detach();
|
||||
return kDone;
|
||||
},
|
||||
|
||||
throw() {
|
||||
detach();
|
||||
return kDone;
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
cancel(reason) {
|
||||
if (this.#cancelled) return;
|
||||
this.#cancelled = true;
|
||||
this.#ended = true; // Prevents [kAbort]() from redundantly iterating consumers
|
||||
|
||||
if (reason !== undefined) {
|
||||
this.#error = reason;
|
||||
}
|
||||
|
||||
// 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 (reason !== undefined) {
|
||||
consumer.reject?.(reason);
|
||||
} else {
|
||||
consumer.resolve({ __proto__: null, done: true, value: undefined });
|
||||
}
|
||||
consumer.resolve = null;
|
||||
consumer.reject = null;
|
||||
}
|
||||
consumer.detached = true;
|
||||
}
|
||||
this.#consumers.clear();
|
||||
}
|
||||
|
||||
[SymbolDispose]() {
|
||||
this.cancel();
|
||||
}
|
||||
|
||||
// Methods accessed by BroadcastWriter via symbol keys
|
||||
|
||||
[kWrite](chunk) {
|
||||
if (this.#ended || this.#cancelled) return false;
|
||||
|
||||
if (this.#buffer.length >= this.#options.highWaterMark) {
|
||||
switch (this.#options.backpressure) {
|
||||
case 'strict':
|
||||
case 'block':
|
||||
return false;
|
||||
case 'drop-oldest':
|
||||
this.#buffer.shift();
|
||||
this.#bufferStart++;
|
||||
for (const consumer of this.#consumers) {
|
||||
if (consumer.cursor < this.#bufferStart) {
|
||||
consumer.cursor = this.#bufferStart;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'drop-newest':
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
this.#buffer.push(chunk);
|
||||
this.#notifyConsumers();
|
||||
return true;
|
||||
}
|
||||
|
||||
[kEnd]() {
|
||||
if (this.#ended) return;
|
||||
this.#ended = true;
|
||||
|
||||
for (const consumer of this.#consumers) {
|
||||
if (consumer.resolve) {
|
||||
const bufferIndex = consumer.cursor - this.#bufferStart;
|
||||
if (bufferIndex < this.#buffer.length) {
|
||||
const chunk = this.#buffer.get(bufferIndex);
|
||||
consumer.cursor++;
|
||||
consumer.resolve({ __proto__: null, done: false, value: chunk });
|
||||
} else {
|
||||
consumer.resolve({ __proto__: null, done: true, value: undefined });
|
||||
}
|
||||
consumer.resolve = null;
|
||||
consumer.reject = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[kAbort](reason) {
|
||||
if (this.#ended || this.#error) return;
|
||||
this.#error = reason;
|
||||
this.#ended = true;
|
||||
|
||||
// Notify all waiting consumers and detach them
|
||||
for (const consumer of this.#consumers) {
|
||||
if (consumer.reject) {
|
||||
consumer.reject(reason);
|
||||
consumer.resolve = null;
|
||||
consumer.reject = null;
|
||||
}
|
||||
consumer.detached = true;
|
||||
}
|
||||
this.#consumers.clear();
|
||||
}
|
||||
|
||||
[kGetDesiredSize]() {
|
||||
if (this.#ended || this.#cancelled) return null;
|
||||
return MathMax(0, this.#options.highWaterMark - this.#buffer.length);
|
||||
}
|
||||
|
||||
[kCanWrite]() {
|
||||
if (this.#ended || this.#cancelled) return false;
|
||||
if ((this.#options.backpressure === 'strict' ||
|
||||
this.#options.backpressure === 'block') &&
|
||||
this.#buffer.length >= this.#options.highWaterMark) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Private methods
|
||||
|
||||
#recomputeMinCursor() {
|
||||
this.#cachedMinCursor = getMinCursor(
|
||||
this.#consumers, this.#bufferStart + this.#buffer.length);
|
||||
this.#minCursorDirty = false;
|
||||
}
|
||||
|
||||
#tryTrimBuffer() {
|
||||
if (this.#minCursorDirty) {
|
||||
this.#recomputeMinCursor();
|
||||
}
|
||||
const trimCount = this.#cachedMinCursor - this.#bufferStart;
|
||||
if (trimCount > 0) {
|
||||
this.#buffer.trimFront(trimCount);
|
||||
this.#bufferStart = this.#cachedMinCursor;
|
||||
|
||||
if (this[kOnBufferDrained] &&
|
||||
this.#buffer.length < this.#options.highWaterMark) {
|
||||
this[kOnBufferDrained]();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#notifyConsumers() {
|
||||
const waiters = this.#waiters;
|
||||
if (waiters.length === 0) return;
|
||||
// Swap out the waiters list so consumers that re-wait during
|
||||
// resolve don't get processed twice in this cycle.
|
||||
this.#waiters = [];
|
||||
for (let i = 0; i < waiters.length; i++) {
|
||||
const consumer = waiters[i];
|
||||
if (consumer.resolve) {
|
||||
const bufferIndex = consumer.cursor - this.#bufferStart;
|
||||
if (bufferIndex < this.#buffer.length) {
|
||||
const chunk = this.#buffer.get(bufferIndex);
|
||||
if (consumer.cursor <= this.#cachedMinCursor) {
|
||||
this.#minCursorDirty = true;
|
||||
}
|
||||
consumer.cursor++;
|
||||
const resolve = consumer.resolve;
|
||||
consumer.resolve = null;
|
||||
consumer.reject = null;
|
||||
resolve({ __proto__: null, done: false, value: chunk });
|
||||
} else {
|
||||
// Still waiting -- put back
|
||||
ArrayPrototypePush(this.#waiters, consumer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// BroadcastWriter
|
||||
// =============================================================================
|
||||
|
||||
let getBroadcastPendingWrites;
|
||||
|
||||
class BroadcastWriter {
|
||||
#broadcast;
|
||||
#totalBytes = 0;
|
||||
#closed;
|
||||
#aborted = false;
|
||||
#pendingWrites = new RingBuffer();
|
||||
#pendingDrains = [];
|
||||
|
||||
static {
|
||||
// Used in wireBroadcastWriteSignal ensure the signal listener can be
|
||||
// constructed without closing over the chunk data, which may be large.
|
||||
getBroadcastPendingWrites = (obj) => obj.#pendingWrites;
|
||||
}
|
||||
|
||||
constructor(broadcastImpl) {
|
||||
this.#broadcast = broadcastImpl;
|
||||
|
||||
this.#broadcast[kOnBufferDrained] = () => {
|
||||
this.#resolvePendingWrites();
|
||||
this.#resolvePendingDrains(true);
|
||||
};
|
||||
}
|
||||
|
||||
// The drainable protocol works with Stream.ondrain to provide a notification
|
||||
// when the writer can accept more data after being backpressured.
|
||||
[drainableProtocol]() {
|
||||
const desired = this.desiredSize;
|
||||
if (desired === null) return null;
|
||||
if (desired > 0) return PromiseResolve(true);
|
||||
const { promise, resolve, reject } = PromiseWithResolvers();
|
||||
ArrayPrototypePush(this.#pendingDrains, { __proto__: null, resolve, reject });
|
||||
return promise;
|
||||
}
|
||||
|
||||
#isClosed() {
|
||||
return this.#closed !== undefined;
|
||||
}
|
||||
|
||||
#isClosedOrAborted() {
|
||||
return this.#isClosed() || this.#aborted;
|
||||
}
|
||||
|
||||
get desiredSize() {
|
||||
return this.#isClosedOrAborted() ? null : this.#broadcast[kGetDesiredSize]();
|
||||
}
|
||||
|
||||
#canUseWriteFastPath(options) {
|
||||
return !options?.signal && !this.#isClosed() && !this.#aborted &&
|
||||
this.#broadcast[kCanWrite]();
|
||||
}
|
||||
|
||||
write(chunk, options) {
|
||||
// Fast path: no signal, writer open, buffer has space
|
||||
if (this.#canUseWriteFastPath(options)) {
|
||||
const converted = toUint8Array(chunk);
|
||||
this.#broadcast[kWrite]([converted]);
|
||||
this.#totalBytes += TypedArrayPrototypeGetByteLength(converted);
|
||||
return kResolvedPromise;
|
||||
}
|
||||
return this.#writevSlow([chunk], options);
|
||||
}
|
||||
|
||||
writev(chunks, options) {
|
||||
// Fast path: no signal, writer open, buffer has space
|
||||
if (this.#canUseWriteFastPath(options)) {
|
||||
const converted = convertChunks(chunks);
|
||||
this.#broadcast[kWrite](converted);
|
||||
for (let i = 0; i < converted.length; i++) {
|
||||
this.#totalBytes += TypedArrayPrototypeGetByteLength(converted[i]);
|
||||
}
|
||||
return kResolvedPromise;
|
||||
}
|
||||
return this.#writevSlow(chunks, options);
|
||||
}
|
||||
|
||||
async #writevSlow(chunks, options) {
|
||||
const signal = options?.signal;
|
||||
|
||||
// Check for pre-aborted
|
||||
signal?.throwIfAborted();
|
||||
|
||||
if (this.#isClosedOrAborted()) {
|
||||
throw new ERR_INVALID_STATE.TypeError('Writer is closed');
|
||||
}
|
||||
|
||||
const converted = convertChunks(chunks);
|
||||
|
||||
if (this.#broadcast[kWrite](converted)) {
|
||||
for (let i = 0; i < converted.length; i++) {
|
||||
this.#totalBytes += TypedArrayPrototypeGetByteLength(converted[i]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const policy = this.#broadcast.backpressurePolicy;
|
||||
const hwm = this.#broadcast.highWaterMark;
|
||||
|
||||
if (policy === 'strict') {
|
||||
if (this.#pendingWrites.length >= hwm) {
|
||||
throw new ERR_INVALID_STATE.TypeError(
|
||||
'Backpressure violation: too many pending writes. ' +
|
||||
'Await each write() call to respect backpressure.');
|
||||
}
|
||||
return this.#createPendingWrite(converted, signal);
|
||||
}
|
||||
|
||||
// 'block' policy
|
||||
return this.#createPendingWrite(converted, signal);
|
||||
}
|
||||
|
||||
writeSync(chunk) {
|
||||
if (this.#isClosedOrAborted()) return false;
|
||||
if (!this.#broadcast[kCanWrite]()) return false;
|
||||
const converted =
|
||||
toUint8Array(chunk);
|
||||
if (this.#broadcast[kWrite]([converted])) {
|
||||
this.#totalBytes += TypedArrayPrototypeGetByteLength(converted);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
writevSync(chunks) {
|
||||
if (this.#isClosedOrAborted()) return false;
|
||||
if (!this.#broadcast[kCanWrite]()) return false;
|
||||
const converted = convertChunks(chunks);
|
||||
if (this.#broadcast[kWrite](converted)) {
|
||||
for (let i = 0; i < converted.length; i++) {
|
||||
this.#totalBytes += TypedArrayPrototypeGetByteLength(converted[i]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// end() is synchronous internally - signal accepted for interface compliance.
|
||||
end(options) {
|
||||
if (this.#isClosed()) return this.#closed;
|
||||
this.#closed = PromiseResolve(this.#totalBytes);
|
||||
this.#broadcast[kEnd]();
|
||||
this.#resolvePendingDrains(false);
|
||||
return this.#closed;
|
||||
}
|
||||
|
||||
endSync() {
|
||||
if (this.#closed) return this.#totalBytes;
|
||||
this.#closed = PromiseResolve(this.#totalBytes);
|
||||
this.#broadcast[kEnd]();
|
||||
this.#resolvePendingDrains(false);
|
||||
return this.#totalBytes;
|
||||
}
|
||||
|
||||
fail(reason) {
|
||||
if (this.#isClosedOrAborted()) return;
|
||||
this.#aborted = true;
|
||||
this.#closed = PromiseResolve(this.#totalBytes);
|
||||
const error = reason ?? new ERR_INVALID_STATE.TypeError('Failed');
|
||||
this.#rejectPendingWrites(error);
|
||||
this.#rejectPendingDrains(error);
|
||||
this.#broadcast[kAbort](error);
|
||||
}
|
||||
|
||||
[SymbolAsyncDispose]() {
|
||||
this.fail();
|
||||
return PromiseResolve();
|
||||
}
|
||||
|
||||
[SymbolDispose]() {
|
||||
this.fail();
|
||||
}
|
||||
|
||||
[kCancelWriter]() {
|
||||
if (this.#isClosed()) return;
|
||||
this.#closed = PromiseResolve(this.#totalBytes);
|
||||
this.#rejectPendingWrites(
|
||||
lazyDOMException('Broadcast cancelled', 'AbortError'));
|
||||
this.#resolvePendingDrains(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a pending write promise, optionally racing against a signal.
|
||||
* If the signal fires, the entry is removed from pendingWrites and the
|
||||
* promise rejects. Signal listeners are cleaned up on normal resolution.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
#createPendingWrite(chunk, signal) {
|
||||
const { promise, resolve, reject } = PromiseWithResolvers();
|
||||
const entry = { __proto__: null, chunk, resolve, reject };
|
||||
this.#pendingWrites.push(entry);
|
||||
if (signal) {
|
||||
wireBroadcastWriteSignal(entry, signal, resolve, reject, this);
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
|
||||
#resolvePendingWrites() {
|
||||
while (this.#pendingWrites.length > 0 && this.#broadcast[kCanWrite]()) {
|
||||
const pending = this.#pendingWrites.shift();
|
||||
if (this.#broadcast[kWrite](pending.chunk)) {
|
||||
for (let i = 0; i < pending.chunk.length; i++) {
|
||||
this.#totalBytes += TypedArrayPrototypeGetByteLength(pending.chunk[i]);
|
||||
}
|
||||
pending.resolve();
|
||||
} else {
|
||||
this.#pendingWrites.unshift(pending);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#rejectPendingWrites(error) {
|
||||
while (this.#pendingWrites.length > 0) {
|
||||
this.#pendingWrites.shift().reject(error);
|
||||
}
|
||||
}
|
||||
|
||||
#resolvePendingDrains(canWrite) {
|
||||
const drains = this.#pendingDrains;
|
||||
this.#pendingDrains = [];
|
||||
for (let i = 0; i < drains.length; i++) {
|
||||
drains[i].resolve(canWrite);
|
||||
}
|
||||
}
|
||||
|
||||
#rejectPendingDrains(error) {
|
||||
const drains = this.#pendingDrains;
|
||||
this.#pendingDrains = [];
|
||||
for (let i = 0; i < drains.length; i++) {
|
||||
drains[i].reject(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function wireBroadcastWriteSignal(entry, signal, resolve, reject, self) {
|
||||
const onAbort = () => {
|
||||
const pendingWrites = getBroadcastPendingWrites(self);
|
||||
const idx = pendingWrites.indexOf(entry);
|
||||
if (idx !== -1) pendingWrites.removeAt(idx);
|
||||
entry.chunk = null;
|
||||
reject(signal.reason ?? lazyDOMException('Aborted', 'AbortError'));
|
||||
};
|
||||
entry.resolve = function() {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
entry.chunk = null;
|
||||
resolve();
|
||||
};
|
||||
entry.reject = function(reason) {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
entry.chunk = null;
|
||||
reject(reason);
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { __proto__: null, once: true });
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Public API
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Create a broadcast channel for push-model multi-consumer streaming.
|
||||
* @param {{ highWaterMark?: number, backpressure?: string, signal?: AbortSignal }} [options]
|
||||
* @returns {{ writer: Writer, broadcast: Broadcast }}
|
||||
*/
|
||||
function broadcast(options = { __proto__: null }) {
|
||||
validateObject(options, 'options');
|
||||
const {
|
||||
highWaterMark = kMultiConsumerDefaultHWM,
|
||||
backpressure = 'strict',
|
||||
signal,
|
||||
} = options;
|
||||
validateInteger(highWaterMark, 'options.highWaterMark');
|
||||
validateBackpressure(backpressure);
|
||||
if (signal !== undefined) {
|
||||
validateAbortSignal(signal, 'options.signal');
|
||||
}
|
||||
|
||||
const opts = {
|
||||
__proto__: null,
|
||||
highWaterMark: clampHWM(highWaterMark),
|
||||
backpressure,
|
||||
signal,
|
||||
};
|
||||
|
||||
const broadcastImpl = new BroadcastImpl(opts);
|
||||
const writer = new BroadcastWriter(broadcastImpl);
|
||||
broadcastImpl.setWriter(writer);
|
||||
|
||||
if (signal) {
|
||||
onSignalAbort(signal, () => broadcastImpl.cancel());
|
||||
}
|
||||
|
||||
return { __proto__: null, writer, broadcast: broadcastImpl };
|
||||
}
|
||||
|
||||
function isBroadcastable(value) {
|
||||
return hasProtocol(value, broadcastProtocol);
|
||||
}
|
||||
|
||||
const Broadcast = {
|
||||
__proto__: null,
|
||||
from(input, options) {
|
||||
if (isBroadcastable(input)) {
|
||||
const bc = input[broadcastProtocol](options);
|
||||
if (bc === null || typeof bc !== 'object') {
|
||||
throw new ERR_INVALID_RETURN_VALUE(
|
||||
'an object', '[Symbol.for(\'Stream.broadcastProtocol\')]', bc);
|
||||
}
|
||||
return { __proto__: null, writer: { __proto__: null }, broadcast: bc };
|
||||
}
|
||||
|
||||
if (!isAsyncIterable(input) && !isSyncIterable(input)) {
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'input', ['Broadcastable', 'AsyncIterable', 'Iterable'], input);
|
||||
}
|
||||
|
||||
const result = broadcast(options);
|
||||
const signal = options?.signal;
|
||||
|
||||
const pump = async () => {
|
||||
const w = result.writer;
|
||||
try {
|
||||
if (isAsyncIterable(input)) {
|
||||
for await (const chunks of input) {
|
||||
signal?.throwIfAborted();
|
||||
if (ArrayIsArray(chunks)) {
|
||||
if (!w.writevSync(chunks)) {
|
||||
await w.writev(chunks, signal ? { signal } : undefined);
|
||||
}
|
||||
} else if (!w.writeSync(chunks)) {
|
||||
await w.write(chunks, signal ? { signal } : undefined);
|
||||
}
|
||||
}
|
||||
} else if (isSyncIterable(input)) {
|
||||
for (const chunks of input) {
|
||||
signal?.throwIfAborted();
|
||||
if (ArrayIsArray(chunks)) {
|
||||
if (!w.writevSync(chunks)) {
|
||||
await w.writev(chunks, signal ? { signal } : undefined);
|
||||
}
|
||||
} else if (!w.writeSync(chunks)) {
|
||||
await w.write(chunks, signal ? { signal } : undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (w.endSync() < 0) {
|
||||
await w.end(signal ? { signal } : undefined);
|
||||
}
|
||||
} catch (error) {
|
||||
w.fail(wrapError(error));
|
||||
}
|
||||
};
|
||||
PromisePrototypeThen(pump(), undefined, () => {});
|
||||
|
||||
return result;
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
Broadcast,
|
||||
broadcast,
|
||||
};
|
||||
@@ -0,0 +1,523 @@
|
||||
'use strict';
|
||||
|
||||
// New Streams API - Consumers & Utilities
|
||||
//
|
||||
// bytes(), text(), arrayBuffer() - collect entire stream
|
||||
// tap(), tapSync() - observe without modifying
|
||||
// merge() - temporal combining of sources
|
||||
// ondrain() - backpressure drain utility
|
||||
|
||||
const {
|
||||
ArrayBufferPrototypeGetByteLength,
|
||||
ArrayBufferPrototypeSlice,
|
||||
ArrayPrototypeMap,
|
||||
ArrayPrototypePush,
|
||||
ArrayPrototypeSlice,
|
||||
Promise,
|
||||
PromisePrototypeThen,
|
||||
SafePromiseAllReturnVoid,
|
||||
SymbolAsyncIterator,
|
||||
TypedArrayPrototypeGetBuffer,
|
||||
TypedArrayPrototypeGetByteLength,
|
||||
TypedArrayPrototypeGetByteOffset,
|
||||
} = primordials;
|
||||
|
||||
const {
|
||||
codes: {
|
||||
ERR_INVALID_ARG_TYPE,
|
||||
ERR_INVALID_ARG_VALUE,
|
||||
ERR_OUT_OF_RANGE,
|
||||
},
|
||||
} = require('internal/errors');
|
||||
const { TextDecoder } = require('internal/encoding');
|
||||
const {
|
||||
validateAbortSignal,
|
||||
validateFunction,
|
||||
validateInteger,
|
||||
validateObject,
|
||||
} = require('internal/validators');
|
||||
|
||||
const {
|
||||
from,
|
||||
fromSync,
|
||||
isAsyncIterable,
|
||||
isSyncIterable,
|
||||
} = require('internal/streams/iter/from');
|
||||
|
||||
const {
|
||||
concatBytes,
|
||||
} = require('internal/streams/iter/utils');
|
||||
|
||||
const {
|
||||
drainableProtocol,
|
||||
} = require('internal/streams/iter/types');
|
||||
|
||||
const {
|
||||
isSharedArrayBuffer,
|
||||
} = require('internal/util/types');
|
||||
|
||||
// =============================================================================
|
||||
// Type Guards
|
||||
// =============================================================================
|
||||
|
||||
function isMergeOptions(value) {
|
||||
return (
|
||||
value !== null &&
|
||||
typeof value === 'object' &&
|
||||
!isAsyncIterable(value) &&
|
||||
!isSyncIterable(value)
|
||||
);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Shared chunk collection helpers
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Collect chunks from a sync source into an array.
|
||||
* @param {Iterable<Uint8Array[]>} source
|
||||
* @param {number} [limit]
|
||||
* @returns {Uint8Array[]}
|
||||
*/
|
||||
function collectSync(source, limit) {
|
||||
// Normalize source via fromSync() - accepts strings, ArrayBuffers, protocols, etc.
|
||||
const normalized = fromSync(source);
|
||||
const chunks = [];
|
||||
let totalBytes = 0;
|
||||
|
||||
for (const batch of normalized) {
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
const chunk = batch[i];
|
||||
if (limit !== undefined) {
|
||||
totalBytes += TypedArrayPrototypeGetByteLength(chunk);
|
||||
if (totalBytes > limit) {
|
||||
throw new ERR_OUT_OF_RANGE('totalBytes', `<= ${limit}`, totalBytes);
|
||||
}
|
||||
}
|
||||
ArrayPrototypePush(chunks, chunk);
|
||||
}
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect chunks from an async or sync source into an array.
|
||||
* @param {AsyncIterable<Uint8Array[]>|Iterable<Uint8Array[]>} source
|
||||
* @param {AbortSignal} [signal]
|
||||
* @param {number} [limit]
|
||||
* @returns {Promise<Uint8Array[]>}
|
||||
*/
|
||||
async function collectAsync(source, signal, limit) {
|
||||
signal?.throwIfAborted();
|
||||
|
||||
// Normalize source via from() - accepts strings, ArrayBuffers, protocols, etc.
|
||||
const normalized = from(source);
|
||||
const chunks = [];
|
||||
|
||||
// Fast path: no signal and no limit
|
||||
if (!signal && limit === undefined) {
|
||||
for await (const batch of normalized) {
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
ArrayPrototypePush(chunks, batch[i]);
|
||||
}
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
// Slow path: with signal or limit checks
|
||||
let totalBytes = 0;
|
||||
|
||||
for await (const batch of normalized) {
|
||||
signal?.throwIfAborted();
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
const chunk = batch[i];
|
||||
if (limit !== undefined) {
|
||||
totalBytes += TypedArrayPrototypeGetByteLength(chunk);
|
||||
if (totalBytes > limit) {
|
||||
throw new ERR_OUT_OF_RANGE('totalBytes', `<= ${limit}`, totalBytes);
|
||||
}
|
||||
}
|
||||
ArrayPrototypePush(chunks, chunk);
|
||||
}
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a Uint8Array to its backing ArrayBuffer, slicing if necessary.
|
||||
* Handles both ArrayBuffer and SharedArrayBuffer backing stores.
|
||||
* @param {Uint8Array} data
|
||||
* @returns {ArrayBuffer|SharedArrayBuffer}
|
||||
*/
|
||||
function toArrayBuffer(data) {
|
||||
const byteOffset = TypedArrayPrototypeGetByteOffset(data);
|
||||
const byteLength = TypedArrayPrototypeGetByteLength(data);
|
||||
const buffer = TypedArrayPrototypeGetBuffer(data);
|
||||
// SharedArrayBuffer is not available in primordials, so use
|
||||
// direct property access for its byteLength and slice.
|
||||
if (isSharedArrayBuffer(buffer)) {
|
||||
if (byteOffset === 0 && byteLength === buffer.byteLength) {
|
||||
return buffer;
|
||||
}
|
||||
return buffer.slice(byteOffset, byteOffset + byteLength);
|
||||
}
|
||||
if (byteOffset === 0 &&
|
||||
byteLength === ArrayBufferPrototypeGetByteLength(buffer)) {
|
||||
return buffer;
|
||||
}
|
||||
return ArrayBufferPrototypeSlice(buffer, byteOffset,
|
||||
byteOffset + byteLength);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Shared option validation
|
||||
// =============================================================================
|
||||
|
||||
function validateBaseConsumerOptions(options) {
|
||||
validateObject(options, 'options');
|
||||
if (options.limit !== undefined) {
|
||||
validateInteger(options.limit, 'options.limit', 0);
|
||||
}
|
||||
if (options.encoding !== undefined) {
|
||||
if (typeof options.encoding !== 'string') {
|
||||
throw new ERR_INVALID_ARG_TYPE('options.encoding', 'string',
|
||||
options.encoding);
|
||||
}
|
||||
try {
|
||||
new TextDecoder(options.encoding);
|
||||
} catch {
|
||||
throw new ERR_INVALID_ARG_VALUE.RangeError(
|
||||
'options.encoding', options.encoding);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function validateConsumerOptions(options) {
|
||||
validateBaseConsumerOptions(options);
|
||||
if (options.signal !== undefined) {
|
||||
validateAbortSignal(options.signal, 'options.signal');
|
||||
}
|
||||
}
|
||||
|
||||
function validateSyncConsumerOptions(options) {
|
||||
validateBaseConsumerOptions(options);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Sync Consumers
|
||||
// =============================================================================
|
||||
|
||||
const kNullPrototype = { __proto__: null };
|
||||
|
||||
/**
|
||||
* Collect all bytes from a sync source.
|
||||
* @param {Iterable<Uint8Array[]>} source
|
||||
* @param {{ limit?: number }} [options]
|
||||
* @returns {Uint8Array}
|
||||
*/
|
||||
function bytesSync(source, options = kNullPrototype) {
|
||||
validateSyncConsumerOptions(options);
|
||||
return concatBytes(collectSync(source, options.limit));
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect and decode text from a sync source.
|
||||
* @param {Iterable<Uint8Array[]>} source
|
||||
* @param {{ encoding?: string, limit?: number }} [options]
|
||||
* @returns {string}
|
||||
*/
|
||||
function textSync(source, options = kNullPrototype) {
|
||||
validateSyncConsumerOptions(options);
|
||||
const data = concatBytes(collectSync(source, options.limit));
|
||||
const decoder = new TextDecoder(options.encoding ?? 'utf-8', {
|
||||
__proto__: null,
|
||||
fatal: true,
|
||||
});
|
||||
return decoder.decode(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect bytes as ArrayBuffer from a sync source.
|
||||
* @param {Iterable<Uint8Array[]>} source
|
||||
* @param {{ limit?: number }} [options]
|
||||
* @returns {ArrayBuffer}
|
||||
*/
|
||||
function arrayBufferSync(source, options = kNullPrototype) {
|
||||
validateSyncConsumerOptions(options);
|
||||
return toArrayBuffer(concatBytes(collectSync(source, options.limit)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect all chunks as an array from a sync source.
|
||||
* @param {Iterable<Uint8Array[]>} source
|
||||
* @param {{ limit?: number }} [options]
|
||||
* @returns {Uint8Array[]}
|
||||
*/
|
||||
function arraySync(source, options = kNullPrototype) {
|
||||
validateSyncConsumerOptions(options);
|
||||
return collectSync(source, options.limit);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Async Consumers
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Collect all bytes from an async or sync source.
|
||||
* @param {AsyncIterable<Uint8Array[]>|Iterable<Uint8Array[]>} source
|
||||
* @param {{ signal?: AbortSignal, limit?: number }} [options]
|
||||
* @returns {Promise<Uint8Array>}
|
||||
*/
|
||||
async function bytes(source, options = kNullPrototype) {
|
||||
validateConsumerOptions(options);
|
||||
const chunks = await collectAsync(source, options.signal, options.limit);
|
||||
return concatBytes(chunks);
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect and decode text from an async or sync source.
|
||||
* @param {AsyncIterable<Uint8Array[]>|Iterable<Uint8Array[]>} source
|
||||
* @param {{ encoding?: string, signal?: AbortSignal, limit?: number }} [options]
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async function text(source, options = kNullPrototype) {
|
||||
validateConsumerOptions(options);
|
||||
const chunks = await collectAsync(source, options.signal, options.limit);
|
||||
const data = concatBytes(chunks);
|
||||
const decoder = new TextDecoder(options.encoding ?? 'utf-8', {
|
||||
__proto__: null,
|
||||
fatal: true,
|
||||
});
|
||||
return decoder.decode(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect bytes as ArrayBuffer from an async or sync source.
|
||||
* @param {AsyncIterable<Uint8Array[]>|Iterable<Uint8Array[]>} source
|
||||
* @param {{ signal?: AbortSignal, limit?: number }} [options]
|
||||
* @returns {Promise<ArrayBuffer>}
|
||||
*/
|
||||
async function arrayBuffer(source, options = kNullPrototype) {
|
||||
validateConsumerOptions(options);
|
||||
const chunks = await collectAsync(source, options.signal, options.limit);
|
||||
return toArrayBuffer(concatBytes(chunks));
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect all chunks as an array from an async or sync source.
|
||||
* @param {AsyncIterable<Uint8Array[]>|Iterable<Uint8Array[]>} source
|
||||
* @param {{ signal?: AbortSignal, limit?: number }} [options]
|
||||
* @returns {Promise<Uint8Array[]>}
|
||||
*/
|
||||
async function array(source, options = kNullPrototype) {
|
||||
validateConsumerOptions(options);
|
||||
return collectAsync(source, options.signal, options.limit);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Tap Utilities
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Create a pass-through transform that observes chunks without modifying them.
|
||||
* @param {Function} callback
|
||||
* @returns {Function}
|
||||
*/
|
||||
function tap(callback) {
|
||||
validateFunction(callback, 'callback');
|
||||
return async (chunks, options) => {
|
||||
await callback(chunks, options);
|
||||
return chunks;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a sync pass-through transform that observes chunks.
|
||||
* @param {Function} callback
|
||||
* @returns {Function}
|
||||
*/
|
||||
function tapSync(callback) {
|
||||
validateFunction(callback, 'callback');
|
||||
return (chunks) => {
|
||||
callback(chunks);
|
||||
return chunks;
|
||||
};
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Drain Utility
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Wait for a drainable object's backpressure to clear.
|
||||
* @param {object} drainable
|
||||
* @returns {Promise<boolean>|null}
|
||||
*/
|
||||
function ondrain(drainable) {
|
||||
if (
|
||||
drainable === null ||
|
||||
drainable === undefined ||
|
||||
typeof drainable !== 'object'
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
!(drainableProtocol in drainable) ||
|
||||
typeof drainable[drainableProtocol] !== 'function'
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return drainable[drainableProtocol]();
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Merge Utility
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Merge multiple async iterables by yielding values in temporal order.
|
||||
* @param {...(AsyncIterable<Uint8Array[]>|object)} args
|
||||
* @returns {AsyncIterable<Uint8Array[]>}
|
||||
*/
|
||||
function merge(...args) {
|
||||
let sources;
|
||||
let options;
|
||||
|
||||
if (args.length > 0 && isMergeOptions(args[args.length - 1])) {
|
||||
options = args[args.length - 1];
|
||||
sources = ArrayPrototypeSlice(args, 0, -1);
|
||||
} else {
|
||||
sources = args;
|
||||
}
|
||||
|
||||
if (options?.signal !== undefined) {
|
||||
validateAbortSignal(options.signal, 'options.signal');
|
||||
}
|
||||
|
||||
// Normalize each source via from()
|
||||
const normalized = ArrayPrototypeMap(sources, (source) => from(source));
|
||||
|
||||
return {
|
||||
__proto__: null,
|
||||
async *[SymbolAsyncIterator]() {
|
||||
const signal = options?.signal;
|
||||
|
||||
signal?.throwIfAborted();
|
||||
|
||||
if (normalized.length === 0) return;
|
||||
|
||||
if (normalized.length === 1) {
|
||||
for await (const batch of normalized[0]) {
|
||||
signal?.throwIfAborted();
|
||||
yield batch;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Multiple sources - use a ready queue so that batches that settle
|
||||
// between consumer pulls are drained synchronously without an extra
|
||||
// async tick per batch. Each source has at most one pending .next()
|
||||
// at a time. Every batch from every source is preserved.
|
||||
const ready = [];
|
||||
let activeCount = normalized.length;
|
||||
let waitResolve = null;
|
||||
|
||||
// Called when a source's .next() settles. Pushes the result into
|
||||
// the ready queue and wakes the consumer if it's waiting.
|
||||
const onSettled = (iterator, result) => {
|
||||
if (result.done) {
|
||||
activeCount--;
|
||||
} else {
|
||||
ArrayPrototypePush(ready, result.value);
|
||||
// Immediately request the next value from this source
|
||||
// (at most one pending .next() per source)
|
||||
PromisePrototypeThen(
|
||||
iterator.next(),
|
||||
(r) => onSettled(iterator, r),
|
||||
(err) => {
|
||||
ArrayPrototypePush(ready, { __proto__: null, error: err });
|
||||
if (waitResolve) {
|
||||
waitResolve();
|
||||
waitResolve = null;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
if (waitResolve) {
|
||||
waitResolve();
|
||||
waitResolve = null;
|
||||
}
|
||||
};
|
||||
|
||||
// Start one .next() per source
|
||||
const iterators = [];
|
||||
for (let i = 0; i < normalized.length; i++) {
|
||||
const iterator = normalized[i][SymbolAsyncIterator]();
|
||||
ArrayPrototypePush(iterators, iterator);
|
||||
PromisePrototypeThen(
|
||||
iterator.next(),
|
||||
(r) => onSettled(iterator, r),
|
||||
(err) => {
|
||||
ArrayPrototypePush(ready, { __proto__: null, error: err });
|
||||
if (waitResolve) {
|
||||
waitResolve();
|
||||
waitResolve = null;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
while (activeCount > 0 || ready.length > 0) {
|
||||
signal?.throwIfAborted();
|
||||
|
||||
// Drain ready queue synchronously
|
||||
while (ready.length > 0) {
|
||||
const item = ready.shift();
|
||||
if (item?.error) {
|
||||
throw item.error;
|
||||
}
|
||||
yield item;
|
||||
}
|
||||
|
||||
// If sources are still active, wait for the next settlement
|
||||
if (activeCount > 0) {
|
||||
await new Promise((resolve) => {
|
||||
waitResolve = resolve;
|
||||
});
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
// Clean up: return all iterators
|
||||
await SafePromiseAllReturnVoid(iterators, async (iterator) => {
|
||||
if (iterator.return) {
|
||||
try {
|
||||
await iterator.return();
|
||||
} catch {
|
||||
// Ignore return errors
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
array,
|
||||
arrayBuffer,
|
||||
arrayBufferSync,
|
||||
arraySync,
|
||||
bytes,
|
||||
bytesSync,
|
||||
merge,
|
||||
ondrain,
|
||||
tap,
|
||||
tapSync,
|
||||
text,
|
||||
textSync,
|
||||
};
|
||||
@@ -0,0 +1,141 @@
|
||||
'use strict';
|
||||
|
||||
// New Streams API - Duplex Channel
|
||||
//
|
||||
// Creates a pair of connected channels where data written to one
|
||||
// channel's writer appears in the other channel's readable.
|
||||
|
||||
const {
|
||||
SymbolAsyncDispose,
|
||||
SymbolAsyncIterator,
|
||||
} = primordials;
|
||||
|
||||
const {
|
||||
push,
|
||||
} = require('internal/streams/iter/push');
|
||||
const {
|
||||
validateAbortSignal,
|
||||
validateObject,
|
||||
} = require('internal/validators');
|
||||
|
||||
/**
|
||||
* Create a pair of connected duplex channels for bidirectional communication.
|
||||
* @param {{ highWaterMark?: number, backpressure?: string, signal?: AbortSignal,
|
||||
* a?: object, b?: object }} [options]
|
||||
* @returns {[DuplexChannel, DuplexChannel]}
|
||||
*/
|
||||
function duplex(options = { __proto__: null }) {
|
||||
validateObject(options, 'options');
|
||||
const { highWaterMark, backpressure, signal, a, b } = options;
|
||||
if (a !== undefined) {
|
||||
validateObject(a, 'options.a');
|
||||
}
|
||||
if (b !== undefined) {
|
||||
validateObject(b, 'options.b');
|
||||
}
|
||||
if (signal !== undefined) {
|
||||
validateAbortSignal(signal, 'options.signal');
|
||||
}
|
||||
|
||||
// Channel A writes to B's readable (A->B direction).
|
||||
// Signal is NOT passed to push() -- we handle abort via close() below.
|
||||
const { writer: aWriter, readable: bReadable } = push({
|
||||
highWaterMark: a?.highWaterMark ?? highWaterMark,
|
||||
backpressure: a?.backpressure ?? backpressure,
|
||||
});
|
||||
|
||||
// Channel B writes to A's readable (B->A direction)
|
||||
const { writer: bWriter, readable: aReadable } = push({
|
||||
highWaterMark: b?.highWaterMark ?? highWaterMark,
|
||||
backpressure: b?.backpressure ?? backpressure,
|
||||
});
|
||||
|
||||
let aClosed = false;
|
||||
let bClosed = false;
|
||||
// Track active iterators so close() can call .return() on them
|
||||
let aReadableIterator = null;
|
||||
let bReadableIterator = null;
|
||||
|
||||
const channelA = {
|
||||
__proto__: null,
|
||||
get writer() { return aWriter; },
|
||||
// Wrap readable to track the iterator for cleanup on close()
|
||||
get readable() {
|
||||
return {
|
||||
__proto__: null,
|
||||
[SymbolAsyncIterator]() {
|
||||
const iter = aReadable[SymbolAsyncIterator]();
|
||||
aReadableIterator = iter;
|
||||
return iter;
|
||||
},
|
||||
};
|
||||
},
|
||||
async close() {
|
||||
if (aClosed) return;
|
||||
aClosed = true;
|
||||
// End the writer (signals end-of-stream to B's readable)
|
||||
if (aWriter.endSync() < 0) {
|
||||
await aWriter.end();
|
||||
}
|
||||
// Stop iteration of this channel's readable
|
||||
if (aReadableIterator?.return) {
|
||||
await aReadableIterator.return();
|
||||
aReadableIterator = null;
|
||||
}
|
||||
},
|
||||
[SymbolAsyncDispose]() {
|
||||
return this.close();
|
||||
},
|
||||
};
|
||||
|
||||
const channelB = {
|
||||
__proto__: null,
|
||||
get writer() { return bWriter; },
|
||||
get readable() {
|
||||
return {
|
||||
__proto__: null,
|
||||
[SymbolAsyncIterator]() {
|
||||
const iter = bReadable[SymbolAsyncIterator]();
|
||||
bReadableIterator = iter;
|
||||
return iter;
|
||||
},
|
||||
};
|
||||
},
|
||||
async close() {
|
||||
if (bClosed) return;
|
||||
bClosed = true;
|
||||
if (bWriter.endSync() < 0) {
|
||||
await bWriter.end();
|
||||
}
|
||||
if (bReadableIterator?.return) {
|
||||
await bReadableIterator.return();
|
||||
bReadableIterator = null;
|
||||
}
|
||||
},
|
||||
[SymbolAsyncDispose]() {
|
||||
return this.close();
|
||||
},
|
||||
};
|
||||
|
||||
// Signal handler: fail both writers with the abort reason so consumers
|
||||
// see the error. This is an error-path shutdown, not a clean close.
|
||||
if (signal) {
|
||||
const abortBoth = () => {
|
||||
const reason = signal.reason;
|
||||
aWriter.fail(reason);
|
||||
bWriter.fail(reason);
|
||||
};
|
||||
if (signal.aborted) {
|
||||
abortBoth();
|
||||
} else {
|
||||
signal.addEventListener('abort', abortBoth,
|
||||
{ __proto__: null, once: true });
|
||||
}
|
||||
}
|
||||
|
||||
return [channelA, channelB];
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
duplex,
|
||||
};
|
||||
@@ -0,0 +1,577 @@
|
||||
'use strict';
|
||||
|
||||
// New Streams API - from() and fromSync()
|
||||
//
|
||||
// Creates normalized byte stream iterables from various input types.
|
||||
// Handles recursive flattening of nested iterables and protocol conversions.
|
||||
|
||||
const {
|
||||
ArrayBufferIsView,
|
||||
ArrayIsArray,
|
||||
ArrayPrototypeEvery,
|
||||
ArrayPrototypePush,
|
||||
ArrayPrototypeSlice,
|
||||
DataViewPrototypeGetBuffer,
|
||||
DataViewPrototypeGetByteLength,
|
||||
DataViewPrototypeGetByteOffset,
|
||||
FunctionPrototypeCall,
|
||||
SymbolAsyncIterator,
|
||||
SymbolIterator,
|
||||
TypedArrayPrototypeGetBuffer,
|
||||
TypedArrayPrototypeGetByteLength,
|
||||
TypedArrayPrototypeGetByteOffset,
|
||||
Uint8Array,
|
||||
} = primordials;
|
||||
|
||||
const {
|
||||
codes: {
|
||||
ERR_INVALID_ARG_TYPE,
|
||||
},
|
||||
} = require('internal/errors');
|
||||
|
||||
const {
|
||||
isAnyArrayBuffer,
|
||||
isDataView,
|
||||
isPromise,
|
||||
isUint8Array,
|
||||
} = require('internal/util/types');
|
||||
|
||||
const {
|
||||
toStreamable,
|
||||
toAsyncStreamable,
|
||||
} = require('internal/streams/iter/types');
|
||||
|
||||
const {
|
||||
hasProtocol,
|
||||
toUint8Array,
|
||||
} = require('internal/streams/iter/utils');
|
||||
|
||||
// Maximum number of chunks to yield per batch from from(Uint8Array[]).
|
||||
// Bounds peak memory when arrays flow through transforms, which must
|
||||
// allocate output for the entire batch at once.
|
||||
const FROM_BATCH_SIZE = 128;
|
||||
|
||||
// =============================================================================
|
||||
// Type Guards and Detection
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Check if value is a primitive chunk (string, ArrayBuffer, or ArrayBufferView).
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isPrimitiveChunk(value) {
|
||||
return typeof value === 'string' || isAnyArrayBuffer(value) || ArrayBufferIsView(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if value is a sync iterable (has Symbol.iterator).
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isSyncIterable(value) {
|
||||
// We do not consider regular strings to be sync iterables in this context.
|
||||
// We don't care about boxed strings (String objects) since they are uncommon.
|
||||
return typeof value !== 'string' &&
|
||||
typeof value?.[SymbolIterator] === 'function';
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if value is an async iterable (has Symbol.asyncIterator).
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isAsyncIterable(value) {
|
||||
return typeof value?.[SymbolAsyncIterator] === 'function';
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Primitive Conversion
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @param {string|ArrayBuffer|ArrayBufferView} chunk
|
||||
* @returns {Uint8Array}
|
||||
*/
|
||||
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.)
|
||||
if (isDataView(chunk)) {
|
||||
return new Uint8Array(
|
||||
DataViewPrototypeGetBuffer(chunk),
|
||||
DataViewPrototypeGetByteOffset(chunk),
|
||||
DataViewPrototypeGetByteLength(chunk),
|
||||
);
|
||||
}
|
||||
return new Uint8Array(
|
||||
TypedArrayPrototypeGetBuffer(chunk),
|
||||
TypedArrayPrototypeGetByteOffset(chunk),
|
||||
TypedArrayPrototypeGetByteLength(chunk),
|
||||
);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Sync Normalization (for fromSync and sync contexts)
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Normalize a sync streamable yield value to Uint8Array chunks.
|
||||
* Recursively flattens arrays, iterables, and protocol conversions.
|
||||
* @yields {Uint8Array}
|
||||
*/
|
||||
function* normalizeSyncValue(value) {
|
||||
// Handle primitives
|
||||
if (isPrimitiveChunk(value)) {
|
||||
yield primitiveToUint8Array(value);
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle ToStreamable protocol
|
||||
if (hasProtocol(value, toStreamable)) {
|
||||
const result = FunctionPrototypeCall(value[toStreamable], value);
|
||||
yield* normalizeSyncValue(result);
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle arrays (which are also iterable, but check first for efficiency)
|
||||
if (ArrayIsArray(value)) {
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
yield* normalizeSyncValue(value[i]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle other sync iterables
|
||||
if (isSyncIterable(value)) {
|
||||
for (const item of value) {
|
||||
yield* normalizeSyncValue(item);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Reject: no valid conversion
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'value',
|
||||
['string', 'ArrayBuffer', 'ArrayBufferView', 'Iterable', 'toStreamable'],
|
||||
value,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if value is already a Uint8Array[] batch (fast path).
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isUint8ArrayBatch(value) {
|
||||
if (!ArrayIsArray(value)) return false;
|
||||
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]);
|
||||
// Check first and last before iterating all elements
|
||||
if (!isUint8Array(value[0]) || !isUint8Array(value[len - 1])) return false;
|
||||
if (len === 2) return true;
|
||||
for (let i = 1; i < len - 1; i++) {
|
||||
if (!isUint8Array(value[i])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a sync streamable source, yielding batches of Uint8Array.
|
||||
* @param {Iterable} source
|
||||
* @yields {Uint8Array[]}
|
||||
*/
|
||||
function* normalizeSyncSource(source) {
|
||||
for (const value of source) {
|
||||
// Fast path 1: value is already a Uint8Array[] batch
|
||||
if (isUint8ArrayBatch(value)) {
|
||||
if (value.length > 0) {
|
||||
yield value;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Fast path 2: value is a single Uint8Array (very common)
|
||||
if (isUint8Array(value)) {
|
||||
yield [value];
|
||||
continue;
|
||||
}
|
||||
// Slow path: normalize the value
|
||||
const batch = [];
|
||||
for (const chunk of normalizeSyncValue(value)) {
|
||||
ArrayPrototypePush(batch, chunk);
|
||||
}
|
||||
if (batch.length > 0) {
|
||||
yield batch;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Async Normalization (for from and async contexts)
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Normalize an async streamable yield value to Uint8Array chunks.
|
||||
* Recursively flattens arrays, iterables, async iterables, promises,
|
||||
* and protocol conversions.
|
||||
* @yields {Uint8Array}
|
||||
*/
|
||||
async function* normalizeAsyncValue(value) {
|
||||
// Handle promises first
|
||||
if (isPromise(value)) {
|
||||
const resolved = await value;
|
||||
yield* normalizeAsyncValue(resolved);
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle primitives
|
||||
if (isPrimitiveChunk(value)) {
|
||||
yield primitiveToUint8Array(value);
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle ToAsyncStreamable protocol (check before ToStreamable)
|
||||
if (hasProtocol(value, toAsyncStreamable)) {
|
||||
const result = FunctionPrototypeCall(value[toAsyncStreamable], value);
|
||||
if (isPromise(result)) {
|
||||
yield* normalizeAsyncValue(await result);
|
||||
} else {
|
||||
yield* normalizeAsyncValue(result);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle ToStreamable protocol
|
||||
if (hasProtocol(value, toStreamable)) {
|
||||
const result = FunctionPrototypeCall(value[toStreamable], value);
|
||||
yield* normalizeAsyncValue(result);
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle arrays (which are also iterable, but check first for efficiency)
|
||||
if (ArrayIsArray(value)) {
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
yield* normalizeAsyncValue(value[i]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle async iterables (check before sync iterables since some objects
|
||||
// have both)
|
||||
if (isAsyncIterable(value)) {
|
||||
for await (const item of value) {
|
||||
yield* normalizeAsyncValue(item);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle sync iterables
|
||||
if (isSyncIterable(value)) {
|
||||
for (const item of value) {
|
||||
yield* normalizeAsyncValue(item);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Reject: no valid conversion
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'value',
|
||||
['string', 'ArrayBuffer', 'ArrayBufferView', 'Iterable', 'AsyncIterable',
|
||||
'toStreamable', 'toAsyncStreamable'],
|
||||
value,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize an async streamable source, yielding batches of Uint8Array.
|
||||
* @param {AsyncIterable|Iterable} source
|
||||
* @yields {Uint8Array[]}
|
||||
*/
|
||||
async function* normalizeAsyncSource(source) {
|
||||
// Prefer async iteration if available
|
||||
if (isAsyncIterable(source)) {
|
||||
for await (const value of source) {
|
||||
// Fast path 1: value is already a Uint8Array[] batch
|
||||
if (isUint8ArrayBatch(value)) {
|
||||
if (value.length > 0) {
|
||||
yield value;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Fast path 2: value is a single Uint8Array (very common)
|
||||
if (isUint8Array(value)) {
|
||||
yield [value];
|
||||
continue;
|
||||
}
|
||||
// Slow path: normalize the value
|
||||
const batch = [];
|
||||
for await (const chunk of normalizeAsyncValue(value)) {
|
||||
ArrayPrototypePush(batch, chunk);
|
||||
}
|
||||
if (batch.length > 0) {
|
||||
yield batch;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Fall back to sync iteration - batch all sync values together
|
||||
if (isSyncIterable(source)) {
|
||||
const batch = [];
|
||||
|
||||
for (const value of source) {
|
||||
// Fast path 1: value is already a Uint8Array[] batch
|
||||
if (isUint8ArrayBatch(value)) {
|
||||
// Flush any accumulated batch first
|
||||
if (batch.length > 0) {
|
||||
yield ArrayPrototypeSlice(batch);
|
||||
batch.length = 0;
|
||||
}
|
||||
if (value.length > 0) {
|
||||
yield value;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Fast path 2: value is a single Uint8Array (very common)
|
||||
if (isUint8Array(value)) {
|
||||
ArrayPrototypePush(batch, value);
|
||||
continue;
|
||||
}
|
||||
// Slow path: normalize the value - must flush and yield individually
|
||||
if (batch.length > 0) {
|
||||
yield ArrayPrototypeSlice(batch);
|
||||
batch.length = 0;
|
||||
}
|
||||
const asyncBatch = [];
|
||||
for await (const chunk of normalizeAsyncValue(value)) {
|
||||
ArrayPrototypePush(asyncBatch, chunk);
|
||||
}
|
||||
if (asyncBatch.length > 0) {
|
||||
yield asyncBatch;
|
||||
}
|
||||
}
|
||||
|
||||
// Yield any remaining batched values
|
||||
if (batch.length > 0) {
|
||||
yield batch;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'source',
|
||||
['Iterable', 'AsyncIterable'],
|
||||
source,
|
||||
);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Public API: from() and fromSync()
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Create a SyncByteStreamReadable from a ByteInput or SyncStreamable.
|
||||
* @param {string|ArrayBuffer|ArrayBufferView|Iterable} input
|
||||
* @returns {Iterable<Uint8Array[]>}
|
||||
*/
|
||||
function fromSync(input) {
|
||||
if (input == null) {
|
||||
throw new ERR_INVALID_ARG_TYPE('input', 'a non-null value', input);
|
||||
}
|
||||
|
||||
// Check for primitives first (ByteInput)
|
||||
if (isPrimitiveChunk(input)) {
|
||||
const chunk = primitiveToUint8Array(input);
|
||||
return {
|
||||
__proto__: null,
|
||||
*[SymbolIterator]() {
|
||||
yield [chunk];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Fast path: Uint8Array[] - yield in bounded sub-batches.
|
||||
// Yielding the entire array as one batch forces downstream transforms
|
||||
// to process all data at once, causing peak memory proportional to total
|
||||
// data volume. Sub-batching keeps peak memory bounded while preserving
|
||||
// the throughput benefit of batched processing.
|
||||
if (ArrayIsArray(input)) {
|
||||
if (input.length === 0) {
|
||||
return {
|
||||
__proto__: null,
|
||||
*[SymbolIterator]() {
|
||||
// Empty - yield nothing
|
||||
},
|
||||
};
|
||||
}
|
||||
// Check if it's an array of Uint8Array (common case)
|
||||
if (isUint8Array(input[0])) {
|
||||
const allUint8 = ArrayPrototypeEvery(input, isUint8Array);
|
||||
if (allUint8) {
|
||||
const batch = input;
|
||||
return {
|
||||
__proto__: null,
|
||||
*[SymbolIterator]() {
|
||||
if (batch.length <= FROM_BATCH_SIZE) {
|
||||
yield batch;
|
||||
} else {
|
||||
for (let i = 0; i < batch.length; i += FROM_BATCH_SIZE) {
|
||||
yield ArrayPrototypeSlice(batch, i, i + FROM_BATCH_SIZE);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check toStreamable protocol (takes precedence over iteration protocols).
|
||||
// toAsyncStreamable is ignored entirely in fromSync.
|
||||
if (typeof input[toStreamable] === 'function') {
|
||||
return fromSync(input[toStreamable]());
|
||||
}
|
||||
|
||||
// Reject explicit async inputs
|
||||
if (isAsyncIterable(input)) {
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'input',
|
||||
'a synchronous input (not AsyncIterable)',
|
||||
input,
|
||||
);
|
||||
}
|
||||
if (typeof input === 'object' && input !== null && typeof input.then === 'function') {
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'input',
|
||||
'a synchronous input (not Promise)',
|
||||
input,
|
||||
);
|
||||
}
|
||||
|
||||
// Must be a SyncStreamable
|
||||
if (!isSyncIterable(input)) {
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'input',
|
||||
['string', 'ArrayBuffer', 'ArrayBufferView', 'Iterable', 'toStreamable'],
|
||||
input,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
__proto__: null,
|
||||
*[SymbolIterator]() {
|
||||
yield* normalizeSyncSource(input);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a ByteStreamReadable from a ByteInput or Streamable.
|
||||
* @param {string|ArrayBuffer|ArrayBufferView|Iterable|AsyncIterable} input
|
||||
* @returns {AsyncIterable<Uint8Array[]>}
|
||||
*/
|
||||
function from(input) {
|
||||
if (input == null) {
|
||||
throw new ERR_INVALID_ARG_TYPE('input', 'a non-null value', input);
|
||||
}
|
||||
|
||||
// Check for primitives first (ByteInput)
|
||||
if (isPrimitiveChunk(input)) {
|
||||
const chunk = primitiveToUint8Array(input);
|
||||
return {
|
||||
__proto__: null,
|
||||
async *[SymbolAsyncIterator]() {
|
||||
yield [chunk];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Fast path: Uint8Array[] - yield in bounded sub-batches.
|
||||
// Yielding the entire array as one batch forces downstream transforms
|
||||
// to process all data at once, causing peak memory proportional to total
|
||||
// data volume. Sub-batching keeps peak memory bounded while preserving
|
||||
// the throughput benefit of batched processing.
|
||||
if (ArrayIsArray(input)) {
|
||||
if (input.length === 0) {
|
||||
return {
|
||||
__proto__: null,
|
||||
async *[SymbolAsyncIterator]() {
|
||||
// Empty - yield nothing
|
||||
},
|
||||
};
|
||||
}
|
||||
if (isUint8Array(input[0])) {
|
||||
const allUint8 = ArrayPrototypeEvery(input, isUint8Array);
|
||||
if (allUint8) {
|
||||
const batch = input;
|
||||
return {
|
||||
__proto__: null,
|
||||
async *[SymbolAsyncIterator]() {
|
||||
if (batch.length <= FROM_BATCH_SIZE) {
|
||||
yield batch;
|
||||
} else {
|
||||
for (let i = 0; i < batch.length; i += FROM_BATCH_SIZE) {
|
||||
yield ArrayPrototypeSlice(batch, i, i + FROM_BATCH_SIZE);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check toAsyncStreamable protocol (takes precedence over toStreamable and
|
||||
// iteration protocols)
|
||||
if (typeof input[toAsyncStreamable] === 'function') {
|
||||
return {
|
||||
__proto__: null,
|
||||
async *[SymbolAsyncIterator]() {
|
||||
const result = await input[toAsyncStreamable]();
|
||||
yield* from(result)[SymbolAsyncIterator]();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Check toStreamable protocol (takes precedence over iteration protocols)
|
||||
if (typeof input[toStreamable] === 'function') {
|
||||
return from(input[toStreamable]());
|
||||
}
|
||||
|
||||
// Must be a Streamable (sync or async iterable)
|
||||
if (!isSyncIterable(input) && !isAsyncIterable(input)) {
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'input',
|
||||
['string', 'ArrayBuffer', 'ArrayBufferView', 'Iterable',
|
||||
'AsyncIterable', 'toStreamable', 'toAsyncStreamable'],
|
||||
input,
|
||||
);
|
||||
}
|
||||
|
||||
return normalizeAsyncSource(input);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Exports
|
||||
// =============================================================================
|
||||
|
||||
module.exports = {
|
||||
from,
|
||||
fromSync,
|
||||
isAsyncIterable,
|
||||
isPrimitiveChunk,
|
||||
isSyncIterable,
|
||||
isUint8ArrayBatch,
|
||||
normalizeAsyncSource,
|
||||
normalizeAsyncValue,
|
||||
normalizeSyncSource,
|
||||
normalizeSyncValue,
|
||||
primitiveToUint8Array,
|
||||
};
|
||||
@@ -0,0 +1,935 @@
|
||||
'use strict';
|
||||
|
||||
// New Streams API - Pull Pipeline
|
||||
//
|
||||
// pull(), pullSync(), pipeTo(), pipeToSync()
|
||||
// Pull-through pipelines with transforms. Data flows on-demand from source
|
||||
// through transforms to consumer.
|
||||
|
||||
const {
|
||||
ArrayBufferIsView,
|
||||
ArrayPrototypePush,
|
||||
ArrayPrototypeSlice,
|
||||
PromisePrototypeThen,
|
||||
SymbolAsyncIterator,
|
||||
SymbolIterator,
|
||||
TypedArrayPrototypeGetByteLength,
|
||||
Uint8Array,
|
||||
} = primordials;
|
||||
|
||||
const {
|
||||
codes: {
|
||||
ERR_INVALID_ARG_TYPE,
|
||||
ERR_INVALID_ARG_VALUE,
|
||||
},
|
||||
} = require('internal/errors');
|
||||
const { lazyDOMException } = require('internal/util');
|
||||
const { validateAbortSignal } = require('internal/validators');
|
||||
const {
|
||||
isAnyArrayBuffer,
|
||||
isPromise,
|
||||
isUint8Array,
|
||||
} = require('internal/util/types');
|
||||
const { AbortController } = require('internal/abort_controller');
|
||||
|
||||
const {
|
||||
from,
|
||||
fromSync,
|
||||
primitiveToUint8Array,
|
||||
isSyncIterable,
|
||||
isAsyncIterable,
|
||||
isUint8ArrayBatch,
|
||||
} = require('internal/streams/iter/from');
|
||||
|
||||
const {
|
||||
isPullOptions,
|
||||
isTransform,
|
||||
isTransformObject,
|
||||
parsePullArgs,
|
||||
toUint8Array,
|
||||
wrapError,
|
||||
} = require('internal/streams/iter/utils');
|
||||
|
||||
const {
|
||||
kTrustedTransform,
|
||||
} = require('internal/streams/iter/types');
|
||||
|
||||
// =============================================================================
|
||||
// Type Guards and Helpers
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Check if a value is a Writer (has write method).
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function hasMethod(value, name) {
|
||||
return typeof value?.[name] === 'function';
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse pipeTo/pipeToSync arguments: [...transforms, writer, options?]
|
||||
* @param {Array} args
|
||||
* @param {string} requiredMethod - 'write' for pipeTo, 'writeSync' for pipeToSync
|
||||
* @returns {{ transforms: Array, writer: object, options: object }}
|
||||
*/
|
||||
function parsePipeToArgs(args, requiredMethod) {
|
||||
if (args.length === 0) {
|
||||
throw new ERR_INVALID_ARG_VALUE('args', args, 'pipeTo requires a writer argument');
|
||||
}
|
||||
|
||||
let options;
|
||||
let writerIndex = args.length - 1;
|
||||
|
||||
// Check if last arg is options
|
||||
const last = args[args.length - 1];
|
||||
if (isPullOptions(last) && !hasMethod(last, requiredMethod)) {
|
||||
options = last;
|
||||
writerIndex = args.length - 2;
|
||||
}
|
||||
|
||||
if (writerIndex < 0) {
|
||||
throw new ERR_INVALID_ARG_VALUE('args', args, 'pipeTo requires a writer argument');
|
||||
}
|
||||
|
||||
const writer = args[writerIndex];
|
||||
if (!hasMethod(writer, requiredMethod)) {
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'writer', `object with a ${requiredMethod} method`, writer);
|
||||
}
|
||||
|
||||
const transforms = ArrayPrototypeSlice(args, 0, writerIndex);
|
||||
for (let i = 0; i < transforms.length; i++) {
|
||||
if (!isTransform(transforms[i])) {
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
`transforms[${i}]`, ['Function', 'Object with transform()'],
|
||||
transforms[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
__proto__: null,
|
||||
transforms,
|
||||
writer,
|
||||
options,
|
||||
};
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Transform Output Flattening
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Flatten transform yield to Uint8Array chunks (sync).
|
||||
* @yields {Uint8Array}
|
||||
*/
|
||||
function* flattenTransformYieldSync(value) {
|
||||
if (isUint8Array(value)) {
|
||||
yield value;
|
||||
return;
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
yield toUint8Array(value);
|
||||
return;
|
||||
}
|
||||
if (isAnyArrayBuffer(value)) {
|
||||
yield new Uint8Array(value);
|
||||
return;
|
||||
}
|
||||
if (ArrayBufferIsView(value)) {
|
||||
yield primitiveToUint8Array(value);
|
||||
return;
|
||||
}
|
||||
// Must be Iterable<TransformYield>
|
||||
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 (isUint8Array(value)) {
|
||||
yield value;
|
||||
return;
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
yield toUint8Array(value);
|
||||
return;
|
||||
}
|
||||
if (isAnyArrayBuffer(value)) {
|
||||
yield new Uint8Array(value);
|
||||
return;
|
||||
}
|
||||
if (ArrayBufferIsView(value)) {
|
||||
yield primitiveToUint8Array(value);
|
||||
return;
|
||||
}
|
||||
// Check for async iterable first
|
||||
if (isAsyncIterable(value)) {
|
||||
for await (const item of value) {
|
||||
yield* flattenTransformYieldAsync(item);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Must be sync Iterable<TransformYield>
|
||||
if (isSyncIterable(value)) {
|
||||
for (const item of value) {
|
||||
yield* flattenTransformYieldAsync(item);
|
||||
}
|
||||
return;
|
||||
}
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'value',
|
||||
['Uint8Array', 'string', 'ArrayBuffer', 'ArrayBufferView',
|
||||
'Iterable', 'AsyncIterable'],
|
||||
value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process transform result (sync).
|
||||
* @yields {Uint8Array[]}
|
||||
*/
|
||||
function* processTransformResultSync(result) {
|
||||
if (result === null) {
|
||||
return;
|
||||
}
|
||||
// Single Uint8Array -> wrap as batch
|
||||
if (isUint8Array(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 [new Uint8Array(result)];
|
||||
return;
|
||||
}
|
||||
if (ArrayBufferIsView(result)) {
|
||||
yield [primitiveToUint8Array(result)];
|
||||
return;
|
||||
}
|
||||
// Uint8Array[] batch
|
||||
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)) {
|
||||
ArrayPrototypePush(batch, chunk);
|
||||
}
|
||||
}
|
||||
if (batch.length > 0) {
|
||||
yield batch;
|
||||
}
|
||||
return;
|
||||
}
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'result',
|
||||
['null', 'Uint8Array', 'string', 'ArrayBuffer',
|
||||
'ArrayBufferView', 'Array', 'Iterable'],
|
||||
result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process transform result (async).
|
||||
* @yields {Uint8Array[]}
|
||||
*/
|
||||
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 (isUint8Array(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 [new Uint8Array(result)];
|
||||
return;
|
||||
}
|
||||
if (ArrayBufferIsView(result)) {
|
||||
yield [primitiveToUint8Array(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 (isUint8Array(item)) {
|
||||
ArrayPrototypePush(batch, item);
|
||||
continue;
|
||||
}
|
||||
for await (const chunk of flattenTransformYieldAsync(item)) {
|
||||
ArrayPrototypePush(batch, chunk);
|
||||
}
|
||||
}
|
||||
if (batch.length > 0) {
|
||||
yield batch;
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Sync Iterable or Generator
|
||||
if (isSyncIterable(result)) {
|
||||
const batch = [];
|
||||
for (const item of result) {
|
||||
if (isUint8Array(item)) {
|
||||
ArrayPrototypePush(batch, item);
|
||||
continue;
|
||||
}
|
||||
for await (const chunk of flattenTransformYieldAsync(item)) {
|
||||
ArrayPrototypePush(batch, 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);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Sync Pipeline Implementation
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Apply a single stateless sync transform to a source.
|
||||
* @yields {Uint8Array[]}
|
||||
*/
|
||||
/**
|
||||
* Apply a fused run of stateless sync transforms.
|
||||
* @param {Iterable<Uint8Array[]>} source
|
||||
* @param {Array<Function>} run - Array of stateless transform functions
|
||||
* @yields {Uint8Array[]}
|
||||
*/
|
||||
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);
|
||||
if (result === null) {
|
||||
current = null;
|
||||
break;
|
||||
}
|
||||
current = result;
|
||||
}
|
||||
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 (isUint8Array(current)) {
|
||||
yield [current];
|
||||
} else if (typeof current === 'string') {
|
||||
yield [toUint8Array(current)];
|
||||
} else if (isAnyArrayBuffer(current)) {
|
||||
yield [new Uint8Array(current)];
|
||||
} else if (ArrayBufferIsView(current)) {
|
||||
yield [primitiveToUint8Array(current)];
|
||||
} else {
|
||||
yield* processTransformResultSync(current);
|
||||
}
|
||||
}
|
||||
// Flush
|
||||
let current = null;
|
||||
for (let i = 0; i < run.length; i++) {
|
||||
const result = run[i](current);
|
||||
if (result === null) {
|
||||
current = null;
|
||||
continue;
|
||||
}
|
||||
current = result;
|
||||
}
|
||||
if (current != null) {
|
||||
yield* processTransformResultSync(current);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a single stateful sync transform to a source.
|
||||
* @yields {Uint8Array[]}
|
||||
*/
|
||||
function* withFlushSync(source) {
|
||||
yield* source;
|
||||
yield null;
|
||||
}
|
||||
|
||||
function* applyStatefulSyncTransform(source, transform) {
|
||||
const output = transform(withFlushSync(source));
|
||||
for (const item of output) {
|
||||
const batch = [];
|
||||
for (const chunk of flattenTransformYieldSync(item)) {
|
||||
ArrayPrototypePush(batch, chunk);
|
||||
}
|
||||
if (batch.length > 0) {
|
||||
yield batch;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a sync pipeline from source through transforms.
|
||||
* @yields {Uint8Array[]}
|
||||
*/
|
||||
function* createSyncPipeline(source, transforms) {
|
||||
let current = source;
|
||||
|
||||
// Apply transforms - fuse consecutive stateless transforms into a single
|
||||
// generator layer to avoid unnecessary generator ticks.
|
||||
let statelessRun = [];
|
||||
|
||||
for (let i = 0; i < transforms.length; i++) {
|
||||
const transform = transforms[i];
|
||||
if (isTransformObject(transform)) {
|
||||
if (statelessRun.length > 0) {
|
||||
current = applyFusedStatelessSyncTransforms(current, statelessRun);
|
||||
statelessRun = [];
|
||||
}
|
||||
current = applyStatefulSyncTransform(current, transform.transform);
|
||||
} else {
|
||||
statelessRun.push(transform);
|
||||
}
|
||||
}
|
||||
if (statelessRun.length > 0) {
|
||||
current = applyFusedStatelessSyncTransforms(current, statelessRun);
|
||||
}
|
||||
|
||||
yield* current;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Async Pipeline Implementation
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Apply a single stateless async transform to a source.
|
||||
* @yields {Uint8Array[]}
|
||||
*/
|
||||
/**
|
||||
* Apply a fused run of stateless async transforms to a source.
|
||||
* All transforms in the run are applied in a tight synchronous loop per batch,
|
||||
* avoiding the overhead of N async generator ticks for N transforms.
|
||||
*
|
||||
* INVARIANT: This function accepts a signal, NOT a pre-built options object.
|
||||
* A fresh { __proto__: null, signal } options object is created for each
|
||||
* transform invocation to prevent cross-transform mutation.
|
||||
* @param {AsyncIterable<Uint8Array[]>} source
|
||||
* @param {Array<Function>} run - Array of stateless transform functions
|
||||
* @param {AbortSignal} signal - The pipeline's abort signal
|
||||
* @yields {Uint8Array[]}
|
||||
*/
|
||||
async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
|
||||
for await (const chunks of source) {
|
||||
let current = chunks;
|
||||
for (let i = 0; i < run.length; i++) {
|
||||
const result = run[i](current, { __proto__: null, signal });
|
||||
if (result === null) {
|
||||
current = null;
|
||||
break;
|
||||
}
|
||||
if (isPromise(result)) {
|
||||
const resolved = await result;
|
||||
if (resolved === null) {
|
||||
current = null;
|
||||
break;
|
||||
}
|
||||
current = resolved;
|
||||
} else {
|
||||
current = result;
|
||||
}
|
||||
}
|
||||
if (current === null) continue;
|
||||
// Normalize the final output
|
||||
if (isUint8ArrayBatch(current)) {
|
||||
if (current.length > 0) yield current;
|
||||
} else if (isUint8Array(current)) {
|
||||
yield [current];
|
||||
} else if (typeof current === 'string') {
|
||||
yield [toUint8Array(current)];
|
||||
} else if (isAnyArrayBuffer(current)) {
|
||||
yield [new Uint8Array(current)];
|
||||
} else if (ArrayBufferIsView(current)) {
|
||||
yield [primitiveToUint8Array(current)];
|
||||
} else {
|
||||
yield* processTransformResultAsync(current);
|
||||
}
|
||||
}
|
||||
// Flush: send null through each transform in order
|
||||
let current = null;
|
||||
for (let i = 0; i < run.length; i++) {
|
||||
const result = run[i](current, { __proto__: null, signal });
|
||||
if (result === null) {
|
||||
current = null;
|
||||
continue;
|
||||
}
|
||||
if (isPromise(result)) {
|
||||
current = await result;
|
||||
} else {
|
||||
current = result;
|
||||
}
|
||||
}
|
||||
if (current !== null) {
|
||||
if (isUint8ArrayBatch(current)) {
|
||||
if (current.length > 0) yield current;
|
||||
} else if (isUint8Array(current)) {
|
||||
yield [current];
|
||||
} else if (typeof current === 'string') {
|
||||
yield [toUint8Array(current)];
|
||||
} else {
|
||||
yield* processTransformResultAsync(current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Append a null flush signal after the source is exhausted.
|
||||
* @yields {Uint8Array[]}
|
||||
*/
|
||||
/**
|
||||
* Append a null flush signal after the source is exhausted.
|
||||
* @yields {Uint8Array[]}
|
||||
*/
|
||||
async function* withFlushAsync(source) {
|
||||
for await (const batch of source) {
|
||||
yield batch;
|
||||
}
|
||||
yield null;
|
||||
}
|
||||
|
||||
async function* applyStatefulAsyncTransform(source, transform, options) {
|
||||
const output = transform(withFlushAsync(source), options);
|
||||
for await (const item of output) {
|
||||
// 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 (isUint8Array(item)) {
|
||||
yield [item];
|
||||
continue;
|
||||
}
|
||||
// Slow path: flatten arbitrary transform yield
|
||||
const batch = [];
|
||||
for await (const chunk of flattenTransformYieldAsync(item)) {
|
||||
ArrayPrototypePush(batch, chunk);
|
||||
}
|
||||
if (batch.length > 0) {
|
||||
yield batch;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fast path for trusted stateful transforms (e.g. compression).
|
||||
* Skips withFlushAsync (transform handles done internally) and
|
||||
* skips isUint8ArrayBatch validation (transform guarantees valid output).
|
||||
* @yields {Uint8Array[]}
|
||||
*/
|
||||
async function* applyTrustedStatefulAsyncTransform(source, transform, options) {
|
||||
const output = transform(source, options);
|
||||
for await (const batch of output) {
|
||||
if (batch.length > 0) {
|
||||
yield batch;
|
||||
}
|
||||
}
|
||||
// Check abort after the transform completes - without the
|
||||
// withFlushAsync wrapper there is no extra yield to give
|
||||
// the outer pipeline a chance to see the abort.
|
||||
options.signal?.throwIfAborted();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an async pipeline from source through transforms.
|
||||
* @yields {Uint8Array[]}
|
||||
*/
|
||||
async function* createAsyncPipeline(source, transforms, signal) {
|
||||
// Check for abort
|
||||
signal?.throwIfAborted();
|
||||
|
||||
const normalized = source;
|
||||
|
||||
// Fast path: no transforms, just yield normalized source directly
|
||||
if (transforms.length === 0) {
|
||||
for await (const batch of normalized) {
|
||||
signal?.throwIfAborted();
|
||||
yield batch;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Create internal controller for transform cancellation.
|
||||
// Note: if signal was already aborted, we threw above - no need to check here.
|
||||
const controller = new AbortController();
|
||||
let abortHandler;
|
||||
if (signal) {
|
||||
abortHandler = () => {
|
||||
controller.abort(signal.reason ??
|
||||
lazyDOMException('Aborted', 'AbortError'));
|
||||
};
|
||||
signal.addEventListener('abort', abortHandler, { __proto__: null, once: true });
|
||||
}
|
||||
|
||||
// Apply transforms - fuse consecutive stateless transforms into a single
|
||||
// generator layer to avoid unnecessary async generator ticks.
|
||||
//
|
||||
// INVARIANT: Each transform invocation MUST receive its own fresh options
|
||||
// object ({ __proto__: null, signal }). Transforms may mutate the options
|
||||
// object, so sharing a single object across invocations would allow one
|
||||
// transform to corrupt the options seen by another. The signal is shared
|
||||
// across calls (mutations to it are acceptable), but the containing options
|
||||
// object must be unique per call. This is enforced inside
|
||||
// applyFusedStatelessAsyncTransforms and applyStatefulAsyncTransform, which
|
||||
// accept the signal directly and create the options object per invocation.
|
||||
// DO NOT pass a pre-built options object.
|
||||
let current = normalized;
|
||||
const transformSignal = controller.signal;
|
||||
let statelessRun = [];
|
||||
|
||||
for (let i = 0; i < transforms.length; i++) {
|
||||
const transform = transforms[i];
|
||||
if (isTransformObject(transform)) {
|
||||
// Flush any accumulated stateless run before the stateful transform
|
||||
if (statelessRun.length > 0) {
|
||||
current = applyFusedStatelessAsyncTransforms(current, statelessRun,
|
||||
transformSignal);
|
||||
statelessRun = [];
|
||||
}
|
||||
const opts = { __proto__: null, signal: transformSignal };
|
||||
if (transform[kTrustedTransform]) {
|
||||
current = applyTrustedStatefulAsyncTransform(
|
||||
current, transform.transform, opts);
|
||||
} else {
|
||||
current = applyStatefulAsyncTransform(
|
||||
current, transform.transform, opts);
|
||||
}
|
||||
} else {
|
||||
statelessRun.push(transform);
|
||||
}
|
||||
}
|
||||
// Flush remaining stateless run
|
||||
if (statelessRun.length > 0) {
|
||||
current = applyFusedStatelessAsyncTransforms(current, statelessRun,
|
||||
transformSignal);
|
||||
}
|
||||
|
||||
let completed = false;
|
||||
try {
|
||||
for await (const batch of current) {
|
||||
controller.signal.throwIfAborted();
|
||||
yield batch;
|
||||
}
|
||||
completed = true;
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted) {
|
||||
controller.abort(wrapError(error));
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
if (!completed && !controller.signal.aborted) {
|
||||
// Consumer stopped early or generator return() was called.
|
||||
// If a transform listener throws here, let it propagate.
|
||||
controller.abort(lazyDOMException('Aborted', 'AbortError'));
|
||||
}
|
||||
// Clean up user signal listener to prevent holding controller alive
|
||||
if (signal && abortHandler) {
|
||||
signal.removeEventListener('abort', abortHandler);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Public API: pull() and pullSync()
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Create a sync pull-through pipeline with transforms.
|
||||
* @param {Iterable} source - The sync streamable source
|
||||
* @param {...Function} transforms - Variadic transforms
|
||||
* @returns {Iterable<Uint8Array[]>}
|
||||
*/
|
||||
function pullSync(source, ...transforms) {
|
||||
for (let i = 0; i < transforms.length; i++) {
|
||||
if (!isTransform(transforms[i])) {
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
`transforms[${i}]`, ['Function', 'Object with transform()'],
|
||||
transforms[i]);
|
||||
}
|
||||
}
|
||||
return {
|
||||
__proto__: null,
|
||||
*[SymbolIterator]() {
|
||||
yield* createSyncPipeline(fromSync(source), transforms);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an async pull-through pipeline with transforms.
|
||||
* @param {Iterable|AsyncIterable} source - The streamable source
|
||||
* @param {...(Function|object)} args - Transforms, with optional PullOptions
|
||||
* as last argument
|
||||
* @returns {AsyncIterable<Uint8Array[]>}
|
||||
*/
|
||||
function pull(source, ...args) {
|
||||
const { transforms, options } = parsePullArgs(args);
|
||||
const signal = options?.signal;
|
||||
if (signal !== undefined) {
|
||||
validateAbortSignal(signal, 'options.signal');
|
||||
// Eagerly check abort at call time per spec
|
||||
if (signal.aborted) {
|
||||
return {
|
||||
__proto__: null,
|
||||
// eslint-disable-next-line require-yield
|
||||
async *[SymbolAsyncIterator]() {
|
||||
throw signal.reason;
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
__proto__: null,
|
||||
async *[SymbolAsyncIterator]() {
|
||||
yield* createAsyncPipeline(from(source), transforms, signal);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Public API: pipeTo() and pipeToSync()
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Write a sync source through transforms to a sync writer.
|
||||
* @param {Iterable<Uint8Array[]>} source
|
||||
* @param {...(Function|object)} args - Transforms, writer, and optional options
|
||||
* @returns {number} Total bytes written
|
||||
*/
|
||||
function pipeToSync(source, ...args) {
|
||||
const { transforms, writer, options } = parsePipeToArgs(args, 'writeSync');
|
||||
|
||||
// Handle transform-writer
|
||||
if (isTransformObject(writer)) {
|
||||
ArrayPrototypePush(transforms, writer);
|
||||
}
|
||||
|
||||
// Normalize source and create pipeline
|
||||
const normalized = fromSync(source);
|
||||
const pipeline = transforms.length > 0 ?
|
||||
createSyncPipeline(normalized, transforms) :
|
||||
normalized;
|
||||
|
||||
let totalBytes = 0;
|
||||
const hasWriteSync = typeof writer.writeSync === 'function';
|
||||
const hasWritevSync = typeof writer.writevSync === 'function';
|
||||
const hasEndSync = typeof writer.endSync === 'function';
|
||||
|
||||
try {
|
||||
for (const batch of pipeline) {
|
||||
if (hasWritevSync && batch.length > 1) {
|
||||
writer.writevSync(batch);
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
totalBytes += TypedArrayPrototypeGetByteLength(batch[i]);
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
const chunk = batch[i];
|
||||
if (hasWriteSync) {
|
||||
writer.writeSync(chunk);
|
||||
} else {
|
||||
writer.write(chunk);
|
||||
}
|
||||
totalBytes += TypedArrayPrototypeGetByteLength(chunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!options?.preventClose) {
|
||||
if (!hasEndSync || writer.endSync() < 0) {
|
||||
writer.end?.();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (!options?.preventFail) {
|
||||
writer.fail?.(wrapError(error));
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return totalBytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write an async source through transforms to a writer.
|
||||
* @param {AsyncIterable<Uint8Array[]>|Iterable<Uint8Array[]>} source
|
||||
* @param {...(Function|object)} args - Transforms, writer, and optional options
|
||||
* @returns {Promise<number>} Total bytes written
|
||||
*/
|
||||
async function pipeTo(source, ...args) {
|
||||
const { transforms, writer, options } = parsePipeToArgs(args, 'write');
|
||||
if (options?.signal !== undefined) {
|
||||
validateAbortSignal(options.signal, 'options.signal');
|
||||
}
|
||||
|
||||
// Handle transform-writer
|
||||
if (isTransformObject(writer)) {
|
||||
ArrayPrototypePush(transforms, writer);
|
||||
}
|
||||
|
||||
const signal = options?.signal;
|
||||
|
||||
// Check for abort
|
||||
signal?.throwIfAborted();
|
||||
|
||||
// Normalize source via from()
|
||||
const normalized = from(source);
|
||||
|
||||
let totalBytes = 0;
|
||||
const hasWritev = typeof writer.writev === 'function';
|
||||
const hasWriteSync = typeof writer.writeSync === 'function';
|
||||
const hasWritevSync = typeof writer.writevSync === 'function';
|
||||
const hasEndSync = typeof writer.endSync === 'function';
|
||||
// Async fallback for writeBatch when sync write fails partway through.
|
||||
// Continues writing from batch[startIndex] using async write().
|
||||
async function writeBatchAsyncFallback(batch, startIndex) {
|
||||
for (let i = startIndex; i < batch.length; i++) {
|
||||
const chunk = batch[i];
|
||||
if (hasWriteSync && writer.writeSync(chunk)) {
|
||||
// Sync retry succeeded
|
||||
} else {
|
||||
const result = writer.write(
|
||||
chunk, signal ? { __proto__: null, signal } : undefined);
|
||||
if (result !== undefined) {
|
||||
await result;
|
||||
}
|
||||
}
|
||||
totalBytes += TypedArrayPrototypeGetByteLength(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
// Write a batch using try-fallback: sync first, async if needed.
|
||||
// Returns undefined on sync success, or a Promise when async fallback
|
||||
// is required. Callers must check: const p = writeBatch(b); if (p) await p;
|
||||
function writeBatch(batch) {
|
||||
if (hasWritev && batch.length > 1) {
|
||||
if (!hasWritevSync || !writer.writevSync(batch)) {
|
||||
const opts = signal ? { __proto__: null, signal } : undefined;
|
||||
return PromisePrototypeThen(writer.writev(batch, opts), () => {
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
totalBytes += TypedArrayPrototypeGetByteLength(batch[i]);
|
||||
}
|
||||
});
|
||||
}
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
totalBytes += TypedArrayPrototypeGetByteLength(batch[i]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
const chunk = batch[i];
|
||||
if (!hasWriteSync || !writer.writeSync(chunk)) {
|
||||
// Sync path failed at index i - fall back to async for the rest.
|
||||
// Count bytes for chunks already written synchronously (0..i-1).
|
||||
return writeBatchAsyncFallback(batch, i);
|
||||
}
|
||||
totalBytes += TypedArrayPrototypeGetByteLength(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Fast path: no transforms - iterate normalized source directly
|
||||
if (transforms.length === 0) {
|
||||
if (signal) {
|
||||
for await (const batch of normalized) {
|
||||
signal.throwIfAborted();
|
||||
const p = writeBatch(batch);
|
||||
if (p) await p;
|
||||
}
|
||||
} else {
|
||||
for await (const batch of normalized) {
|
||||
const p = writeBatch(batch);
|
||||
if (p) await p;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const pipeline = createAsyncPipeline(normalized, transforms, signal);
|
||||
|
||||
if (signal) {
|
||||
for await (const batch of pipeline) {
|
||||
signal.throwIfAborted();
|
||||
const p = writeBatch(batch);
|
||||
if (p) await p;
|
||||
}
|
||||
} else {
|
||||
for await (const batch of pipeline) {
|
||||
const p = writeBatch(batch);
|
||||
if (p) await p;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!options?.preventClose) {
|
||||
if (!hasEndSync || writer.endSync() < 0) {
|
||||
await writer.end?.(signal ? { __proto__: null, signal } : undefined);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (!options?.preventFail) {
|
||||
writer.fail?.(wrapError(error));
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return totalBytes;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
pipeTo,
|
||||
pipeToSync,
|
||||
pull,
|
||||
pullSync,
|
||||
};
|
||||
@@ -0,0 +1,721 @@
|
||||
'use strict';
|
||||
|
||||
// New Streams API - Push Stream Implementation
|
||||
//
|
||||
// Creates a bonded pair of writer and async iterable for push-based streaming
|
||||
// with built-in backpressure.
|
||||
|
||||
const {
|
||||
ArrayIsArray,
|
||||
ArrayPrototypePush,
|
||||
MathMax,
|
||||
PromiseReject,
|
||||
PromiseResolve,
|
||||
PromiseWithResolvers,
|
||||
SymbolAsyncDispose,
|
||||
SymbolAsyncIterator,
|
||||
SymbolDispose,
|
||||
TypedArrayPrototypeGetByteLength,
|
||||
} = primordials;
|
||||
|
||||
const {
|
||||
codes: {
|
||||
ERR_INVALID_ARG_TYPE,
|
||||
ERR_INVALID_STATE,
|
||||
},
|
||||
} = require('internal/errors');
|
||||
const { isError, lazyDOMException } = require('internal/util');
|
||||
const {
|
||||
validateAbortSignal,
|
||||
validateInteger,
|
||||
} = require('internal/validators');
|
||||
|
||||
const {
|
||||
drainableProtocol,
|
||||
} = require('internal/streams/iter/types');
|
||||
|
||||
const {
|
||||
kPushDefaultHWM,
|
||||
kResolvedPromise,
|
||||
clampHWM,
|
||||
onSignalAbort,
|
||||
toUint8Array,
|
||||
convertChunks,
|
||||
parsePullArgs,
|
||||
validateBackpressure,
|
||||
} = require('internal/streams/iter/utils');
|
||||
|
||||
const {
|
||||
pull: pullWithTransforms,
|
||||
} = require('internal/streams/iter/pull');
|
||||
|
||||
const {
|
||||
RingBuffer,
|
||||
} = require('internal/streams/iter/ringbuffer');
|
||||
|
||||
// =============================================================================
|
||||
// PushQueue - Internal Queue with Chunk-Based Backpressure
|
||||
// =============================================================================
|
||||
|
||||
class PushQueue {
|
||||
/** Buffered chunks (each slot is from one write/writev call) */
|
||||
#slots = new RingBuffer();
|
||||
/** Pending writes waiting for buffer space */
|
||||
#pendingWrites = new RingBuffer();
|
||||
/** Pending reads waiting for data */
|
||||
#pendingReads = new RingBuffer();
|
||||
/** Pending drains waiting for backpressure to clear */
|
||||
#pendingDrains = [];
|
||||
/** Writer state: 'open' | 'closing' | 'closed' | 'errored' */
|
||||
#writerState = 'open';
|
||||
/** Consumer state: 'active' | 'returned' | 'thrown' */
|
||||
#consumerState = 'active';
|
||||
/** Error that closed the stream */
|
||||
#error = null;
|
||||
/** Total bytes written */
|
||||
#bytesWritten = 0;
|
||||
/** Pending end promise (resolves when consumer drains past end sentinel) */
|
||||
#pendingEnd = null;
|
||||
|
||||
/** Configuration */
|
||||
#highWaterMark;
|
||||
#backpressure;
|
||||
#signal;
|
||||
#abortHandler;
|
||||
|
||||
constructor(options = { __proto__: null }) {
|
||||
const {
|
||||
highWaterMark = kPushDefaultHWM,
|
||||
backpressure = 'strict',
|
||||
signal,
|
||||
} = options;
|
||||
validateInteger(highWaterMark, 'options.highWaterMark');
|
||||
validateBackpressure(backpressure);
|
||||
if (signal !== undefined) {
|
||||
validateAbortSignal(signal, 'options.signal');
|
||||
}
|
||||
this.#highWaterMark = clampHWM(highWaterMark);
|
||||
this.#backpressure = backpressure;
|
||||
this.#signal = signal;
|
||||
this.#abortHandler = undefined;
|
||||
|
||||
if (this.#signal) {
|
||||
this.#abortHandler = () => {
|
||||
this.fail(isError(this.#signal.reason) ?
|
||||
this.#signal.reason :
|
||||
lazyDOMException('Aborted', 'AbortError'));
|
||||
};
|
||||
onSignalAbort(this.#signal, this.#abortHandler);
|
||||
}
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// Writer Methods
|
||||
// ===========================================================================
|
||||
|
||||
/**
|
||||
* Get slots available before hitting highWaterMark.
|
||||
* Returns null if writer is closed/errored or consumer has terminated.
|
||||
* @returns {number | null}
|
||||
*/
|
||||
get desiredSize() {
|
||||
if (this.#writerState !== 'open' || this.#consumerState !== 'active') {
|
||||
return null;
|
||||
}
|
||||
return MathMax(0, this.#highWaterMark - this.#slots.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a sync write would be accepted.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
canWriteSync() {
|
||||
if (this.#writerState !== 'open') return false;
|
||||
if (this.#consumerState !== 'active') return false;
|
||||
if ((this.#backpressure === 'strict' ||
|
||||
this.#backpressure === 'block') &&
|
||||
this.#slots.length >= this.#highWaterMark) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write chunks synchronously if possible.
|
||||
* Returns true if write completed, false if buffer is full.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
writeSync(chunks) {
|
||||
if (this.#writerState !== 'open') return false;
|
||||
if (this.#consumerState !== 'active') return false;
|
||||
|
||||
if (this.#slots.length >= this.#highWaterMark) {
|
||||
switch (this.#backpressure) {
|
||||
case 'strict':
|
||||
return false;
|
||||
case 'block':
|
||||
return false;
|
||||
case 'drop-oldest':
|
||||
if (this.#slots.length > 0) {
|
||||
this.#slots.shift();
|
||||
}
|
||||
break;
|
||||
case 'drop-newest':
|
||||
// Discard this write, but return true
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
this.#bytesWritten += TypedArrayPrototypeGetByteLength(chunks[i]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
this.#slots.push(chunks);
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
this.#bytesWritten += TypedArrayPrototypeGetByteLength(chunks[i]);
|
||||
}
|
||||
|
||||
this.#resolvePendingReads();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write chunks asynchronously.
|
||||
* If signal is provided, a write blocked on backpressure will reject
|
||||
* immediately when the signal fires. The cancelled write is removed from
|
||||
* pendingWrites so it does not occupy a slot. The queue itself is NOT put
|
||||
* into an error state - this is per-operation cancellation, not terminal
|
||||
* failure.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async writeAsync(chunks, signal) {
|
||||
// Check writer state before signal (spec order: state, then signal)
|
||||
if (this.#writerState === 'closed') {
|
||||
throw new ERR_INVALID_STATE.TypeError('Writer is closed');
|
||||
}
|
||||
if (this.#writerState === 'closing') {
|
||||
throw new ERR_INVALID_STATE.TypeError('Writer is closing');
|
||||
}
|
||||
if (this.#writerState === 'errored') {
|
||||
throw this.#error;
|
||||
}
|
||||
if (this.#consumerState !== 'active') {
|
||||
throw this.#consumerState === 'thrown' && this.#error ?
|
||||
this.#error :
|
||||
new ERR_INVALID_STATE.TypeError('Stream closed by consumer');
|
||||
}
|
||||
|
||||
// Check for pre-aborted signal (after state checks per spec)
|
||||
signal?.throwIfAborted();
|
||||
|
||||
// Try sync first
|
||||
if (this.writeSync(chunks)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Buffer is full
|
||||
switch (this.#backpressure) {
|
||||
case 'strict':
|
||||
if (this.#pendingWrites.length >= this.#highWaterMark) {
|
||||
throw new ERR_INVALID_STATE.RangeError(
|
||||
'Backpressure violation: too many pending writes. ' +
|
||||
'Await each write() call to respect backpressure.');
|
||||
}
|
||||
return this.#createPendingWrite(chunks, signal);
|
||||
case 'block':
|
||||
return this.#createPendingWrite(chunks, signal);
|
||||
default:
|
||||
throw new ERR_INVALID_STATE(
|
||||
'Unexpected: writeSync should have handled non-strict policy');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a pending write promise, optionally racing against a signal.
|
||||
* If the signal fires, the entry is removed from pendingWrites and the
|
||||
* promise rejects. Signal listeners are cleaned up on normal resolution.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
#createPendingWrite(chunks, signal) {
|
||||
const { promise, resolve, reject } = PromiseWithResolvers();
|
||||
const entry = { __proto__: null, chunks, resolve, reject };
|
||||
this.#pendingWrites.push(entry);
|
||||
|
||||
if (signal) {
|
||||
const onAbort = () => {
|
||||
// Remove from queue so it doesn't occupy a slot
|
||||
const idx = this.#pendingWrites.indexOf(entry);
|
||||
if (idx !== -1) this.#pendingWrites.removeAt(idx);
|
||||
reject(signal.reason ?? lazyDOMException('Aborted', 'AbortError'));
|
||||
};
|
||||
|
||||
// Wrap resolve/reject to clean up signal listener
|
||||
entry.resolve = function() {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
};
|
||||
entry.reject = function(reason) {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
reject(reason);
|
||||
};
|
||||
|
||||
signal.addEventListener('abort', onAbort, { __proto__: null, once: true });
|
||||
}
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Signal end of stream. Returns total bytes written.
|
||||
* @returns {number}
|
||||
*/
|
||||
end() {
|
||||
if (this.#writerState === 'errored') {
|
||||
return -2; // Signal to reject with stored error
|
||||
}
|
||||
if (this.#writerState === 'closing' || this.#writerState === 'closed') {
|
||||
return this.#bytesWritten; // Idempotent
|
||||
}
|
||||
|
||||
this.#cleanup();
|
||||
this.#rejectPendingWrites(
|
||||
new ERR_INVALID_STATE.TypeError('Writer closed'));
|
||||
this.#resolvePendingDrains(false);
|
||||
|
||||
// If buffer is empty, close immediately
|
||||
if (this.#slots.length === 0) {
|
||||
this.#writerState = 'closed';
|
||||
this.#resolvePendingReads();
|
||||
return this.#bytesWritten;
|
||||
}
|
||||
|
||||
// Buffer has data: transition to closing, defer completion until drained
|
||||
this.#writerState = 'closing';
|
||||
return -3; // Signal to PushWriter: create deferred end promise
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by the read path when the consumer has drained all data while
|
||||
* the writer is in the 'closing' state. Transitions to 'closed' and
|
||||
* resolves the pending end promise.
|
||||
*/
|
||||
endDrained() {
|
||||
if (this.#writerState !== 'closing') return;
|
||||
this.#writerState = 'closed';
|
||||
if (this.#pendingEnd) {
|
||||
this.#pendingEnd.resolve(this.#bytesWritten);
|
||||
this.#pendingEnd = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Put queue into terminal error state.
|
||||
* No-op if errored or closed (fully drained).
|
||||
* If closing (draining), short-circuits the drain.
|
||||
*/
|
||||
fail(reason) {
|
||||
if (this.#writerState === 'errored' || this.#writerState === 'closed') {
|
||||
return;
|
||||
}
|
||||
|
||||
const wasClosing = this.#writerState === 'closing';
|
||||
this.#writerState = 'errored';
|
||||
this.#error = reason ?? new ERR_INVALID_STATE('Failed');
|
||||
this.#cleanup();
|
||||
this.#rejectPendingReads(this.#error);
|
||||
this.#rejectPendingDrains(this.#error);
|
||||
|
||||
if (wasClosing) {
|
||||
// Short-circuit the graceful drain: reject the pending end promise
|
||||
if (this.#pendingEnd) {
|
||||
this.#pendingEnd.reject(this.#error);
|
||||
this.#pendingEnd = null;
|
||||
}
|
||||
} else {
|
||||
this.#rejectPendingWrites(this.#error);
|
||||
}
|
||||
}
|
||||
|
||||
get totalBytesWritten() {
|
||||
return this.#bytesWritten;
|
||||
}
|
||||
|
||||
get error() {
|
||||
return this.#error;
|
||||
}
|
||||
|
||||
get backpressurePolicy() {
|
||||
return this.#backpressure;
|
||||
}
|
||||
|
||||
get writerState() {
|
||||
return this.#writerState;
|
||||
}
|
||||
|
||||
get pendingEndPromise() {
|
||||
return this.#pendingEnd?.promise ?? null;
|
||||
}
|
||||
|
||||
setPendingEnd(pending) {
|
||||
this.#pendingEnd = pending;
|
||||
}
|
||||
|
||||
/**
|
||||
* Force-enqueue chunks into the slots buffer, bypassing capacity checks.
|
||||
* Used by PushWriter.writeSync() for 'block' policy where the data is
|
||||
* accepted but false is returned as a backpressure signal.
|
||||
*/
|
||||
forceEnqueue(chunks) {
|
||||
this.#slots.push(chunks);
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
this.#bytesWritten += TypedArrayPrototypeGetByteLength(chunks[i]);
|
||||
}
|
||||
this.#resolvePendingReads();
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for backpressure to clear (desiredSize > 0).
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
waitForDrain() {
|
||||
const { promise, resolve, reject } = PromiseWithResolvers();
|
||||
ArrayPrototypePush(this.#pendingDrains, { __proto__: null, resolve, reject });
|
||||
return promise;
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// Consumer Methods
|
||||
// ===========================================================================
|
||||
|
||||
async read() {
|
||||
// If there's data in the buffer, return it immediately
|
||||
if (this.#slots.length > 0) {
|
||||
const result = this.#drain();
|
||||
this.#resolvePendingWrites();
|
||||
// After draining, check if writer was closing and buffer is now empty
|
||||
if (this.#writerState === 'closing' && this.#slots.length === 0) {
|
||||
this.endDrained();
|
||||
}
|
||||
return { __proto__: null, value: result, done: false };
|
||||
}
|
||||
|
||||
// Buffer empty and writer closing = drain complete
|
||||
if (this.#writerState === 'closing') {
|
||||
this.endDrained();
|
||||
return { __proto__: null, value: undefined, done: true };
|
||||
}
|
||||
|
||||
if (this.#writerState === 'closed') {
|
||||
return { __proto__: null, value: undefined, done: true };
|
||||
}
|
||||
|
||||
if (this.#writerState === 'errored' && this.#error) {
|
||||
throw this.#error;
|
||||
}
|
||||
|
||||
const { promise, resolve, reject } = PromiseWithResolvers();
|
||||
this.#pendingReads.push({ __proto__: null, resolve, reject });
|
||||
return promise;
|
||||
}
|
||||
|
||||
consumerReturn() {
|
||||
if (this.#consumerState !== 'active') return;
|
||||
this.#consumerState = 'returned';
|
||||
this.#cleanup();
|
||||
this.#rejectPendingWrites(
|
||||
new ERR_INVALID_STATE.TypeError('Stream closed by consumer'));
|
||||
// If closing, reject the pending end promise
|
||||
if (this.#writerState === 'closing' && this.#pendingEnd) {
|
||||
this.#pendingEnd.reject(
|
||||
new ERR_INVALID_STATE.TypeError('Stream closed by consumer'));
|
||||
this.#pendingEnd = null;
|
||||
}
|
||||
// Resolve pending drains with false - no more data will be consumed
|
||||
this.#resolvePendingDrains(false);
|
||||
}
|
||||
|
||||
consumerThrow(error) {
|
||||
if (this.#consumerState !== 'active') return;
|
||||
this.#consumerState = 'thrown';
|
||||
this.#error = error;
|
||||
this.#cleanup();
|
||||
this.#rejectPendingWrites(error);
|
||||
// Reject pending drains - the consumer errored
|
||||
this.#rejectPendingDrains(error);
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// Private Methods
|
||||
// ===========================================================================
|
||||
|
||||
#drain() {
|
||||
const result = [];
|
||||
for (let i = 0; i < this.#slots.length; i++) {
|
||||
const slot = this.#slots.get(i);
|
||||
for (let j = 0; j < slot.length; j++) {
|
||||
ArrayPrototypePush(result, slot[j]);
|
||||
}
|
||||
}
|
||||
this.#slots.clear();
|
||||
return result;
|
||||
}
|
||||
|
||||
#resolvePendingReads() {
|
||||
while (this.#pendingReads.length > 0) {
|
||||
if (this.#slots.length > 0) {
|
||||
const pending = this.#pendingReads.shift();
|
||||
const result = this.#drain();
|
||||
this.#resolvePendingWrites();
|
||||
pending.resolve({ __proto__: null, value: result, done: false });
|
||||
} else if (this.#writerState === 'closing' && this.#slots.length === 0) {
|
||||
this.endDrained();
|
||||
const pending = this.#pendingReads.shift();
|
||||
pending.resolve({ __proto__: null, value: undefined, done: true });
|
||||
} else if (this.#writerState === 'closed') {
|
||||
const pending = this.#pendingReads.shift();
|
||||
pending.resolve({ __proto__: null, value: undefined, done: true });
|
||||
} else if (this.#writerState === 'errored' && this.#error) {
|
||||
const pending = this.#pendingReads.shift();
|
||||
pending.reject(this.#error);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#resolvePendingWrites() {
|
||||
while (this.#pendingWrites.length > 0 &&
|
||||
this.#slots.length < this.#highWaterMark) {
|
||||
const pending = this.#pendingWrites.shift();
|
||||
this.#slots.push(pending.chunks);
|
||||
for (let i = 0; i < pending.chunks.length; i++) {
|
||||
this.#bytesWritten += TypedArrayPrototypeGetByteLength(pending.chunks[i]);
|
||||
}
|
||||
pending.resolve();
|
||||
}
|
||||
|
||||
if (this.#slots.length < this.#highWaterMark) {
|
||||
this.#resolvePendingDrains(true);
|
||||
}
|
||||
}
|
||||
|
||||
#resolvePendingDrains(canWrite) {
|
||||
const drains = this.#pendingDrains;
|
||||
this.#pendingDrains = [];
|
||||
for (let i = 0; i < drains.length; i++) {
|
||||
drains[i].resolve(canWrite);
|
||||
}
|
||||
}
|
||||
|
||||
#rejectPendingDrains(error) {
|
||||
const drains = this.#pendingDrains;
|
||||
this.#pendingDrains = [];
|
||||
for (let i = 0; i < drains.length; i++) {
|
||||
drains[i].reject(error);
|
||||
}
|
||||
}
|
||||
|
||||
#rejectPendingReads(error) {
|
||||
while (this.#pendingReads.length > 0) {
|
||||
this.#pendingReads.shift().reject(error);
|
||||
}
|
||||
}
|
||||
|
||||
#rejectPendingWrites(error) {
|
||||
while (this.#pendingWrites.length > 0) {
|
||||
this.#pendingWrites.shift().reject(error);
|
||||
}
|
||||
}
|
||||
|
||||
#cleanup() {
|
||||
if (this.#signal && this.#abortHandler) {
|
||||
this.#signal.removeEventListener('abort', this.#abortHandler);
|
||||
this.#abortHandler = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// PushWriter Implementation
|
||||
// =============================================================================
|
||||
|
||||
class PushWriter {
|
||||
#queue;
|
||||
|
||||
constructor(queue) {
|
||||
this.#queue = queue;
|
||||
}
|
||||
|
||||
[drainableProtocol]() {
|
||||
const desired = this.desiredSize;
|
||||
if (desired === null) return null;
|
||||
if (desired > 0) return PromiseResolve(true);
|
||||
return this.#queue.waitForDrain();
|
||||
}
|
||||
|
||||
get desiredSize() {
|
||||
return this.#queue.desiredSize;
|
||||
}
|
||||
|
||||
write(chunk, options) {
|
||||
if (!options?.signal && this.#queue.canWriteSync()) {
|
||||
const bytes = toUint8Array(chunk);
|
||||
this.#queue.writeSync([bytes]);
|
||||
return kResolvedPromise;
|
||||
}
|
||||
const bytes = toUint8Array(chunk);
|
||||
return this.#queue.writeAsync([bytes], options?.signal);
|
||||
}
|
||||
|
||||
writev(chunks, options) {
|
||||
if (!ArrayIsArray(chunks)) {
|
||||
throw new ERR_INVALID_ARG_TYPE('chunks', 'Array', chunks);
|
||||
}
|
||||
if (!options?.signal && this.#queue.canWriteSync()) {
|
||||
const bytes = convertChunks(chunks);
|
||||
this.#queue.writeSync(bytes);
|
||||
return kResolvedPromise;
|
||||
}
|
||||
const bytes = convertChunks(chunks);
|
||||
return this.#queue.writeAsync(bytes, options?.signal);
|
||||
}
|
||||
|
||||
writeSync(chunk) {
|
||||
const bytes = toUint8Array(chunk);
|
||||
const result = this.#queue.writeSync([bytes]);
|
||||
if (!result && this.#queue.backpressurePolicy === 'block') {
|
||||
// Block policy: force-enqueue and return false as backpressure signal.
|
||||
// Data IS accepted; false tells caller to slow down.
|
||||
this.#queue.forceEnqueue([bytes]);
|
||||
return false;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
writevSync(chunks) {
|
||||
if (!ArrayIsArray(chunks)) {
|
||||
throw new ERR_INVALID_ARG_TYPE('chunks', 'Array', chunks);
|
||||
}
|
||||
const bytes = convertChunks(chunks);
|
||||
const result = this.#queue.writeSync(bytes);
|
||||
if (!result && this.#queue.backpressurePolicy === 'block') {
|
||||
this.#queue.forceEnqueue(bytes);
|
||||
return false;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
end(options) {
|
||||
const result = this.#queue.end();
|
||||
if (result === -2) {
|
||||
// Errored: reject with stored error
|
||||
return PromiseReject(this.#queue.error);
|
||||
}
|
||||
if (result === -3) {
|
||||
// Closing: buffer has data, create deferred promise that resolves
|
||||
// when consumer drains past the end sentinel
|
||||
const { promise, resolve, reject } = PromiseWithResolvers();
|
||||
this.#queue.setPendingEnd({ __proto__: null, promise, resolve, reject });
|
||||
return promise;
|
||||
}
|
||||
// >= 0: byte count (immediate close or idempotent)
|
||||
return PromiseResolve(result);
|
||||
}
|
||||
|
||||
endSync() {
|
||||
const result = this.#queue.end();
|
||||
if (result === -2) return -1; // Errored
|
||||
if (result === -3) return -1; // Buffer not empty, can't wait
|
||||
return result;
|
||||
}
|
||||
|
||||
fail(reason) {
|
||||
this.#queue.fail(reason);
|
||||
}
|
||||
|
||||
[SymbolAsyncDispose]() {
|
||||
const state = this.#queue.writerState;
|
||||
if (state === 'closing') {
|
||||
// Wait for graceful drain
|
||||
return this.#queue.pendingEndPromise ?? PromiseResolve();
|
||||
}
|
||||
if (state === 'open') {
|
||||
this.fail();
|
||||
}
|
||||
return PromiseResolve();
|
||||
}
|
||||
|
||||
[SymbolDispose]() {
|
||||
this.fail();
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Readable Implementation
|
||||
// =============================================================================
|
||||
|
||||
function createReadable(queue) {
|
||||
return {
|
||||
__proto__: null,
|
||||
[SymbolAsyncIterator]() {
|
||||
return {
|
||||
__proto__: null,
|
||||
async next() {
|
||||
return queue.read();
|
||||
},
|
||||
async return() {
|
||||
queue.consumerReturn();
|
||||
return { __proto__: null, value: undefined, done: true };
|
||||
},
|
||||
async throw(error) {
|
||||
queue.consumerThrow(error);
|
||||
return { __proto__: null, value: undefined, done: true };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Stream.push() Factory
|
||||
// =============================================================================
|
||||
|
||||
function parseArgs(args) {
|
||||
const result = parsePullArgs(args);
|
||||
// PushQueue constructor requires a non-undefined options object.
|
||||
if (result.options === undefined) {
|
||||
result.options = { __proto__: null };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a push stream with optional transforms.
|
||||
* @param {...(Function|object)} args - Transforms, then options (optional)
|
||||
* @returns {{ writer: Writer, readable: AsyncIterable<Uint8Array[]> }}
|
||||
*/
|
||||
function push(...args) {
|
||||
const { transforms, options } = parseArgs(args);
|
||||
|
||||
const queue = new PushQueue(options);
|
||||
const writer = new PushWriter(queue);
|
||||
const rawReadable = createReadable(queue);
|
||||
|
||||
// Apply transforms lazily if provided
|
||||
let readable;
|
||||
if (transforms.length > 0) {
|
||||
if (options.signal) {
|
||||
readable = pullWithTransforms(
|
||||
rawReadable, ...transforms, { __proto__: null, signal: options.signal });
|
||||
} else {
|
||||
readable = pullWithTransforms(rawReadable, ...transforms);
|
||||
}
|
||||
} else {
|
||||
readable = rawReadable;
|
||||
}
|
||||
|
||||
return { __proto__: null, writer, readable };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
push,
|
||||
};
|
||||
@@ -0,0 +1,151 @@
|
||||
'use strict';
|
||||
|
||||
// RingBuffer - O(1) FIFO queue with indexed access.
|
||||
//
|
||||
// Replaces plain JS arrays that are used as queues with shift()/push().
|
||||
// Array.shift() is O(n) because it copies all remaining elements;
|
||||
// RingBuffer.shift() is O(1) -- it just advances a head pointer.
|
||||
//
|
||||
// Also provides O(1) trimFront(count) to replace Array.splice(0, count).
|
||||
//
|
||||
// Capacity is always a power of 2, so modulo is replaced with bitwise AND.
|
||||
|
||||
const {
|
||||
Array,
|
||||
} = primordials;
|
||||
|
||||
class RingBuffer {
|
||||
#backing;
|
||||
#head = 0;
|
||||
#size = 0;
|
||||
#mask;
|
||||
|
||||
constructor(initialCapacity = 16) {
|
||||
this.#mask = initialCapacity - 1;
|
||||
this.#backing = new Array(initialCapacity);
|
||||
}
|
||||
|
||||
get length() {
|
||||
return this.#size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Append an item to the tail. O(1) amortized.
|
||||
*/
|
||||
push(item) {
|
||||
if (this.#size > this.#mask) {
|
||||
this.#grow();
|
||||
}
|
||||
this.#backing[(this.#head + this.#size) & this.#mask] = item;
|
||||
this.#size++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepend an item to the head. O(1) amortized.
|
||||
*/
|
||||
unshift(item) {
|
||||
if (this.#size > this.#mask) {
|
||||
this.#grow();
|
||||
}
|
||||
this.#head = (this.#head - 1 + this.#mask + 1) & this.#mask;
|
||||
this.#backing[this.#head] = item;
|
||||
this.#size++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove and return the item at the head. O(1).
|
||||
* @returns {any}
|
||||
*/
|
||||
shift() {
|
||||
if (this.#size === 0) return undefined;
|
||||
const item = this.#backing[this.#head];
|
||||
this.#backing[this.#head] = undefined; // Help GC
|
||||
this.#head = (this.#head + 1) & this.#mask;
|
||||
this.#size--;
|
||||
return item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read item at a logical index (0 = head). O(1).
|
||||
* Returns undefined if index is out of bounds.
|
||||
* @returns {any}
|
||||
*/
|
||||
get(index) {
|
||||
if (index < 0 || index >= this.#size) return undefined;
|
||||
return this.#backing[(this.#head + index) & this.#mask];
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove `count` items from the head without returning them.
|
||||
* O(count) for GC cleanup.
|
||||
*/
|
||||
trimFront(count) {
|
||||
if (count <= 0) return;
|
||||
if (count >= this.#size) {
|
||||
this.clear();
|
||||
return;
|
||||
}
|
||||
for (let i = 0; i < count; i++) {
|
||||
this.#backing[(this.#head + i) & this.#mask] = undefined;
|
||||
}
|
||||
this.#head = (this.#head + count) & this.#mask;
|
||||
this.#size -= count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the logical index of `item` (reference equality). O(n).
|
||||
* Returns -1 if not found.
|
||||
* @returns {number}
|
||||
*/
|
||||
indexOf(item) {
|
||||
for (let i = 0; i < this.#size; i++) {
|
||||
if (this.#backing[(this.#head + i) & this.#mask] === item) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the item at logical `index`, shifting later elements. O(n) worst case.
|
||||
* Used only on rare abort-signal cancellation path.
|
||||
*/
|
||||
removeAt(index) {
|
||||
if (index < 0 || index >= this.#size) return;
|
||||
for (let i = index; i < this.#size - 1; i++) {
|
||||
const from = (this.#head + i + 1) & this.#mask;
|
||||
const to = (this.#head + i) & this.#mask;
|
||||
this.#backing[to] = this.#backing[from];
|
||||
}
|
||||
const last = (this.#head + this.#size - 1) & this.#mask;
|
||||
this.#backing[last] = undefined;
|
||||
this.#size--;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all items. O(n) for GC cleanup.
|
||||
*/
|
||||
clear() {
|
||||
for (let i = 0; i < this.#size; i++) {
|
||||
this.#backing[(this.#head + i) & this.#mask] = undefined;
|
||||
}
|
||||
this.#head = 0;
|
||||
this.#size = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Double the backing capacity, linearizing the circular layout.
|
||||
*/
|
||||
#grow() {
|
||||
const newCapacity = (this.#mask + 1) * 2;
|
||||
const newBacking = new Array(newCapacity);
|
||||
for (let i = 0; i < this.#size; i++) {
|
||||
newBacking[i] = this.#backing[(this.#head + i) & this.#mask];
|
||||
}
|
||||
this.#backing = newBacking;
|
||||
this.#head = 0;
|
||||
this.#mask = newCapacity - 1;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { RingBuffer };
|
||||
@@ -0,0 +1,651 @@
|
||||
'use strict';
|
||||
|
||||
// New Streams API - Share
|
||||
//
|
||||
// Pull-model multi-consumer streaming. Shares a single source among
|
||||
// multiple consumers with explicit buffering.
|
||||
|
||||
const {
|
||||
ArrayPrototypePush,
|
||||
PromisePrototypeThen,
|
||||
PromiseResolve,
|
||||
PromiseWithResolvers,
|
||||
SafeSet,
|
||||
SymbolAsyncIterator,
|
||||
SymbolDispose,
|
||||
SymbolIterator,
|
||||
} = primordials;
|
||||
|
||||
const {
|
||||
shareProtocol,
|
||||
shareSyncProtocol,
|
||||
} = require('internal/streams/iter/types');
|
||||
|
||||
const {
|
||||
from,
|
||||
fromSync,
|
||||
isAsyncIterable,
|
||||
isSyncIterable,
|
||||
} = require('internal/streams/iter/from');
|
||||
|
||||
const {
|
||||
pull: pullWithTransforms,
|
||||
pullSync: pullSyncWithTransforms,
|
||||
} = require('internal/streams/iter/pull');
|
||||
|
||||
const {
|
||||
kMultiConsumerDefaultHWM,
|
||||
clampHWM,
|
||||
getMinCursor,
|
||||
hasProtocol,
|
||||
onSignalAbort,
|
||||
wrapError,
|
||||
parsePullArgs,
|
||||
validateBackpressure,
|
||||
} = require('internal/streams/iter/utils');
|
||||
|
||||
const {
|
||||
RingBuffer,
|
||||
} = require('internal/streams/iter/ringbuffer');
|
||||
|
||||
const {
|
||||
codes: {
|
||||
ERR_INVALID_ARG_TYPE,
|
||||
ERR_INVALID_RETURN_VALUE,
|
||||
ERR_OUT_OF_RANGE,
|
||||
},
|
||||
} = require('internal/errors');
|
||||
const {
|
||||
validateAbortSignal,
|
||||
validateInteger,
|
||||
validateObject,
|
||||
} = require('internal/validators');
|
||||
|
||||
// =============================================================================
|
||||
// Async Share Implementation
|
||||
// =============================================================================
|
||||
|
||||
class ShareImpl {
|
||||
#source;
|
||||
#options;
|
||||
#buffer = new RingBuffer();
|
||||
#bufferStart = 0;
|
||||
#consumers = new SafeSet();
|
||||
#sourceIterator = null;
|
||||
#sourceExhausted = false;
|
||||
#sourceError = null;
|
||||
#cancelled = false;
|
||||
#pulling = false;
|
||||
#pullWaiters = [];
|
||||
|
||||
constructor(source, options) {
|
||||
this.#source = source;
|
||||
this.#options = options;
|
||||
}
|
||||
|
||||
get consumerCount() {
|
||||
return this.#consumers.size;
|
||||
}
|
||||
|
||||
get bufferSize() {
|
||||
return this.#buffer.length;
|
||||
}
|
||||
|
||||
pull(...args) {
|
||||
const { transforms, options } = parsePullArgs(args);
|
||||
const rawConsumer = this.#createRawConsumer();
|
||||
|
||||
if (transforms.length > 0) {
|
||||
if (options) {
|
||||
return pullWithTransforms(rawConsumer, ...transforms, options);
|
||||
}
|
||||
return pullWithTransforms(rawConsumer, ...transforms);
|
||||
}
|
||||
return rawConsumer;
|
||||
}
|
||||
|
||||
#createRawConsumer() {
|
||||
const state = {
|
||||
__proto__: null,
|
||||
cursor: this.#bufferStart,
|
||||
resolve: null,
|
||||
reject: null,
|
||||
detached: false,
|
||||
};
|
||||
|
||||
this.#consumers.add(state);
|
||||
const self = this;
|
||||
|
||||
return {
|
||||
__proto__: null,
|
||||
[SymbolAsyncIterator]() {
|
||||
return {
|
||||
__proto__: null,
|
||||
async next() {
|
||||
if (self.#sourceError) {
|
||||
state.detached = true;
|
||||
self.#consumers.delete(state);
|
||||
throw self.#sourceError;
|
||||
}
|
||||
|
||||
// Loop until we get data, source is exhausted, or
|
||||
// consumer is detached. Multiple consumers may be woken
|
||||
// after a single pull - those that find no data at their
|
||||
// cursor must re-pull rather than terminating prematurely.
|
||||
for (;;) {
|
||||
if (state.detached) {
|
||||
return { __proto__: null, done: true, value: undefined };
|
||||
}
|
||||
|
||||
if (self.#cancelled) {
|
||||
state.detached = true;
|
||||
self.#consumers.delete(state);
|
||||
return { __proto__: null, done: true, value: undefined };
|
||||
}
|
||||
|
||||
// Check if data is available in buffer
|
||||
const bufferIndex = state.cursor - self.#bufferStart;
|
||||
if (bufferIndex < self.#buffer.length) {
|
||||
const chunk = self.#buffer.get(bufferIndex);
|
||||
state.cursor++;
|
||||
self.#tryTrimBuffer();
|
||||
return { __proto__: null, done: false, value: chunk };
|
||||
}
|
||||
|
||||
if (self.#sourceExhausted) {
|
||||
state.detached = true;
|
||||
self.#consumers.delete(state);
|
||||
if (self.#sourceError) throw self.#sourceError;
|
||||
return { __proto__: null, done: true, value: undefined };
|
||||
}
|
||||
|
||||
// Need to pull from source - check buffer limit
|
||||
const canPull = await self.#waitForBufferSpace();
|
||||
if (!canPull) {
|
||||
state.detached = true;
|
||||
self.#consumers.delete(state);
|
||||
if (self.#sourceError) throw self.#sourceError;
|
||||
return { __proto__: null, done: true, value: undefined };
|
||||
}
|
||||
|
||||
await self.#pullFromSource();
|
||||
}
|
||||
},
|
||||
|
||||
async return() {
|
||||
state.detached = true;
|
||||
state.resolve = null;
|
||||
state.reject = null;
|
||||
self.#consumers.delete(state);
|
||||
self.#tryTrimBuffer();
|
||||
return { __proto__: null, done: true, value: undefined };
|
||||
},
|
||||
|
||||
async throw() {
|
||||
state.detached = true;
|
||||
state.resolve = null;
|
||||
state.reject = null;
|
||||
self.#consumers.delete(state);
|
||||
self.#tryTrimBuffer();
|
||||
return { __proto__: null, done: true, value: undefined };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
cancel(reason) {
|
||||
if (this.#cancelled) return;
|
||||
this.#cancelled = true;
|
||||
|
||||
if (reason !== undefined) {
|
||||
this.#sourceError = reason;
|
||||
}
|
||||
|
||||
if (this.#sourceIterator?.return) {
|
||||
PromisePrototypeThen(this.#sourceIterator.return(), undefined, () => {});
|
||||
}
|
||||
|
||||
for (const consumer of this.#consumers) {
|
||||
if (consumer.resolve) {
|
||||
if (reason !== undefined) {
|
||||
consumer.reject?.(reason);
|
||||
} else {
|
||||
consumer.resolve({ __proto__: null, done: true, value: undefined });
|
||||
}
|
||||
consumer.resolve = null;
|
||||
consumer.reject = null;
|
||||
}
|
||||
consumer.detached = true;
|
||||
}
|
||||
this.#consumers.clear();
|
||||
|
||||
for (let i = 0; i < this.#pullWaiters.length; i++) {
|
||||
this.#pullWaiters[i]();
|
||||
}
|
||||
this.#pullWaiters = [];
|
||||
}
|
||||
|
||||
[SymbolDispose]() {
|
||||
this.cancel();
|
||||
}
|
||||
|
||||
// Internal methods
|
||||
|
||||
async #waitForBufferSpace() {
|
||||
while (this.#buffer.length >= this.#options.highWaterMark) {
|
||||
if (this.#cancelled || this.#sourceError || this.#sourceExhausted) {
|
||||
return !this.#cancelled;
|
||||
}
|
||||
|
||||
switch (this.#options.backpressure) {
|
||||
case 'strict':
|
||||
throw new ERR_OUT_OF_RANGE(
|
||||
'buffer size', `<= ${this.#options.highWaterMark}`,
|
||||
this.#buffer.length);
|
||||
case 'block': {
|
||||
const { promise, resolve } = PromiseWithResolvers();
|
||||
ArrayPrototypePush(this.#pullWaiters, resolve);
|
||||
await promise;
|
||||
break;
|
||||
}
|
||||
case 'drop-oldest':
|
||||
this.#buffer.shift();
|
||||
this.#bufferStart++;
|
||||
for (const consumer of this.#consumers) {
|
||||
if (consumer.cursor < this.#bufferStart) {
|
||||
consumer.cursor = this.#bufferStart;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
case 'drop-newest':
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#pullFromSource() {
|
||||
if (this.#sourceExhausted || this.#cancelled) {
|
||||
return PromiseResolve();
|
||||
}
|
||||
|
||||
if (this.#pulling) {
|
||||
const { promise, resolve } = PromiseWithResolvers();
|
||||
ArrayPrototypePush(this.#pullWaiters, resolve);
|
||||
return promise;
|
||||
}
|
||||
|
||||
this.#pulling = true;
|
||||
|
||||
return (async () => {
|
||||
try {
|
||||
if (!this.#sourceIterator) {
|
||||
if (isAsyncIterable(this.#source)) {
|
||||
this.#sourceIterator =
|
||||
this.#source[SymbolAsyncIterator]();
|
||||
} else if (isSyncIterable(this.#source)) {
|
||||
const syncIterator =
|
||||
this.#source[SymbolIterator]();
|
||||
this.#sourceIterator = {
|
||||
__proto__: null,
|
||||
async next() {
|
||||
return syncIterator.next();
|
||||
},
|
||||
async return() {
|
||||
return syncIterator.return?.() ??
|
||||
{ __proto__: null, done: true, value: undefined };
|
||||
},
|
||||
};
|
||||
} else {
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'source', ['AsyncIterable', 'Iterable'], this.#source);
|
||||
}
|
||||
}
|
||||
|
||||
const result = await this.#sourceIterator.next();
|
||||
|
||||
if (result.done) {
|
||||
this.#sourceExhausted = true;
|
||||
} else {
|
||||
this.#buffer.push(result.value);
|
||||
}
|
||||
} catch (error) {
|
||||
this.#sourceError = wrapError(error);
|
||||
this.#sourceExhausted = true;
|
||||
} finally {
|
||||
this.#pulling = false;
|
||||
for (let i = 0; i < this.#pullWaiters.length; i++) {
|
||||
this.#pullWaiters[i]();
|
||||
}
|
||||
this.#pullWaiters = [];
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
#tryTrimBuffer() {
|
||||
const minCursor = getMinCursor(
|
||||
this.#consumers, this.#bufferStart + this.#buffer.length);
|
||||
const trimCount = minCursor - this.#bufferStart;
|
||||
if (trimCount > 0) {
|
||||
this.#buffer.trimFront(trimCount);
|
||||
this.#bufferStart = minCursor;
|
||||
for (let i = 0; i < this.#pullWaiters.length; i++) {
|
||||
this.#pullWaiters[i]();
|
||||
}
|
||||
this.#pullWaiters = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Sync Share Implementation
|
||||
// =============================================================================
|
||||
|
||||
class SyncShareImpl {
|
||||
#source;
|
||||
#options;
|
||||
#buffer = new RingBuffer();
|
||||
#bufferStart = 0;
|
||||
#consumers = new SafeSet();
|
||||
#sourceIterator = null;
|
||||
#sourceExhausted = false;
|
||||
#sourceError = null;
|
||||
#cancelled = false;
|
||||
|
||||
constructor(source, options) {
|
||||
this.#source = source;
|
||||
this.#options = options;
|
||||
}
|
||||
|
||||
get consumerCount() {
|
||||
return this.#consumers.size;
|
||||
}
|
||||
|
||||
get bufferSize() {
|
||||
return this.#buffer.length;
|
||||
}
|
||||
|
||||
pull(...transforms) {
|
||||
const rawConsumer = this.#createRawConsumer();
|
||||
|
||||
if (transforms.length > 0) {
|
||||
return pullSyncWithTransforms(rawConsumer, ...transforms);
|
||||
}
|
||||
return rawConsumer;
|
||||
}
|
||||
|
||||
#createRawConsumer() {
|
||||
const state = {
|
||||
__proto__: null,
|
||||
cursor: this.#bufferStart,
|
||||
detached: false,
|
||||
};
|
||||
|
||||
this.#consumers.add(state);
|
||||
const self = this;
|
||||
|
||||
return {
|
||||
__proto__: null,
|
||||
[SymbolIterator]() {
|
||||
return {
|
||||
__proto__: null,
|
||||
next() {
|
||||
if (state.detached) {
|
||||
return { __proto__: null, done: true, value: undefined };
|
||||
}
|
||||
if (self.#sourceError) {
|
||||
state.detached = true;
|
||||
self.#consumers.delete(state);
|
||||
throw self.#sourceError;
|
||||
}
|
||||
if (self.#cancelled) {
|
||||
state.detached = true;
|
||||
self.#consumers.delete(state);
|
||||
return { __proto__: null, done: true, value: undefined };
|
||||
}
|
||||
|
||||
const bufferIndex = state.cursor - self.#bufferStart;
|
||||
if (bufferIndex < self.#buffer.length) {
|
||||
const chunk = self.#buffer.get(bufferIndex);
|
||||
state.cursor++;
|
||||
self.#tryTrimBuffer();
|
||||
return { __proto__: null, done: false, value: chunk };
|
||||
}
|
||||
|
||||
if (self.#sourceExhausted) {
|
||||
state.detached = true;
|
||||
self.#consumers.delete(state);
|
||||
return { __proto__: null, done: true, value: undefined };
|
||||
}
|
||||
|
||||
// Check buffer limit
|
||||
if (self.#buffer.length >= self.#options.highWaterMark) {
|
||||
switch (self.#options.backpressure) {
|
||||
case 'strict':
|
||||
throw new ERR_OUT_OF_RANGE(
|
||||
'buffer size', `<= ${self.#options.highWaterMark}`,
|
||||
self.#buffer.length);
|
||||
case 'block':
|
||||
throw new ERR_OUT_OF_RANGE(
|
||||
'buffer size', `<= ${self.#options.highWaterMark} ` +
|
||||
'(blocking not available in sync context)',
|
||||
self.#buffer.length);
|
||||
case 'drop-oldest':
|
||||
self.#buffer.shift();
|
||||
self.#bufferStart++;
|
||||
for (const consumer of self.#consumers) {
|
||||
if (consumer.cursor < self.#bufferStart) {
|
||||
consumer.cursor = self.#bufferStart;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'drop-newest':
|
||||
state.detached = true;
|
||||
self.#consumers.delete(state);
|
||||
return { __proto__: null, done: true, value: undefined };
|
||||
}
|
||||
}
|
||||
|
||||
self.#pullFromSource();
|
||||
|
||||
if (self.#sourceError) {
|
||||
state.detached = true;
|
||||
self.#consumers.delete(state);
|
||||
throw self.#sourceError;
|
||||
}
|
||||
|
||||
const newBufferIndex = state.cursor - self.#bufferStart;
|
||||
if (newBufferIndex < self.#buffer.length) {
|
||||
const chunk = self.#buffer.get(newBufferIndex);
|
||||
state.cursor++;
|
||||
self.#tryTrimBuffer();
|
||||
return { __proto__: null, done: false, value: chunk };
|
||||
}
|
||||
|
||||
if (self.#sourceExhausted) {
|
||||
state.detached = true;
|
||||
self.#consumers.delete(state);
|
||||
return { __proto__: null, done: true, value: undefined };
|
||||
}
|
||||
|
||||
return { __proto__: null, done: true, value: undefined };
|
||||
},
|
||||
|
||||
return() {
|
||||
state.detached = true;
|
||||
self.#consumers.delete(state);
|
||||
self.#tryTrimBuffer();
|
||||
return { __proto__: null, done: true, value: undefined };
|
||||
},
|
||||
|
||||
throw() {
|
||||
state.detached = true;
|
||||
self.#consumers.delete(state);
|
||||
self.#tryTrimBuffer();
|
||||
return { __proto__: null, done: true, value: undefined };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
cancel(reason) {
|
||||
if (this.#cancelled) return;
|
||||
this.#cancelled = true;
|
||||
|
||||
if (reason !== undefined) {
|
||||
this.#sourceError = reason;
|
||||
}
|
||||
|
||||
if (this.#sourceIterator?.return) {
|
||||
this.#sourceIterator.return();
|
||||
}
|
||||
|
||||
for (const consumer of this.#consumers) {
|
||||
consumer.detached = true;
|
||||
}
|
||||
this.#consumers.clear();
|
||||
}
|
||||
|
||||
[SymbolDispose]() {
|
||||
this.cancel();
|
||||
}
|
||||
|
||||
#pullFromSource() {
|
||||
if (this.#sourceExhausted || this.#cancelled) return;
|
||||
|
||||
try {
|
||||
this.#sourceIterator ||= this.#source[SymbolIterator]();
|
||||
|
||||
const result = this.#sourceIterator.next();
|
||||
|
||||
if (result.done) {
|
||||
this.#sourceExhausted = true;
|
||||
} else {
|
||||
this.#buffer.push(result.value);
|
||||
}
|
||||
} catch (error) {
|
||||
this.#sourceError = wrapError(error);
|
||||
this.#sourceExhausted = true;
|
||||
}
|
||||
}
|
||||
|
||||
#tryTrimBuffer() {
|
||||
const minCursor = getMinCursor(
|
||||
this.#consumers, this.#bufferStart + this.#buffer.length);
|
||||
const trimCount = minCursor - this.#bufferStart;
|
||||
if (trimCount > 0) {
|
||||
this.#buffer.trimFront(trimCount);
|
||||
this.#bufferStart = minCursor;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Public API
|
||||
// =============================================================================
|
||||
|
||||
function share(source, options = { __proto__: null }) {
|
||||
// Normalize source via from() - accepts strings, ArrayBuffers, protocols, etc.
|
||||
const normalized = from(source);
|
||||
validateObject(options, 'options');
|
||||
const {
|
||||
highWaterMark = kMultiConsumerDefaultHWM,
|
||||
backpressure = 'strict',
|
||||
signal,
|
||||
} = options;
|
||||
validateInteger(highWaterMark, 'options.highWaterMark');
|
||||
validateBackpressure(backpressure);
|
||||
if (signal !== undefined) {
|
||||
validateAbortSignal(signal, 'options.signal');
|
||||
}
|
||||
|
||||
const opts = {
|
||||
__proto__: null,
|
||||
highWaterMark: clampHWM(highWaterMark),
|
||||
backpressure,
|
||||
signal,
|
||||
};
|
||||
|
||||
const shareImpl = new ShareImpl(normalized, opts);
|
||||
|
||||
if (signal) {
|
||||
onSignalAbort(signal, () => shareImpl.cancel());
|
||||
}
|
||||
|
||||
return shareImpl;
|
||||
}
|
||||
|
||||
function shareSync(source, options = { __proto__: null }) {
|
||||
// Normalize source via fromSync() - accepts strings, ArrayBuffers, protocols, etc.
|
||||
const normalized = fromSync(source);
|
||||
validateObject(options, 'options');
|
||||
const {
|
||||
highWaterMark = kMultiConsumerDefaultHWM,
|
||||
backpressure = 'strict',
|
||||
} = options;
|
||||
validateInteger(highWaterMark, 'options.highWaterMark');
|
||||
validateBackpressure(backpressure);
|
||||
|
||||
const opts = {
|
||||
__proto__: null,
|
||||
highWaterMark: clampHWM(highWaterMark),
|
||||
backpressure,
|
||||
};
|
||||
|
||||
return new SyncShareImpl(normalized, opts);
|
||||
}
|
||||
|
||||
function isShareable(value) {
|
||||
return hasProtocol(value, shareProtocol);
|
||||
}
|
||||
|
||||
function isSyncShareable(value) {
|
||||
return hasProtocol(value, shareSyncProtocol);
|
||||
}
|
||||
|
||||
const Share = {
|
||||
__proto__: null,
|
||||
from(input, options) {
|
||||
if (isShareable(input)) {
|
||||
const result = input[shareProtocol](options);
|
||||
if (result === null || typeof result !== 'object') {
|
||||
throw new ERR_INVALID_RETURN_VALUE(
|
||||
'an object', '[Symbol.for(\'Stream.shareProtocol\')]', result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if (isAsyncIterable(input) || isSyncIterable(input)) {
|
||||
return share(input, options);
|
||||
}
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'input', ['Shareable', 'AsyncIterable', 'Iterable'], input);
|
||||
},
|
||||
};
|
||||
|
||||
const SyncShare = {
|
||||
__proto__: null,
|
||||
fromSync(input, options) {
|
||||
if (isSyncShareable(input)) {
|
||||
const result = input[shareSyncProtocol](options);
|
||||
if (result === null || typeof result !== 'object') {
|
||||
throw new ERR_INVALID_RETURN_VALUE(
|
||||
'an object', '[Symbol.for(\'Stream.shareSyncProtocol\')]', result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if (isSyncIterable(input)) {
|
||||
return shareSync(input, options);
|
||||
}
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'input', ['SyncShareable', 'Iterable'], input);
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
Share,
|
||||
SyncShare,
|
||||
share,
|
||||
shareSync,
|
||||
};
|
||||
@@ -0,0 +1,830 @@
|
||||
'use strict';
|
||||
|
||||
// Compression / Decompression Transforms
|
||||
//
|
||||
// Creates bare native zlib handles via internalBinding('zlib'), bypassing
|
||||
// the stream.Transform / ZlibBase / EventEmitter machinery entirely.
|
||||
// Compression runs on the libuv threadpool via handle.write() (async) so
|
||||
// I/O and upstream transforms can overlap with compression work.
|
||||
// Each factory returns a transform descriptor that can be passed to pull().
|
||||
|
||||
const {
|
||||
ArrayPrototypeMap,
|
||||
ArrayPrototypePush,
|
||||
ArrayPrototypeShift,
|
||||
MathMax,
|
||||
NumberIsNaN,
|
||||
ObjectEntries,
|
||||
ObjectKeys,
|
||||
PromiseWithResolvers,
|
||||
StringPrototypeStartsWith,
|
||||
SymbolAsyncIterator,
|
||||
TypedArrayPrototypeFill,
|
||||
TypedArrayPrototypeGetByteLength,
|
||||
TypedArrayPrototypeSlice,
|
||||
Uint32Array,
|
||||
} = primordials;
|
||||
|
||||
const { Buffer } = require('buffer');
|
||||
const {
|
||||
codes: {
|
||||
ERR_BROTLI_INVALID_PARAM,
|
||||
ERR_INVALID_ARG_TYPE,
|
||||
ERR_OUT_OF_RANGE,
|
||||
ERR_ZSTD_INVALID_PARAM,
|
||||
},
|
||||
genericNodeError,
|
||||
} = require('internal/errors');
|
||||
const { lazyDOMException } = require('internal/util');
|
||||
const { isArrayBufferView, isAnyArrayBuffer } = require('internal/util/types');
|
||||
const { kTrustedTransform } = require('internal/streams/iter/types');
|
||||
const {
|
||||
checkRangesOrGetDefault,
|
||||
validateFiniteNumber,
|
||||
validateObject,
|
||||
} = require('internal/validators');
|
||||
const binding = internalBinding('zlib');
|
||||
const constants = internalBinding('constants').zlib;
|
||||
|
||||
const {
|
||||
// Zlib modes
|
||||
DEFLATE, INFLATE, GZIP, GUNZIP,
|
||||
BROTLI_ENCODE, BROTLI_DECODE,
|
||||
ZSTD_COMPRESS, ZSTD_DECOMPRESS,
|
||||
// Zlib flush
|
||||
Z_NO_FLUSH, Z_FINISH,
|
||||
// Zlib defaults
|
||||
Z_DEFAULT_WINDOWBITS,
|
||||
Z_DEFAULT_STRATEGY,
|
||||
// Brotli flush
|
||||
BROTLI_OPERATION_PROCESS, BROTLI_OPERATION_FINISH,
|
||||
// Zlib ranges
|
||||
Z_MIN_CHUNK, Z_MIN_WINDOWBITS, Z_MAX_WINDOWBITS,
|
||||
Z_MIN_LEVEL, Z_MAX_LEVEL,
|
||||
Z_MIN_MEMLEVEL, Z_MAX_MEMLEVEL,
|
||||
Z_FIXED,
|
||||
// Zstd flush
|
||||
ZSTD_e_continue, ZSTD_e_end,
|
||||
} = constants;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Option validation helpers (matching lib/zlib.js validation patterns)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Default output buffer size for compression transforms. Larger than
|
||||
// Z_DEFAULT_CHUNK (16KB) to reduce the number of threadpool re-entries
|
||||
// when the engine has more output than fits in one buffer. 64KB matches
|
||||
// BATCH_HWM and the typical input chunk size from pull().
|
||||
const DEFAULT_OUTPUT_SIZE = 64 * 1024;
|
||||
|
||||
// Batch high water mark - yield output in chunks of approximately this size.
|
||||
const BATCH_HWM = DEFAULT_OUTPUT_SIZE;
|
||||
|
||||
// Pre-allocated empty buffer for flush/finalize calls.
|
||||
const kEmpty = Buffer.alloc(0);
|
||||
|
||||
function validateChunkSize(options) {
|
||||
let chunkSize = options.chunkSize;
|
||||
if (!validateFiniteNumber(chunkSize, 'options.chunkSize')) {
|
||||
chunkSize = DEFAULT_OUTPUT_SIZE;
|
||||
} else if (chunkSize < Z_MIN_CHUNK) {
|
||||
throw new ERR_OUT_OF_RANGE('options.chunkSize',
|
||||
`>= ${Z_MIN_CHUNK}`, chunkSize);
|
||||
}
|
||||
return chunkSize;
|
||||
}
|
||||
|
||||
function validateDictionary(dictionary) {
|
||||
if (dictionary === undefined) return undefined;
|
||||
if (isArrayBufferView(dictionary)) return dictionary;
|
||||
if (isAnyArrayBuffer(dictionary)) return Buffer.from(dictionary);
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
'options.dictionary',
|
||||
['Buffer', 'TypedArray', 'DataView', 'ArrayBuffer'],
|
||||
dictionary);
|
||||
}
|
||||
|
||||
function validateParams(params, maxParam, errClass) {
|
||||
if (params === undefined) return;
|
||||
if (typeof params !== 'object' || params === null) {
|
||||
throw new ERR_INVALID_ARG_TYPE('options.params', 'Object', params);
|
||||
}
|
||||
const keys = ObjectKeys(params);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const origKey = keys[i];
|
||||
const key = +origKey;
|
||||
if (NumberIsNaN(key) || key < 0 || key > maxParam) {
|
||||
throw new errClass(origKey);
|
||||
}
|
||||
const value = params[origKey];
|
||||
if (typeof value !== 'number' && typeof value !== 'boolean') {
|
||||
throw new ERR_INVALID_ARG_TYPE('options.params[key]', 'number', value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Brotli / Zstd parameter arrays (computed once, reused per init call).
|
||||
// Mirrors the pattern in lib/zlib.js.
|
||||
// ---------------------------------------------------------------------------
|
||||
const kMaxBrotliParam = MathMax(
|
||||
...ArrayPrototypeMap(
|
||||
ObjectEntries(constants),
|
||||
({ 0: key, 1: value }) =>
|
||||
(StringPrototypeStartsWith(key, 'BROTLI_PARAM_') ? value : 0),
|
||||
),
|
||||
);
|
||||
const brotliInitParamsArray = new Uint32Array(kMaxBrotliParam + 1);
|
||||
|
||||
const kMaxZstdCParam = MathMax(
|
||||
...ArrayPrototypeMap(
|
||||
ObjectKeys(constants),
|
||||
(key) => (StringPrototypeStartsWith(key, 'ZSTD_c_') ? constants[key] : 0),
|
||||
),
|
||||
);
|
||||
const zstdInitCParamsArray = new Uint32Array(kMaxZstdCParam + 1);
|
||||
|
||||
const kMaxZstdDParam = MathMax(
|
||||
...ArrayPrototypeMap(
|
||||
ObjectKeys(constants),
|
||||
(key) => (StringPrototypeStartsWith(key, 'ZSTD_d_') ? constants[key] : 0),
|
||||
),
|
||||
);
|
||||
const zstdInitDParamsArray = new Uint32Array(kMaxZstdDParam + 1);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Handle creation - bare native handles, no Transform/EventEmitter overhead.
|
||||
//
|
||||
// Each factory accepts a processCallback (called from the threadpool
|
||||
// completion path in C++) and an onError handler.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create a bare Zlib handle (gzip, gunzip, deflate, inflate).
|
||||
* @returns {{ handle: object, writeState: Uint32Array, chunkSize: number }}
|
||||
*/
|
||||
function createZlibHandle(mode, options, processCallback, onError) {
|
||||
// Validate all options before creating the native handle to avoid
|
||||
// "close before init" assertion if validation throws.
|
||||
const chunkSize = validateChunkSize(options);
|
||||
const windowBits = checkRangesOrGetDefault(
|
||||
options.windowBits, 'options.windowBits',
|
||||
Z_MIN_WINDOWBITS, Z_MAX_WINDOWBITS, Z_DEFAULT_WINDOWBITS);
|
||||
// Default compression level 4 (not Z_DEFAULT_COMPRESSION which maps to
|
||||
// level 6). Level 4 is ~1.5x faster with only ~5-10% worse compression
|
||||
// ratio - the sweet spot for streaming and HTTP content-encoding.
|
||||
const level = checkRangesOrGetDefault(
|
||||
options.level, 'options.level',
|
||||
Z_MIN_LEVEL, Z_MAX_LEVEL, 4);
|
||||
// memLevel 9 uses ~128KB more memory than 8 but provides faster hash
|
||||
// lookups during compression. Negligible memory cost for the speed gain.
|
||||
const memLevel = checkRangesOrGetDefault(
|
||||
options.memLevel, 'options.memLevel',
|
||||
Z_MIN_MEMLEVEL, Z_MAX_MEMLEVEL, 9);
|
||||
const strategy = checkRangesOrGetDefault(
|
||||
options.strategy, 'options.strategy',
|
||||
Z_DEFAULT_STRATEGY, Z_FIXED, Z_DEFAULT_STRATEGY);
|
||||
const dictionary = validateDictionary(options.dictionary);
|
||||
|
||||
const handle = new binding.Zlib(mode);
|
||||
const writeState = new Uint32Array(2);
|
||||
|
||||
handle.onerror = onError;
|
||||
handle.init(
|
||||
windowBits, level, memLevel, strategy,
|
||||
writeState, processCallback, dictionary,
|
||||
);
|
||||
|
||||
return { __proto__: null, handle, writeState, chunkSize };
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a bare Brotli handle.
|
||||
* @returns {{ handle: object, writeState: Uint32Array, chunkSize: number }}
|
||||
*/
|
||||
function createBrotliHandle(mode, options, processCallback, onError) {
|
||||
// Validate before creating native handle.
|
||||
const chunkSize = validateChunkSize(options);
|
||||
const dictionary = validateDictionary(options.dictionary);
|
||||
validateParams(options.params, kMaxBrotliParam, ERR_BROTLI_INVALID_PARAM);
|
||||
|
||||
const handle = mode === BROTLI_ENCODE ?
|
||||
new binding.BrotliEncoder(mode) : new binding.BrotliDecoder(mode);
|
||||
const writeState = new Uint32Array(2);
|
||||
|
||||
TypedArrayPrototypeFill(brotliInitParamsArray, -1);
|
||||
// Streaming-appropriate defaults: quality 6 (not 11) and lgwin 20 (1MB,
|
||||
// not 4MB). Quality 11 is intended for offline/build-time compression
|
||||
// and allocates ~400MB of internal state. Quality 6 is ~10x faster with
|
||||
// only ~10-15% worse compression ratio - the standard for dynamic HTTP
|
||||
// content-encoding (nginx, Caddy, Cloudflare all use 4-6).
|
||||
if (mode === BROTLI_ENCODE) {
|
||||
brotliInitParamsArray[constants.BROTLI_PARAM_QUALITY] = 6;
|
||||
brotliInitParamsArray[constants.BROTLI_PARAM_LGWIN] = 20;
|
||||
}
|
||||
if (options.params) {
|
||||
// User-supplied params override the defaults above.
|
||||
const params = options.params;
|
||||
const keys = ObjectKeys(params);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = +keys[i];
|
||||
brotliInitParamsArray[key] = params[keys[i]];
|
||||
}
|
||||
}
|
||||
|
||||
handle.onerror = onError;
|
||||
handle.init(
|
||||
brotliInitParamsArray,
|
||||
writeState,
|
||||
processCallback,
|
||||
dictionary,
|
||||
);
|
||||
|
||||
return { __proto__: null, handle, writeState, chunkSize };
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a bare Zstd handle.
|
||||
* @returns {{ handle: object, writeState: Uint32Array, chunkSize: number }}
|
||||
*/
|
||||
function createZstdHandle(mode, options, processCallback, onError) {
|
||||
const isCompress = mode === ZSTD_COMPRESS;
|
||||
|
||||
// Validate before creating native handle.
|
||||
const chunkSize = validateChunkSize(options);
|
||||
const dictionary = validateDictionary(options.dictionary);
|
||||
const maxParam = isCompress ? kMaxZstdCParam : kMaxZstdDParam;
|
||||
validateParams(options.params, maxParam, ERR_ZSTD_INVALID_PARAM);
|
||||
|
||||
const pledgedSrcSize = options.pledgedSrcSize;
|
||||
if (pledgedSrcSize !== undefined) {
|
||||
if (typeof pledgedSrcSize !== 'number' || NumberIsNaN(pledgedSrcSize)) {
|
||||
throw new ERR_INVALID_ARG_TYPE('options.pledgedSrcSize', 'number',
|
||||
pledgedSrcSize);
|
||||
}
|
||||
if (pledgedSrcSize < 0) {
|
||||
throw new ERR_OUT_OF_RANGE('options.pledgedSrcSize', '>= 0',
|
||||
pledgedSrcSize);
|
||||
}
|
||||
}
|
||||
|
||||
const handle = isCompress ?
|
||||
new binding.ZstdCompress() : new binding.ZstdDecompress();
|
||||
const writeState = new Uint32Array(2);
|
||||
|
||||
const initArray = isCompress ? zstdInitCParamsArray : zstdInitDParamsArray;
|
||||
TypedArrayPrototypeFill(initArray, -1);
|
||||
if (options.params) {
|
||||
const params = options.params;
|
||||
const keys = ObjectKeys(params);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = +keys[i];
|
||||
initArray[key] = params[keys[i]];
|
||||
}
|
||||
}
|
||||
|
||||
handle.onerror = onError;
|
||||
handle.init(
|
||||
initArray,
|
||||
pledgedSrcSize,
|
||||
writeState,
|
||||
processCallback,
|
||||
dictionary,
|
||||
);
|
||||
|
||||
return { __proto__: null, handle, writeState, chunkSize };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Core: makeZlibTransform
|
||||
//
|
||||
// Uses async handle.write() so compression runs on the libuv threadpool.
|
||||
// The generator manually iterates the source with pre-reading: the next
|
||||
// upstream read+transform is started before awaiting the current compression,
|
||||
// so I/O and upstream work overlap with threadpool compression.
|
||||
// ---------------------------------------------------------------------------
|
||||
function makeZlibTransform(createHandleFn, processFlag, finishFlag) {
|
||||
return {
|
||||
__proto__: null,
|
||||
[kTrustedTransform]: true,
|
||||
transform: async function*(source, options) {
|
||||
const { signal } = options;
|
||||
|
||||
// Fail fast if already aborted - don't allocate a native handle.
|
||||
signal?.throwIfAborted();
|
||||
|
||||
// ---- Per-invocation state shared with the write callback ----
|
||||
let outBuf;
|
||||
let outOffset = 0;
|
||||
let chunkSize;
|
||||
let pending = [];
|
||||
let pendingBytes = 0;
|
||||
|
||||
// Current write operation state (read by the callback for looping).
|
||||
let resolveWrite, rejectWrite;
|
||||
let writeInput, writeFlush;
|
||||
let writeInOff, writeAvailIn, writeAvailOutBefore;
|
||||
|
||||
// processCallback: called by C++ AfterThreadPoolWork when compression
|
||||
// on the threadpool completes. Collects output, loops if the engine
|
||||
// has more output to produce (availOut === 0), then resolves the
|
||||
// promise when all output for this input chunk is collected.
|
||||
function onWriteComplete() {
|
||||
const availOut = writeState[0];
|
||||
const availInAfter = writeState[1];
|
||||
const have = writeAvailOutBefore - availOut;
|
||||
const bufferExhausted = availOut === 0 || outOffset + have >= chunkSize;
|
||||
|
||||
if (have > 0) {
|
||||
if (bufferExhausted && outOffset === 0) {
|
||||
// Entire buffer filled from start - yield directly, no copy.
|
||||
ArrayPrototypePush(pending, outBuf);
|
||||
} else if (bufferExhausted) {
|
||||
// Tail of buffer filled and buffer is being replaced -
|
||||
// subarray is safe since outBuf reference is overwritten below.
|
||||
ArrayPrototypePush(pending,
|
||||
outBuf.subarray(outOffset, outOffset + have));
|
||||
} else {
|
||||
// Partial fill, buffer will be reused - must copy.
|
||||
ArrayPrototypePush(pending,
|
||||
TypedArrayPrototypeSlice(outBuf,
|
||||
outOffset,
|
||||
outOffset + have));
|
||||
}
|
||||
pendingBytes += have;
|
||||
outOffset += have;
|
||||
}
|
||||
|
||||
// Reallocate output buffer if exhausted.
|
||||
if (bufferExhausted) {
|
||||
outBuf = Buffer.allocUnsafe(chunkSize);
|
||||
outOffset = 0;
|
||||
}
|
||||
|
||||
if (availOut === 0) {
|
||||
// Engine has more output - but if aborted, don't loop.
|
||||
if (!resolveWrite) return;
|
||||
|
||||
const consumed = writeAvailIn - availInAfter;
|
||||
writeInOff += consumed;
|
||||
writeAvailIn = availInAfter;
|
||||
writeAvailOutBefore = chunkSize - outOffset;
|
||||
|
||||
handle.write(writeFlush,
|
||||
writeInput, writeInOff, writeAvailIn,
|
||||
outBuf, outOffset, writeAvailOutBefore);
|
||||
return; // Will call onWriteComplete again.
|
||||
}
|
||||
|
||||
// All input consumed and output collected.
|
||||
handle.buffer = null;
|
||||
const resolve = resolveWrite;
|
||||
resolveWrite = undefined;
|
||||
rejectWrite = undefined;
|
||||
if (resolve) resolve();
|
||||
}
|
||||
|
||||
// onError: called by C++ when the engine encounters an error.
|
||||
// Fires instead of onWriteComplete - reject the promise.
|
||||
function onError(message, errno, code) {
|
||||
const error = genericNodeError(message, { __proto__: null, errno, code });
|
||||
error.errno = errno;
|
||||
error.code = code;
|
||||
const reject = rejectWrite;
|
||||
resolveWrite = undefined;
|
||||
rejectWrite = undefined;
|
||||
if (reject) reject(error);
|
||||
}
|
||||
|
||||
// ---- Create the handle with our callbacks ----
|
||||
const result = createHandleFn(onWriteComplete, onError);
|
||||
const handle = result.handle;
|
||||
const writeState = result.writeState;
|
||||
chunkSize = result.chunkSize;
|
||||
outBuf = Buffer.allocUnsafe(chunkSize);
|
||||
|
||||
// Abort handler: reject any in-flight threadpool operation so the
|
||||
// generator doesn't block waiting for compression to finish.
|
||||
const onAbort = () => {
|
||||
const reject = rejectWrite;
|
||||
resolveWrite = undefined;
|
||||
rejectWrite = undefined;
|
||||
if (reject) {
|
||||
reject(signal.reason ??
|
||||
lazyDOMException('The operation was aborted', 'AbortError'));
|
||||
}
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { __proto__: null, once: true });
|
||||
|
||||
// Dispatch input to the threadpool and return a promise.
|
||||
function processInputAsync(input, flushFlag) {
|
||||
const { promise, resolve, reject } = PromiseWithResolvers();
|
||||
resolveWrite = resolve;
|
||||
rejectWrite = reject;
|
||||
writeInput = input;
|
||||
writeFlush = flushFlag;
|
||||
writeInOff = 0;
|
||||
writeAvailIn = TypedArrayPrototypeGetByteLength(input);
|
||||
writeAvailOutBefore = chunkSize - outOffset;
|
||||
|
||||
// Keep input alive while the threadpool references it.
|
||||
handle.buffer = input;
|
||||
|
||||
handle.write(flushFlag,
|
||||
input, 0, writeAvailIn,
|
||||
outBuf, outOffset, writeAvailOutBefore);
|
||||
return promise;
|
||||
}
|
||||
|
||||
function drainBatch() {
|
||||
if (pendingBytes <= BATCH_HWM) {
|
||||
// Swap instead of splice - avoids copying the array.
|
||||
const batch = pending;
|
||||
pending = [];
|
||||
pendingBytes = 0;
|
||||
return batch;
|
||||
}
|
||||
const batch = [];
|
||||
let batchBytes = 0;
|
||||
while (pending.length > 0 && batchBytes < BATCH_HWM) {
|
||||
const buf = ArrayPrototypeShift(pending);
|
||||
ArrayPrototypePush(batch, buf);
|
||||
const len = TypedArrayPrototypeGetByteLength(buf);
|
||||
batchBytes += len;
|
||||
pendingBytes -= len;
|
||||
}
|
||||
return batch;
|
||||
}
|
||||
|
||||
let finalized = false;
|
||||
|
||||
const iter = source[SymbolAsyncIterator]();
|
||||
try {
|
||||
// Manually iterate the source so we can pre-read: calling
|
||||
// iter.next() starts the upstream read + transform on libuv
|
||||
// before we await the current compression on the threadpool.
|
||||
let nextResult = iter.next();
|
||||
|
||||
while (true) {
|
||||
const { value: chunks, done } = await nextResult;
|
||||
if (done) break;
|
||||
|
||||
signal?.throwIfAborted();
|
||||
|
||||
if (chunks === null) {
|
||||
// Flush signal - finalize the engine.
|
||||
if (!finalized) {
|
||||
finalized = true;
|
||||
await processInputAsync(kEmpty, finishFlag);
|
||||
while (pending.length > 0) {
|
||||
yield drainBatch();
|
||||
}
|
||||
}
|
||||
nextResult = iter.next();
|
||||
continue;
|
||||
}
|
||||
|
||||
// Pre-read: start upstream I/O + transform for the NEXT batch
|
||||
// while we compress the current batch on the threadpool.
|
||||
nextResult = iter.next();
|
||||
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
await processInputAsync(chunks[i], processFlag);
|
||||
}
|
||||
|
||||
if (pendingBytes >= BATCH_HWM) {
|
||||
while (pending.length > 0 && pendingBytes >= BATCH_HWM) {
|
||||
yield drainBatch();
|
||||
}
|
||||
}
|
||||
if (pending.length > 0) {
|
||||
yield drainBatch();
|
||||
}
|
||||
}
|
||||
|
||||
// Source ended - finalize if not already done by a null signal.
|
||||
if (!finalized && !signal.aborted) {
|
||||
finalized = true;
|
||||
await processInputAsync(kEmpty, finishFlag);
|
||||
while (pending.length > 0) {
|
||||
yield drainBatch();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
handle.close();
|
||||
// Close the upstream iterator so its finally blocks run promptly
|
||||
// rather than waiting for GC.
|
||||
try { await iter.return?.(); } catch { /* Intentional no-op. */ }
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Compression factories
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Core: makeZlibTransformSync
|
||||
//
|
||||
// Synchronous counterpart to makeZlibTransform. Uses handle.writeSync()
|
||||
// which runs compression directly on the main thread (no threadpool).
|
||||
// Returns a stateful sync transform (generator function).
|
||||
// ---------------------------------------------------------------------------
|
||||
function makeZlibTransformSync(createHandleFn, processFlag, finishFlag) {
|
||||
return {
|
||||
__proto__: null,
|
||||
transform: function*(source) {
|
||||
// The processCallback is never called in sync mode, but handle.init()
|
||||
// requires it. Pass a no-op.
|
||||
let error = null;
|
||||
function onError(message, errno, code) {
|
||||
error = genericNodeError(message, { __proto__: null, errno, code });
|
||||
error.errno = errno;
|
||||
error.code = code;
|
||||
}
|
||||
|
||||
const result = createHandleFn(() => {}, onError);
|
||||
const handle = result.handle;
|
||||
const writeState = result.writeState;
|
||||
const chunkSize = result.chunkSize;
|
||||
let outBuf = Buffer.allocUnsafe(chunkSize);
|
||||
let outOffset = 0;
|
||||
let pending = [];
|
||||
let pendingBytes = 0;
|
||||
|
||||
function processSyncInput(input, flushFlag) {
|
||||
let inOff = 0;
|
||||
let availIn = TypedArrayPrototypeGetByteLength(input);
|
||||
let availOutBefore = chunkSize - outOffset;
|
||||
|
||||
handle.writeSync(flushFlag,
|
||||
input, inOff, availIn,
|
||||
outBuf, outOffset, availOutBefore);
|
||||
if (error) throw error;
|
||||
|
||||
while (true) {
|
||||
const availOut = writeState[0];
|
||||
const availInAfter = writeState[1];
|
||||
const have = availOutBefore - availOut;
|
||||
const bufferExhausted = availOut === 0 ||
|
||||
outOffset + have >= chunkSize;
|
||||
|
||||
if (have > 0) {
|
||||
if (bufferExhausted && outOffset === 0) {
|
||||
// Entire buffer filled - yield directly, no copy.
|
||||
ArrayPrototypePush(pending, outBuf);
|
||||
} else if (bufferExhausted) {
|
||||
// Tail filled, buffer being replaced - subarray is safe.
|
||||
ArrayPrototypePush(pending,
|
||||
outBuf.subarray(outOffset, outOffset + have));
|
||||
} else {
|
||||
// Partial fill, buffer reused - must copy.
|
||||
ArrayPrototypePush(pending,
|
||||
TypedArrayPrototypeSlice(outBuf,
|
||||
outOffset,
|
||||
outOffset + have));
|
||||
}
|
||||
pendingBytes += have;
|
||||
outOffset += have;
|
||||
}
|
||||
|
||||
if (bufferExhausted) {
|
||||
outBuf = Buffer.allocUnsafe(chunkSize);
|
||||
outOffset = 0;
|
||||
}
|
||||
|
||||
if (availOut === 0) {
|
||||
// Engine has more output - loop.
|
||||
const consumed = availIn - availInAfter;
|
||||
inOff += consumed;
|
||||
availIn = availInAfter;
|
||||
availOutBefore = chunkSize - outOffset;
|
||||
|
||||
handle.writeSync(flushFlag,
|
||||
input, inOff, availIn,
|
||||
outBuf, outOffset, availOutBefore);
|
||||
if (error) throw error;
|
||||
continue;
|
||||
}
|
||||
|
||||
// All input consumed.
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function drainBatch() {
|
||||
if (pendingBytes <= BATCH_HWM) {
|
||||
const batch = pending;
|
||||
pending = [];
|
||||
pendingBytes = 0;
|
||||
return batch;
|
||||
}
|
||||
const batch = [];
|
||||
let batchBytes = 0;
|
||||
while (pending.length > 0 && batchBytes < BATCH_HWM) {
|
||||
const buf = ArrayPrototypeShift(pending);
|
||||
const len = TypedArrayPrototypeGetByteLength(buf);
|
||||
ArrayPrototypePush(batch, buf);
|
||||
batchBytes += len;
|
||||
pendingBytes -= len;
|
||||
}
|
||||
return batch;
|
||||
}
|
||||
|
||||
try {
|
||||
for (const batch of source) {
|
||||
if (batch === null) {
|
||||
// Flush signal - finalize the engine.
|
||||
processSyncInput(Buffer.alloc(0), finishFlag);
|
||||
while (pending.length > 0) {
|
||||
yield drainBatch();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
processSyncInput(batch[i], processFlag);
|
||||
}
|
||||
|
||||
if (pendingBytes >= BATCH_HWM) {
|
||||
while (pending.length > 0 && pendingBytes >= BATCH_HWM) {
|
||||
yield drainBatch();
|
||||
}
|
||||
}
|
||||
if (pending.length > 0) {
|
||||
yield drainBatch();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
handle.close();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Async compression factories
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const kNullPrototype = { __proto__: null };
|
||||
|
||||
function compressGzip(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransform(
|
||||
(cb, onErr) => createZlibHandle(GZIP, options, cb, onErr),
|
||||
Z_NO_FLUSH, Z_FINISH,
|
||||
);
|
||||
}
|
||||
|
||||
function compressDeflate(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransform(
|
||||
(cb, onErr) => createZlibHandle(DEFLATE, options, cb, onErr),
|
||||
Z_NO_FLUSH, Z_FINISH,
|
||||
);
|
||||
}
|
||||
|
||||
function compressBrotli(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransform(
|
||||
(cb, onErr) => createBrotliHandle(BROTLI_ENCODE, options, cb, onErr),
|
||||
BROTLI_OPERATION_PROCESS, BROTLI_OPERATION_FINISH,
|
||||
);
|
||||
}
|
||||
|
||||
function compressZstd(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransform(
|
||||
(cb, onErr) => createZstdHandle(ZSTD_COMPRESS, options, cb, onErr),
|
||||
ZSTD_e_continue, ZSTD_e_end,
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Decompression factories
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function decompressGzip(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransform(
|
||||
(cb, onErr) => createZlibHandle(GUNZIP, options, cb, onErr),
|
||||
Z_NO_FLUSH, Z_FINISH,
|
||||
);
|
||||
}
|
||||
|
||||
function decompressDeflate(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransform(
|
||||
(cb, onErr) => createZlibHandle(INFLATE, options, cb, onErr),
|
||||
Z_NO_FLUSH, Z_FINISH,
|
||||
);
|
||||
}
|
||||
|
||||
function decompressBrotli(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransform(
|
||||
(cb, onErr) => createBrotliHandle(BROTLI_DECODE, options, cb, onErr),
|
||||
BROTLI_OPERATION_PROCESS, BROTLI_OPERATION_FINISH,
|
||||
);
|
||||
}
|
||||
|
||||
function decompressZstd(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransform(
|
||||
(cb, onErr) => createZstdHandle(ZSTD_DECOMPRESS, options, cb, onErr),
|
||||
ZSTD_e_continue, ZSTD_e_end,
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sync compression factories
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function compressGzipSync(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransformSync(
|
||||
(cb, onErr) => createZlibHandle(GZIP, options, cb, onErr),
|
||||
Z_NO_FLUSH, Z_FINISH,
|
||||
);
|
||||
}
|
||||
|
||||
function compressDeflateSync(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransformSync(
|
||||
(cb, onErr) => createZlibHandle(DEFLATE, options, cb, onErr),
|
||||
Z_NO_FLUSH, Z_FINISH,
|
||||
);
|
||||
}
|
||||
|
||||
function compressBrotliSync(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransformSync(
|
||||
(cb, onErr) => createBrotliHandle(BROTLI_ENCODE, options, cb, onErr),
|
||||
BROTLI_OPERATION_PROCESS, BROTLI_OPERATION_FINISH,
|
||||
);
|
||||
}
|
||||
|
||||
function compressZstdSync(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransformSync(
|
||||
(cb, onErr) => createZstdHandle(ZSTD_COMPRESS, options, cb, onErr),
|
||||
ZSTD_e_continue, ZSTD_e_end,
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sync decompression factories
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function decompressGzipSync(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransformSync(
|
||||
(cb, onErr) => createZlibHandle(GUNZIP, options, cb, onErr),
|
||||
Z_NO_FLUSH, Z_FINISH,
|
||||
);
|
||||
}
|
||||
|
||||
function decompressDeflateSync(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransformSync(
|
||||
(cb, onErr) => createZlibHandle(INFLATE, options, cb, onErr),
|
||||
Z_NO_FLUSH, Z_FINISH,
|
||||
);
|
||||
}
|
||||
|
||||
function decompressBrotliSync(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransformSync(
|
||||
(cb, onErr) => createBrotliHandle(BROTLI_DECODE, options, cb, onErr),
|
||||
BROTLI_OPERATION_PROCESS, BROTLI_OPERATION_FINISH,
|
||||
);
|
||||
}
|
||||
|
||||
function decompressZstdSync(options = kNullPrototype) {
|
||||
validateObject(options, 'options');
|
||||
return makeZlibTransformSync(
|
||||
(cb, onErr) => createZstdHandle(ZSTD_DECOMPRESS, options, cb, onErr),
|
||||
ZSTD_e_continue, ZSTD_e_end,
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
compressBrotli,
|
||||
compressBrotliSync,
|
||||
compressDeflate,
|
||||
compressDeflateSync,
|
||||
compressGzip,
|
||||
compressGzipSync,
|
||||
compressZstd,
|
||||
compressZstdSync,
|
||||
decompressBrotli,
|
||||
decompressBrotliSync,
|
||||
decompressDeflate,
|
||||
decompressDeflateSync,
|
||||
decompressGzip,
|
||||
decompressGzipSync,
|
||||
decompressZstd,
|
||||
decompressZstdSync,
|
||||
};
|
||||
@@ -0,0 +1,66 @@
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
Symbol,
|
||||
SymbolFor,
|
||||
} = primordials;
|
||||
|
||||
/**
|
||||
* Symbol for sync value-to-streamable conversion protocol.
|
||||
* Objects implementing this can be written to streams or yielded
|
||||
* from generators. Works in both sync and async contexts.
|
||||
*
|
||||
* Third-party: [Symbol.for('Stream.toStreamable')]() { ... }
|
||||
*/
|
||||
const toStreamable = SymbolFor('Stream.toStreamable');
|
||||
|
||||
/**
|
||||
* Symbol for async value-to-streamable conversion protocol.
|
||||
* Objects implementing this can be written to async streams.
|
||||
* Works in async contexts only.
|
||||
*
|
||||
* Third-party: [Symbol.for('Stream.toAsyncStreamable')]() { ... }
|
||||
*/
|
||||
const toAsyncStreamable = SymbolFor('Stream.toAsyncStreamable');
|
||||
|
||||
/**
|
||||
* Symbol for Broadcastable protocol - object can provide a Broadcast.
|
||||
*/
|
||||
const broadcastProtocol = SymbolFor('Stream.broadcastProtocol');
|
||||
|
||||
/**
|
||||
* Symbol for Shareable protocol - object can provide a Share.
|
||||
*/
|
||||
const shareProtocol = SymbolFor('Stream.shareProtocol');
|
||||
|
||||
/**
|
||||
* Symbol for SyncShareable protocol - object can provide a SyncShare.
|
||||
*/
|
||||
const shareSyncProtocol = SymbolFor('Stream.shareSyncProtocol');
|
||||
|
||||
/**
|
||||
* Symbol for Drainable protocol - object can signal when backpressure
|
||||
* clears. Used to bridge event-driven sources that need drain notification.
|
||||
*/
|
||||
const drainableProtocol = SymbolFor('Stream.drainableProtocol');
|
||||
|
||||
/**
|
||||
* Internal sentinel for trusted stateful transforms. A transform object
|
||||
* with [kTrustedTransform] = true signals that:
|
||||
* 1. It handles source exhaustion (done) internally - no withFlushAsync
|
||||
* wrapper needed.
|
||||
* 2. It always yields valid Uint8Array[] batches - no isUint8ArrayBatch
|
||||
* validation needed on each yield.
|
||||
* This is NOT a public protocol symbol - it uses Symbol() not Symbol.for().
|
||||
*/
|
||||
const kTrustedTransform = Symbol('kTrustedTransform');
|
||||
|
||||
module.exports = {
|
||||
broadcastProtocol,
|
||||
drainableProtocol,
|
||||
kTrustedTransform,
|
||||
shareProtocol,
|
||||
shareSyncProtocol,
|
||||
toAsyncStreamable,
|
||||
toStreamable,
|
||||
};
|
||||
@@ -0,0 +1,291 @@
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
Array,
|
||||
ArrayBufferPrototypeGetByteLength,
|
||||
ArrayPrototypeSlice,
|
||||
MathMax,
|
||||
MathMin,
|
||||
NumberMAX_SAFE_INTEGER,
|
||||
PromiseResolve,
|
||||
String,
|
||||
TypedArrayPrototypeGetBuffer,
|
||||
TypedArrayPrototypeGetByteLength,
|
||||
TypedArrayPrototypeGetByteOffset,
|
||||
Uint8Array,
|
||||
} = primordials;
|
||||
|
||||
const { TextEncoder } = require('internal/encoding');
|
||||
const {
|
||||
codes: {
|
||||
ERR_INVALID_ARG_TYPE,
|
||||
ERR_OPERATION_FAILED,
|
||||
},
|
||||
} = require('internal/errors');
|
||||
const { isError } = require('internal/util');
|
||||
|
||||
const { Buffer } = require('buffer');
|
||||
|
||||
const { isSharedArrayBuffer, isUint8Array } = require('internal/util/types');
|
||||
|
||||
const { validateOneOf } = require('internal/validators');
|
||||
|
||||
// Cached resolved promise to avoid allocating a new one on every sync fast-path.
|
||||
const kResolvedPromise = PromiseResolve();
|
||||
|
||||
// Shared TextEncoder instance for string conversion.
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
// Default high water marks for push and multi-consumer streams. These values
|
||||
// are somewhat arbitrary but have been tested across various workloads and
|
||||
// appear to yield the best overall throughput/latency balance.
|
||||
|
||||
/** Default high water mark for push streams (single-consumer). */
|
||||
const kPushDefaultHWM = 4;
|
||||
|
||||
/** Default high water mark for broadcast and share streams (multi-consumer). */
|
||||
const kMultiConsumerDefaultHWM = 16;
|
||||
|
||||
/**
|
||||
* Clamp a high water mark to [1, MAX_SAFE_INTEGER].
|
||||
* @param {number} value
|
||||
* @returns {number}
|
||||
*/
|
||||
function clampHWM(value) {
|
||||
return MathMax(1, MathMin(NumberMAX_SAFE_INTEGER, value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a handler for an AbortSignal, handling the already-aborted case.
|
||||
* If the signal is already aborted, calls handler immediately.
|
||||
* Otherwise, adds a one-time 'abort' listener.
|
||||
* @param {AbortSignal} signal
|
||||
* @param {Function} handler
|
||||
*/
|
||||
function onSignalAbort(signal, handler) {
|
||||
if (signal.aborted) {
|
||||
handler();
|
||||
} else {
|
||||
signal.addEventListener('abort', handler, { __proto__: null, once: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the minimum cursor across a set of consumers.
|
||||
* Returns fallback if the set is empty.
|
||||
* @param {Set} consumers - Set of objects with a `cursor` property
|
||||
* @param {number} fallback - Value to return when set is empty
|
||||
* @returns {number}
|
||||
*/
|
||||
function getMinCursor(consumers, fallback) {
|
||||
let min = Infinity;
|
||||
for (const consumer of consumers) {
|
||||
if (consumer.cursor < min) {
|
||||
min = consumer.cursor;
|
||||
}
|
||||
}
|
||||
return min === Infinity ? fallback : min;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a chunk (string or Uint8Array) to Uint8Array.
|
||||
* Strings are UTF-8 encoded.
|
||||
* @param {Uint8Array|string} chunk
|
||||
* @returns {Uint8Array}
|
||||
*/
|
||||
function toUint8Array(chunk) {
|
||||
if (typeof chunk === 'string') {
|
||||
return encoder.encode(chunk);
|
||||
}
|
||||
if (!isUint8Array(chunk)) {
|
||||
throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Uint8Array'], chunk);
|
||||
}
|
||||
return chunk;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if all chunks in an array are already Uint8Array (no strings).
|
||||
* Short-circuits on the first string found.
|
||||
* @param {Array<Uint8Array|string>} chunks
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function allUint8Array(chunks) {
|
||||
// Ok, well, kind of. This is more a check for "no strings"...
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
if (typeof chunks[i] === 'string') return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Concatenate multiple Uint8Arrays into a single Uint8Array.
|
||||
* @param {Uint8Array[]} chunks
|
||||
* @returns {Uint8Array}
|
||||
*/
|
||||
function concatBytes(chunks) {
|
||||
// Empty stream: return zero-length Uint8Array
|
||||
if (chunks.length === 0) {
|
||||
return new Uint8Array(0);
|
||||
}
|
||||
// Single chunk: return directly if it covers the entire backing buffer
|
||||
if (chunks.length === 1) {
|
||||
const chunk = chunks[0];
|
||||
const buf = TypedArrayPrototypeGetBuffer(chunk);
|
||||
// SharedArrayBuffer is not available in primordials, so use
|
||||
// direct property access for its byteLength.
|
||||
const bufByteLength = isSharedArrayBuffer(buf) ?
|
||||
buf.byteLength :
|
||||
ArrayBufferPrototypeGetByteLength(buf);
|
||||
if (TypedArrayPrototypeGetByteOffset(chunk) === 0 &&
|
||||
TypedArrayPrototypeGetByteLength(chunk) === bufByteLength) {
|
||||
return chunk;
|
||||
}
|
||||
}
|
||||
// Multiple chunks or shared buffer: concatenate
|
||||
const buf = Buffer.concat(chunks);
|
||||
return new Uint8Array(
|
||||
TypedArrayPrototypeGetBuffer(buf),
|
||||
TypedArrayPrototypeGetByteOffset(buf),
|
||||
TypedArrayPrototypeGetByteLength(buf));
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an array of chunks (strings or Uint8Arrays) to a Uint8Array[].
|
||||
* Always returns a fresh copy of the array.
|
||||
* @param {Array<Uint8Array|string>} chunks
|
||||
* @returns {Uint8Array[]}
|
||||
*/
|
||||
function convertChunks(chunks) {
|
||||
if (allUint8Array(chunks)) {
|
||||
return ArrayPrototypeSlice(chunks);
|
||||
}
|
||||
const len = chunks.length;
|
||||
const result = new Array(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
result[i] = toUint8Array(chunks[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a caught value as an Error, converting non-Error values.
|
||||
* @param {unknown} error
|
||||
* @returns {Error}
|
||||
*/
|
||||
function wrapError(error) {
|
||||
return isError(error) ? error : new ERR_OPERATION_FAILED(String(error));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a value implements a Symbol-keyed protocol (has a function
|
||||
* at the given symbol key).
|
||||
* @param {unknown} value
|
||||
* @param {symbol} symbol
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function hasProtocol(value, symbol) {
|
||||
return (
|
||||
value !== null &&
|
||||
typeof value === 'object' &&
|
||||
symbol in value &&
|
||||
typeof value[symbol] === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a value is PullOptions (object without transform or write property).
|
||||
* @param {unknown} value
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isPullOptions(value) {
|
||||
return (
|
||||
value !== null &&
|
||||
typeof value === 'object' &&
|
||||
!('transform' in value) &&
|
||||
!('write' in value)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a value is a stateful transform object (has a transform method).
|
||||
* @param {unknown} value
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isTransformObject(value) {
|
||||
return typeof value?.transform === 'function';
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a value is a valid transform (function or transform object).
|
||||
* @param {unknown} value
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isTransform(value) {
|
||||
return typeof value === 'function' || isTransformObject(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse variadic arguments for pull/pullSync.
|
||||
* Returns { transforms, options }
|
||||
* @param {Array} args
|
||||
* @returns {{ transforms: Array, options: object|undefined }}
|
||||
*/
|
||||
function parsePullArgs(args) {
|
||||
if (args.length === 0) {
|
||||
return { __proto__: null, transforms: [], options: undefined };
|
||||
}
|
||||
|
||||
let transforms;
|
||||
let options;
|
||||
const last = args[args.length - 1];
|
||||
if (isPullOptions(last)) {
|
||||
transforms = ArrayPrototypeSlice(args, 0, -1);
|
||||
options = last;
|
||||
} else {
|
||||
transforms = args;
|
||||
options = undefined;
|
||||
}
|
||||
|
||||
for (let i = 0; i < transforms.length; i++) {
|
||||
if (!isTransform(transforms[i])) {
|
||||
throw new ERR_INVALID_ARG_TYPE(
|
||||
`transforms[${i}]`, ['Function', 'Object with transform()'],
|
||||
transforms[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return { __proto__: null, transforms, options };
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate backpressure option value.
|
||||
* @param {string} value
|
||||
*/
|
||||
function validateBackpressure(value) {
|
||||
validateOneOf(value, 'options.backpressure', [
|
||||
'strict',
|
||||
'block',
|
||||
'drop-oldest',
|
||||
'drop-newest',
|
||||
]);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
kMultiConsumerDefaultHWM,
|
||||
kPushDefaultHWM,
|
||||
kResolvedPromise,
|
||||
allUint8Array,
|
||||
clampHWM,
|
||||
concatBytes,
|
||||
convertChunks,
|
||||
getMinCursor,
|
||||
hasProtocol,
|
||||
isPullOptions,
|
||||
isTransform,
|
||||
isTransformObject,
|
||||
onSignalAbort,
|
||||
parsePullArgs,
|
||||
toUint8Array,
|
||||
validateBackpressure,
|
||||
wrapError,
|
||||
};
|
||||
@@ -0,0 +1,180 @@
|
||||
'use strict';
|
||||
|
||||
// Public entry point for the iterable streams API.
|
||||
// Usage: require('stream/iter') or require('node:stream/iter')
|
||||
// Requires: --experimental-stream-iter
|
||||
|
||||
const {
|
||||
ObjectFreeze,
|
||||
} = primordials;
|
||||
|
||||
const { emitExperimentalWarning } = require('internal/util');
|
||||
emitExperimentalWarning('stream/iter');
|
||||
|
||||
// Protocol symbols
|
||||
const {
|
||||
toStreamable,
|
||||
toAsyncStreamable,
|
||||
broadcastProtocol,
|
||||
shareProtocol,
|
||||
shareSyncProtocol,
|
||||
drainableProtocol,
|
||||
} = require('internal/streams/iter/types');
|
||||
|
||||
// Factories
|
||||
const { push } = require('internal/streams/iter/push');
|
||||
const { duplex } = require('internal/streams/iter/duplex');
|
||||
const { from, fromSync } = require('internal/streams/iter/from');
|
||||
|
||||
// Pipelines
|
||||
const {
|
||||
pull,
|
||||
pullSync,
|
||||
pipeTo,
|
||||
pipeToSync,
|
||||
} = require('internal/streams/iter/pull');
|
||||
|
||||
// Consumers
|
||||
const {
|
||||
bytes,
|
||||
bytesSync,
|
||||
text,
|
||||
textSync,
|
||||
arrayBuffer,
|
||||
arrayBufferSync,
|
||||
array,
|
||||
arraySync,
|
||||
tap,
|
||||
tapSync,
|
||||
merge,
|
||||
ondrain,
|
||||
} = require('internal/streams/iter/consumers');
|
||||
|
||||
// Multi-consumer
|
||||
const { broadcast, Broadcast } = require('internal/streams/iter/broadcast');
|
||||
const {
|
||||
share,
|
||||
shareSync,
|
||||
Share,
|
||||
SyncShare,
|
||||
} = require('internal/streams/iter/share');
|
||||
|
||||
/**
|
||||
* Stream namespace - unified access to all stream functions.
|
||||
* @example
|
||||
* const { Stream } = require('stream/iter');
|
||||
*
|
||||
* const { writer, readable } = Stream.push();
|
||||
* await writer.write("hello");
|
||||
* await writer.end();
|
||||
*
|
||||
* const output = Stream.pull(readable, transform1, transform2);
|
||||
* const data = await Stream.bytes(output);
|
||||
*/
|
||||
const Stream = ObjectFreeze({
|
||||
// Factories
|
||||
push,
|
||||
duplex,
|
||||
from,
|
||||
fromSync,
|
||||
|
||||
// Pipelines
|
||||
pull,
|
||||
pullSync,
|
||||
|
||||
// Pipe to destination
|
||||
pipeTo,
|
||||
pipeToSync,
|
||||
|
||||
// Consumers (async)
|
||||
bytes,
|
||||
text,
|
||||
arrayBuffer,
|
||||
array,
|
||||
|
||||
// Consumers (sync)
|
||||
bytesSync,
|
||||
textSync,
|
||||
arrayBufferSync,
|
||||
arraySync,
|
||||
|
||||
// Combining
|
||||
merge,
|
||||
|
||||
// Multi-consumer (push model)
|
||||
broadcast,
|
||||
|
||||
// Multi-consumer (pull model)
|
||||
share,
|
||||
shareSync,
|
||||
|
||||
// Utilities
|
||||
tap,
|
||||
tapSync,
|
||||
|
||||
// Drain utility for event source integration
|
||||
ondrain,
|
||||
|
||||
// Protocol symbols
|
||||
toStreamable,
|
||||
toAsyncStreamable,
|
||||
broadcastProtocol,
|
||||
shareProtocol,
|
||||
shareSyncProtocol,
|
||||
drainableProtocol,
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
// The Stream namespace
|
||||
Stream,
|
||||
|
||||
// Also export everything individually for destructured imports
|
||||
|
||||
// Protocol symbols
|
||||
toStreamable,
|
||||
toAsyncStreamable,
|
||||
broadcastProtocol,
|
||||
shareProtocol,
|
||||
shareSyncProtocol,
|
||||
drainableProtocol,
|
||||
|
||||
// Factories
|
||||
push,
|
||||
duplex,
|
||||
from,
|
||||
fromSync,
|
||||
|
||||
// Pipelines
|
||||
pull,
|
||||
pullSync,
|
||||
pipeTo,
|
||||
pipeToSync,
|
||||
|
||||
// Consumers (async)
|
||||
bytes,
|
||||
text,
|
||||
arrayBuffer,
|
||||
array,
|
||||
|
||||
// Consumers (sync)
|
||||
bytesSync,
|
||||
textSync,
|
||||
arrayBufferSync,
|
||||
arraySync,
|
||||
|
||||
// Combining
|
||||
merge,
|
||||
|
||||
// Multi-consumer
|
||||
broadcast,
|
||||
Broadcast,
|
||||
share,
|
||||
shareSync,
|
||||
Share,
|
||||
SyncShare,
|
||||
|
||||
// Utilities
|
||||
tap,
|
||||
tapSync,
|
||||
ondrain,
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
// Public entry point for the iterable compression/decompression API.
|
||||
// Usage: require('zlib/iter') or require('node:zlib/iter')
|
||||
// Requires: --experimental-stream-iter
|
||||
|
||||
const { emitExperimentalWarning } = require('internal/util');
|
||||
emitExperimentalWarning('zlib/iter');
|
||||
|
||||
const {
|
||||
compressGzip,
|
||||
compressGzipSync,
|
||||
compressDeflate,
|
||||
compressDeflateSync,
|
||||
compressBrotli,
|
||||
compressBrotliSync,
|
||||
compressZstd,
|
||||
compressZstdSync,
|
||||
decompressGzip,
|
||||
decompressGzipSync,
|
||||
decompressDeflate,
|
||||
decompressDeflateSync,
|
||||
decompressBrotli,
|
||||
decompressBrotliSync,
|
||||
decompressZstd,
|
||||
decompressZstdSync,
|
||||
} = require('internal/streams/iter/transform');
|
||||
|
||||
module.exports = {
|
||||
// Compression transforms (async)
|
||||
compressGzip,
|
||||
compressDeflate,
|
||||
compressBrotli,
|
||||
compressZstd,
|
||||
|
||||
// Compression transforms (sync)
|
||||
compressGzipSync,
|
||||
compressDeflateSync,
|
||||
compressBrotliSync,
|
||||
compressZstdSync,
|
||||
|
||||
// Decompression transforms (async)
|
||||
decompressGzip,
|
||||
decompressDeflate,
|
||||
decompressBrotli,
|
||||
decompressZstd,
|
||||
|
||||
// Decompression transforms (sync)
|
||||
decompressGzipSync,
|
||||
decompressDeflateSync,
|
||||
decompressBrotliSync,
|
||||
decompressZstdSync,
|
||||
};
|
||||
@@ -134,15 +134,17 @@ BuiltinLoader::BuiltinCategories BuiltinLoader::GetBuiltinCategories() const {
|
||||
"internal/tls/wrap", "internal/tls/secure-context",
|
||||
"internal/http2/core", "internal/http2/compat",
|
||||
"internal/streams/lazy_transform",
|
||||
#endif // !HAVE_OPENSSL
|
||||
#endif // !HAVE_OPENSSL
|
||||
#ifndef OPENSSL_NO_QUIC
|
||||
"internal/quic/quic", "internal/quic/symbols", "internal/quic/stats",
|
||||
"internal/quic/state",
|
||||
#endif // !OPENSSL_NO_QUIC
|
||||
"quic", // Experimental.
|
||||
"sqlite", // Experimental.
|
||||
"sys", // Deprecated.
|
||||
"wasi", // Experimental.
|
||||
#endif // !OPENSSL_NO_QUIC
|
||||
"quic", // Experimental.
|
||||
"sqlite", // Experimental.
|
||||
"stream/iter", // Experimental.
|
||||
"zlib/iter", // Experimental.
|
||||
"sys", // Deprecated.
|
||||
"wasi", // Experimental.
|
||||
#if !HAVE_SQLITE
|
||||
"internal/webstorage", // Experimental.
|
||||
#endif
|
||||
|
||||
+471
-263
File diff suppressed because it is too large.
Load diff
+21
-11
@@ -80,8 +80,7 @@ class BindingData : public SnapshotableObject {
|
||||
AliasedFloat64Array statfs_field_array;
|
||||
AliasedBigInt64Array statfs_field_bigint_array;
|
||||
|
||||
std::vector<BaseObjectPtr<FileHandleReadWrap>>
|
||||
file_handle_read_wrap_freelist;
|
||||
std::vector<BaseObjectPtr<FileHandleReadWrap>> file_handle_read_wrap_freelist;
|
||||
|
||||
SERIALIZABLE_OBJECT_METHODS()
|
||||
SET_BINDING_ID(fs_binding_data)
|
||||
@@ -146,7 +145,8 @@ class FSReqBase : public ReqWrap<uv_fs_t> {
|
||||
const char* data,
|
||||
size_t len,
|
||||
enum encoding encoding);
|
||||
inline FSReqBuffer& Init(const char* syscall, size_t len,
|
||||
inline FSReqBuffer& Init(const char* syscall,
|
||||
size_t len,
|
||||
enum encoding encoding);
|
||||
|
||||
virtual void Reject(v8::Local<v8::Value> reject) = 0;
|
||||
@@ -240,8 +240,7 @@ inline v8::Local<v8::Value> FillGlobalStatFsArray(BindingData* binding_data,
|
||||
template <typename AliasedBufferT>
|
||||
class FSReqPromise final : public FSReqBase {
|
||||
public:
|
||||
static inline FSReqPromise* New(BindingData* binding_data,
|
||||
bool use_bigint);
|
||||
static inline FSReqPromise* New(BindingData* binding_data, bool use_bigint);
|
||||
inline ~FSReqPromise() override;
|
||||
|
||||
inline void Reject(v8::Local<v8::Value> reject) override;
|
||||
@@ -345,6 +344,9 @@ class FileHandle final : public AsyncWrap, public StreamBase {
|
||||
// be resolved once closing is complete.
|
||||
static void Close(const v8::FunctionCallbackInfo<v8::Value>& args);
|
||||
|
||||
// Synchronously closes the FD. Throws on error.
|
||||
static void CloseSync(const v8::FunctionCallbackInfo<v8::Value>& args);
|
||||
|
||||
// Releases ownership of the FD.
|
||||
static void ReleaseFD(const v8::FunctionCallbackInfo<v8::Value>& args);
|
||||
|
||||
@@ -499,19 +501,27 @@ inline FSReqBase* GetReqWrap(const v8::FunctionCallbackInfo<v8::Value>& args,
|
||||
|
||||
// Returns nullptr if the operation fails from the start.
|
||||
template <typename Func, typename... Args>
|
||||
inline FSReqBase* AsyncDestCall(Environment* env, FSReqBase* req_wrap,
|
||||
inline FSReqBase* AsyncDestCall(Environment* env,
|
||||
FSReqBase* req_wrap,
|
||||
const v8::FunctionCallbackInfo<v8::Value>& args,
|
||||
const char* syscall, const char* dest,
|
||||
size_t len, enum encoding enc, uv_fs_cb after,
|
||||
Func fn, Args... fn_args);
|
||||
const char* syscall,
|
||||
const char* dest,
|
||||
size_t len,
|
||||
enum encoding enc,
|
||||
uv_fs_cb after,
|
||||
Func fn,
|
||||
Args... fn_args);
|
||||
|
||||
// Returns nullptr if the operation fails from the start.
|
||||
template <typename Func, typename... Args>
|
||||
inline FSReqBase* AsyncCall(Environment* env,
|
||||
FSReqBase* req_wrap,
|
||||
const v8::FunctionCallbackInfo<v8::Value>& args,
|
||||
const char* syscall, enum encoding enc,
|
||||
uv_fs_cb after, Func fn, Args... fn_args);
|
||||
const char* syscall,
|
||||
enum encoding enc,
|
||||
uv_fs_cb after,
|
||||
Func fn,
|
||||
Args... fn_args);
|
||||
|
||||
// Template counterpart of SYNC_CALL, except that it only puts
|
||||
// the error number and the syscall in the context instead of
|
||||
|
||||
@@ -599,6 +599,10 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() {
|
||||
&EnvironmentOptions::experimental_sqlite,
|
||||
kAllowedInEnvvar,
|
||||
true);
|
||||
AddOption("--experimental-stream-iter",
|
||||
"experimental iterable streams API (node:stream/iter)",
|
||||
&EnvironmentOptions::experimental_stream_iter,
|
||||
kAllowedInEnvvar);
|
||||
AddOption("--experimental-quic",
|
||||
#ifndef OPENSSL_NO_QUIC
|
||||
"experimental QUIC support",
|
||||
|
||||
+16
-18
@@ -127,10 +127,9 @@ class EnvironmentOptions : public Options {
|
||||
bool experimental_fetch = true;
|
||||
bool experimental_websocket = true;
|
||||
bool experimental_sqlite = true;
|
||||
bool experimental_stream_iter = false;
|
||||
bool webstorage = HAVE_SQLITE;
|
||||
#ifndef OPENSSL_NO_QUIC
|
||||
bool experimental_quic = false;
|
||||
#endif
|
||||
std::string localstorage_file;
|
||||
bool experimental_global_navigator = true;
|
||||
bool experimental_global_web_crypto = true;
|
||||
@@ -286,7 +285,7 @@ class PerIsolateOptions : public Options {
|
||||
PerIsolateOptions() = default;
|
||||
PerIsolateOptions(PerIsolateOptions&&) = default;
|
||||
|
||||
std::shared_ptr<EnvironmentOptions> per_env { new EnvironmentOptions() };
|
||||
std::shared_ptr<EnvironmentOptions> per_env{new EnvironmentOptions()};
|
||||
bool track_heap_objects = false;
|
||||
bool report_uncaught_exception = false;
|
||||
bool report_on_signal = false;
|
||||
@@ -319,7 +318,7 @@ class PerProcessOptions : public Options {
|
||||
// using the node::per_process::cli_options_mutex, typically:
|
||||
//
|
||||
// Mutex::ScopedLock lock(node::per_process::cli_options_mutex);
|
||||
std::shared_ptr<PerIsolateOptions> per_isolate { new PerIsolateOptions() };
|
||||
std::shared_ptr<PerIsolateOptions> per_isolate{new PerIsolateOptions()};
|
||||
|
||||
std::string title;
|
||||
std::string trace_event_categories;
|
||||
@@ -529,8 +528,7 @@ class OptionsParser {
|
||||
// if the option has a non-option argument (not starting with -) following it.
|
||||
void AddAlias(const char* from, const char* to);
|
||||
void AddAlias(const char* from, const std::vector<std::string>& to);
|
||||
void AddAlias(const char* from,
|
||||
const std::initializer_list<std::string>& to);
|
||||
void AddAlias(const char* from, const std::initializer_list<std::string>& to);
|
||||
|
||||
// Add implications from some arbitrary option to a boolean one, either
|
||||
// in a way that makes `from` set `to` to true or to false.
|
||||
@@ -542,7 +540,7 @@ class OptionsParser {
|
||||
// type.
|
||||
template <typename ChildOptions>
|
||||
void Insert(const OptionsParser<ChildOptions>& child_options_parser,
|
||||
ChildOptions* (Options::* get_child)());
|
||||
ChildOptions* (Options::*get_child)());
|
||||
|
||||
// Parse a sequence of options into an options struct, a list of
|
||||
// arguments that were parsed as options, a list of unknown/JS engine options,
|
||||
@@ -631,17 +629,15 @@ class OptionsParser {
|
||||
// These are helpers that make `Insert()` support properties of other
|
||||
// options structs, if we know how to access them.
|
||||
template <typename OriginalField, typename ChildOptions>
|
||||
static auto Convert(
|
||||
std::shared_ptr<OriginalField> original,
|
||||
ChildOptions* (Options::* get_child)());
|
||||
static auto Convert(std::shared_ptr<OriginalField> original,
|
||||
ChildOptions* (Options::*get_child)());
|
||||
template <typename ChildOptions>
|
||||
static auto Convert(
|
||||
typename OptionsParser<ChildOptions>::OptionInfo original,
|
||||
ChildOptions* (Options::* get_child)());
|
||||
static auto Convert(typename OptionsParser<ChildOptions>::OptionInfo original,
|
||||
ChildOptions* (Options::*get_child)());
|
||||
template <typename ChildOptions>
|
||||
static auto Convert(
|
||||
typename OptionsParser<ChildOptions>::Implication original,
|
||||
ChildOptions* (Options::* get_child)());
|
||||
ChildOptions* (Options::*get_child)());
|
||||
|
||||
std::unordered_map<std::string, OptionInfo> options_;
|
||||
std::unordered_map<std::string, std::vector<std::string>> aliases_;
|
||||
@@ -668,10 +664,12 @@ class OptionsParser {
|
||||
|
||||
using StringVector = std::vector<std::string>;
|
||||
template <class OptionsType, class = Options>
|
||||
void Parse(
|
||||
StringVector* const args, StringVector* const exec_args,
|
||||
StringVector* const v8_args, OptionsType* const options,
|
||||
OptionEnvvarSettings required_env_settings, StringVector* const errors);
|
||||
void Parse(StringVector* const args,
|
||||
StringVector* const exec_args,
|
||||
StringVector* const v8_args,
|
||||
OptionsType* const options,
|
||||
OptionEnvvarSettings required_env_settings,
|
||||
StringVector* const errors);
|
||||
|
||||
} // namespace options_parser
|
||||
|
||||
|
||||
Reference in new issue
Block a user