/** @jest-environment node */ import { Readable } from 'node:stream' import AdmZip from 'adm-zip' import { ExternalZipBusyError, MAX_ACTIVE_EXTERNAL_ZIPS, streamExternalZip } from '@/lib/external-zip-stream' test('ZIP entries open in order without buffering multiple upstream sources', async () => { const opened: string[] = [] let active = 0 let peak = 0 const entries = Array.from({ length: 40 }, (_, index) => ({ name: 'main/' + String(index).padStart(2, '0') + '.jpg', open: async () => { const source = Readable.from((async function* () { active++ peak = Math.max(peak, active) try { yield Buffer.alloc(128 * 1024, index) } finally { active-- } })(), { objectMode: false }) opened.push(String(index)) return source }, })) const stream = await streamExternalZip(entries) const bytes = Buffer.from(await new Response(stream).arrayBuffer()) const zip = new AdmZip(bytes) expect(peak).toBe(1) expect(opened).toEqual(entries.map((_, index) => String(index))) expect(zip.getEntries().map(entry => entry.entryName)).toEqual(entries.map(entry => entry.name)) entries.forEach((entry, index) => expect(zip.readFile(entry.name)?.[0]).toBe(index)) }) test('concurrent slow ZIPs are bounded and cancellation releases the slot', async () => { const entry = { name: 'main/wait.jpg', open: (signal: AbortSignal) => new Promise((_, reject) => { signal.addEventListener('abort', () => reject(signal.reason), { once: true }) }), } const active = await Promise.all(Array.from({ length: MAX_ACTIVE_EXTERNAL_ZIPS }, () => streamExternalZip([entry]))) try { await expect(streamExternalZip([entry])).rejects.toBeInstanceOf(ExternalZipBusyError) await active.shift()!.cancel() await new Promise(resolve => setImmediate(resolve)) await expect(streamExternalZip([]).then(stream => new Response(stream).arrayBuffer())).resolves.toBeDefined() } finally { await Promise.all(active.map(stream => stream.cancel())) } })