diff --git a/src/node_zlib.cc b/src/node_zlib.cc index fd97a1ddad0..04babfeadc3 100644 --- a/src/node_zlib.cc +++ b/src/node_zlib.cc @@ -1893,8 +1893,19 @@ void ZstdCompressContext::DoThreadPoolWork() { } // Zstd overrides a configured pledge when the first call uses ZSTD_e_end. size_t const input_pos = input_.pos; - size_t const remaining = - ZSTD_compressStream2(cctx_.get(), &output_, &input_, flush_); + // With ZSTD_c_nbWorkers >= 1, ZSTD_e_continue can return with input left and + // output space free, which lib/zlib.js treats as the end of the stream. + size_t remaining; + while (true) { + const size_t in_pos = input_.pos; + const size_t out_pos = output_.pos; + remaining = ZSTD_compressStream2(cctx_.get(), &output_, &input_, flush_); + if (flush_ != ZSTD_e_continue || ZSTD_isError(remaining) || + input_.pos == input_.size || output_.pos == output_.size || + (input_.pos == in_pos && output_.pos == out_pos)) { + break; + } + } if (consumed_src_size_.has_value()) { *consumed_src_size_ += input_.pos - input_pos; } diff --git a/test/parallel/test-zlib-zstd-multithreaded.js b/test/parallel/test-zlib-zstd-multithreaded.js new file mode 100644 index 00000000000..ed9cdb447fd --- /dev/null +++ b/test/parallel/test-zlib-zstd-multithreaded.js @@ -0,0 +1,50 @@ +'use strict'; + +// Zstd compression with ZSTD_c_nbWorkers >= 1 must not drop input. + +const common = require('../common'); +const assert = require('assert'); +const zlib = require('zlib'); +const { Readable } = require('stream'); +const { pipeline } = require('stream/promises'); + +const { ZSTD_c_nbWorkers, ZSTD_c_jobSize } = zlib.constants; + +try { + zlib.zstdCompressSync('', { params: { [ZSTD_c_nbWorkers]: 1 } }); +} catch (err) { + // The bundled zstd is always built with multithreading; a shared one may not. + if (!process.config.variables.node_shared_zstd) throw err; + common.skip('libzstd built without multithreading support'); +} + +// Smallest allowed job size; input longer than one job triggers the bug. +const jobSize = 512 * 1024; +const params = { [ZSTD_c_nbWorkers]: 2, [ZSTD_c_jobSize]: jobSize }; +const input = Buffer.alloc(3 * jobSize); +for (let i = 0; i < input.length; i++) input[i] = (i * 7) ^ (i >> 10); + +function assertRoundTrips(compressed) { + const decompressed = zlib.zstdDecompressSync(compressed); + assert.strictEqual(decompressed.length, input.length); + assert(decompressed.equals(input)); +} + +zlib.zstdCompress(input, { params }, common.mustSucceed(assertRoundTrips)); + +(async () => { + const writeSize = jobSize / 2 + 1000; + const chunks = []; + for (let off = 0; off < input.length; off += writeSize) { + chunks.push(input.subarray(off, off + writeSize)); + } + const output = []; + await pipeline( + Readable.from(chunks), + zlib.createZstdCompress({ params }), + async function(source) { + for await (const chunk of source) output.push(chunk); + }, + ); + assertRoundTrips(Buffer.concat(output)); +})().then(common.mustCall());