Skip to content

Commit a70e8eb

Browse files
jasnelladuh95
authored andcommitted
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 <jasnell@gmail.com> PR-URL: #66504 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
1 parent 4bb015c commit a70e8eb

3 files changed

Lines changed: 104 additions & 0 deletions

File tree

‎lib/internal/streams/iter/pull.js‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const {
1919
PromiseResolve,
2020
SymbolAsyncIterator,
2121
SymbolIterator,
22+
TypedArrayPrototypeGetByteLength,
2223
Uint8Array,
2324
} = primordials;
2425

@@ -54,6 +55,7 @@ const {
5455
const {
5556
IterResult,
5657
kNullOnceOption,
58+
callWithByteView,
5759
createBatchEntry,
5860
isTransformObject,
5961
parsePullArgs,
@@ -1063,6 +1065,16 @@ function pipeToSync(source, ...args) {
10631065

10641066
try {
10651067
for (const batch of pipeline) {
1068+
// Single chunk, the common case: no batch entry needed.
1069+
if (batch.length === 1) {
1070+
const chunk = batch[0];
1071+
if (callWithByteView(chunk, writer.writeSync, writer) === false) {
1072+
throw new ERR_OUT_OF_RANGE(
1073+
'write', 'within byte budget', 'budget exhausted');
1074+
}
1075+
totalBytes += TypedArrayPrototypeGetByteLength(chunk);
1076+
continue;
1077+
}
10661078
const entry = createBatchEntry(batch);
10671079
if (hasWritevSync && batch.length > 1) {
10681080
const accepted = writer.writevSync(validateBatchEntry(entry));
@@ -1190,6 +1202,17 @@ async function pipeTo(source, ...args) {
11901202
// Returns undefined on sync success, or a Promise when async fallback
11911203
// is required. Callers must check: const p = writeBatch(b); if (p) await p;
11921204
function writeBatch(batch) {
1205+
// Single chunk, the common case: check the view around writeSync()
1206+
// without allocating a batch entry, and create one only to fall back to
1207+
// the async path.
1208+
if (batch.length === 1 && hasWriteSync) {
1209+
const chunk = batch[0];
1210+
if (callWithByteView(chunk, writer.writeSync, writer)) {
1211+
totalBytes += TypedArrayPrototypeGetByteLength(chunk);
1212+
return;
1213+
}
1214+
return writeBatchAsyncFallback(createBatchEntry(batch), 0);
1215+
}
11931216
const entry = createBatchEntry(batch);
11941217
if (hasWritev && batch.length > 1) {
11951218
if (!hasWritevSync ||

‎lib/internal/streams/iter/utils.js‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const {
77
ArrayBufferPrototypeGetResizable,
88
ArrayPrototypePush,
99
ArrayPrototypeSlice,
10+
FunctionPrototypeCall,
1011
ObjectDefineProperty,
1112
ObjectFreeze,
1213
PromiseResolve,
@@ -295,6 +296,41 @@ function validateByteView(snapshot) {
295296
return value;
296297
}
297298

299+
/**
300+
* Call `method` on `receiver` with the byte view `value`, and throw if the
301+
* call resized or detached it, as validateByteView() does for a snapshot
302+
* taken just before the call. Used for single-chunk writes, the common case:
303+
* for views on an ArrayBuffer the snapshot is kept in locals instead of a
304+
* ByteViewSnapshot, so that nothing is allocated per chunk.
305+
* @param {Uint8Array} value
306+
* @param {Function} method
307+
* @param {object} receiver
308+
* @returns {any} The result of the call.
309+
*/
310+
function callWithByteView(value, method, receiver) {
311+
const buffer = TypedArrayPrototypeGetBuffer(value);
312+
if (isSharedArrayBuffer(buffer)) {
313+
const snapshot = snapshotByteView(value);
314+
const result = FunctionPrototypeCall(method, receiver, value);
315+
validateByteView(snapshot);
316+
return result;
317+
}
318+
const bufferByteLength = ArrayBufferPrototypeGetByteLength(buffer);
319+
const byteLength = TypedArrayPrototypeGetByteLength(value);
320+
const byteOffset = TypedArrayPrototypeGetByteOffset(value);
321+
const detached = ArrayBufferPrototypeGetDetached(buffer);
322+
const result = FunctionPrototypeCall(method, receiver, value);
323+
if (TypedArrayPrototypeGetBuffer(value) !== buffer ||
324+
ArrayBufferPrototypeGetByteLength(buffer) !== bufferByteLength ||
325+
TypedArrayPrototypeGetByteLength(value) !== byteLength ||
326+
TypedArrayPrototypeGetByteOffset(value) !== byteOffset ||
327+
ArrayBufferPrototypeGetDetached(buffer) !== detached) {
328+
throw new ERR_INVALID_STATE.TypeError(
329+
'Byte view was resized or detached after being accepted');
330+
}
331+
return result;
332+
}
333+
298334
/**
299335
* Validate an explicit `budget` option. The spec only requires the default
300336
* budget to be at least 16384 bytes; any positive explicit budget is valid.
@@ -602,6 +638,7 @@ module.exports = {
602638
kNullOnceOption,
603639
kPushDefaultBudget,
604640
kResolvedPromise,
641+
callWithByteView,
605642
concatBytes,
606643
convertChunks,
607644
createBatchEntry,

‎test/parallel/test-stream-iter-resizable-buffers.js‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,49 @@ async function testPipeRejectsWriterResize() {
167167
);
168168
}
169169

170+
// Single-chunk batches are checked around writeSync() without a snapshot
171+
// object. Detaching or resizing the view in writeSync() must still be
172+
// rejected, for views on ArrayBuffers and on growable SharedArrayBuffers.
173+
async function testPipeRejectsSyncWriteDetachOrResize() {
174+
const cases = [
175+
['detach', () => new ArrayBuffer(2), (buffer) => buffer.transfer()],
176+
['resize', () => new ArrayBuffer(1, { maxByteLength: 2 }),
177+
(buffer) => buffer.resize(2)],
178+
['grow shared', () => new SharedArrayBuffer(1, { maxByteLength: 2 }),
179+
(buffer) => buffer.grow(2)],
180+
];
181+
for (const [, createBuffer, change] of cases) {
182+
const asyncBuffer = createBuffer();
183+
await assert.rejects(pipeTo([new Uint8Array(asyncBuffer)], {
184+
writeSync() {
185+
change(asyncBuffer);
186+
return true;
187+
},
188+
write: common.mustNotCall(),
189+
fail: common.mustCall(),
190+
}), kResizeError);
191+
192+
const syncBuffer = createBuffer();
193+
assert.throws(() => pipeToSync([new Uint8Array(syncBuffer)], {
194+
writeSync() {
195+
change(syncBuffer);
196+
return true;
197+
},
198+
fail: common.mustCall(),
199+
}, { preventClose: true }), kResizeError);
200+
}
201+
202+
// An unchanged view is written; when writeSync() declines it, pipeTo()
203+
// falls back to write() for it.
204+
const chunk = Uint8Array.of(1, 2);
205+
const written = [];
206+
assert.strictEqual(await pipeTo([chunk], {
207+
writeSync: () => false,
208+
write(value) { written.push(value); },
209+
}, { preventClose: true }), 2);
210+
assert.deepStrictEqual(written, [chunk]);
211+
}
212+
170213
async function testConsumersRejectDetachedViews() {
171214
// Views of fixed-length buffers are tracked without a full snapshot; they
172215
// must still be rejected when detached after being accepted.
@@ -205,4 +248,5 @@ Promise.all([
205248
testConsumersRejectResizedViews(),
206249
testConsumersRejectDetachedViews(),
207250
testPipeRejectsWriterResize(),
251+
testPipeRejectsSyncWriteDetachOrResize(),
208252
]).then(common.mustCall());

0 commit comments

Comments
 (0)