Skip to content

Commit acd3794

Browse files
jasnelladuh95
authored andcommitted
stream: check stream/iter byte views by their byteLength alone
To detect that a byte view was resized or detached after being accepted, stream/iter recorded, for views not known to be of a fixed-length, non-shared buffer, a snapshot object with the view's buffer, the buffer's byteLength and detached state, and the view's byteLength and byteOffset. Telling the two cases apart read every view's buffer, which for a small typed array that V8 keeps on the heap, such as one just allocated by a transform, moves its contents to a new ArrayBuffer. What stream/iter accounts for a view is its byteLength, and a view whose bytes are no longer those accounted for has a different byteLength: a detached view, a view out of bounds of a shrunk buffer, and a length-tracking view of a resized or grown buffer. Record and check the byteLength alone, without reading the buffer, for every view. A fixed-length view of a resizable buffer that is resized while the view stays in bounds, whose bytes are unchanged, is no longer rejected. For 16-byte chunks, piping through a transform that copies each chunk is about 1.6 times faster, and 2.8 times with pipeToSync(); piping a sync generator of 64-chunk batches about 1.75 times faster; and piping a sync generator one chunk per batch to a writer with writeSync() about 1.2-1.3 times faster. 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 404e671 commit acd3794

4 files changed

Lines changed: 83 additions & 169 deletions

File tree

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

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -109,19 +109,19 @@ function collectSync(source, limit) {
109109
// Normalize source via fromSync() - accepts strings, ArrayBuffers, protocols, etc.
110110
const normalized = fromSync(source);
111111
const chunks = [];
112-
const checks = [];
112+
const byteLengths = [];
113113
let totalBytes = 0;
114114

115115
for (const batch of normalized) {
116116
for (let i = 0; i < batch.length; i++) {
117-
totalBytes += recordChunk(chunks, checks, batch[i]);
117+
totalBytes += recordChunk(chunks, byteLengths, batch[i]);
118118
if (limit !== undefined && totalBytes > limit) {
119119
throw new ERR_OUT_OF_RANGE('totalBytes', `<= ${limit}`, totalBytes);
120120
}
121121
}
122122
}
123123

124-
return validateRecordedChunks(chunks, checks);
124+
return validateRecordedChunks(chunks, byteLengths);
125125
}
126126

127127
/**
@@ -137,23 +137,23 @@ async function collectAsync(source, signal, limit) {
137137
// Normalize source via from() - accepts strings, ArrayBuffers, protocols, etc.
138138
const normalized = from(source);
139139
const chunks = [];
140-
const checks = [];
140+
const byteLengths = [];
141141

142142
// Fast path: no signal and no limit
143143
if (!signal && limit === undefined) {
144144
for await (const batch of normalized) {
145145
for (let i = 0; i < batch.length; i++) {
146-
recordChunk(chunks, checks, batch[i]);
146+
recordChunk(chunks, byteLengths, batch[i]);
147147
}
148148
}
149-
return validateRecordedChunks(chunks, checks);
149+
return validateRecordedChunks(chunks, byteLengths);
150150
}
151151

152-
// Slow path: with signal or limit checks
152+
// Slow path: with signal or limit byteLengths
153153
let totalBytes = 0;
154154
function recordBatch(batch) {
155155
for (let i = 0; i < batch.length; i++) {
156-
totalBytes += recordChunk(chunks, checks, batch[i]);
156+
totalBytes += recordChunk(chunks, byteLengths, batch[i]);
157157
if (limit !== undefined && totalBytes > limit) {
158158
throw new ERR_OUT_OF_RANGE('totalBytes', `<= ${limit}`, totalBytes);
159159
}
@@ -162,7 +162,7 @@ async function collectAsync(source, signal, limit) {
162162

163163
if (!signal) {
164164
for await (const batch of normalized) recordBatch(batch);
165-
return validateRecordedChunks(chunks, checks);
165+
return validateRecordedChunks(chunks, byteLengths);
166166
}
167167

168168
// Read as for await...of does, stopping once the signal aborts; see
@@ -187,7 +187,7 @@ async function collectAsync(source, signal, limit) {
187187
}
188188
}
189189
await raceSignal(normalized[SymbolAsyncIterator](), signal, state, consume);
190-
return validateRecordedChunks(chunks, checks);
190+
return validateRecordedChunks(chunks, byteLengths);
191191
}
192192

193193
/**

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

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1629,21 +1629,19 @@ function pipeToSync(source, ...args) {
16291629
}
16301630
if (!hasWritevSync) {
16311631
// Chunks written one at a time: snapshot them without an object for
1632-
// every chunk when possible.
1632+
// every chunk.
16331633
const fixed = snapshotFixedBatch(batch);
1634-
if (fixed !== null) {
1635-
for (let i = 0; i < batch.length; i++) {
1636-
const chunk = checkFixedBatchChunk(fixed, i);
1637-
const accepted = writer.writeSync(chunk);
1638-
checkFixedBatchChunk(fixed, i);
1639-
if (accepted === false) {
1640-
throw new ERR_OUT_OF_RANGE(
1641-
'write', 'within byte budget', 'budget exhausted');
1642-
}
1643-
totalBytes += fixed.byteLengths[i];
1634+
for (let i = 0; i < batch.length; i++) {
1635+
const chunk = checkFixedBatchChunk(fixed, i);
1636+
const accepted = writer.writeSync(chunk);
1637+
checkFixedBatchChunk(fixed, i);
1638+
if (accepted === false) {
1639+
throw new ERR_OUT_OF_RANGE(
1640+
'write', 'within byte budget', 'budget exhausted');
16441641
}
1645-
continue;
1642+
totalBytes += fixed.byteLengths[i];
16461643
}
1644+
continue;
16471645
}
16481646
const entry = createBatchEntry(batch);
16491647
if (hasWritevSync && batch.length > 1) {
@@ -1771,9 +1769,6 @@ async function pipeTo(source, ...args) {
17711769
}
17721770
}
17731771

1774-
// Write a batch using try-fallback: sync first, async if needed.
1775-
// Returns undefined on sync success, or a Promise when async fallback
1776-
// is required. Callers must check: const p = writeBatch(b); if (p) await p;
17771772
// Write a FixedBatch with writeSync(), like the loop at the end of
17781773
// writeBatch(), falling back to the async path for the rest of the batch.
17791774
function writeFixedBatch(fixed) {
@@ -1863,6 +1858,9 @@ async function pipeTo(source, ...args) {
18631858
}
18641859
}
18651860

1861+
// Write a batch using try-fallback: sync first, async if needed.
1862+
// Returns undefined on sync success, or a Promise when async fallback
1863+
// is required. Callers must check: const p = writeBatch(b); if (p) await p;
18661864
function writeBatch(batch) {
18671865
// Single chunk, the common case: check the view around writeSync()
18681866
// without allocating a batch entry, and create one only to fall back to
@@ -1876,8 +1874,7 @@ async function pipeTo(source, ...args) {
18761874
return writeBatchAsyncFallback(createBatchEntry(batch), 0);
18771875
}
18781876
if (!hasWritev && hasWriteSync) {
1879-
const fixed = snapshotFixedBatch(batch);
1880-
if (fixed !== null) return writeFixedBatch(fixed);
1877+
return writeFixedBatch(snapshotFixedBatch(batch));
18811878
}
18821879
const entry = createBatchEntry(batch);
18831880
if (hasWritev && batch.length > 1) {

0 commit comments

Comments
 (0)