mirror of
https://github.com/nodejs/node.git
synced 2026-11-27 17:52:27 -05:00
stream: canWrite and ondrain now reflect physical capacity
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode PR-URL: https://github.com/nodejs/node/pull/65658 Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
This commit is contained in:
1 parent
2f494cb7aa
commit
2dc09ca9ca
5 files changed
+87
-17
No files matched your search
+14
-6
@@ -417,9 +417,13 @@ writer.fail(err); // Always synchronous, no fallback needed
|
||||
|
||||
* {boolean|null}
|
||||
|
||||
Returns `true` if the next write is likely to be accepted (buffered data is
|
||||
below capacity), `false` if backpressure is active, or `null` if the writer
|
||||
is closed or the consumer has disconnected.
|
||||
Returns `true` if the slots buffer has physical capacity (buffered data is
|
||||
below the configured byte budget), `false` if the budget is exhausted, or
|
||||
`null` if the writer is closed or the consumer has disconnected.
|
||||
|
||||
This reports physical capacity independently of the backpressure policy. With
|
||||
`'drop-oldest'` or `'drop-newest'`, writes still complete when this is `false`
|
||||
by evicting buffered data or discarding the incoming data, respectively.
|
||||
|
||||
This is a hint, not a guarantee: the state can change between the check and
|
||||
the write. Use [`ondrain()`][] to wait for capacity rather than polling.
|
||||
@@ -1055,9 +1059,13 @@ added: v25.9.0
|
||||
* `drainable` {Object} An object implementing the drainable protocol.
|
||||
* Returns: {Promise|null}
|
||||
|
||||
Wait for a drainable writer's backpressure to clear. Returns `null` if
|
||||
the object does not implement the drainable protocol, or a promise that
|
||||
fulfills with `true` when the writer can accept more data.
|
||||
Wait for a drainable writer to regain physical buffer capacity. Returns `null`
|
||||
if the object does not implement the drainable protocol, or a promise that
|
||||
fulfills with `true` when buffered data falls below the byte budget.
|
||||
|
||||
For writers using `'drop-oldest'` or `'drop-newest'`, this waits for physical
|
||||
capacity even though writes do not block. This allows producers to avoid data
|
||||
loss by waiting before writing.
|
||||
|
||||
```mjs
|
||||
import { push, ondrain, text } from 'node:stream/iter';
|
||||
|
||||
@@ -310,6 +310,7 @@ class BroadcastImpl {
|
||||
if (this.#ended || this.#cancelled) return false;
|
||||
|
||||
const batchSize = entry.byteLength;
|
||||
let droppedOldest = false;
|
||||
|
||||
// Skip empty chunks -- zero-byte writes would accumulate infinitely
|
||||
// without ever triggering backpressure under a byte-budget model.
|
||||
@@ -321,6 +322,7 @@ class BroadcastImpl {
|
||||
case 'unbounded':
|
||||
return false;
|
||||
case 'drop-oldest':
|
||||
droppedOldest = true;
|
||||
while (this.#bufferedBytes >= this.#options.budget &&
|
||||
this.#buffer.length > 0) {
|
||||
const evicted = this.#buffer.shift();
|
||||
@@ -343,6 +345,10 @@ class BroadcastImpl {
|
||||
this.#buffer.push(entry);
|
||||
this.#bufferedBytes += batchSize;
|
||||
this.#notifyConsumers();
|
||||
if (droppedOldest &&
|
||||
this.#bufferedBytes < this.#options.budget) {
|
||||
this[kOnBufferDrained]?.();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -399,15 +405,13 @@ class BroadcastImpl {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the next write is likely to be accepted.
|
||||
* Check whether the slots buffer has capacity.
|
||||
* Returns null if ended/cancelled, true/false otherwise.
|
||||
* @returns {boolean | null}
|
||||
*/
|
||||
[kCanWrite]() {
|
||||
if (this.#ended || this.#cancelled) return null;
|
||||
if ((this.#options.backpressure === 'strict' ||
|
||||
this.#options.backpressure === 'unbounded') &&
|
||||
this.#bufferedBytes >= this.#options.budget) {
|
||||
if (this.#bufferedBytes >= this.#options.budget) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -666,7 +670,6 @@ class BroadcastWriter {
|
||||
|
||||
writeSync(chunk) {
|
||||
if (this.#state !== 'open') return false;
|
||||
if (!this.#broadcast[kCanWrite]()) return false;
|
||||
const converted =
|
||||
toUint8Array(chunk);
|
||||
const batch = createBatchEntry([converted]);
|
||||
@@ -680,7 +683,6 @@ class BroadcastWriter {
|
||||
writevSync(chunks) {
|
||||
validateArray(chunks, 'chunks');
|
||||
if (this.#state !== 'open') return false;
|
||||
if (!this.#broadcast[kCanWrite]()) return false;
|
||||
const converted = convertChunks(chunks);
|
||||
const batch = createBatchEntry(converted);
|
||||
if (this.#broadcast[kWrite](batch)) {
|
||||
|
||||
@@ -152,7 +152,7 @@ class PushQueue {
|
||||
// ===========================================================================
|
||||
|
||||
/**
|
||||
* Check if the next write is likely to be accepted.
|
||||
* Check whether the slots buffer has capacity.
|
||||
* Returns null if writer is closed/errored or consumer has terminated.
|
||||
* @returns {boolean | null}
|
||||
*/
|
||||
@@ -160,9 +160,7 @@ class PushQueue {
|
||||
if (this.#writerState !== 'open' || this.#consumerState !== 'active') {
|
||||
return null;
|
||||
}
|
||||
if ((this.#backpressure === 'strict' ||
|
||||
this.#backpressure === 'unbounded') &&
|
||||
this.#bufferedBytes >= this.#budget) {
|
||||
if (this.#bufferedBytes >= this.#budget) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
const common = require('../common');
|
||||
const assert = require('assert');
|
||||
const { broadcast, text } = require('stream/iter');
|
||||
const { broadcast, ondrain, text } = require('stream/iter');
|
||||
|
||||
// =============================================================================
|
||||
// Backpressure policies
|
||||
@@ -47,6 +47,36 @@ async function testDropNewest() {
|
||||
assert.strictEqual(data, 'K'.repeat(16384));
|
||||
}
|
||||
|
||||
async function testDropPoliciesReportPhysicalCapacity() {
|
||||
const chunk = new Uint8Array(16384);
|
||||
|
||||
for (const backpressure of ['drop-oldest', 'drop-newest']) {
|
||||
const { writer, broadcast: bc } = broadcast({
|
||||
budget: chunk.byteLength,
|
||||
backpressure,
|
||||
});
|
||||
const iterator = bc.push()[Symbol.asyncIterator]();
|
||||
|
||||
assert.strictEqual(writer.writeSync(chunk), true);
|
||||
assert.strictEqual(writer.canWrite, false);
|
||||
|
||||
let drained = false;
|
||||
const drain = ondrain(writer);
|
||||
drain.then(common.mustCall(() => { drained = true; }));
|
||||
|
||||
// Drop policies still accept writes despite having no physical capacity.
|
||||
assert.strictEqual(writer.writeSync(chunk), true);
|
||||
assert.strictEqual(writer.canWrite, false);
|
||||
await new Promise(setImmediate);
|
||||
assert.strictEqual(drained, false);
|
||||
|
||||
assert.strictEqual((await iterator.next()).done, false);
|
||||
assert.strictEqual(await drain, true);
|
||||
assert.strictEqual(writer.canWrite, true);
|
||||
bc.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Block backpressure
|
||||
// =============================================================================
|
||||
@@ -269,6 +299,7 @@ async function testEndSyncReturnValue() {
|
||||
Promise.all([
|
||||
testDropOldest(),
|
||||
testDropNewest(),
|
||||
testDropPoliciesReportPhysicalCapacity(),
|
||||
testBlockBackpressure(),
|
||||
testBlockBackpressureContent(),
|
||||
testStrictBackpressureOverflow(),
|
||||
|
||||
@@ -19,6 +19,36 @@ async function testOndrain() {
|
||||
assert.strictEqual(ondrain(writer), null);
|
||||
}
|
||||
|
||||
async function testDropPoliciesReportPhysicalCapacity() {
|
||||
const chunk = new Uint8Array(16384);
|
||||
|
||||
for (const backpressure of ['drop-oldest', 'drop-newest']) {
|
||||
const { writer, readable } = push({
|
||||
budget: chunk.byteLength,
|
||||
backpressure,
|
||||
});
|
||||
const iterator = readable[Symbol.asyncIterator]();
|
||||
|
||||
assert.strictEqual(writer.writeSync(chunk), true);
|
||||
assert.strictEqual(writer.canWrite, false);
|
||||
|
||||
let drained = false;
|
||||
const drain = ondrain(writer);
|
||||
drain.then(common.mustCall(() => { drained = true; }));
|
||||
|
||||
// Drop policies still accept writes despite having no physical capacity.
|
||||
assert.strictEqual(writer.writeSync(chunk), true);
|
||||
assert.strictEqual(writer.canWrite, false);
|
||||
await new Promise(setImmediate);
|
||||
assert.strictEqual(drained, false);
|
||||
|
||||
assert.strictEqual((await iterator.next()).done, false);
|
||||
assert.strictEqual(await drain, true);
|
||||
assert.strictEqual(writer.canWrite, true);
|
||||
await iterator.return();
|
||||
}
|
||||
}
|
||||
|
||||
async function testOndrainNonDrainable() {
|
||||
// Non-drainable objects return null
|
||||
assert.strictEqual(ondrain(null), null);
|
||||
@@ -586,6 +616,7 @@ async function testFailRejectsPendingReadWithFalsyReason() {
|
||||
|
||||
Promise.all([
|
||||
testOndrain(),
|
||||
testDropPoliciesReportPhysicalCapacity(),
|
||||
testOndrainNonDrainable(),
|
||||
testWriteWithSignalRejects(),
|
||||
testWriteWithPreAbortedSignal(),
|
||||
|
||||
Reference in new issue
Block a user