From 32c3d1ecded451de320edbe5b059fc7a62b23582 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 4 Oct 2026 03:21:12 +0000 Subject: [PATCH] stream: avoid batch entries for single-chunk pipeTo() writes pipeTo() and pipeToSync() created a batch entry for every batch, with an array and a seven-field snapshot per chunk, to reject a chunk that is resized or detached after being accepted. For the common single-chunk batch, check the view around writeSync() with the snapshot kept in locals instead, and create a batch entry in pipeTo() only to fall back to write(). Views on SharedArrayBuffers and batches of more chunks are still snapshotted as before, since writing one chunk can change another. With 16-byte chunks, one per batch, this saves about 100-175 bytes of allocation per chunk: pipeTo() from a sync source is about 17% faster, pipeToSync() about 15% faster and pipeTo() from an async generator about 7% faster. A new test covers detaching, resizing and growing a shared view in writeSync() for both, and the fallback to write(). Assisted-by: OpenCode Signed-off-by: James M Snell PR-URL: https://github.com/nodejs/node/pull/66504 Reviewed-By: Matteo Collina Reviewed-By: Trivikram Kamat --- lib/internal/streams/iter/pull.js | 23 ++++++++++ lib/internal/streams/iter/utils.js | 37 ++++++++++++++++ .../test-stream-iter-resizable-buffers.js | 44 +++++++++++++++++++ 3 files changed, 104 insertions(+) diff --git a/lib/internal/streams/iter/pull.js b/lib/internal/streams/iter/pull.js index fc8fa9902c1..f4b1bc4e7bb 100644 --- a/lib/internal/streams/iter/pull.js +++ b/lib/internal/streams/iter/pull.js @@ -19,6 +19,7 @@ const { PromiseResolve, SymbolAsyncIterator, SymbolIterator, + TypedArrayPrototypeGetByteLength, Uint8Array, } = primordials; @@ -54,6 +55,7 @@ const { const { IterResult, kNullOnceOption, + callWithByteView, createBatchEntry, isTransformObject, parsePullArgs, @@ -1063,6 +1065,16 @@ function pipeToSync(source, ...args) { try { for (const batch of pipeline) { + // Single chunk, the common case: no batch entry needed. + if (batch.length === 1) { + const chunk = batch[0]; + if (callWithByteView(chunk, writer.writeSync, writer) === false) { + throw new ERR_OUT_OF_RANGE( + 'write', 'within byte budget', 'budget exhausted'); + } + totalBytes += TypedArrayPrototypeGetByteLength(chunk); + continue; + } const entry = createBatchEntry(batch); if (hasWritevSync && batch.length > 1) { const accepted = writer.writevSync(validateBatchEntry(entry)); @@ -1190,6 +1202,17 @@ async function pipeTo(source, ...args) { // 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) { + // Single chunk, the common case: check the view around writeSync() + // without allocating a batch entry, and create one only to fall back to + // the async path. + if (batch.length === 1 && hasWriteSync) { + const chunk = batch[0]; + if (callWithByteView(chunk, writer.writeSync, writer)) { + totalBytes += TypedArrayPrototypeGetByteLength(chunk); + return; + } + return writeBatchAsyncFallback(createBatchEntry(batch), 0); + } const entry = createBatchEntry(batch); if (hasWritev && batch.length > 1) { if (!hasWritevSync || diff --git a/lib/internal/streams/iter/utils.js b/lib/internal/streams/iter/utils.js index 8c2835acd8b..bc57920bcbc 100644 --- a/lib/internal/streams/iter/utils.js +++ b/lib/internal/streams/iter/utils.js @@ -7,6 +7,7 @@ const { ArrayBufferPrototypeGetResizable, ArrayPrototypePush, ArrayPrototypeSlice, + FunctionPrototypeCall, ObjectDefineProperty, ObjectFreeze, PromiseResolve, @@ -295,6 +296,41 @@ function validateByteView(snapshot) { return value; } +/** + * Call `method` on `receiver` with the byte view `value`, and throw if the + * call resized or detached it, as validateByteView() does for a snapshot + * taken just before the call. Used for single-chunk writes, the common case: + * for views on an ArrayBuffer the snapshot is kept in locals instead of a + * ByteViewSnapshot, so that nothing is allocated per chunk. + * @param {Uint8Array} value + * @param {Function} method + * @param {object} receiver + * @returns {any} The result of the call. + */ +function callWithByteView(value, method, receiver) { + const buffer = TypedArrayPrototypeGetBuffer(value); + if (isSharedArrayBuffer(buffer)) { + const snapshot = snapshotByteView(value); + const result = FunctionPrototypeCall(method, receiver, value); + validateByteView(snapshot); + return result; + } + const bufferByteLength = ArrayBufferPrototypeGetByteLength(buffer); + const byteLength = TypedArrayPrototypeGetByteLength(value); + const byteOffset = TypedArrayPrototypeGetByteOffset(value); + const detached = ArrayBufferPrototypeGetDetached(buffer); + const result = FunctionPrototypeCall(method, receiver, value); + if (TypedArrayPrototypeGetBuffer(value) !== buffer || + ArrayBufferPrototypeGetByteLength(buffer) !== bufferByteLength || + TypedArrayPrototypeGetByteLength(value) !== byteLength || + TypedArrayPrototypeGetByteOffset(value) !== byteOffset || + ArrayBufferPrototypeGetDetached(buffer) !== detached) { + throw new ERR_INVALID_STATE.TypeError( + 'Byte view was resized or detached after being accepted'); + } + return result; +} + /** * Validate an explicit `budget` option. The spec only requires the default * budget to be at least 16384 bytes; any positive explicit budget is valid. @@ -602,6 +638,7 @@ module.exports = { kNullOnceOption, kPushDefaultBudget, kResolvedPromise, + callWithByteView, concatBytes, convertChunks, createBatchEntry, diff --git a/test/parallel/test-stream-iter-resizable-buffers.js b/test/parallel/test-stream-iter-resizable-buffers.js index 91f7429ec12..ab75d07c455 100644 --- a/test/parallel/test-stream-iter-resizable-buffers.js +++ b/test/parallel/test-stream-iter-resizable-buffers.js @@ -167,6 +167,49 @@ async function testPipeRejectsWriterResize() { ); } +// Single-chunk batches are checked around writeSync() without a snapshot +// object. Detaching or resizing the view in writeSync() must still be +// rejected, for views on ArrayBuffers and on growable SharedArrayBuffers. +async function testPipeRejectsSyncWriteDetachOrResize() { + const cases = [ + ['detach', () => new ArrayBuffer(2), (buffer) => buffer.transfer()], + ['resize', () => new ArrayBuffer(1, { maxByteLength: 2 }), + (buffer) => buffer.resize(2)], + ['grow shared', () => new SharedArrayBuffer(1, { maxByteLength: 2 }), + (buffer) => buffer.grow(2)], + ]; + for (const [, createBuffer, change] of cases) { + const asyncBuffer = createBuffer(); + await assert.rejects(pipeTo([new Uint8Array(asyncBuffer)], { + writeSync() { + change(asyncBuffer); + return true; + }, + write: common.mustNotCall(), + fail: common.mustCall(), + }), kResizeError); + + const syncBuffer = createBuffer(); + assert.throws(() => pipeToSync([new Uint8Array(syncBuffer)], { + writeSync() { + change(syncBuffer); + return true; + }, + fail: common.mustCall(), + }, { preventClose: true }), kResizeError); + } + + // An unchanged view is written; when writeSync() declines it, pipeTo() + // falls back to write() for it. + const chunk = Uint8Array.of(1, 2); + const written = []; + assert.strictEqual(await pipeTo([chunk], { + writeSync: () => false, + write(value) { written.push(value); }, + }, { preventClose: true }), 2); + assert.deepStrictEqual(written, [chunk]); +} + async function testConsumersRejectDetachedViews() { // Views of fixed-length buffers are tracked without a full snapshot; they // must still be rejected when detached after being accepted. @@ -205,4 +248,5 @@ Promise.all([ testConsumersRejectResizedViews(), testConsumersRejectDetachedViews(), testPipeRejectsWriterResize(), + testPipeRejectsSyncWriteDetachOrResize(), ]).then(common.mustCall());