From 2dc09ca9ca7bbed39d99b0ce22934383e3032254 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 30 Aug 2026 01:12:34 +0000 Subject: [PATCH] stream: canWrite and ondrain now reflect physical capacity Signed-off-by: James M Snell Assisted-by: Opencode PR-URL: https://github.com/nodejs/node/pull/65658 Reviewed-By: Trivikram Kamat --- doc/api/stream_iter.md | 20 +++++++---- lib/internal/streams/iter/broadcast.js | 14 ++++---- lib/internal/streams/iter/push.js | 6 ++-- ...test-stream-iter-broadcast-backpressure.js | 33 ++++++++++++++++++- test/parallel/test-stream-iter-push-writer.js | 31 +++++++++++++++++ 5 files changed, 87 insertions(+), 17 deletions(-) diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index 899f19b3867..32158e36cee 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -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'; diff --git a/lib/internal/streams/iter/broadcast.js b/lib/internal/streams/iter/broadcast.js index 0dc6364768d..4131fbf2b8e 100644 --- a/lib/internal/streams/iter/broadcast.js +++ b/lib/internal/streams/iter/broadcast.js @@ -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)) { diff --git a/lib/internal/streams/iter/push.js b/lib/internal/streams/iter/push.js index fa84cafdfde..c53fc7e902c 100644 --- a/lib/internal/streams/iter/push.js +++ b/lib/internal/streams/iter/push.js @@ -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; diff --git a/test/parallel/test-stream-iter-broadcast-backpressure.js b/test/parallel/test-stream-iter-broadcast-backpressure.js index 698f1821aee..6efa7eb54c7 100644 --- a/test/parallel/test-stream-iter-broadcast-backpressure.js +++ b/test/parallel/test-stream-iter-broadcast-backpressure.js @@ -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(), diff --git a/test/parallel/test-stream-iter-push-writer.js b/test/parallel/test-stream-iter-push-writer.js index dd6cf7d494b..4f47675da14 100644 --- a/test/parallel/test-stream-iter-push-writer.js +++ b/test/parallel/test-stream-iter-push-writer.js @@ -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(),