diff --git a/lib/internal/streams/iter/transform.js b/lib/internal/streams/iter/transform.js index c6c315cf6bd..8e60589aba3 100644 --- a/lib/internal/streams/iter/transform.js +++ b/lib/internal/streams/iter/transform.js @@ -11,7 +11,7 @@ const { ArrayPrototypeMap, ArrayPrototypePush, - ArrayPrototypeShift, + ArrayPrototypeSlice, FunctionPrototypeCall, MathMax, NumberIsNaN, @@ -311,6 +311,8 @@ function makeZlibTransform(createHandleFn, processFlag, finishFlag) { let outOffset = 0; let chunkSize; let pending = []; + // Index of the first buffer of `pending` not yet taken by drainBatch(). + let pendingHead = 0; let pendingBytes = 0; // Current write operation state (read by the callback for looping). @@ -442,20 +444,33 @@ function makeZlibTransform(createHandleFn, processFlag, finishFlag) { function drainBatch() { if (pendingBytes <= BATCH_HWM) { - // Swap instead of splice - avoids copying the array. - const batch = pending; + // Take everything: swap instead of copying, unless batches have + // already been taken from the front. + const batch = pendingHead === 0 ? pending : + ArrayPrototypeSlice(pending, pendingHead); pending = []; + pendingHead = 0; pendingBytes = 0; return batch; } - const batch = []; + // Take up to BATCH_HWM bytes from the front by advancing pendingHead: + // shifting them off instead would copy the rest of the array, which + // makes draining a large output quadratic. + let end = pendingHead; let batchBytes = 0; - while (pending.length > 0 && batchBytes < BATCH_HWM) { - const buf = ArrayPrototypeShift(pending); - ArrayPrototypePush(batch, buf); - const len = TypedArrayPrototypeGetByteLength(buf); - batchBytes += len; - pendingBytes -= len; + while (end < pending.length && batchBytes < BATCH_HWM) { + batchBytes += TypedArrayPrototypeGetByteLength(pending[end]); + end++; + } + const batch = ArrayPrototypeSlice(pending, pendingHead, end); + pendingBytes -= batchBytes; + if (end === pending.length) { + pending = []; + pendingHead = 0; + } else { + // Do not keep the buffers taken alive. + for (let i = pendingHead; i < end; i++) pending[i] = undefined; + pendingHead = end; } return batch; } @@ -511,7 +526,7 @@ function makeZlibTransform(createHandleFn, processFlag, finishFlag) { processInputBatches(kEmpty, finishFlag)) { yield batch; } - while (pending.length > 0) { + while (pending.length > pendingHead) { yield drainBatch(); } } @@ -531,11 +546,12 @@ function makeZlibTransform(createHandleFn, processFlag, finishFlag) { } if (pendingBytes >= BATCH_HWM) { - while (pending.length > 0 && pendingBytes >= BATCH_HWM) { + while (pending.length > pendingHead && + pendingBytes >= BATCH_HWM) { yield drainBatch(); } } - if (pending.length > 0) { + if (pending.length > pendingHead) { yield drainBatch(); } } @@ -547,7 +563,7 @@ function makeZlibTransform(createHandleFn, processFlag, finishFlag) { processInputBatches(kEmpty, finishFlag)) { yield batch; } - while (pending.length > 0) { + while (pending.length > pendingHead) { yield drainBatch(); } } @@ -602,6 +618,8 @@ function makeZlibTransformSync(createHandleFn, processFlag, finishFlag) { let outBuf = Buffer.allocUnsafe(chunkSize); let outOffset = 0; let pending = []; + // Index of the first buffer of `pending` not yet taken by drainBatch(). + let pendingHead = 0; let pendingBytes = 0; function processSyncInput(input, flushFlag) { @@ -666,19 +684,33 @@ function makeZlibTransformSync(createHandleFn, processFlag, finishFlag) { function drainBatch() { if (pendingBytes <= BATCH_HWM) { - const batch = pending; + // Take everything: swap instead of copying, unless batches have + // already been taken from the front. + const batch = pendingHead === 0 ? pending : + ArrayPrototypeSlice(pending, pendingHead); pending = []; + pendingHead = 0; pendingBytes = 0; return batch; } - const batch = []; + // Take up to BATCH_HWM bytes from the front by advancing pendingHead: + // shifting them off instead would copy the rest of the array, which + // makes draining a large output quadratic. + let end = pendingHead; let batchBytes = 0; - while (pending.length > 0 && batchBytes < BATCH_HWM) { - const buf = ArrayPrototypeShift(pending); - const len = TypedArrayPrototypeGetByteLength(buf); - ArrayPrototypePush(batch, buf); - batchBytes += len; - pendingBytes -= len; + while (end < pending.length && batchBytes < BATCH_HWM) { + batchBytes += TypedArrayPrototypeGetByteLength(pending[end]); + end++; + } + const batch = ArrayPrototypeSlice(pending, pendingHead, end); + pendingBytes -= batchBytes; + if (end === pending.length) { + pending = []; + pendingHead = 0; + } else { + // Do not keep the buffers taken alive. + for (let i = pendingHead; i < end; i++) pending[i] = undefined; + pendingHead = end; } return batch; } @@ -688,7 +720,7 @@ function makeZlibTransformSync(createHandleFn, processFlag, finishFlag) { if (batch === null) { // Flush signal - finalize the engine. processSyncInput(Buffer.alloc(0), finishFlag); - while (pending.length > 0) { + while (pending.length > pendingHead) { yield drainBatch(); } continue; @@ -699,11 +731,12 @@ function makeZlibTransformSync(createHandleFn, processFlag, finishFlag) { } if (pendingBytes >= BATCH_HWM) { - while (pending.length > 0 && pendingBytes >= BATCH_HWM) { + while (pending.length > pendingHead && + pendingBytes >= BATCH_HWM) { yield drainBatch(); } } - if (pending.length > 0) { + if (pending.length > pendingHead) { yield drainBatch(); } } diff --git a/test/parallel/test-stream-iter-transform-buffering.js b/test/parallel/test-stream-iter-transform-buffering.js index b1b813f60b9..95b9a71f65c 100644 --- a/test/parallel/test-stream-iter-transform-buffering.js +++ b/test/parallel/test-stream-iter-transform-buffering.js @@ -4,8 +4,13 @@ const common = require('../common'); const assert = require('assert'); const { brotliDecompressSync, gunzipSync, gzipSync } = require('zlib'); -const { compressBrotli, compressGzip, decompressGzip } = require('zlib/iter'); -const { bytes, from, pull } = require('stream/iter'); +const { + compressBrotli, + compressGzip, + decompressGzip, + decompressGzipSync, +} = require('zlib/iter'); +const { bytes, from, fromSync, pull, pullSync } = require('stream/iter'); async function testDecompressionOutputIsBounded() { let input = Buffer.alloc(32 * 1024 * 1024, 0x61); @@ -38,6 +43,34 @@ async function testSmallChunkSizeDecompression() { assert.deepStrictEqual(Buffer.from(output), input); } +// With a chunk size that does not divide the batch size, output collected +// beyond a batch is taken a batch at a time, from the front. +async function testPartialBatchDrains() { + const input = Buffer.alloc(1024 * 1024); + for (let i = 0; i < input.length; i++) input[i] = (i * 7 + (i >> 12)) & 0xff; + const compressed = gzipSync(input); + const batchSizes = (batches) => batches.map((batch) => { + return batch.reduce((total, chunk) => total + chunk.length, 0); + }); + + const asyncBatches = []; + for await (const batch of pull(from(compressed), + decompressGzip({ chunkSize: 1000 }))) { + asyncBatches.push(batch); + } + const syncBatches = [ + ...pullSync(fromSync(compressed), decompressGzipSync({ chunkSize: 1000 })), + ]; + for (const batches of [asyncBatches, syncBatches]) { + assert.deepStrictEqual(Buffer.concat(batches.flat()), input); + assert.ok(batches.length > 1); + // A batch is closed once it holds 64 KiB. + for (const size of batchSizes(batches)) { + assert.ok(size <= 64 * 1024 + 1000, `batch of ${size} bytes`); + } + } +} + // Deterministic incompressible data. Brotli's buffering decisions depend on // content, so random data would make the tests below flaky. function incompressible(size) { @@ -108,6 +141,7 @@ async function testSourceReturnFailuresAreIgnored() { await testDecompressionOutputIsBounded(); await Promise.all([ testSmallChunkSizeDecompression(), + testPartialBatchDrains(), testLargeFinishOutput(), testExplicitFlushSignal(), testSourceReturnFailuresAreIgnored(),