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());