mirror of
https://github.com/nodejs/node.git
synced 2026-11-24 21:50:36 -05:00
stream, quic: update iterable streams backpressure
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode/Opus PR-URL: https://github.com/nodejs/node/pull/64464 Reviewed-By: Tim Perry <pimterry@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com> Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>
This commit is contained in:
1 parent
193091f1ba
commit
125c19da43
28 files changed
+292
-280
No files matched your search
@@ -5,7 +5,7 @@ const common = require('../common.js');
|
||||
const bench = common.createBenchmark(main, {
|
||||
consumers: [2, 8, 32],
|
||||
batches: [1e4],
|
||||
backpressure: ['block'],
|
||||
backpressure: ['unbounded'],
|
||||
n: [5],
|
||||
}, {
|
||||
flags: ['--experimental-stream-iter'],
|
||||
@@ -24,7 +24,7 @@ async function main({ consumers, batches, backpressure, n }) {
|
||||
|
||||
bench.start();
|
||||
for (let i = 0; i < n; i++) {
|
||||
const shared = share(source(), { highWaterMark: 64, backpressure });
|
||||
const shared = share(source(), { budget: 65536, backpressure });
|
||||
const readers = Array.from({ length: consumers }, () => array(shared.pull()));
|
||||
await Promise.all(readers);
|
||||
}
|
||||
|
||||
+5
-4
@@ -1276,7 +1276,7 @@ added: v23.8.0
|
||||
interleaved with data from other streams of the same priority level.
|
||||
When `false`, the stream should be completed before same-priority peers.
|
||||
**Default:** `false`.
|
||||
* `highWaterMark` {number} The maximum number of bytes that the writer
|
||||
* `budget` {number} The maximum number of bytes that the writer
|
||||
will buffer before `writeSync()` returns `false`. When the buffered
|
||||
data exceeds this limit, the caller should wait for drain before
|
||||
writing more. **Default:** `65536` (64 KB).
|
||||
@@ -1317,7 +1317,7 @@ added: v23.8.0
|
||||
interleaved with data from other streams of the same priority level.
|
||||
When `false`, the stream should be completed before same-priority peers.
|
||||
**Default:** `false`.
|
||||
* `highWaterMark` {number} The maximum number of bytes that the writer
|
||||
* `budget` {number} The maximum number of bytes that the writer
|
||||
will buffer before `writeSync()` returns `false`. When the buffered
|
||||
data exceeds this limit, the caller should wait for drain before
|
||||
writing more. **Default:** `65536` (64 KB).
|
||||
@@ -1924,7 +1924,7 @@ added: v23.8.0
|
||||
The directionality of the stream, or `null` if the stream has been destroyed
|
||||
or is still pending. Read only.
|
||||
|
||||
### `stream.highWaterMark`
|
||||
### `stream.budget`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
@@ -2236,7 +2236,8 @@ The Writer has the following methods:
|
||||
the QUIC transport-layer `INTERNAL_ERROR` (`0x1`) for raw QUIC).
|
||||
See [`stream.destroy()`][] for a full-stream abort that also resets
|
||||
the readable side via `STOP_SENDING`.
|
||||
* `desiredSize` — Available capacity in bytes, or `null` if closed/errored.
|
||||
* `canWrite` — `true` if writes will be accepted, `false` if at capacity,
|
||||
or `null` if closed/errored.
|
||||
|
||||
The bytes from each `writeSync()` / `writevSync()` / `write()` / `writev()`
|
||||
input chunk are copied into an internal buffer, so the caller's source
|
||||
|
||||
@@ -223,7 +223,7 @@ How each policy uses these buffers:
|
||||
|
||||
| Policy | Buffer limit | Pending writes limit |
|
||||
| --------------- | ------------ | -------------------- |
|
||||
| `'strict'` | `budget` | `budget` |
|
||||
| `'strict'` | `budget` | 1 |
|
||||
| `'unbounded'` | `budget` | Unbounded |
|
||||
| `'drop-oldest'` | `budget` | N/A (never waits) |
|
||||
| `'drop-newest'` | `budget` | N/A (never waits) |
|
||||
@@ -232,8 +232,8 @@ How each policy uses these buffers:
|
||||
|
||||
Strict mode catches "fire-and-forget" patterns where the producer calls
|
||||
`write()` without awaiting, which would cause unbounded memory growth.
|
||||
It limits both the buffer and the pending writes queue to
|
||||
`budget` bytes.
|
||||
It limits the buffer to `budget` bytes and the pending writes queue
|
||||
to a single entry.
|
||||
|
||||
If you properly await each write, you can only ever have one pending
|
||||
write at a time (yours), so you never hit the pending writes limit.
|
||||
|
||||
+25
-25
@@ -297,8 +297,8 @@ const endpointRegistry = new SafeSet();
|
||||
* (e.g. HTTP/3).
|
||||
* @property {'high'|'default'|'low'} [priority] The priority level of the stream.
|
||||
* @property {boolean} [incremental] Whether to interleave data with same-priority streams.
|
||||
* @property {number} [highWaterMark] The high water mark for write
|
||||
* backpressure, in bytes. **Default:** `65536`.
|
||||
* @property {number} [budget] The byte budget for write backpressure.
|
||||
* **Default:** `65536`.
|
||||
* @property {OnHeadersCallback} [onheaders] Callback for incoming initial headers
|
||||
* @property {OnTrailersCallback} [ontrailers] Callback for incoming trailing headers
|
||||
* @property {OnInfoCallback} [oninfo] Callback for informational (1xx) headers
|
||||
@@ -1325,7 +1325,7 @@ function applyCallbacks(session, cbs) {
|
||||
* @param {QuicStream} stream The JS stream object
|
||||
* @param {any} body The body source
|
||||
*/
|
||||
const kDefaultHighWaterMark = 65536;
|
||||
const kDefaultBudget = 65536;
|
||||
const kDefaultMaxPendingDatagrams = 128;
|
||||
|
||||
function configureOutbound(handle, stream, body) {
|
||||
@@ -1405,7 +1405,7 @@ function configureOutbound(handle, stream, body) {
|
||||
);
|
||||
}
|
||||
|
||||
// Sets the high water mark and initial writeDesiredSize for a streaming
|
||||
// Sets the budget and initial writeDesiredSize for a streaming
|
||||
// outbound source. Called after handle.initStreamingSource() for both
|
||||
// body-source and writer paths. One-shot body sources (string, Uint8Array,
|
||||
// Blob, FileHandle, etc.) do not use this -- they go through attachSource
|
||||
@@ -1413,12 +1413,12 @@ function configureOutbound(handle, stream, body) {
|
||||
function initStreamingBackpressure(stream) {
|
||||
const state = getQuicStreamState(stream);
|
||||
// Only set defaults if the user hasn't already configured them
|
||||
// (e.g., via createBidirectionalStream({ highWaterMark: N })).
|
||||
if (state.highWaterMark === 0) {
|
||||
state.highWaterMark = kDefaultHighWaterMark;
|
||||
// (e.g., via createBidirectionalStream({ budget: N })).
|
||||
if (state.budget === 0) {
|
||||
state.budget = kDefaultBudget;
|
||||
}
|
||||
if (state.writeDesiredSize === 0) {
|
||||
state.writeDesiredSize = state.highWaterMark;
|
||||
state.writeDesiredSize = state.budget;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1699,23 +1699,23 @@ class QuicStream {
|
||||
}
|
||||
|
||||
/**
|
||||
* The high water mark for write backpressure. When the total queued
|
||||
* The byte budget for write backpressure. When the total queued
|
||||
* outbound bytes exceeds this value, writeSync returns false and
|
||||
* desiredSize drops to 0. Default is 65536 (64KB).
|
||||
* canWrite returns false. Default is 65536 (64KB).
|
||||
* @type {number}
|
||||
*/
|
||||
get highWaterMark() {
|
||||
get budget() {
|
||||
assertIsQuicStream(this);
|
||||
return this.#inner.state.highWaterMark;
|
||||
return this.#inner.state.budget;
|
||||
}
|
||||
|
||||
set highWaterMark(val) {
|
||||
set budget(val) {
|
||||
assertIsQuicStream(this);
|
||||
validateInteger(val, 'highWaterMark', 0, 0xFFFFFFFF);
|
||||
validateInteger(val, 'budget', 0, 0xFFFFFFFF);
|
||||
const inner = this.#inner;
|
||||
inner.state.highWaterMark = val;
|
||||
inner.state.budget = val;
|
||||
// If writeDesiredSize hasn't been set yet (still 0 from initialization),
|
||||
// initialize it to the highWaterMark so the first write can proceed.
|
||||
// initialize it to the budget so the first write can proceed.
|
||||
if (inner.state.writeDesiredSize === 0 && val > 0) {
|
||||
inner.state.writeDesiredSize = val;
|
||||
}
|
||||
@@ -2163,8 +2163,8 @@ class QuicStream {
|
||||
// will accept the data into the DataQueue and
|
||||
// UpdateWriteDesiredSize() will drop writeDesiredSize toward 0,
|
||||
// at which point the standard drain mechanism takes over.
|
||||
// This follows the Web Streams model where writes beyond the HWM
|
||||
// succeed and backpressure applies to *subsequent* writes.
|
||||
// This follows the iter-streams model where writes beyond the
|
||||
// budget succeed and backpressure applies to *subsequent* writes.
|
||||
if (stream.#inner.state.writeDesiredSize === 0) return false;
|
||||
const result = handle.write([chunk]);
|
||||
if (result === undefined) return false;
|
||||
@@ -2323,9 +2323,9 @@ class QuicStream {
|
||||
|
||||
const writer = {
|
||||
__proto__: null,
|
||||
get desiredSize() {
|
||||
get canWrite() {
|
||||
if (closed || errored || stream.#inner.state.writeEnded) return null;
|
||||
return stream.#inner.state.writeDesiredSize;
|
||||
return stream.#inner.state.writeDesiredSize > 0;
|
||||
},
|
||||
writeSync,
|
||||
write,
|
||||
@@ -3254,7 +3254,7 @@ class QuicSession {
|
||||
body,
|
||||
priority = 'default',
|
||||
incremental = false,
|
||||
highWaterMark = kDefaultHighWaterMark,
|
||||
budget = kDefaultBudget,
|
||||
headers,
|
||||
onheaders,
|
||||
ontrailers,
|
||||
@@ -3290,8 +3290,8 @@ class QuicSession {
|
||||
stream[kAttachFileHandle](body);
|
||||
}
|
||||
|
||||
// Set the high water mark for backpressure.
|
||||
stream.highWaterMark = highWaterMark;
|
||||
// Set the byte budget for backpressure.
|
||||
stream.budget = budget;
|
||||
|
||||
// Set stream callbacks before sending headers to avoid missing events.
|
||||
if (onheaders) stream.onheaders = onheaders;
|
||||
@@ -4047,8 +4047,8 @@ class QuicSession {
|
||||
const stream = new QuicStream(kPrivateConstructor, handle, this, direction,
|
||||
false /* isLocal */);
|
||||
|
||||
// Set the default high water mark for received streams.
|
||||
stream.highWaterMark = kDefaultHighWaterMark;
|
||||
// Set the default byte budget for received streams.
|
||||
stream.budget = kDefaultBudget;
|
||||
|
||||
// A new stream was received. If we don't have an onstream callback, then
|
||||
// there's nothing we can do about it. Destroy the stream in this case.
|
||||
|
||||
@@ -104,7 +104,7 @@ const {
|
||||
IDX_STATE_STREAM_WANTS_TRAILERS,
|
||||
IDX_STATE_STREAM_RECEIVED_EARLY_DATA,
|
||||
IDX_STATE_STREAM_WRITE_DESIRED_SIZE,
|
||||
IDX_STATE_STREAM_HIGH_WATER_MARK,
|
||||
IDX_STATE_STREAM_BUDGET,
|
||||
IDX_STATE_STREAM_RESET_CODE,
|
||||
} = internalBinding('quic');
|
||||
|
||||
@@ -871,18 +871,18 @@ class QuicStreamState {
|
||||
}
|
||||
|
||||
/** @type {number} */
|
||||
get highWaterMark() {
|
||||
get budget() {
|
||||
const handle = this.#handle;
|
||||
if (handle === undefined) return undefined;
|
||||
return DataViewPrototypeGetUint32(
|
||||
handle, this.#offset + IDX_STATE_STREAM_HIGH_WATER_MARK, kIsLittleEndian);
|
||||
handle, this.#offset + IDX_STATE_STREAM_BUDGET, kIsLittleEndian);
|
||||
}
|
||||
|
||||
set highWaterMark(val) {
|
||||
set budget(val) {
|
||||
const handle = this.#handle;
|
||||
if (handle === undefined) return;
|
||||
DataViewPrototypeSetUint32(
|
||||
handle, this.#offset + IDX_STATE_STREAM_HIGH_WATER_MARK, val, kIsLittleEndian);
|
||||
handle, this.#offset + IDX_STATE_STREAM_BUDGET, val, kIsLittleEndian);
|
||||
}
|
||||
|
||||
toString() {
|
||||
@@ -908,7 +908,7 @@ class QuicStreamState {
|
||||
early,
|
||||
resetCode,
|
||||
writeDesiredSize,
|
||||
highWaterMark,
|
||||
budget,
|
||||
} = this;
|
||||
return {
|
||||
__proto__: null,
|
||||
@@ -928,7 +928,7 @@ class QuicStreamState {
|
||||
early,
|
||||
resetCode,
|
||||
writeDesiredSize,
|
||||
highWaterMark,
|
||||
budget,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -965,7 +965,7 @@ class QuicStreamState {
|
||||
early,
|
||||
resetCode,
|
||||
writeDesiredSize,
|
||||
highWaterMark,
|
||||
budget,
|
||||
} = this;
|
||||
|
||||
return `QuicStreamState ${inspect({
|
||||
@@ -985,7 +985,7 @@ class QuicStreamState {
|
||||
early,
|
||||
resetCode,
|
||||
writeDesiredSize,
|
||||
highWaterMark,
|
||||
budget,
|
||||
}, opts)}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -55,7 +55,6 @@ const {
|
||||
const {
|
||||
kMultiConsumerDefaultBudget,
|
||||
kResolvedPromise,
|
||||
clampBudget,
|
||||
convertChunks,
|
||||
getWriterSignal,
|
||||
getMinCursor,
|
||||
@@ -779,7 +778,7 @@ function broadcast(options = { __proto__: null }) {
|
||||
|
||||
const opts = {
|
||||
__proto__: null,
|
||||
budget: clampBudget(budget),
|
||||
budget,
|
||||
backpressure,
|
||||
signal,
|
||||
};
|
||||
|
||||
@@ -37,7 +37,6 @@ const {
|
||||
const {
|
||||
kPushDefaultBudget,
|
||||
kResolvedPromise,
|
||||
clampBudget,
|
||||
onSignalAbort,
|
||||
toUint8Array,
|
||||
convertChunks,
|
||||
@@ -99,7 +98,7 @@ class PushQueue {
|
||||
if (signal !== undefined) {
|
||||
validateAbortSignal(signal, 'options.signal');
|
||||
}
|
||||
this.#budget = clampBudget(budget);
|
||||
this.#budget = budget;
|
||||
this.#backpressure = backpressure;
|
||||
this.#signal = signal;
|
||||
this.#abortHandler = undefined;
|
||||
@@ -127,7 +126,12 @@ class PushQueue {
|
||||
if (this.#writerState !== 'open' || this.#consumerState !== 'active') {
|
||||
return null;
|
||||
}
|
||||
return this.#bufferedBytes < this.#budget;
|
||||
if ((this.#backpressure === 'strict' ||
|
||||
this.#backpressure === 'unbounded') &&
|
||||
this.#bufferedBytes >= this.#budget) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -156,6 +160,10 @@ class PushQueue {
|
||||
|
||||
const batchSize = this.#batchByteSize(chunks);
|
||||
|
||||
// Skip empty chunks -- zero-byte writes would accumulate infinitely
|
||||
// without ever triggering backpressure under a byte-budget model.
|
||||
if (batchSize === 0) return true;
|
||||
|
||||
if (this.#bufferedBytes >= this.#budget) {
|
||||
switch (this.#backpressure) {
|
||||
case 'strict':
|
||||
@@ -181,6 +189,11 @@ class PushQueue {
|
||||
this.#bytesWritten += batchSize;
|
||||
|
||||
this.#resolvePendingReads();
|
||||
// After drop-oldest, evicting a large chunk may bring us under budget.
|
||||
// Resolve pending drains so writers waiting on backpressure can proceed.
|
||||
if (this.#bufferedBytes < this.#budget) {
|
||||
this.#resolvePendingDrains(true);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,6 @@ const {
|
||||
|
||||
const {
|
||||
kMultiConsumerDefaultBudget,
|
||||
clampBudget,
|
||||
getMinCursor,
|
||||
hasProtocol,
|
||||
onSignalAbort,
|
||||
@@ -696,7 +695,7 @@ function share(source, options = { __proto__: null }) {
|
||||
|
||||
const opts = {
|
||||
__proto__: null,
|
||||
budget: clampBudget(budget),
|
||||
budget,
|
||||
backpressure,
|
||||
signal,
|
||||
};
|
||||
@@ -723,7 +722,7 @@ function shareSync(source, options = { __proto__: null }) {
|
||||
|
||||
const opts = {
|
||||
__proto__: null,
|
||||
budget: clampBudget(budget),
|
||||
budget,
|
||||
backpressure,
|
||||
};
|
||||
|
||||
|
||||
@@ -4,9 +4,6 @@ const {
|
||||
Array,
|
||||
ArrayBufferPrototypeGetByteLength,
|
||||
ArrayPrototypeSlice,
|
||||
MathMax,
|
||||
MathMin,
|
||||
NumberMAX_SAFE_INTEGER,
|
||||
PromiseResolve,
|
||||
PromiseWithResolvers,
|
||||
SafePromisePrototypeFinally,
|
||||
@@ -56,15 +53,6 @@ const kPushDefaultBudget = 16384;
|
||||
/** Default byte budget for broadcast and share streams (multi-consumer). */
|
||||
const kMultiConsumerDefaultBudget = 65536;
|
||||
|
||||
/**
|
||||
* Clamp a byte budget to [16384, MAX_SAFE_INTEGER].
|
||||
* @param {number} value
|
||||
* @returns {number}
|
||||
*/
|
||||
function clampBudget(value) {
|
||||
return MathMax(16384, 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.
|
||||
@@ -389,7 +377,6 @@ module.exports = {
|
||||
kPushDefaultBudget,
|
||||
kResolvedPromise,
|
||||
allUint8Array,
|
||||
clampBudget,
|
||||
concatBytes,
|
||||
convertChunks,
|
||||
getWriterSignal,
|
||||
|
||||
+8
-8
@@ -66,7 +66,7 @@ namespace quic {
|
||||
/* True when 0-RTT early data was received */ \
|
||||
V(RECEIVED_EARLY_DATA, received_early_data, uint8_t) \
|
||||
V(WRITE_DESIRED_SIZE, write_desired_size, uint32_t) \
|
||||
V(HIGH_WATER_MARK, high_water_mark, uint32_t)
|
||||
V(BUDGET, budget, uint32_t)
|
||||
|
||||
#define STREAM_STATS(V) \
|
||||
/* Marks the timestamp when the stream object was created. */ \
|
||||
@@ -1857,13 +1857,13 @@ void Stream::UpdateWriteDesiredSize() {
|
||||
if (!outbound_ || !outbound_->is_streaming()) return;
|
||||
|
||||
uint64_t available;
|
||||
uint64_t hwm = state()->high_water_mark;
|
||||
uint64_t bgt = state()->budget;
|
||||
|
||||
if (is_pending()) {
|
||||
// Pending streams don't have a stream ID yet, so ngtcp2 can't
|
||||
// report their flow control window. Use the high water mark as
|
||||
// the available capacity so writes can proceed while pending.
|
||||
available = hwm > 0 ? hwm : std::numeric_limits<uint32_t>::max();
|
||||
// report their flow control window. Use the budget as the
|
||||
// available capacity so writes can proceed while pending.
|
||||
available = bgt > 0 ? bgt : std::numeric_limits<uint32_t>::max();
|
||||
} else {
|
||||
// Calculate available capacity based on QUIC flow control.
|
||||
// The effective limit is the minimum of stream-level and
|
||||
@@ -1873,9 +1873,9 @@ void Stream::UpdateWriteDesiredSize() {
|
||||
uint64_t conn_left = ngtcp2_conn_get_max_data_left(conn);
|
||||
available = std::min(stream_left, conn_left);
|
||||
|
||||
// Apply the high water mark as an additional ceiling.
|
||||
if (hwm > 0) {
|
||||
available = std::min(available, hwm);
|
||||
// Apply the budget as an additional ceiling.
|
||||
if (bgt > 0) {
|
||||
available = std::min(available, bgt);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ const encoder = new TextEncoder();
|
||||
await clientSession.opened;
|
||||
|
||||
const stream = await clientSession.createBidirectionalStream({
|
||||
highWaterMark: 512,
|
||||
budget: 512,
|
||||
});
|
||||
const w = stream.writer;
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ const clientSession = await connect(serverEndpoint.address);
|
||||
await clientSession.opened;
|
||||
|
||||
const stream = await clientSession.createUnidirectionalStream({
|
||||
highWaterMark: 512,
|
||||
budget: 512,
|
||||
});
|
||||
const w = stream.writer;
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ const stream = await clientSession.createBidirectionalStream();
|
||||
const w = stream.writer;
|
||||
|
||||
// Writer should be open.
|
||||
strictEqual(typeof w.desiredSize, 'number');
|
||||
strictEqual(typeof w.canWrite, 'boolean');
|
||||
|
||||
// Write multiple chunks synchronously.
|
||||
strictEqual(w.writeSync(encoder.encode('chunk1')), true);
|
||||
@@ -55,8 +55,8 @@ strictEqual(totalWritten, 18); // 6 * 3
|
||||
// After end, write should return false.
|
||||
strictEqual(w.writeSync(encoder.encode('nope')), false);
|
||||
|
||||
// desiredSize should be null after close.
|
||||
strictEqual(w.desiredSize, null);
|
||||
// canWrite should be null after close.
|
||||
strictEqual(w.canWrite, null);
|
||||
|
||||
await Promise.all([stream.closed, done.promise]);
|
||||
await clientSession.close();
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// from the peer's perspective and they would keep transmitting until
|
||||
// the session-level idle timer fired.
|
||||
//
|
||||
// Verified via the server-side writer's `desiredSize` getter, which
|
||||
// Verified via the server-side writer's `canWrite` getter, which
|
||||
// returns `null` once `state.writeEnded` is set. STOP_SENDING from
|
||||
// the client triggers `Stream::ReceiveStopSending -> EndWritable` on
|
||||
// the server, which sets `state.writeEnded = 1`.
|
||||
@@ -16,7 +16,7 @@
|
||||
// processes RESET_STREAM first (firing `onreset`) and then
|
||||
// STOP_SENDING. The observation must therefore be deferred until
|
||||
// after the `onreset` callback returns so ngtcp2 can finish
|
||||
// processing the packet. Capturing `writer.desiredSize` synchronously
|
||||
// processing the packet. Capturing `writer.canWrite` synchronously
|
||||
// inside `onreset` would always see the pre-STOP_SENDING value.
|
||||
// Throwing inside `onreset` would also crash the process before
|
||||
// STOP_SENDING could be processed.
|
||||
@@ -38,12 +38,12 @@ const serverEndpoint = await listen(mustCall((serverSession) => {
|
||||
serverSession.onstream = mustCall(async (stream) => {
|
||||
const writer = stream.writer;
|
||||
// Sanity: the writer is active before the peer tears the stream
|
||||
// down, so desiredSize is a number reflecting the initial
|
||||
// down, so canWrite is a boolean reflecting the initial
|
||||
// flow-control window.
|
||||
if (typeof writer.desiredSize !== 'number') {
|
||||
if (typeof writer.canWrite !== 'boolean') {
|
||||
serverObservation.reject(new Error(
|
||||
`expected initial writer.desiredSize to be a number, ` +
|
||||
`got ${writer.desiredSize}`));
|
||||
`expected initial writer.canWrite to be a boolean, ` +
|
||||
`got ${writer.canWrite}`));
|
||||
return;
|
||||
}
|
||||
stream.onreset = mustCall(() => {
|
||||
@@ -53,9 +53,9 @@ const serverEndpoint = await listen(mustCall((serverSession) => {
|
||||
// next event loop tick the rest of the packet has been
|
||||
// processed and `Stream::ReceiveStopSending -> EndWritable` has
|
||||
// flipped `state.writeEnded` to 1, which makes the writer's
|
||||
// desiredSize getter return null.
|
||||
// canWrite getter return null.
|
||||
setImmediate(() => {
|
||||
serverObservation.resolve(writer.desiredSize);
|
||||
serverObservation.resolve(writer.canWrite);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -78,8 +78,8 @@ const clientClosedAssertion = assert.rejects(stream.closed, err);
|
||||
|
||||
stream.destroy(err);
|
||||
|
||||
const observedDesiredSize = await serverObservation.promise;
|
||||
strictEqual(observedDesiredSize, null);
|
||||
const observedCanWrite = await serverObservation.promise;
|
||||
strictEqual(observedCanWrite, null);
|
||||
|
||||
await clientClosedAssertion;
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ clientSession.onstream = mustCall(async (stream) => {
|
||||
// The receiving side of a uni stream should not be writable.
|
||||
// The writer should be pre-closed.
|
||||
const w = stream.writer;
|
||||
strictEqual(w.desiredSize, null);
|
||||
strictEqual(w.canWrite, null);
|
||||
|
||||
await stream.closed;
|
||||
clientSession.close();
|
||||
|
||||
@@ -93,12 +93,12 @@ await clientSession.opened;
|
||||
{
|
||||
const stream = await clientSession.createBidirectionalStream();
|
||||
const w = stream.writer;
|
||||
// desiredSize should be a number (may be 0 initially before flow
|
||||
// control window opens, or > 0 if the window is already open).
|
||||
strictEqual(typeof w.desiredSize, 'number');
|
||||
ok(w.desiredSize >= 0, `desiredSize should be >= 0, got ${w.desiredSize}`);
|
||||
// drainableProtocol should return null when desiredSize > 0 (has capacity),
|
||||
// or a promise when desiredSize <= 0 (backpressured). Either way, it
|
||||
// canWrite should be a boolean (false initially before flow
|
||||
// control window opens, or true if the window is already open).
|
||||
strictEqual(typeof w.canWrite, 'boolean');
|
||||
ok(w.canWrite !== null, `canWrite should not be null, got ${w.canWrite}`);
|
||||
// drainableProtocol should return null when canWrite is true (has capacity),
|
||||
// or a promise when canWrite is false (backpressured). Either way, it
|
||||
// should not throw.
|
||||
const { drainableProtocol: dp } = await import('stream/iter');
|
||||
const drain = w[dp]();
|
||||
@@ -115,8 +115,8 @@ await clientSession.opened;
|
||||
const w = stream.writer;
|
||||
const testError = new Error('writer fail test');
|
||||
w.fail(testError);
|
||||
// After fail, desiredSize is null.
|
||||
strictEqual(w.desiredSize, null);
|
||||
// After fail, canWrite is null.
|
||||
strictEqual(w.canWrite, null);
|
||||
// drainableProtocol returns null when errored.
|
||||
const { drainableProtocol: dp } = await import('stream/iter');
|
||||
strictEqual(w[dp](), null);
|
||||
|
||||
@@ -33,14 +33,14 @@ await clientSession.opened;
|
||||
const stream = await clientSession.createBidirectionalStream();
|
||||
const w = stream.writer;
|
||||
|
||||
// Writer is active — desiredSize should be a number (not null).
|
||||
strictEqual(typeof w.desiredSize, 'number');
|
||||
// Writer is active — canWrite should be a boolean (not null).
|
||||
strictEqual(typeof w.canWrite, 'boolean');
|
||||
|
||||
// Symbol.dispose calls fail() if not already closed/errored.
|
||||
w[Symbol.dispose]();
|
||||
|
||||
// After dispose, writer should be errored.
|
||||
strictEqual(w.desiredSize, null);
|
||||
strictEqual(w.canWrite, null);
|
||||
strictEqual(w.writeSync(encoder.encode('x')), false);
|
||||
|
||||
// stream.closed resolves because fail() with default code 0
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Flags: --experimental-quic --experimental-stream-iter --no-warnings
|
||||
|
||||
// Test: writer backpressure.
|
||||
// writeSync returns false when highWaterMark is exceeded.
|
||||
// drainableProtocol returns promise when desiredSize <= 0.
|
||||
// writeSync returns false when budget is exceeded.
|
||||
// drainableProtocol returns promise when canWrite is false.
|
||||
// drainableProtocol promise resolves when drain fires.
|
||||
// Try-fallback pattern: writeSync false, await drain, retry.
|
||||
|
||||
@@ -18,7 +18,7 @@ if (!hasQuic) {
|
||||
const { listen, connect } = await import('../common/quic.mjs');
|
||||
const { bytes, drainableProtocol: dp } = await import('stream/iter');
|
||||
|
||||
// Total data: 8 x 1KB = 8KB. highWaterMark: 2KB.
|
||||
// Total data: 8 x 1KB = 8KB. budget: 2KB.
|
||||
const numChunks = 8;
|
||||
const chunkSize = 1024;
|
||||
const totalSize = numChunks * chunkSize;
|
||||
@@ -40,13 +40,13 @@ const clientSession = await connect(serverEndpoint.address);
|
||||
await clientSession.opened;
|
||||
|
||||
const stream = await clientSession.createBidirectionalStream({
|
||||
highWaterMark: 2048,
|
||||
budget: 2048,
|
||||
});
|
||||
const w = stream.writer;
|
||||
|
||||
// Initial desiredSize should be the highWaterMark.
|
||||
strictEqual(w.desiredSize, 2048);
|
||||
strictEqual(stream.highWaterMark, 2048);
|
||||
// Initial canWrite should be true.
|
||||
strictEqual(w.canWrite, true);
|
||||
strictEqual(stream.budget, 2048);
|
||||
|
||||
let backpressureCount = 0;
|
||||
|
||||
@@ -64,14 +64,14 @@ for (let i = 0; i < numChunks; i++) {
|
||||
// The promise resolves when drain fires.
|
||||
await drain;
|
||||
|
||||
// After drain, desiredSize should be > 0.
|
||||
ok(w.desiredSize > 0, `desiredSize after drain should be > 0, got ${w.desiredSize}`);
|
||||
// After drain, canWrite should be true.
|
||||
ok(w.canWrite === true, `canWrite after drain should be true, got ${w.canWrite}`);
|
||||
}
|
||||
}
|
||||
|
||||
w.endSync();
|
||||
|
||||
// Backpressure should have been hit with a 2KB highWaterMark
|
||||
// Backpressure should have been hit with a 2KB budget
|
||||
// and 1KB chunks (every 2 chunks fills the buffer).
|
||||
ok(backpressureCount > 0, 'backpressure should have been hit');
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
// Test: write() rejects when flow-controlled.
|
||||
// The async write() method rejects with ERR_INVALID_STATE when the
|
||||
// chunk exceeds desiredSize.
|
||||
// chunk exceeds capacity (canWrite is false).
|
||||
|
||||
import { hasQuic, skip, mustCall } from '../common/index.mjs';
|
||||
import assert from 'node:assert';
|
||||
@@ -31,17 +31,17 @@ const serverEndpoint = await listen(mustCall((serverSession) => {
|
||||
const clientSession = await connect(serverEndpoint.address);
|
||||
await clientSession.opened;
|
||||
|
||||
// Use a small highWaterMark to trigger backpressure easily.
|
||||
// Use a small budget to trigger backpressure easily.
|
||||
const stream = await clientSession.createBidirectionalStream({
|
||||
highWaterMark: 1024,
|
||||
budget: 1024,
|
||||
});
|
||||
const w = stream.writer;
|
||||
|
||||
// Fill the buffer.
|
||||
strictEqual(w.writeSync(new Uint8Array(1024)), true);
|
||||
|
||||
// desiredSize should now be 0 or very small.
|
||||
strictEqual(w.desiredSize, 0);
|
||||
// canWrite should now be false.
|
||||
strictEqual(w.canWrite, false);
|
||||
|
||||
// Async write() should reject when buffer is full.
|
||||
await rejects(
|
||||
@@ -53,7 +53,7 @@ await rejects(
|
||||
const drain = w[dp]();
|
||||
ok(drain instanceof Promise);
|
||||
await drain;
|
||||
ok(w.desiredSize > 0);
|
||||
ok(w.canWrite === true);
|
||||
|
||||
// Now write succeeds.
|
||||
await w.write(new Uint8Array(100));
|
||||
|
||||
@@ -10,36 +10,41 @@ const { broadcast, text } = require('stream/iter');
|
||||
// =============================================================================
|
||||
|
||||
async function testDropOldest() {
|
||||
const chunk1 = new Uint8Array(16384).fill(49); // '1'
|
||||
const chunk2 = new Uint8Array(16384).fill(50); // '2'
|
||||
const chunk3 = new Uint8Array(16384).fill(51); // '3'
|
||||
const { writer, broadcast: bc } = broadcast({
|
||||
budget: 16384,
|
||||
budget: 32768,
|
||||
backpressure: 'drop-oldest',
|
||||
});
|
||||
const consumer = bc.push();
|
||||
|
||||
writer.writeSync('first');
|
||||
writer.writeSync('second');
|
||||
// This should drop 'first'
|
||||
writer.writeSync('third');
|
||||
writer.writeSync(chunk1); // 16384 < 32768
|
||||
writer.writeSync(chunk2); // 32768 >= 32768
|
||||
// Buffer full: this drops chunk1, adds chunk3
|
||||
writer.writeSync(chunk3);
|
||||
writer.endSync();
|
||||
|
||||
const data = await text(consumer);
|
||||
assert.strictEqual(data, 'secondthird');
|
||||
assert.strictEqual(data, '2'.repeat(16384) + '3'.repeat(16384));
|
||||
}
|
||||
|
||||
async function testDropNewest() {
|
||||
const kept = new Uint8Array(16384).fill(75); // 'K'
|
||||
const dropped = new Uint8Array(16384).fill(68); // 'D'
|
||||
const { writer, broadcast: bc } = broadcast({
|
||||
budget: 16384,
|
||||
backpressure: 'drop-newest',
|
||||
});
|
||||
const consumer = bc.push();
|
||||
|
||||
writer.writeSync('kept');
|
||||
// This should be silently dropped
|
||||
writer.writeSync('dropped');
|
||||
writer.writeSync(kept);
|
||||
// Buffer full: new write is silently discarded
|
||||
writer.writeSync(dropped);
|
||||
writer.endSync();
|
||||
|
||||
const data = await text(consumer);
|
||||
assert.strictEqual(data, 'kept');
|
||||
assert.strictEqual(data, 'K'.repeat(16384));
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
@@ -47,16 +52,17 @@ async function testDropNewest() {
|
||||
// =============================================================================
|
||||
|
||||
async function testBlockBackpressure() {
|
||||
const kChunk = new Uint8Array(16384);
|
||||
const { writer, broadcast: bc } = broadcast({
|
||||
budget: 16384,
|
||||
backpressure: 'unbounded',
|
||||
});
|
||||
const consumer = bc.push();
|
||||
writer.writeSync('a');
|
||||
writer.writeSync(kChunk);
|
||||
|
||||
// Next write should block
|
||||
let writeResolved = false;
|
||||
const writePromise = writer.write('b').then(() => { writeResolved = true; });
|
||||
const writePromise = writer.write(kChunk).then(() => { writeResolved = true; });
|
||||
await new Promise(setImmediate);
|
||||
assert.strictEqual(writeResolved, false);
|
||||
|
||||
@@ -76,30 +82,32 @@ async function testBlockBackpressure() {
|
||||
|
||||
// Verify block backpressure data flows correctly end-to-end
|
||||
async function testBlockBackpressureContent() {
|
||||
const chunk1 = new Uint8Array(16384).fill(65); // 'A'
|
||||
const chunk2 = new Uint8Array(16384).fill(66); // 'B'
|
||||
const { writer, broadcast: bc } = broadcast({
|
||||
budget: 16384,
|
||||
backpressure: 'unbounded',
|
||||
});
|
||||
const consumer = bc.push();
|
||||
|
||||
writer.writeSync('a');
|
||||
const writePromise = writer.write('b');
|
||||
writer.writeSync(chunk1);
|
||||
const writePromise = writer.write(chunk2);
|
||||
await new Promise(setImmediate);
|
||||
|
||||
// Read all and verify content
|
||||
const iter = consumer[Symbol.asyncIterator]();
|
||||
const first = await iter.next();
|
||||
assert.strictEqual(first.done, false);
|
||||
const firstStr = new TextDecoder().decode(first.value[0]);
|
||||
assert.strictEqual(firstStr, 'a');
|
||||
assert.strictEqual(first.value[0].byteLength, 16384);
|
||||
assert.strictEqual(first.value[0][0], 65); // 'A'
|
||||
|
||||
await writePromise;
|
||||
writer.endSync();
|
||||
|
||||
const second = await iter.next();
|
||||
assert.strictEqual(second.done, false);
|
||||
const secondStr = new TextDecoder().decode(second.value[0]);
|
||||
assert.strictEqual(secondStr, 'b');
|
||||
assert.strictEqual(second.value[0].byteLength, 16384);
|
||||
assert.strictEqual(second.value[0][0], 66); // 'B'
|
||||
|
||||
const done = await iter.next();
|
||||
assert.strictEqual(done.done, true);
|
||||
|
||||
@@ -74,18 +74,18 @@ async function testConsumerCount() {
|
||||
// =============================================================================
|
||||
|
||||
async function testWriteSync() {
|
||||
const kChunk = new Uint8Array(16384);
|
||||
const { writer, broadcast: bc } = broadcast({ budget: 16384 });
|
||||
const consumer = bc.push();
|
||||
|
||||
assert.strictEqual(writer.writeSync('a'), true);
|
||||
assert.strictEqual(writer.writeSync('b'), true);
|
||||
// Buffer full (budget=16384, strict policy)
|
||||
assert.strictEqual(writer.writeSync('c'), false);
|
||||
assert.strictEqual(writer.writeSync(kChunk), true);
|
||||
// Buffer full (16384 >= budget), strict policy rejects
|
||||
assert.strictEqual(writer.writeSync(kChunk), false);
|
||||
|
||||
writer.endSync();
|
||||
|
||||
const data = await text(consumer);
|
||||
assert.strictEqual(data, 'ab');
|
||||
assert.strictEqual(data.length, 16384);
|
||||
}
|
||||
|
||||
async function testWritevSync() {
|
||||
|
||||
@@ -21,11 +21,11 @@ async function testBroadcastWriteAbort() {
|
||||
const consumer = bc.push();
|
||||
|
||||
// Fill the buffer to capacity
|
||||
writer.writeSync(new Uint8Array([1]));
|
||||
writer.writeSync(new Uint8Array(16384).fill(1));
|
||||
|
||||
// Next write will block — pass a signal
|
||||
const ac = new AbortController();
|
||||
const writePromise = writer.write(new Uint8Array([2]),
|
||||
const writePromise = writer.write(new Uint8Array(16384).fill(2),
|
||||
{ signal: ac.signal });
|
||||
|
||||
// Abort the signal
|
||||
|
||||
@@ -155,26 +155,18 @@ async function testPushWriterBlockSyncFalseAccepted() {
|
||||
}
|
||||
|
||||
async function testPipeToSyncPushWriterStrictFalseRejected() {
|
||||
const decoder = new TextDecoder();
|
||||
const { writer, readable } = push({ budget: 16384 });
|
||||
const kChunk = new Uint8Array(16384);
|
||||
const { writer } = push({ budget: 16384 });
|
||||
|
||||
const total = pipeToSync(['a', 'b'], writer, { preventClose: true });
|
||||
assert.strictEqual(total, 1);
|
||||
// Pre-fill the buffer so it's at capacity
|
||||
writer.writeSync(kChunk);
|
||||
|
||||
const iter = readable[Symbol.asyncIterator]();
|
||||
const first = await iter.next();
|
||||
assert.strictEqual(first.done, false);
|
||||
assert.strictEqual(decoder.decode(first.value[0]), 'a');
|
||||
|
||||
const second = await Promise.race([
|
||||
iter.next().then((result) => {
|
||||
return result.done ? '<done>' : decoder.decode(result.value[0]);
|
||||
}),
|
||||
setImmediatePromise().then(() => '<no second chunk>'),
|
||||
]);
|
||||
assert.strictEqual(second, '<no second chunk>');
|
||||
|
||||
await iter.return?.();
|
||||
// pipeToSync should throw when writeSync returns false (budget exhausted)
|
||||
assert.throws(
|
||||
() => pipeToSync([kChunk], writer,
|
||||
{ preventClose: true, preventFail: true }),
|
||||
{ code: 'ERR_OUT_OF_RANGE' },
|
||||
);
|
||||
}
|
||||
|
||||
async function testPipeToSyncWritevFalseNotCounted() {
|
||||
@@ -187,8 +179,11 @@ async function testPipeToSyncWritevFalseNotCounted() {
|
||||
yield [new Uint8Array([1]), new Uint8Array([2])];
|
||||
}
|
||||
|
||||
const total = pipeToSync(source(), writer);
|
||||
assert.strictEqual(total, 0);
|
||||
// pipeToSync throws when writevSync returns false (budget exhausted)
|
||||
assert.throws(
|
||||
() => pipeToSync(source(), writer),
|
||||
{ code: 'ERR_OUT_OF_RANGE' },
|
||||
);
|
||||
}
|
||||
|
||||
// pipeToSync with writevSync
|
||||
|
||||
@@ -6,74 +6,71 @@ const assert = require('assert');
|
||||
const { push, text } = require('stream/iter');
|
||||
|
||||
async function testStrictBackpressure() {
|
||||
const kChunk = new Uint8Array(16384).fill(65); // 'A'
|
||||
const { writer, readable } = push({
|
||||
budget: 16384,
|
||||
backpressure: 'strict',
|
||||
});
|
||||
|
||||
// First write should succeed synchronously
|
||||
assert.strictEqual(writer.writeSync('a'), true);
|
||||
// Second write should fail synchronously (buffer full)
|
||||
assert.strictEqual(writer.writeSync('b'), false);
|
||||
// First write fills the budget
|
||||
assert.strictEqual(writer.writeSync(kChunk), true);
|
||||
// Second write rejected (buffer full)
|
||||
assert.strictEqual(writer.writeSync(kChunk), false);
|
||||
|
||||
// Consume to free space, then end
|
||||
const resultPromise = text(readable);
|
||||
writer.end();
|
||||
const data = await resultPromise;
|
||||
assert.strictEqual(data, 'a');
|
||||
assert.strictEqual(data, 'A'.repeat(16384));
|
||||
}
|
||||
|
||||
async function testDropOldest() {
|
||||
const chunk1 = new Uint8Array(16384).fill(49); // '1'
|
||||
const chunk2 = new Uint8Array(16384).fill(50); // '2'
|
||||
const chunk3 = new Uint8Array(16384).fill(51); // '3'
|
||||
const { writer, readable } = push({
|
||||
budget: 16384,
|
||||
budget: 32768,
|
||||
backpressure: 'drop-oldest',
|
||||
});
|
||||
|
||||
assert.strictEqual(writer.writeSync('first'), true);
|
||||
assert.strictEqual(writer.writeSync('second'), true);
|
||||
// This should drop 'first' — return value is true (write accepted via drop)
|
||||
assert.strictEqual(writer.writeSync('third'), true);
|
||||
assert.strictEqual(writer.writeSync(chunk1), true); // 16384 < 32768
|
||||
assert.strictEqual(writer.writeSync(chunk2), true); // 32768 >= 32768
|
||||
// Buffer full: this drops chunk1, adds chunk3
|
||||
assert.strictEqual(writer.writeSync(chunk3), true);
|
||||
writer.end();
|
||||
|
||||
const batches = [];
|
||||
for await (const batch of readable) {
|
||||
batches.push(batch);
|
||||
}
|
||||
// Should have 'second' and 'third'
|
||||
const allBytes = [];
|
||||
for (const batch of batches) {
|
||||
for (const chunk of batch) {
|
||||
allBytes.push(...chunk);
|
||||
}
|
||||
}
|
||||
const result = new TextDecoder().decode(new Uint8Array(allBytes));
|
||||
assert.strictEqual(result, 'secondthird');
|
||||
const data = await text(readable);
|
||||
// chunk2 ('2' x 16384) + chunk3 ('3' x 16384) survived
|
||||
assert.strictEqual(data, '2'.repeat(16384) + '3'.repeat(16384));
|
||||
}
|
||||
|
||||
async function testDropNewest() {
|
||||
const kept = new Uint8Array(16384).fill(75); // 'K'
|
||||
const dropped = new Uint8Array(16384).fill(68); // 'D'
|
||||
const { writer, readable } = push({
|
||||
budget: 16384,
|
||||
backpressure: 'drop-newest',
|
||||
});
|
||||
|
||||
assert.strictEqual(writer.writeSync('kept'), true);
|
||||
// This is silently dropped — return value is true (accepted but discarded)
|
||||
assert.strictEqual(writer.writeSync('dropped'), true);
|
||||
assert.strictEqual(writer.writeSync(kept), true);
|
||||
// Buffer full: new write is silently discarded
|
||||
assert.strictEqual(writer.writeSync(dropped), true);
|
||||
writer.end();
|
||||
|
||||
const data = await text(readable);
|
||||
assert.strictEqual(data, 'kept');
|
||||
assert.strictEqual(data, 'K'.repeat(16384));
|
||||
}
|
||||
|
||||
async function testBlockBackpressure() {
|
||||
const kChunk = new Uint8Array(16384);
|
||||
const { writer, readable } = push({ budget: 16384, backpressure: 'unbounded' });
|
||||
|
||||
// Fill the buffer
|
||||
writer.writeSync('a');
|
||||
writer.writeSync(kChunk);
|
||||
|
||||
// Next write should block (not throw, not drop)
|
||||
let writeState = 'pending';
|
||||
const writePromise = writer.write('b').then(() => { writeState = 'resolved'; });
|
||||
const writePromise = writer.write(kChunk).then(() => { writeState = 'resolved'; });
|
||||
|
||||
// The write cannot resolve until the buffer is drained, so a microtask
|
||||
// tick is sufficient to confirm it is still blocked.
|
||||
@@ -82,7 +79,7 @@ async function testBlockBackpressure() {
|
||||
|
||||
// Read from the consumer to drain
|
||||
const iter = readable[Symbol.asyncIterator]();
|
||||
const first = await iter.next(); // Drains 'a'
|
||||
const first = await iter.next();
|
||||
assert.strictEqual(first.done, false);
|
||||
|
||||
// After draining, the pending write resolves as a microtask
|
||||
@@ -90,7 +87,7 @@ async function testBlockBackpressure() {
|
||||
assert.strictEqual(writeState, 'resolved'); // Now unblocked
|
||||
|
||||
writer.endSync();
|
||||
const second = await iter.next(); // Read 'b'
|
||||
const second = await iter.next();
|
||||
assert.strictEqual(second.done, false);
|
||||
await writePromise;
|
||||
}
|
||||
@@ -99,42 +96,44 @@ async function testBlockWriteSyncDoesNotEnqueue() {
|
||||
// With block policy, writeSync returns false when the buffer is full.
|
||||
// The data is NOT accepted — writeSync only operates on the slots buffer.
|
||||
// The caller should fall back to write() which uses the pending queue.
|
||||
const kChunk = new Uint8Array(16384);
|
||||
const { writer, readable } = push({ budget: 16384, backpressure: 'unbounded' });
|
||||
|
||||
// Fill the buffer
|
||||
assert.strictEqual(writer.writeSync('a'), true);
|
||||
assert.strictEqual(writer.writeSync(kChunk), true);
|
||||
|
||||
// Buffer full: writeSync returns false, data NOT enqueued
|
||||
assert.strictEqual(writer.writeSync('b'), false);
|
||||
assert.strictEqual(writer.writeSync(kChunk), false);
|
||||
|
||||
// Use the async write (try-fallback pattern) — this goes to pending queue
|
||||
const consuming = text(readable);
|
||||
await writer.write('b');
|
||||
await writer.write(kChunk);
|
||||
await writer.end();
|
||||
|
||||
// Both chunks should be delivered
|
||||
// Both chunks should be delivered (sync + async)
|
||||
const result = await consuming;
|
||||
assert.strictEqual(result, 'ab');
|
||||
assert.strictEqual(result.length, 32768);
|
||||
}
|
||||
|
||||
async function testStrictPendingQueueOverflow() {
|
||||
// With budget: 16384 and strict, the pending writes queue is also limited to 1.
|
||||
// With strict mode, the pending writes queue is limited to 1.
|
||||
// Filling the buffer (1 sync write) + filling the pending queue (1 async write)
|
||||
// should leave no room. A third write must reject with a RangeError.
|
||||
const kChunk = new Uint8Array(16384);
|
||||
const { writer, readable } = push({
|
||||
budget: 16384,
|
||||
backpressure: 'strict',
|
||||
});
|
||||
|
||||
// Fill the buffer
|
||||
assert.strictEqual(writer.writeSync('a'), true);
|
||||
assert.strictEqual(writer.writeSync(kChunk), true);
|
||||
|
||||
// This async write goes into the pending queue (buffer full, queue has room)
|
||||
const pendingWrite = writer.write('b');
|
||||
const pendingWrite = writer.write(kChunk);
|
||||
|
||||
// This write should reject: buffer full AND pending queue at capacity
|
||||
await assert.rejects(
|
||||
() => writer.write('c'),
|
||||
() => writer.write(kChunk),
|
||||
{
|
||||
code: 'ERR_INVALID_STATE',
|
||||
name: 'RangeError',
|
||||
|
||||
@@ -28,15 +28,14 @@ async function testMultipleWrites() {
|
||||
}
|
||||
|
||||
async function testCanWrite() {
|
||||
const kHalf = new Uint8Array(8192);
|
||||
const { writer } = push({ budget: 16384 });
|
||||
|
||||
assert.strictEqual(writer.canWrite, true);
|
||||
writer.writeSync('a');
|
||||
assert.strictEqual(writer.canWrite, true);
|
||||
writer.writeSync('b');
|
||||
assert.strictEqual(writer.canWrite, true);
|
||||
writer.writeSync('c');
|
||||
assert.strictEqual(writer.canWrite, false);
|
||||
writer.writeSync(kHalf);
|
||||
assert.strictEqual(writer.canWrite, true); // 8192 < 16384
|
||||
writer.writeSync(kHalf);
|
||||
assert.strictEqual(writer.canWrite, false); // 16384 >= 16384
|
||||
|
||||
writer.end();
|
||||
assert.strictEqual(writer.canWrite, null);
|
||||
|
||||
@@ -39,13 +39,14 @@ async function testOndrainProtocolErrorPropagates() {
|
||||
}
|
||||
|
||||
async function testWriteWithSignalRejects() {
|
||||
const kChunk = new Uint8Array(16384);
|
||||
const { writer, readable } = push({ budget: 16384 });
|
||||
|
||||
// Fill the buffer so write will block
|
||||
writer.writeSync('a');
|
||||
writer.writeSync(kChunk);
|
||||
|
||||
const ac = new AbortController();
|
||||
const writePromise = writer.write('b', { signal: ac.signal });
|
||||
const writePromise = writer.write(kChunk, { signal: ac.signal });
|
||||
|
||||
// Signal fires while write is pending
|
||||
ac.abort();
|
||||
@@ -75,48 +76,49 @@ async function testWriteWithPreAbortedSignal() {
|
||||
}
|
||||
|
||||
async function testCancelledWriteRemovedFromQueue() {
|
||||
const kChunk = new Uint8Array(16384);
|
||||
const { writer, readable } = push({ budget: 16384 });
|
||||
|
||||
// Fill the buffer
|
||||
writer.writeSync('first');
|
||||
writer.writeSync(kChunk);
|
||||
|
||||
const ac = new AbortController();
|
||||
// This write should be queued since buffer is full
|
||||
const cancelledWrite = writer.write('cancelled', { signal: ac.signal });
|
||||
const cancelledWrite = writer.write(kChunk, { signal: ac.signal });
|
||||
|
||||
// Cancel it
|
||||
ac.abort();
|
||||
await cancelledWrite.catch(() => {});
|
||||
|
||||
// Drain 'first' to make room for the replacement write
|
||||
// Drain to make room for the replacement write
|
||||
const iter = readable[Symbol.asyncIterator]();
|
||||
await iter.next();
|
||||
|
||||
// The cancelled write should NOT occupy a pending slot.
|
||||
// A new write should succeed now that the buffer has room.
|
||||
await writer.write('second');
|
||||
await writer.write(kChunk);
|
||||
writer.end();
|
||||
|
||||
const result = await iter.next();
|
||||
// 'second' should be the next (and only remaining) chunk
|
||||
const decoder = new TextDecoder();
|
||||
let data = '';
|
||||
assert.ok(!result.done);
|
||||
let totalBytes = 0;
|
||||
for (const chunk of result.value) {
|
||||
data += decoder.decode(chunk, { stream: true });
|
||||
totalBytes += chunk.byteLength;
|
||||
}
|
||||
assert.strictEqual(data, 'second');
|
||||
assert.strictEqual(totalBytes, 16384);
|
||||
await iter.return();
|
||||
}
|
||||
|
||||
async function testOndrainResolvesFalseOnConsumerBreak() {
|
||||
const kChunk = new Uint8Array(16384);
|
||||
const { writer, readable } = push({ budget: 16384 });
|
||||
|
||||
// Fill the buffer so canWrite = false
|
||||
writer.writeSync('a');
|
||||
writer.writeSync(kChunk);
|
||||
|
||||
// Also queue a pending write so that reading one chunk
|
||||
// doesn't clear backpressure (the pending write refills the slot)
|
||||
const pendingWrite = writer.write('b');
|
||||
// doesn't clear backpressure (the pending write refills the buffer)
|
||||
const pendingWrite = writer.write(kChunk);
|
||||
|
||||
// Start a drain wait - still at capacity
|
||||
const drainPromise = ondrain(writer);
|
||||
@@ -132,14 +134,15 @@ async function testOndrainResolvesFalseOnConsumerBreak() {
|
||||
}
|
||||
|
||||
async function testOndrainRejectsOnConsumerThrow() {
|
||||
const kChunk = new Uint8Array(16384);
|
||||
const { writer, readable } = push({ budget: 16384 });
|
||||
|
||||
// Fill the buffer so canWrite = false
|
||||
writer.writeSync('a');
|
||||
writer.writeSync(kChunk);
|
||||
|
||||
// Also queue a pending write so that reading one chunk
|
||||
// doesn't clear backpressure (the pending write refills the slot)
|
||||
const pendingWrite = writer.write('b');
|
||||
// doesn't clear backpressure (the pending write refills the buffer)
|
||||
const pendingWrite = writer.write(kChunk);
|
||||
|
||||
// Start a drain wait - still at capacity
|
||||
const drainPromise = ondrain(writer);
|
||||
@@ -285,8 +288,9 @@ async function testWriteUint8Array() {
|
||||
}
|
||||
|
||||
async function testOndrainWaitsForDrain() {
|
||||
const kChunk = new Uint8Array(16384);
|
||||
const { writer, readable } = push({ budget: 16384 });
|
||||
writer.writeSync('a'); // Fills buffer
|
||||
writer.writeSync(kChunk); // Fills budget
|
||||
|
||||
let drainState = 'pending';
|
||||
const drainPromise = ondrain(writer).then((v) => { drainState = v; });
|
||||
@@ -305,8 +309,9 @@ async function testOndrainWaitsForDrain() {
|
||||
|
||||
// Consumer throw causes subsequent writes to reject with consumer's error
|
||||
async function testConsumerThrowRejectsWrites() {
|
||||
const kChunk = new Uint8Array(16384);
|
||||
const { writer, readable } = push({ budget: 16384 });
|
||||
writer.writeSync('a');
|
||||
writer.writeSync(kChunk);
|
||||
|
||||
const iter = readable[Symbol.asyncIterator]();
|
||||
const err = new Error('consumer boom');
|
||||
@@ -409,11 +414,12 @@ async function testConsumerThrowRejectsPendingRead() {
|
||||
|
||||
// end() while writes are pending rejects those writes
|
||||
async function testEndRejectsPendingWrites() {
|
||||
const kChunk = new Uint8Array(16384);
|
||||
const { writer, readable } = push({ budget: 16384, backpressure: 'unbounded' });
|
||||
writer.writeSync('a'); // fill buffer
|
||||
writer.writeSync(kChunk); // fill budget
|
||||
|
||||
// This write blocks on backpressure
|
||||
const writePromise = writer.write('b');
|
||||
const writePromise = writer.write(kChunk);
|
||||
|
||||
await new Promise(setImmediate);
|
||||
|
||||
|
||||
@@ -135,36 +135,38 @@ async function testShareDropOldest() {
|
||||
// misses old data and only sees recent items.
|
||||
async function* source() {
|
||||
for (let i = 0; i < 4; i++) {
|
||||
yield [new TextEncoder().encode(`${i}`)];
|
||||
const chunk = new Uint8Array(16384);
|
||||
chunk[0] = i; // Tag first byte with index
|
||||
yield [chunk];
|
||||
}
|
||||
}
|
||||
const shared = share(source(), { budget: 16384, backpressure: 'drop-oldest' });
|
||||
const shared = share(source(), { budget: 32768, backpressure: 'drop-oldest' });
|
||||
const fast = shared.pull();
|
||||
const slow = shared.pull();
|
||||
|
||||
// Fast consumer reads all items
|
||||
const fastItems = [];
|
||||
const fastIndices = [];
|
||||
for await (const batch of fast) {
|
||||
for (const chunk of batch) {
|
||||
fastItems.push(new TextDecoder().decode(chunk));
|
||||
fastIndices.push(chunk[0]);
|
||||
}
|
||||
}
|
||||
assert.strictEqual(fastItems.length, 4);
|
||||
assert.strictEqual(fastIndices.length, 4);
|
||||
|
||||
// Slow consumer reads after fast is done — old items were dropped
|
||||
const slowItems = [];
|
||||
const slowIndices = [];
|
||||
for await (const batch of slow) {
|
||||
for (const chunk of batch) {
|
||||
slowItems.push(new TextDecoder().decode(chunk));
|
||||
slowIndices.push(chunk[0]);
|
||||
}
|
||||
}
|
||||
// The slow consumer should see fewer items than were produced
|
||||
assert.ok(slowItems.length < 4,
|
||||
`Expected < 4 items after drop-oldest, got ${slowItems.length}`);
|
||||
assert.ok(slowItems.length > 0,
|
||||
assert.ok(slowIndices.length < 4,
|
||||
`Expected < 4 items after drop-oldest, got ${slowIndices.length}`);
|
||||
assert.ok(slowIndices.length > 0,
|
||||
'Expected at least some items after drop-oldest');
|
||||
// The last item should always be present (most recent items kept)
|
||||
assert.strictEqual(slowItems[slowItems.length - 1], '3');
|
||||
assert.strictEqual(slowIndices[slowIndices.length - 1], 3);
|
||||
}
|
||||
|
||||
async function testShareDropNewest() {
|
||||
@@ -174,31 +176,34 @@ async function testShareDropNewest() {
|
||||
// ultimately see all items.
|
||||
async function* source() {
|
||||
for (let i = 0; i < 4; i++) {
|
||||
yield [new TextEncoder().encode(`${i}`)];
|
||||
const chunk = new Uint8Array(16384);
|
||||
chunk[0] = i;
|
||||
yield [chunk];
|
||||
}
|
||||
}
|
||||
const shared = share(source(), { budget: 16384, backpressure: 'drop-newest' });
|
||||
const shared = share(source(), { budget: 32768, backpressure: 'drop-newest' });
|
||||
const fast = shared.pull();
|
||||
const slow = shared.pull();
|
||||
|
||||
// The fast consumer fills the buffer, then drives the source to completion.
|
||||
const fastItems = [];
|
||||
// Fast consumer reads all items
|
||||
const fastIndices = [];
|
||||
for await (const batch of fast) {
|
||||
for (const chunk of batch) {
|
||||
fastItems.push(new TextDecoder().decode(chunk));
|
||||
fastIndices.push(chunk[0]);
|
||||
}
|
||||
}
|
||||
assert.deepStrictEqual(fastItems, ['0', '1']);
|
||||
assert.strictEqual(shared.bufferSize, 2);
|
||||
assert.strictEqual(fastIndices.length, 2);
|
||||
|
||||
// The stalled consumer sees the buffered items, but not the dropped results.
|
||||
const slowItems = [];
|
||||
// Slow consumer also sees all items (buffer grew past budget)
|
||||
const slowIndices = [];
|
||||
for await (const batch of slow) {
|
||||
for (const chunk of batch) {
|
||||
slowItems.push(new TextDecoder().decode(chunk));
|
||||
slowIndices.push(chunk[0]);
|
||||
}
|
||||
}
|
||||
assert.deepStrictEqual(slowItems, ['0', '1']);
|
||||
assert.strictEqual(slowIndices.length, 2);
|
||||
assert.strictEqual(slowIndices[0], 0);
|
||||
assert.strictEqual(slowIndices[1], 1);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
@@ -208,10 +213,10 @@ async function testShareDropNewest() {
|
||||
async function testShareStrictBackpressure() {
|
||||
async function* source() {
|
||||
for (let i = 0; i < 10; i++) {
|
||||
yield [new TextEncoder().encode(`${i}`)];
|
||||
yield [new Uint8Array(16384)];
|
||||
}
|
||||
}
|
||||
const shared = share(source(), { budget: 16384, backpressure: 'strict' });
|
||||
const shared = share(source(), { budget: 32768, backpressure: 'strict' });
|
||||
const fast = shared.pull();
|
||||
// Create a second consumer that never reads — this prevents buffer trimming
|
||||
shared.pull();
|
||||
|
||||
@@ -21,13 +21,16 @@ const {
|
||||
// push() validation
|
||||
// =============================================================================
|
||||
|
||||
// Budget must be integer >= 1
|
||||
// Budget must be integer >= 16384
|
||||
assert.throws(() => push({ budget: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' });
|
||||
assert.throws(() => push({ budget: 1.5 }), { code: 'ERR_OUT_OF_RANGE' });
|
||||
// Values < 16384 are clamped to 16384
|
||||
assert.strictEqual(push({ budget: 0 }).writer.canWrite, true);
|
||||
assert.strictEqual(push({ budget: -1 }).writer.canWrite, true);
|
||||
assert.strictEqual(push({ budget: -100 }).writer.canWrite, true);
|
||||
// Values < 16384 are rejected
|
||||
assert.throws(() => push({ budget: 0 }), { code: 'ERR_OUT_OF_RANGE' });
|
||||
assert.throws(() => push({ budget: -1 }), { code: 'ERR_OUT_OF_RANGE' });
|
||||
assert.throws(() => push({ budget: -100 }), { code: 'ERR_OUT_OF_RANGE' });
|
||||
assert.throws(() => push({ budget: 16383 }), { code: 'ERR_OUT_OF_RANGE' });
|
||||
// 16384 is the minimum accepted value
|
||||
assert.strictEqual(push({ budget: 16384 }).writer.canWrite, true);
|
||||
// MAX_SAFE_INTEGER is accepted
|
||||
assert.strictEqual(push({ budget: Number.MAX_SAFE_INTEGER }).writer.canWrite,
|
||||
true);
|
||||
@@ -89,14 +92,8 @@ assert.throws(() => duplex({ budget: 1.5 }), { code: 'ERR_OUT_OF_RANGE' });
|
||||
assert.throws(() => duplex({ budget: Number.MAX_SAFE_INTEGER + 1 }),
|
||||
{ code: 'ERR_OUT_OF_RANGE' });
|
||||
|
||||
// Values < 16384 are clamped to 16384 (both directions)
|
||||
{
|
||||
const [a, b] = duplex({ budget: 0 });
|
||||
assert.strictEqual(a.writer.canWrite, true);
|
||||
assert.strictEqual(b.writer.canWrite, true);
|
||||
a.close();
|
||||
b.close();
|
||||
}
|
||||
// Values < 16384 are rejected (both directions)
|
||||
assert.throws(() => duplex({ budget: 0 }), { code: 'ERR_OUT_OF_RANGE' });
|
||||
// MAX_SAFE_INTEGER is accepted
|
||||
{
|
||||
const [a, b] = duplex({ budget: Number.MAX_SAFE_INTEGER });
|
||||
@@ -107,8 +104,8 @@ assert.throws(() => duplex({ budget: Number.MAX_SAFE_INTEGER + 1 }),
|
||||
}
|
||||
// Per-direction overrides
|
||||
{
|
||||
const [a, b] = duplex({ a: { budget: 0 }, b: { budget: 16384 } });
|
||||
assert.strictEqual(a.writer.canWrite, true); // clamped
|
||||
const [a, b] = duplex({ a: { budget: 16384 }, b: { budget: 32768 } });
|
||||
assert.strictEqual(a.writer.canWrite, true);
|
||||
assert.strictEqual(b.writer.canWrite, true);
|
||||
a.close();
|
||||
b.close();
|
||||
@@ -137,15 +134,13 @@ assert.throws(() => broadcast({ budget: 1.5 }), { code: 'ERR_OUT_OF_RANGE' });
|
||||
assert.throws(() => broadcast({ budget: Number.MAX_SAFE_INTEGER + 1 }),
|
||||
{ code: 'ERR_OUT_OF_RANGE' });
|
||||
|
||||
// Values < 16384 are clamped to 16384 (need a consumer for canWrite to work)
|
||||
// Values < 16384 are rejected
|
||||
assert.throws(() => broadcast({ budget: 0 }), { code: 'ERR_OUT_OF_RANGE' });
|
||||
assert.throws(() => broadcast({ budget: -1 }), { code: 'ERR_OUT_OF_RANGE' });
|
||||
assert.throws(() => broadcast({ budget: 16383 }), { code: 'ERR_OUT_OF_RANGE' });
|
||||
// 16384 is the minimum accepted value
|
||||
{
|
||||
const bc = broadcast({ budget: 0 });
|
||||
bc.broadcast.push();
|
||||
assert.strictEqual(bc.writer.canWrite, true);
|
||||
bc.writer.endSync();
|
||||
}
|
||||
{
|
||||
const bc = broadcast({ budget: -1 });
|
||||
const bc = broadcast({ budget: 16384 });
|
||||
bc.broadcast.push();
|
||||
assert.strictEqual(bc.writer.canWrite, true);
|
||||
bc.writer.endSync();
|
||||
@@ -217,9 +212,11 @@ assert.throws(() => share(from('a'), { budget: Number.MAX_SAFE_INTEGER + 1 }),
|
||||
assert.throws(() => share(from('a'), { signal: {} }), { code: 'ERR_INVALID_ARG_TYPE' });
|
||||
assert.throws(() => share(from('a'), { backpressure: 'bad' }), { code: 'ERR_INVALID_ARG_VALUE' });
|
||||
|
||||
// share() values < 16384 are clamped (no canWrite, but accepts the value)
|
||||
share(from('a'), { budget: 0 }).cancel();
|
||||
share(from('a'), { budget: -1 }).cancel();
|
||||
// share() values < 16384 are rejected
|
||||
assert.throws(() => share(from('a'), { budget: 0 }), { code: 'ERR_OUT_OF_RANGE' });
|
||||
assert.throws(() => share(from('a'), { budget: -1 }), { code: 'ERR_OUT_OF_RANGE' });
|
||||
// 16384 is the minimum, MAX_SAFE_INTEGER is accepted
|
||||
share(from('a'), { budget: 16384 }).cancel();
|
||||
share(from('a'), { budget: Number.MAX_SAFE_INTEGER }).cancel();
|
||||
|
||||
assert.throws(() => shareSync(42), { code: 'ERR_INVALID_ARG_TYPE' });
|
||||
@@ -230,9 +227,13 @@ assert.throws(() => shareSync(fromSync('a'), { budget: 1.5 }),
|
||||
assert.throws(() => shareSync(fromSync('a'), { budget: Number.MAX_SAFE_INTEGER + 1 }),
|
||||
{ code: 'ERR_OUT_OF_RANGE' });
|
||||
|
||||
// shareSync() values < 16384 are clamped (accepts the value)
|
||||
shareSync(fromSync('a'), { budget: 0 }).cancel();
|
||||
shareSync(fromSync('a'), { budget: -1 }).cancel();
|
||||
// shareSync() values < 16384 are rejected
|
||||
assert.throws(() => shareSync(fromSync('a'), { budget: 0 }),
|
||||
{ code: 'ERR_OUT_OF_RANGE' });
|
||||
assert.throws(() => shareSync(fromSync('a'), { budget: -1 }),
|
||||
{ code: 'ERR_OUT_OF_RANGE' });
|
||||
// 16384 is the minimum, MAX_SAFE_INTEGER is accepted
|
||||
shareSync(fromSync('a'), { budget: 16384 }).cancel();
|
||||
shareSync(fromSync('a'), { budget: Number.MAX_SAFE_INTEGER }).cancel();
|
||||
|
||||
// Share.from / SyncShare.fromSync reject non-iterable
|
||||
|
||||
Reference in new issue
Block a user