stream: ensure stability of stored metadata

Signed-off-by: James M Snell <jasnell@gmail.com>
Assisted-by: Opencode
PR-URL: https://github.com/nodejs/node/pull/65652
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
James M Snell committed 2026-09-02 13:14:31 +00:00
1 parent 535f934000
commit fdc3770ea7
7 files changed
+463 -157

No files matched your search

+54 -45
View File
@@ -21,7 +21,6 @@ const {
SymbolAsyncDispose,
SymbolAsyncIterator,
SymbolDispose,
TypedArrayPrototypeGetByteLength,
} = primordials;
const { lazyDOMException } = require('internal/util');
@@ -59,6 +58,7 @@ const {
kMultiConsumerDefaultBudget,
kResolvedPromise,
convertChunks,
createBatchEntry,
getWriterSignal,
getMinCursor,
hasProtocol,
@@ -67,6 +67,7 @@ const {
wrapError,
toUint8Array,
validateBackpressure,
validateBatchEntry,
} = require('internal/streams/iter/utils');
const {
@@ -215,7 +216,8 @@ class BroadcastImpl {
const bufferIndex = state.cursor - self.#bufferStart;
if (bufferIndex < self.#buffer.length) {
const chunk = self.#buffer.get(bufferIndex);
const chunk = self.#readEntry(self.#buffer.get(bufferIndex));
if (chunk === null) return PromiseReject(self.#error);
const cursor = state.cursor;
state.cursor++;
if (cursor === self.#cachedMinCursor &&
@@ -304,10 +306,10 @@ class BroadcastImpl {
// Methods accessed by BroadcastWriter via symbol keys
[kWrite](chunk) {
[kWrite](entry) {
if (this.#ended || this.#cancelled) return false;
const batchSize = this.#batchByteSize(chunk);
const batchSize = entry.byteLength;
// Skip empty chunks -- zero-byte writes would accumulate infinitely
// without ever triggering backpressure under a byte-budget model.
@@ -322,7 +324,7 @@ class BroadcastImpl {
while (this.#bufferedBytes >= this.#options.budget &&
this.#buffer.length > 0) {
const evicted = this.#buffer.shift();
this.#bufferedBytes -= this.#batchByteSize(evicted);
this.#bufferedBytes -= evicted.byteLength;
this.#bufferStart++;
}
for (const consumer of this.#consumers) {
@@ -338,7 +340,7 @@ class BroadcastImpl {
}
}
this.#buffer.push(chunk);
this.#buffer.push(entry);
this.#bufferedBytes += batchSize;
this.#notifyConsumers();
return true;
@@ -352,7 +354,8 @@ class BroadcastImpl {
while (consumer.resolve) {
const bufferIndex = consumer.cursor - this.#bufferStart;
if (bufferIndex < this.#buffer.length) {
const chunk = this.#buffer.get(bufferIndex);
const chunk = this.#readEntry(this.#buffer.get(bufferIndex));
if (chunk === null) return;
const cursor = consumer.cursor;
consumer.cursor++;
if (cursor === this.#cachedMinCursor &&
@@ -433,7 +436,7 @@ class BroadcastImpl {
if (trimCount > 0) {
for (let i = 0; i < trimCount; i++) {
const evicted = this.#buffer.get(i);
this.#bufferedBytes -= this.#batchByteSize(evicted);
this.#bufferedBytes -= evicted.byteLength;
}
this.#buffer.trimFront(trimCount);
this.#bufferStart = this.#cachedMinCursor;
@@ -445,12 +448,16 @@ class BroadcastImpl {
}
}
#batchByteSize(batch) {
let size = 0;
for (let i = 0; i < batch.length; i++) {
size += TypedArrayPrototypeGetByteLength(batch[i]);
#readEntry(entry) {
try {
return validateBatchEntry(entry);
} catch (error) {
this.#writer.fail(error);
if (this.#error === undefined) this[kAbort](error);
this.#buffer.clear();
this.#bufferedBytes = 0;
return null;
}
return size;
}
#notifyConsumers() {
@@ -464,7 +471,8 @@ class BroadcastImpl {
if (consumer.resolve) {
const bufferIndex = consumer.cursor - this.#bufferStart;
if (bufferIndex < this.#buffer.length) {
const chunk = this.#buffer.get(bufferIndex);
const chunk = this.#readEntry(this.#buffer.get(bufferIndex));
if (chunk === null) return;
const cursor = consumer.cursor;
consumer.cursor++;
if (cursor === this.#cachedMinCursor &&
@@ -587,8 +595,9 @@ class BroadcastWriter {
// Fast path: no signal, writer open, buffer has space
if (this.#canUseWriteFastPath(signal)) {
const converted = toUint8Array(chunk);
this.#broadcast[kWrite]([converted]);
this.#totalBytes += TypedArrayPrototypeGetByteLength(converted);
const batch = createBatchEntry([converted]);
this.#broadcast[kWrite](batch);
this.#totalBytes += batch.byteLength;
return kResolvedPromise;
}
return this.#writevSlow([chunk], signal);
@@ -600,10 +609,9 @@ class BroadcastWriter {
// Fast path: no signal, writer open, buffer has space
if (this.#canUseWriteFastPath(signal)) {
const converted = convertChunks(chunks);
this.#broadcast[kWrite](converted);
for (let i = 0; i < converted.length; i++) {
this.#totalBytes += TypedArrayPrototypeGetByteLength(converted[i]);
}
const batch = createBatchEntry(converted);
this.#broadcast[kWrite](batch);
this.#totalBytes += batch.byteLength;
return kResolvedPromise;
}
return this.#writevSlow(chunks, signal);
@@ -619,12 +627,10 @@ class BroadcastWriter {
signal?.throwIfAborted();
const converted = convertChunks(chunks);
const batch = createBatchEntry(convertChunks(chunks));
if (this.#broadcast[kWrite](converted)) {
for (let i = 0; i < converted.length; i++) {
this.#totalBytes += TypedArrayPrototypeGetByteLength(converted[i]);
}
if (this.#broadcast[kWrite](batch)) {
this.#totalBytes += batch.byteLength;
return;
}
@@ -636,11 +642,11 @@ class BroadcastWriter {
'Backpressure violation: too many pending writes. ' +
'Await each write() call to respect backpressure.');
}
return this.#createPendingWrite(converted, signal);
return this.#createPendingWrite(batch, signal);
}
// 'unbounded' policy
return this.#createPendingWrite(converted, signal);
return this.#createPendingWrite(batch, signal);
}
writeSync(chunk) {
@@ -648,8 +654,9 @@ class BroadcastWriter {
if (!this.#broadcast[kCanWrite]()) return false;
const converted =
toUint8Array(chunk);
if (this.#broadcast[kWrite]([converted])) {
this.#totalBytes += TypedArrayPrototypeGetByteLength(converted);
const batch = createBatchEntry([converted]);
if (this.#broadcast[kWrite](batch)) {
this.#totalBytes += batch.byteLength;
return true;
}
return false;
@@ -660,10 +667,9 @@ class BroadcastWriter {
if (this.#state !== 'open') return false;
if (!this.#broadcast[kCanWrite]()) return false;
const converted = convertChunks(chunks);
if (this.#broadcast[kWrite](converted)) {
for (let i = 0; i < converted.length; i++) {
this.#totalBytes += TypedArrayPrototypeGetByteLength(converted[i]);
}
const batch = createBatchEntry(converted);
if (this.#broadcast[kWrite](batch)) {
this.#totalBytes += batch.byteLength;
return true;
}
return false;
@@ -752,9 +758,9 @@ class BroadcastWriter {
* promise rejects. Signal listeners are cleaned up on normal resolution.
* @returns {Promise<void>}
*/
#createPendingWrite(chunk, signal) {
#createPendingWrite(batch, signal) {
const { promise, resolve, reject } = PromiseWithResolvers();
const entry = { __proto__: null, chunk, resolve, reject };
const entry = { __proto__: null, batch, resolve, reject };
this.#pendingWrites.push(entry);
if (signal) {
wireBroadcastWriteSignal(entry, signal, resolve, reject, this);
@@ -765,14 +771,17 @@ class BroadcastWriter {
#resolvePendingWrites() {
while (this.#pendingWrites.length > 0 && this.#broadcast[kCanWrite]()) {
const pending = this.#pendingWrites.shift();
if (this.#broadcast[kWrite](pending.chunk)) {
for (let i = 0; i < pending.chunk.length; i++) {
this.#totalBytes += TypedArrayPrototypeGetByteLength(pending.chunk[i]);
try {
validateBatchEntry(pending.batch);
if (this.#broadcast[kWrite](pending.batch)) {
this.#totalBytes += pending.batch.byteLength;
pending.resolve();
} else {
this.#pendingWrites.unshift(pending);
break;
}
pending.resolve();
} else {
this.#pendingWrites.unshift(pending);
break;
} catch (error) {
pending.reject(error);
}
}
this.#finishEndIfReady();
@@ -806,18 +815,18 @@ function wireBroadcastWriteSignal(entry, signal, resolve, reject, self) {
const pendingWrites = getBroadcastPendingWrites(self);
const idx = pendingWrites.indexOf(entry);
if (idx !== -1) pendingWrites.removeAt(idx);
entry.chunk = null;
entry.batch = null;
reject(signal.reason ?? lazyDOMException('Aborted', 'AbortError'));
if (idx !== -1) self[kPendingWriteRemoved]();
};
entry.resolve = function() {
signal.removeEventListener('abort', onAbort);
entry.chunk = null;
entry.batch = null;
resolve();
};
entry.reject = function(reason) {
signal.removeEventListener('abort', onAbort);
entry.chunk = null;
entry.batch = null;
reject(reason);
};
signal.addEventListener('abort', onAbort, { __proto__: null, once: true });
+29 -18
View File
@@ -54,6 +54,8 @@ const {
const {
concatBytes,
createBatchEntry,
validateBatchEntry,
yieldAbortable,
} = require('internal/streams/iter/utils');
@@ -89,6 +91,17 @@ function isMergeOptions(value) {
// Shared chunk collection helpers
// =============================================================================
function flattenBatchEntries(entries) {
const chunks = [];
for (let i = 0; i < entries.length; i++) {
const batch = validateBatchEntry(entries[i]);
for (let j = 0; j < batch.length; j++) {
ArrayPrototypePush(chunks, batch[j]);
}
}
return chunks;
}
/**
* Collect chunks from a sync source into an array.
* @param {Iterable<Uint8Array[]>} source
@@ -98,23 +111,23 @@ function isMergeOptions(value) {
function collectSync(source, limit) {
// Normalize source via fromSync() - accepts strings, ArrayBuffers, protocols, etc.
const normalized = fromSync(source);
const chunks = [];
const entries = [];
let totalBytes = 0;
for (const batch of normalized) {
for (let i = 0; i < batch.length; i++) {
const chunk = batch[i];
if (limit !== undefined) {
totalBytes += TypedArrayPrototypeGetByteLength(chunk);
const entry = createBatchEntry(batch);
if (limit !== undefined) {
for (let i = 0; i < entry.views.length; i++) {
totalBytes += entry.views[i].byteLength;
if (totalBytes > limit) {
throw new ERR_OUT_OF_RANGE('totalBytes', `<= ${limit}`, totalBytes);
}
}
ArrayPrototypePush(chunks, chunk);
}
ArrayPrototypePush(entries, entry);
}
return chunks;
return flattenBatchEntries(entries);
}
/**
@@ -131,16 +144,14 @@ async function collectAsync(source, signal, limit) {
const abortableSource = signal && isAsyncIterable(source) ?
yieldAbortable(source, signal) : source;
const normalized = from(abortableSource);
const chunks = [];
const entries = [];
// Fast path: no signal and no limit
if (!signal && limit === undefined) {
for await (const batch of normalized) {
for (let i = 0; i < batch.length; i++) {
ArrayPrototypePush(chunks, batch[i]);
}
ArrayPrototypePush(entries, createBatchEntry(batch));
}
return chunks;
return flattenBatchEntries(entries);
}
// Slow path: with signal or limit checks
@@ -149,19 +160,19 @@ async function collectAsync(source, signal, limit) {
for await (const batch of iterable) {
signal?.throwIfAborted();
for (let i = 0; i < batch.length; i++) {
const chunk = batch[i];
if (limit !== undefined) {
totalBytes += TypedArrayPrototypeGetByteLength(chunk);
const entry = createBatchEntry(batch);
if (limit !== undefined) {
for (let i = 0; i < entry.views.length; i++) {
totalBytes += entry.views[i].byteLength;
if (totalBytes > limit) {
throw new ERR_OUT_OF_RANGE('totalBytes', `<= ${limit}`, totalBytes);
}
}
ArrayPrototypePush(chunks, chunk);
}
ArrayPrototypePush(entries, entry);
}
return chunks;
return flattenBatchEntries(entries);
}
/**
+51 -35
View File
@@ -17,7 +17,6 @@ const {
PromiseResolve,
SymbolAsyncIterator,
SymbolIterator,
TypedArrayPrototypeGetByteLength,
Uint8Array,
} = primordials;
@@ -52,11 +51,14 @@ const {
} = require('internal/streams/iter/from');
const {
createBatchEntry,
isPullOptions,
isTransform,
isTransformObject,
parsePullArgs,
toUint8Array,
validateBatchEntry,
validateByteView,
wrapError,
yieldAbortable,
} = require('internal/streams/iter/utils');
@@ -992,22 +994,26 @@ function pipeToSync(source, ...args) {
try {
for (const batch of pipeline) {
const entry = createBatchEntry(batch);
if (hasWritevSync && batch.length > 1) {
if (writer.writevSync(batch) === false) {
const accepted = writer.writevSync(validateBatchEntry(entry));
validateBatchEntry(entry);
if (accepted === false) {
throw new ERR_OUT_OF_RANGE(
'write', 'within byte budget', 'budget exhausted');
}
for (let i = 0; i < batch.length; i++) {
totalBytes += TypedArrayPrototypeGetByteLength(batch[i]);
}
totalBytes += entry.byteLength;
} else {
for (let i = 0; i < batch.length; i++) {
const chunk = batch[i];
if (writer.writeSync(chunk) === false) {
for (let i = 0; i < entry.views.length; i++) {
const view = entry.views[i];
const chunk = validateByteView(view);
const accepted = writer.writeSync(chunk);
validateByteView(view);
if (accepted === false) {
throw new ERR_OUT_OF_RANGE(
'write', 'within byte budget', 'budget exhausted');
}
totalBytes += TypedArrayPrototypeGetByteLength(chunk);
totalBytes += view.byteLength;
}
}
}
@@ -1056,19 +1062,26 @@ async function pipeTo(source, ...args) {
// Async fallback for writeBatch when sync write fails partway through.
// Continues writing from batch[startIndex] using async write().
async function writeBatchAsyncFallback(batch, startIndex) {
for (let i = startIndex; i < batch.length; i++) {
const chunk = batch[i];
if (hasWriteSync && writer.writeSync(chunk)) {
// Sync retry succeeded
} else {
const result = writer.write(
chunk, signal ? { __proto__: null, signal } : undefined);
if (result !== undefined) {
await result;
async function writeBatchAsyncFallback(entry, startIndex) {
for (let i = startIndex; i < entry.views.length; i++) {
const view = entry.views[i];
if (hasWriteSync) {
const chunk = validateByteView(view);
if (writer.writeSync(chunk)) {
validateByteView(view);
totalBytes += view.byteLength;
continue;
}
validateByteView(view);
}
totalBytes += TypedArrayPrototypeGetByteLength(chunk);
const result = writer.write(
validateByteView(view),
signal ? { __proto__: null, signal } : undefined);
if (result !== undefined) {
await result;
}
validateByteView(view);
totalBytes += view.byteLength;
}
}
@@ -1076,34 +1089,37 @@ 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) {
const entry = createBatchEntry(batch);
if (hasWritev && batch.length > 1) {
if (!hasWritevSync || !writer.writevSync(batch)) {
if (!hasWritevSync ||
!writer.writevSync(validateBatchEntry(entry))) {
validateBatchEntry(entry);
const opts = signal ? { __proto__: null, signal } : undefined;
const writevResult = writer.writev(batch, opts);
const writevResult = writer.writev(validateBatchEntry(entry), opts);
if (writevResult === undefined) {
for (let i = 0; i < batch.length; i++) {
totalBytes += TypedArrayPrototypeGetByteLength(batch[i]);
}
validateBatchEntry(entry);
totalBytes += entry.byteLength;
return;
}
return PromisePrototypeThen(PromiseResolve(writevResult), () => {
for (let i = 0; i < batch.length; i++) {
totalBytes += TypedArrayPrototypeGetByteLength(batch[i]);
}
validateBatchEntry(entry);
totalBytes += entry.byteLength;
});
}
for (let i = 0; i < batch.length; i++) {
totalBytes += TypedArrayPrototypeGetByteLength(batch[i]);
}
validateBatchEntry(entry);
totalBytes += entry.byteLength;
return;
}
for (let i = 0; i < batch.length; i++) {
const chunk = batch[i];
for (let i = 0; i < entry.views.length; i++) {
const view = entry.views[i];
const chunk = validateByteView(view);
if (!hasWriteSync || !writer.writeSync(chunk)) {
if (hasWriteSync) validateByteView(view);
// Sync path failed at index i - fall back to async for the rest.
return writeBatchAsyncFallback(batch, i);
return writeBatchAsyncFallback(entry, i);
}
totalBytes += TypedArrayPrototypeGetByteLength(chunk);
validateByteView(view);
totalBytes += view.byteLength;
}
}
+51 -37
View File
@@ -15,7 +15,6 @@ const {
SymbolAsyncDispose,
SymbolAsyncIterator,
SymbolDispose,
TypedArrayPrototypeGetByteLength,
} = primordials;
const {
@@ -37,12 +36,14 @@ const {
const {
kPushDefaultBudget,
kResolvedPromise,
createBatchEntry,
onSignalAbort,
toUint8Array,
convertChunks,
getWriterSignal,
parsePullArgs,
validateBackpressure,
validateBatchEntry,
} = require('internal/streams/iter/utils');
const {
@@ -185,7 +186,11 @@ class PushQueue {
if (this.#writerState !== 'open') return false;
if (this.#consumerState !== 'active') return false;
const batchSize = this.#batchByteSize(chunks);
return this.#writeEntry(createBatchEntry(chunks));
}
#writeEntry(entry) {
const batchSize = entry.byteLength;
// Skip empty chunks -- zero-byte writes would accumulate infinitely
// without ever triggering backpressure under a byte-budget model.
@@ -201,7 +206,7 @@ class PushQueue {
while (this.#bufferedBytes >= this.#budget &&
this.#slots.length > 0) {
const evicted = this.#slots.shift();
this.#bufferedBytes -= this.#batchByteSize(evicted);
this.#bufferedBytes -= evicted.byteLength;
}
break;
case 'drop-newest':
@@ -211,7 +216,7 @@ class PushQueue {
}
}
this.#slots.push(chunks);
this.#slots.push(entry);
this.#bufferedBytes += batchSize;
this.#bytesWritten += batchSize;
@@ -253,8 +258,8 @@ class PushQueue {
// Check for pre-aborted signal (after state checks per spec)
signal?.throwIfAborted();
// Try sync first
if (this.writeSync(chunks)) {
const entry = createBatchEntry(chunks);
if (this.#writeEntry(entry)) {
return;
}
@@ -266,9 +271,9 @@ class PushQueue {
'Backpressure violation: too many pending writes. ' +
'Await each write() call to respect backpressure.');
}
return this.#createPendingWrite(chunks, signal);
return this.#createPendingWrite(entry, signal);
case 'unbounded':
return this.#createPendingWrite(chunks, signal);
return this.#createPendingWrite(entry, signal);
default:
throw new ERR_INVALID_STATE(
'Unexpected: writeSync should have handled non-strict policy');
@@ -281,9 +286,9 @@ class PushQueue {
* promise rejects. Signal listeners are cleaned up on normal resolution.
* @returns {Promise<void>}
*/
#createPendingWrite(chunks, signal) {
#createPendingWrite(batch, signal) {
const { promise, resolve, reject } = PromiseWithResolvers();
const entry = { __proto__: null, chunks, resolve, reject };
const entry = { __proto__: null, batch, resolve, reject };
this.#pendingWrites.push(entry);
if (signal) {
@@ -487,28 +492,29 @@ class PushQueue {
// ===========================================================================
#drain() {
this.#bufferedBytes = 0;
if (this.#slots.length === 1) {
return this.#slots.shift();
}
const result = [];
for (let i = 0; i < this.#slots.length; i++) {
const slot = this.#slots.get(i);
for (let j = 0; j < slot.length; j++) {
ArrayPrototypePush(result, slot[j]);
try {
if (this.#slots.length === 1) {
const result = validateBatchEntry(this.#slots.shift());
this.#bufferedBytes = 0;
return result;
}
}
this.#slots.clear();
return result;
}
#batchByteSize(batch) {
let size = 0;
for (let i = 0; i < batch.length; i++) {
size += TypedArrayPrototypeGetByteLength(batch[i]);
const result = [];
for (let i = 0; i < this.#slots.length; i++) {
const batch = validateBatchEntry(this.#slots.get(i));
for (let j = 0; j < batch.length; j++) {
ArrayPrototypePush(result, batch[j]);
}
}
this.#slots.clear();
this.#bufferedBytes = 0;
return result;
} catch (error) {
this.#slots.clear();
this.#bufferedBytes = 0;
this.fail(error);
throw error;
}
return size;
}
#terminateWriterFromConsumer(error) {
@@ -536,9 +542,13 @@ class PushQueue {
pending.reject(this.#error);
} else if (this.#slots.length > 0) {
const pending = this.#pendingReads.shift();
const result = this.#drain();
this.#resolvePendingWrites();
pending.resolve({ __proto__: null, done: false, value: result });
try {
const result = this.#drain();
this.#resolvePendingWrites();
pending.resolve({ __proto__: null, done: false, value: result });
} catch (error) {
pending.reject(error);
}
} else if (this.#writerState === 'closing' && this.#slots.length === 0) {
this.endDrained();
const pending = this.#pendingReads.shift();
@@ -559,11 +569,15 @@ class PushQueue {
while (this.#pendingWrites.length > 0 &&
this.#bufferedBytes < this.#budget) {
const pending = this.#pendingWrites.shift();
const batchSize = this.#batchByteSize(pending.chunks);
this.#slots.push(pending.chunks);
this.#bufferedBytes += batchSize;
this.#bytesWritten += batchSize;
pending.resolve();
try {
validateBatchEntry(pending.batch);
this.#slots.push(pending.batch);
this.#bufferedBytes += pending.batch.byteLength;
this.#bytesWritten += pending.batch.byteLength;
pending.resolve();
} catch (error) {
pending.reject(error);
}
}
if (this.#bufferedBytes < this.#budget) {
+31 -22
View File
@@ -14,7 +14,6 @@ const {
SymbolAsyncIterator,
SymbolDispose,
SymbolIterator,
TypedArrayPrototypeGetByteLength,
} = primordials;
const {
@@ -36,12 +35,14 @@ const {
const {
kMultiConsumerDefaultBudget,
createBatchEntry,
getMinCursor,
hasProtocol,
onSignalAbort,
wrapError,
parsePullArgs,
validateBackpressure,
validateBatchEntry,
} = require('internal/streams/iter/utils');
const {
@@ -166,7 +167,7 @@ class ShareImpl {
// Check if data is available in buffer
const bufferIndex = state.cursor - self.#bufferStart;
if (bufferIndex < self.#buffer.length) {
const chunk = self.#buffer.get(bufferIndex);
const chunk = self.#readEntry(self.#buffer.get(bufferIndex));
const cursor = state.cursor;
state.cursor++;
if (cursor === self.#cachedMinCursor &&
@@ -296,7 +297,7 @@ class ShareImpl {
while (this.#bufferedBytes >= this.#options.budget &&
this.#buffer.length > 0) {
const evicted = this.#buffer.shift();
this.#bufferedBytes -= this.#batchByteSize(evicted);
this.#bufferedBytes -= evicted.byteLength;
this.#bufferStart++;
}
for (const consumer of this.#consumers) {
@@ -368,8 +369,9 @@ class ShareImpl {
if (result.done) {
this.#sourceExhausted = true;
} else if (!discard) {
this.#buffer.push(result.value);
this.#bufferedBytes += this.#batchByteSize(result.value);
const entry = createBatchEntry(result.value);
this.#buffer.push(entry);
this.#bufferedBytes += entry.byteLength;
}
} catch (error) {
this.#sourceError = wrapError(error);
@@ -392,7 +394,7 @@ class ShareImpl {
if (trimCount > 0) {
for (let i = 0; i < trimCount; i++) {
const evicted = this.#buffer.get(i);
this.#bufferedBytes -= this.#batchByteSize(evicted);
this.#bufferedBytes -= evicted.byteLength;
}
this.#buffer.trimFront(trimCount);
this.#bufferStart = this.#cachedMinCursor;
@@ -403,12 +405,15 @@ class ShareImpl {
}
}
#batchByteSize(batch) {
let size = 0;
for (let i = 0; i < batch.length; i++) {
size += TypedArrayPrototypeGetByteLength(batch[i]);
#readEntry(entry) {
try {
return validateBatchEntry(entry);
} catch (error) {
this.cancel(error);
this.#buffer.clear();
this.#bufferedBytes = 0;
throw error;
}
return size;
}
#recomputeMinCursor() {
@@ -511,7 +516,7 @@ class SyncShareImpl {
const bufferIndex = state.cursor - self.#bufferStart;
if (bufferIndex < self.#buffer.length) {
const chunk = self.#buffer.get(bufferIndex);
const chunk = self.#readEntry(self.#buffer.get(bufferIndex));
const cursor = state.cursor;
state.cursor++;
if (cursor === self.#cachedMinCursor &&
@@ -543,7 +548,7 @@ class SyncShareImpl {
while (self.#bufferedBytes >= self.#options.budget &&
self.#buffer.length > 0) {
const evicted = self.#buffer.shift();
self.#bufferedBytes -= self.#batchByteSize(evicted);
self.#bufferedBytes -= evicted.byteLength;
self.#bufferStart++;
}
for (const consumer of self.#consumers) {
@@ -571,7 +576,7 @@ class SyncShareImpl {
const newBufferIndex = state.cursor - self.#bufferStart;
if (newBufferIndex < self.#buffer.length) {
const chunk = self.#buffer.get(newBufferIndex);
const chunk = self.#readEntry(self.#buffer.get(newBufferIndex));
const cursor = state.cursor;
state.cursor++;
if (cursor === self.#cachedMinCursor &&
@@ -643,8 +648,9 @@ class SyncShareImpl {
if (result.done) {
this.#sourceExhausted = true;
} else {
this.#buffer.push(result.value);
this.#bufferedBytes += this.#batchByteSize(result.value);
const entry = createBatchEntry(result.value);
this.#buffer.push(entry);
this.#bufferedBytes += entry.byteLength;
}
} catch (error) {
this.#sourceError = wrapError(error);
@@ -660,19 +666,22 @@ class SyncShareImpl {
if (trimCount > 0) {
for (let i = 0; i < trimCount; i++) {
const evicted = this.#buffer.get(i);
this.#bufferedBytes -= this.#batchByteSize(evicted);
this.#bufferedBytes -= evicted.byteLength;
}
this.#buffer.trimFront(trimCount);
this.#bufferStart = this.#cachedMinCursor;
}
}
#batchByteSize(batch) {
let size = 0;
for (let i = 0; i < batch.length; i++) {
size += TypedArrayPrototypeGetByteLength(batch[i]);
#readEntry(entry) {
try {
return validateBatchEntry(entry);
} catch (error) {
this.cancel(error);
this.#buffer.clear();
this.#bufferedBytes = 0;
throw error;
}
return size;
}
#recomputeMinCursor() {
+70
View File
@@ -3,6 +3,7 @@
const {
Array,
ArrayBufferPrototypeGetByteLength,
ArrayBufferPrototypeGetDetached,
ArrayPrototypeSlice,
PromiseResolve,
PromiseWithResolvers,
@@ -25,6 +26,7 @@ const { TextEncoder } = require('internal/encoding');
const {
codes: {
ERR_INVALID_ARG_TYPE,
ERR_INVALID_STATE,
ERR_OPERATION_FAILED,
},
} = require('internal/errors');
@@ -196,6 +198,71 @@ function allUint8Array(chunks) {
return true;
}
function snapshotByteView(value) {
const buffer = TypedArrayPrototypeGetBuffer(value);
const sharedBufferView = isSharedArrayBuffer(buffer) ?
new Uint8Array(buffer) : undefined;
return {
__proto__: null,
value,
buffer,
bufferByteLength: sharedBufferView === undefined ?
ArrayBufferPrototypeGetByteLength(buffer) :
TypedArrayPrototypeGetByteLength(sharedBufferView),
byteLength: TypedArrayPrototypeGetByteLength(value),
byteOffset: TypedArrayPrototypeGetByteOffset(value),
detached: sharedBufferView === undefined &&
ArrayBufferPrototypeGetDetached(buffer),
sharedBufferView,
};
}
function validateByteView(snapshot) {
const {
value,
buffer,
bufferByteLength,
byteLength,
byteOffset,
detached,
sharedBufferView,
} = snapshot;
const currentBufferByteLength = sharedBufferView === undefined ?
ArrayBufferPrototypeGetByteLength(buffer) :
TypedArrayPrototypeGetByteLength(sharedBufferView);
const currentDetached = sharedBufferView === undefined &&
ArrayBufferPrototypeGetDetached(buffer);
if (TypedArrayPrototypeGetBuffer(value) !== buffer ||
currentBufferByteLength !== bufferByteLength ||
TypedArrayPrototypeGetByteLength(value) !== byteLength ||
TypedArrayPrototypeGetByteOffset(value) !== byteOffset ||
currentDetached !== detached) {
throw new ERR_INVALID_STATE.TypeError(
'Byte view was resized or detached after being accepted');
}
return value;
}
function createBatchEntry(chunks) {
const views = new Array(chunks.length);
let byteLength = 0;
for (let i = 0; i < chunks.length; i++) {
const view = snapshotByteView(chunks[i]);
views[i] = view;
byteLength += view.byteLength;
}
return { __proto__: null, views, byteLength };
}
function validateBatchEntry(entry) {
const chunks = new Array(entry.views.length);
for (let i = 0; i < entry.views.length; i++) {
chunks[i] = validateByteView(entry.views[i]);
}
return chunks;
}
function copyBytes(chunk) {
const copy = new Uint8Array(TypedArrayPrototypeGetByteLength(chunk));
TypedArrayPrototypeSet(copy, chunk);
@@ -382,6 +449,7 @@ module.exports = {
allUint8Array,
concatBytes,
convertChunks,
createBatchEntry,
getWriterSignal,
getMinCursor,
hasProtocol,
@@ -392,6 +460,8 @@ module.exports = {
parsePullArgs,
toUint8Array,
validateBackpressure,
validateBatchEntry,
validateByteView,
wrapError,
yieldAbortable,
};
@@ -0,0 +1,177 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const {
array,
arraySync,
broadcast,
pipeTo,
pipeToSync,
push,
share,
shareSync,
} = require('stream/iter');
const kResizeError = {
code: 'ERR_INVALID_STATE',
message: /resized or detached/,
};
async function testBufferedViewMutationRejected() {
const resizable = new ArrayBuffer(1, { maxByteLength: 2 });
const growable = new SharedArrayBuffer(1, { maxByteLength: 2 });
const detachable = new ArrayBuffer(1);
const cases = [
[new Uint8Array(resizable), () => resizable.resize(2)],
[new Uint8Array(growable), () => growable.grow(2)],
[new Uint8Array(detachable), () => {
structuredClone(detachable, { transfer: [detachable] });
}],
];
for (const [view, mutate] of cases) {
const { writer, readable } = push();
assert.strictEqual(writer.writeSync(view), true);
mutate();
await assert.rejects(
readable[Symbol.asyncIterator]().next(),
kResizeError,
);
}
}
async function testDropOldestUsesAcceptedByteLength() {
const buffer = new ArrayBuffer(16384, { maxByteLength: 16384 });
const { writer, broadcast: bc } = broadcast({
budget: 16384,
backpressure: 'drop-oldest',
});
const iterator = bc.push()[Symbol.asyncIterator]();
assert.strictEqual(writer.writeSync(new Uint8Array(buffer)), true);
buffer.resize(0);
assert.strictEqual(writer.writeSync(Uint8Array.of(2)), true);
assert.strictEqual(writer.writeSync(Uint8Array.of(3)), true);
writer.endSync();
assert.strictEqual((await iterator.next()).value[0][0], 2);
assert.strictEqual((await iterator.next()).value[0][0], 3);
assert.strictEqual((await iterator.next()).done, true);
}
async function testPendingWritesRejectResizedViews() {
const pushResult = push({ budget: 16384, backpressure: 'unbounded' });
assert.strictEqual(
pushResult.writer.writeSync(new Uint8Array(16384)), true);
const pushBuffer = new ArrayBuffer(1, { maxByteLength: 2 });
const pushPending = pushResult.writer.write(new Uint8Array(pushBuffer));
const pushRejected = assert.rejects(pushPending, kResizeError);
pushBuffer.resize(2);
const pushIterator = pushResult.readable[Symbol.asyncIterator]();
assert.strictEqual((await pushIterator.next()).done, false);
await pushRejected;
pushResult.writer.endSync();
assert.strictEqual((await pushIterator.next()).done, true);
const { writer, broadcast: bc } = broadcast({
budget: 16384,
backpressure: 'unbounded',
});
const broadcastIterator = bc.push()[Symbol.asyncIterator]();
assert.strictEqual(writer.writeSync(new Uint8Array(16384)), true);
const broadcastBuffer = new ArrayBuffer(1, { maxByteLength: 2 });
const broadcastPending = writer.write(new Uint8Array(broadcastBuffer));
const broadcastRejected = assert.rejects(broadcastPending, kResizeError);
broadcastBuffer.resize(2);
assert.strictEqual((await broadcastIterator.next()).done, false);
await broadcastRejected;
writer.endSync();
assert.strictEqual((await broadcastIterator.next()).done, true);
}
async function testBroadcastRejectsResizedBufferedView() {
const buffer = new ArrayBuffer(1, { maxByteLength: 2 });
const { writer, broadcast: bc } = broadcast();
const iterator = bc.push()[Symbol.asyncIterator]();
assert.strictEqual(writer.writeSync(new Uint8Array(buffer)), true);
buffer.resize(2);
await assert.rejects(iterator.next(), kResizeError);
await assert.rejects(writer.end(), kResizeError);
}
async function testShareRejectsResizedBufferedView() {
const asyncBuffer = new ArrayBuffer(1, { maxByteLength: 2 });
const shared = share([[new Uint8Array(asyncBuffer)]]);
const first = shared.pull()[Symbol.asyncIterator]();
const second = shared.pull()[Symbol.asyncIterator]();
assert.strictEqual((await first.next()).done, false);
asyncBuffer.resize(2);
await assert.rejects(second.next(), kResizeError);
const syncBuffer = new ArrayBuffer(1, { maxByteLength: 2 });
const sharedSync = shareSync([[new Uint8Array(syncBuffer)]]);
const firstSync = sharedSync.pull()[Symbol.iterator]();
const secondSync = sharedSync.pull()[Symbol.iterator]();
assert.strictEqual(firstSync.next().done, false);
syncBuffer.resize(2);
assert.throws(() => secondSync.next(), kResizeError);
}
async function testConsumersRejectResizedViews() {
const asyncBuffer = new ArrayBuffer(1, { maxByteLength: 2 });
async function* asyncSource() {
yield [new Uint8Array(asyncBuffer)];
asyncBuffer.resize(2);
}
await assert.rejects(array(asyncSource(), { limit: 1 }), kResizeError);
const syncBuffer = new ArrayBuffer(1, { maxByteLength: 2 });
function* syncSource() {
yield [new Uint8Array(syncBuffer)];
syncBuffer.resize(2);
}
assert.throws(() => arraySync(syncSource(), { limit: 1 }), kResizeError);
}
async function testPipeRejectsWriterResize() {
const asyncBuffer = new ArrayBuffer(1, { maxByteLength: 2 });
const asyncWriter = {
write() {
asyncBuffer.resize(2);
},
fail: common.mustCall(),
};
await assert.rejects(
pipeTo([new Uint8Array(asyncBuffer)], asyncWriter),
kResizeError,
);
const syncBuffer = new ArrayBuffer(1, { maxByteLength: 2 });
const syncWriter = {
writeSync() {
syncBuffer.resize(2);
return true;
},
fail: common.mustCall(),
};
assert.throws(
() => pipeToSync([new Uint8Array(syncBuffer)], syncWriter),
kResizeError,
);
}
Promise.all([
testBufferedViewMutationRejected(),
testDropOldestUsesAcceptedByteLength(),
testPendingWritesRejectResizedViews(),
testBroadcastRejectsResizedBufferedView(),
testShareRejectsResizedBufferedView(),
testConsumersRejectResizedViews(),
testPipeRejectsWriterResize(),
]).then(common.mustCall());