From 1c431593bfb78ec1bdd6ee5490aaa4874483d116 Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Fri, 3 Jul 2026 07:06:18 +0000 Subject: [PATCH 1/4] perf(snapshots): stream-extract downloaded archives MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the buffer-everything download+extract with a streaming pipeline: `openSnapshotArchive` returns the unconsumed HTTP response, and `extractZipStream` feeds the body through fflate's streaming `Unzip` (synchronous `UnzipInflate`/`UnzipPassThrough` — no workers, SEA-safe), decompressing and writing each entry to disk as its chunks arrive. Peak memory is now bounded by the in-flight entry rather than the whole archive (+ all decompressed entries) — removing the OOM risk on large baselines (the server caps archives at ~1 GB). Zip-Slip protection is preserved via the shared safeEntryDest guard. - src/lib/api/preprod-artifacts.ts: downloadSnapshotArchive (Buffer) → openSnapshotArchive (Response). - src/lib/snapshots/archive.ts: extractZipToDir → extractZipStream. - src/commands/snapshots/download.ts: stream response.body into extractZipStream. - Tests updated to stream (chunked async iterables); added a large deflated multi-chunk entry case. Verified against a real undici ReadableStream. --- src/commands/snapshots/download.ts | 20 +++- src/lib/api/preprod-artifacts.ts | 20 ++-- src/lib/snapshots/archive.ts | 118 ++++++++++++++++++----- test/commands/snapshots/download.test.ts | 19 +++- test/lib/api/preprod-artifacts.test.ts | 26 ++--- test/lib/snapshots/archive.test.ts | 39 ++++++-- 6 files changed, 179 insertions(+), 63 deletions(-) diff --git a/src/commands/snapshots/download.ts b/src/commands/snapshots/download.ts index 39bf4bf430..c039051531 100644 --- a/src/commands/snapshots/download.ts +++ b/src/commands/snapshots/download.ts @@ -13,13 +13,14 @@ import { resolve } from "node:path"; import type { SentryContext } from "../../context.js"; import { - downloadSnapshotArchive, getLatestBaseSnapshot, + openSnapshotArchive, waitForSnapshotArchive, } from "../../lib/api/preprod-artifacts.js"; import { buildCommand } from "../../lib/command.js"; import { getDefaultProject } from "../../lib/db/defaults.js"; import { + ApiError, ContextError, ResolutionError, ValidationError, @@ -28,7 +29,7 @@ import { mdKvTable, renderMarkdown } from "../../lib/formatters/markdown.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { logger } from "../../lib/logger.js"; import { resolveOrg } from "../../lib/resolve-target.js"; -import { extractZipToDir } from "../../lib/snapshots/archive.js"; +import { extractZipStream } from "../../lib/snapshots/archive.js"; const log = logger.withTag("snapshots.download"); @@ -212,10 +213,21 @@ export const downloadCommand = buildCommand({ ); log.info(`Downloading snapshot ${snapshotId}...`); - const zip = await downloadSnapshotArchive(org, snapshotId); + const response = await openSnapshotArchive(org, snapshotId); + if (!response.body) { + throw new ApiError( + "Snapshot archive response had no body", + response.status, + "Empty response body", + `snapshots/${snapshotId}/archive/` + ); + } const output = resolve(this.cwd, flags.output ?? DEFAULT_OUTPUT); - const imageCount = extractZipToDir(zip, output); + const imageCount = await extractZipStream( + response.body as unknown as AsyncIterable, + output + ); yield new CommandOutput({ org, diff --git a/src/lib/api/preprod-artifacts.ts b/src/lib/api/preprod-artifacts.ts index adcb5026bc..7aa97ea4cf 100644 --- a/src/lib/api/preprod-artifacts.ts +++ b/src/lib/api/preprod-artifacts.ts @@ -454,22 +454,20 @@ export async function waitForSnapshotArchive( } /** - * Download a snapshot's archive ZIP into memory. + * Open a snapshot's archive ZIP for streaming. * - * The endpoint streams the ZIP directly from the region origin (no redirect), so - * the auth token is only ever sent to the region host. Should the server ever - * 302 to third-party storage, undici strips `Authorization` cross-origin. - * - * The whole archive is buffered and later extracted in memory (see - * {@link extractZipToDir}); acceptable for typical screenshot baselines, but a - * very large archive (the server caps at ~1 GB) would need streaming extraction. + * Returns the raw HTTP `Response` (body unconsumed) so the caller can + * stream-extract it without buffering the whole archive in memory. The endpoint + * streams the ZIP directly from the region origin (no redirect), so the auth + * token is only ever sent to the region host; should the server ever 302 to + * third-party storage, undici strips `Authorization` cross-origin. * * @throws {ApiError} On a non-2xx response. */ -export async function downloadSnapshotArchive( +export async function openSnapshotArchive( org: string, snapshotId: string -): Promise { +): Promise { const regionUrl = stripTrailingSlashes(await resolveOrgRegion(org)); const url = `${regionUrl}/api/0/${snapshotArchiveEndpoint( org, @@ -489,5 +487,5 @@ export async function downloadSnapshotArchive( url ); } - return Buffer.from(await response.arrayBuffer()); + return response; } diff --git a/src/lib/snapshots/archive.ts b/src/lib/snapshots/archive.ts index ae3f446c30..c5c334e0eb 100644 --- a/src/lib/snapshots/archive.ts +++ b/src/lib/snapshots/archive.ts @@ -1,54 +1,120 @@ /** * Snapshot archive extraction. * - * Extracts a downloaded snapshot ZIP (baseline images) to a local directory, - * guarding against path traversal (Zip Slip): entries resolving outside the - * output directory, and absolute paths, are skipped. + * Stream-extracts a downloaded snapshot ZIP (baseline images) to a local + * directory without buffering the whole archive — or all decompressed entries — + * in memory. Guards against path traversal (Zip Slip): entries resolving + * outside the output directory, and absolute paths, are skipped. */ -import { mkdirSync, writeFileSync } from "node:fs"; +import { createWriteStream, mkdirSync } from "node:fs"; import { dirname, isAbsolute, relative, resolve, sep } from "node:path"; -import { unzipSync } from "fflate"; +import { Unzip, UnzipInflate, UnzipPassThrough } from "fflate"; import { logger } from "../logger.js"; const log = logger.withTag("snapshots.extract"); /** - * Extract a ZIP archive's file entries into a directory. + * Resolve a safe on-disk destination for a ZIP entry, or `null` to skip it. * - * Directory entries are skipped; parent directories are created as needed. - * Entries that would escape `outDir` are skipped with a warning. + * Skips directory entries (trailing `/`) and empty names, and any entry that + * would escape `root` (segment-aware, so `..name` is allowed) or is absolute. + */ +function safeEntryDest(root: string, name: string): string | null { + if (!name || name.endsWith("/")) { + return null; + } + const dest = resolve(root, name); + const rel = relative(root, dest); + if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) { + log.warn(`Skipping unsafe archive entry: ${name}`); + return null; + } + return dest; +} + +/** + * Stream-extract a ZIP archive to a directory. + * + * Entries are decompressed and written to disk as their chunks arrive, so peak + * memory is bounded by the in-flight entry rather than the archive size. Only + * stored (0) and DEFLATE (8) entries are supported — the formats Sentry's + * snapshot archives use. * - * @param zip - The ZIP archive bytes. + * @param chunks - The raw ZIP bytes as an async stream of chunks. * @param outDir - Destination directory (created if missing). * @returns The number of files written. + * @throws On a malformed archive, an unsupported compression method, or a write + * error. */ -export function extractZipToDir(zip: Uint8Array, outDir: string): number { - const entries = unzipSync(zip); +export async function extractZipStream( + chunks: AsyncIterable, + outDir: string +): Promise { const root = resolve(outDir); mkdirSync(root, { recursive: true }); let written = 0; - for (const [name, bytes] of Object.entries(entries)) { - // fflate represents directories as zero-length entries with a trailing "/". - // Skip those and any empty name (which would resolve to `root` itself). - if (!name || name.endsWith("/")) { - continue; - } + let failure: Error | null = null; + const writes: Promise[] = []; - const dest = resolve(root, name); - const rel = relative(root, dest); - // Segment-aware traversal check: reject entries that escape `root` (rel is - // ".." or begins "../") or resolve to an absolute path — without rejecting - // legitimate names that merely start with ".." (e.g. "..config.png"). - if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) { - log.warn(`Skipping unsafe archive entry: ${name}`); - continue; + const unzip = new Unzip((file) => { + const dest = safeEntryDest(root, file.name); + if (dest === null) { + // A no-op handler in case fflate enables the stream without start(). + file.ondata = () => { + // Intentionally ignore data from skipped entries. + }; + return; } mkdirSync(dirname(dest), { recursive: true }); - writeFileSync(dest, bytes); + const stream = createWriteStream(dest); written += 1; + writes.push( + new Promise((resolveWrite, rejectWrite) => { + stream.on("finish", resolveWrite); + stream.on("error", rejectWrite); + }) + ); + + file.ondata = (err, data, final) => { + if (err) { + failure ??= err; + stream.destroy(err); + return; + } + // Copy: fflate may reuse the underlying buffer after this callback. + if (data.length > 0) { + stream.write(Buffer.from(data)); + } + if (final) { + stream.end(); + } + }; + file.start(); + }); + unzip.register(UnzipInflate); + unzip.register(UnzipPassThrough); + + // Push chunks, flagging the last one by peeking one chunk ahead. Yielding to + // the event loop between pushes lets write streams flush (bounds memory). + const iterator = chunks[Symbol.asyncIterator](); + let pushedAny = false; + let current = await iterator.next(); + while (!current.done) { + const chunk = current.value; + current = await iterator.next(); + unzip.push(chunk, current.done === true); + pushedAny = true; + } + if (!pushedAny) { + unzip.push(new Uint8Array(0), true); + } + + await Promise.all(writes); + if (failure) { + throw failure; } return written; } diff --git a/test/commands/snapshots/download.test.ts b/test/commands/snapshots/download.test.ts index 45e387027c..9345633437 100644 --- a/test/commands/snapshots/download.test.ts +++ b/test/commands/snapshots/download.test.ts @@ -47,6 +47,14 @@ function snapshotZip(): Buffer { ); } +/** Yield a buffer as a chunked async stream (a fresh generator per call). */ +async function* streamOf(buffer: Uint8Array): AsyncIterable { + const chunkSize = 8; + for (let offset = 0; offset < buffer.length; offset += chunkSize) { + yield buffer.subarray(offset, offset + chunkSize); + } +} + describe("snapshots download", () => { let downloadSpy: ReturnType; let latestSpy: ReturnType; @@ -60,9 +68,16 @@ describe("snapshots download", () => { waitSpy = vi .spyOn(preprod, "waitForSnapshotArchive") .mockResolvedValue(undefined); + // Fresh streamable body per call (an async generator is single-use). downloadSpy = vi - .spyOn(preprod, "downloadSnapshotArchive") - .mockResolvedValue(snapshotZip()); + .spyOn(preprod, "openSnapshotArchive") + .mockImplementation(() => + Promise.resolve({ + ok: true, + status: 200, + body: streamOf(snapshotZip()), + } as unknown as Response) + ); latestSpy = vi.spyOn(preprod, "getLatestBaseSnapshot").mockResolvedValue({ headArtifactId: "resolved-art", imageCount: 2, diff --git a/test/lib/api/preprod-artifacts.test.ts b/test/lib/api/preprod-artifacts.test.ts index 5914d3d701..68e2d0e633 100644 --- a/test/lib/api/preprod-artifacts.test.ts +++ b/test/lib/api/preprod-artifacts.test.ts @@ -63,10 +63,10 @@ vi.mock("../../../src/lib/api/chunk-upload.js", async (importOriginal) => { import { buildFormatFromUrl, downloadBuildArtifact, - downloadSnapshotArchive, getBuildInstallDetails, getLatestBaseSnapshot, LatestBaseSnapshotSchema, + openSnapshotArchive, toBinaryDownloadUrl, uploadBuild, waitForSnapshotArchive, @@ -428,24 +428,28 @@ describe("snapshots", () => { expect(onBuild).not.toHaveBeenCalled(); }); - test("downloadSnapshotArchive returns the archive bytes", async () => { - customFetchMock.mockResolvedValue({ - ok: true, - arrayBuffer: () => - Promise.resolve(new TextEncoder().encode("zip-bytes").buffer), - }); + test("openSnapshotArchive returns the response for streaming", async () => { + const response = { ok: true, status: 200, body: {} }; + customFetchMock.mockResolvedValue(response); - const buf = await downloadSnapshotArchive("my-org", "snap-1"); - expect(buf.toString()).toBe("zip-bytes"); + await expect(openSnapshotArchive("my-org", "snap-1")).resolves.toBe( + response + ); + // Auth token attached; URL targets the region archive endpoint. + const [url, init] = customFetchMock.mock.calls.at(-1) ?? []; + expect(url).toContain( + "/preprodartifacts/snapshots/snap-1/archive/?download" + ); + expect(init?.headers?.Authorization).toBe("Bearer secret-token"); }); - test("downloadSnapshotArchive throws on a non-2xx response", async () => { + test("openSnapshotArchive throws on a non-2xx response", async () => { customFetchMock.mockResolvedValue({ ok: false, status: 500, statusText: "Server Error", }); - await expect(downloadSnapshotArchive("my-org", "snap-1")).rejects.toThrow( + await expect(openSnapshotArchive("my-org", "snap-1")).rejects.toThrow( ApiError ); }); diff --git a/test/lib/snapshots/archive.test.ts b/test/lib/snapshots/archive.test.ts index bf9e01c6a2..15291c8013 100644 --- a/test/lib/snapshots/archive.test.ts +++ b/test/lib/snapshots/archive.test.ts @@ -1,5 +1,5 @@ /** - * Tests for snapshot archive extraction, including Zip-Slip protection. + * Tests for streaming snapshot archive extraction, including Zip-Slip protection. */ import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; @@ -7,7 +7,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { strToU8, zipSync } from "fflate"; import { afterEach, describe, expect, test } from "vitest"; -import { extractZipToDir } from "../../../src/lib/snapshots/archive.js"; +import { extractZipStream } from "../../../src/lib/snapshots/archive.js"; const dirs: string[] = []; function tempDir(): string { @@ -16,6 +16,16 @@ function tempDir(): string { return dir; } +/** Yield a buffer as an async stream, split into fixed-size chunks. */ +async function* streamOf( + buffer: Uint8Array, + chunkSize = 8 +): AsyncIterable { + for (let offset = 0; offset < buffer.length; offset += chunkSize) { + yield buffer.subarray(offset, offset + chunkSize); + } +} + afterEach(() => { while (dirs.length > 0) { const dir = dirs.pop(); @@ -25,23 +35,23 @@ afterEach(() => { } }); -describe("extractZipToDir", () => { - test("extracts files (incl. nested) and skips directory entries", () => { +describe("extractZipStream", () => { + test("extracts files (incl. nested) and skips directory entries", async () => { const zip = zipSync({ "a.png": strToU8("A"), - "sub/b.png": strToU8("B"), + "sub/b.png": strToU8("BB"), "emptydir/": new Uint8Array(), }); const out = tempDir(); - const count = extractZipToDir(zip, out); + const count = await extractZipStream(streamOf(zip), out); expect(count).toBe(2); expect(readFileSync(join(out, "a.png"), "utf8")).toBe("A"); - expect(readFileSync(join(out, "sub", "b.png"), "utf8")).toBe("B"); + expect(readFileSync(join(out, "sub", "b.png"), "utf8")).toBe("BB"); }); - test("skips traversal, absolute, and empty entries but keeps safe names", () => { + test("skips traversal, absolute, and empty entries but keeps safe names", async () => { const zip = zipSync({ "../evil.png": strToU8("X"), "a/../../evil2.png": strToU8("X"), @@ -53,7 +63,7 @@ describe("extractZipToDir", () => { }); const out = tempDir(); - const count = extractZipToDir(zip, out); + const count = await extractZipStream(streamOf(zip), out); expect(count).toBe(2); // "..config.png" + "ok.png" expect(existsSync(join(out, "ok.png"))).toBe(true); @@ -62,4 +72,15 @@ describe("extractZipToDir", () => { expect(existsSync(join(out, "..", "evil.png"))).toBe(false); expect(existsSync(join(out, "..", "..", "evil2.png"))).toBe(false); }); + + test("handles a larger deflated entry split across many chunks", async () => { + const big = "pixel-data-".repeat(5000); + const zip = zipSync({ "big.png": strToU8(big) }); + const out = tempDir(); + + const count = await extractZipStream(streamOf(zip, 64), out); + + expect(count).toBe(1); + expect(readFileSync(join(out, "big.png"), "utf8")).toBe(big); + }); }); From ea7f6fcc7b9dda6cc302879c75819af8a9425e0a Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Fri, 3 Jul 2026 07:18:51 +0000 Subject: [PATCH 2/4] fix(snapshots): self-review fixes for stream extraction MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - H1 (high): write-completion promises no longer reject — a write error mid-loop was becoming an unhandled rejection (no handler until Promise.all), producing a spurious Sentry crash in CLI mode and a potential host crash in library mode. Now the per-entry promise resolves on both finish and error, recording the first error and surfacing it after all writes settle. - L1: cancel the source stream (iterator.return) in a finally, so a failed extraction doesn't leak the HTTP body/socket. - N7: count files on "finish", not at stream creation. - M1: docstring now states the true memory bound (one chunk's output + write backlog), not "the in-flight entry". - Tests: add a stored (method 0) entry case and a write-error case asserting the run rejects with zero unhandled rejections (guards H1). --- src/lib/snapshots/archive.ts | 54 +++++++++++++++++++----------- test/lib/snapshots/archive.test.ts | 39 ++++++++++++++++++++- 2 files changed, 72 insertions(+), 21 deletions(-) diff --git a/src/lib/snapshots/archive.ts b/src/lib/snapshots/archive.ts index c5c334e0eb..95909e7bda 100644 --- a/src/lib/snapshots/archive.ts +++ b/src/lib/snapshots/archive.ts @@ -36,10 +36,11 @@ function safeEntryDest(root: string, name: string): string | null { /** * Stream-extract a ZIP archive to a directory. * - * Entries are decompressed and written to disk as their chunks arrive, so peak - * memory is bounded by the in-flight entry rather than the archive size. Only - * stored (0) and DEFLATE (8) entries are supported — the formats Sentry's - * snapshot archives use. + * Entries are decompressed and written to disk as their chunks arrive rather + * than buffering the whole archive (or all decompressed entries) at once. Peak + * memory is bounded by the decompressed output of one source chunk plus the + * write stream's pending backlog — not the archive size. Only stored (0) and + * DEFLATE (8) entries are supported — the formats Sentry's snapshot archives use. * * @param chunks - The raw ZIP bytes as an async stream of chunks. * @param outDir - Destination directory (created if missing). @@ -70,11 +71,19 @@ export async function extractZipStream( mkdirSync(dirname(dest), { recursive: true }); const stream = createWriteStream(dest); - written += 1; + // Never reject: a write error mid-loop must not become an unhandled + // rejection (no handler is attached until Promise.all below). Record the + // first error and resolve; it is surfaced after all writes settle. writes.push( - new Promise((resolveWrite, rejectWrite) => { - stream.on("finish", resolveWrite); - stream.on("error", rejectWrite); + new Promise((resolveWrite) => { + stream.on("finish", () => { + written += 1; + resolveWrite(); + }); + stream.on("error", (err) => { + failure ??= err; + resolveWrite(); + }); }) ); @@ -98,21 +107,26 @@ export async function extractZipStream( unzip.register(UnzipPassThrough); // Push chunks, flagging the last one by peeking one chunk ahead. Yielding to - // the event loop between pushes lets write streams flush (bounds memory). + // the event loop between pushes lets write streams flush. const iterator = chunks[Symbol.asyncIterator](); - let pushedAny = false; - let current = await iterator.next(); - while (!current.done) { - const chunk = current.value; - current = await iterator.next(); - unzip.push(chunk, current.done === true); - pushedAny = true; - } - if (!pushedAny) { - unzip.push(new Uint8Array(0), true); + try { + let pushedAny = false; + let current = await iterator.next(); + while (!current.done) { + const chunk = current.value; + current = await iterator.next(); + unzip.push(chunk, current.done === true); + pushedAny = true; + } + if (!pushedAny) { + unzip.push(new Uint8Array(0), true); + } + await Promise.all(writes); + } finally { + // Cancel the source (e.g. the HTTP body) so a partial read doesn't leak. + await iterator.return?.(); } - await Promise.all(writes); if (failure) { throw failure; } diff --git a/test/lib/snapshots/archive.test.ts b/test/lib/snapshots/archive.test.ts index 15291c8013..181b38d2a3 100644 --- a/test/lib/snapshots/archive.test.ts +++ b/test/lib/snapshots/archive.test.ts @@ -2,7 +2,13 @@ * Tests for streaming snapshot archive extraction, including Zip-Slip protection. */ -import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { strToU8, zipSync } from "fflate"; @@ -83,4 +89,35 @@ describe("extractZipStream", () => { expect(count).toBe(1); expect(readFileSync(join(out, "big.png"), "utf8")).toBe(big); }); + + test("extracts stored (uncompressed, method 0) entries", async () => { + const body = "A".repeat(4000); + // level: 0 → STORE, exercising the UnzipPassThrough decoder. + const zip = zipSync({ "img.png": [strToU8(body), { level: 0 }] }); + const out = tempDir(); + + const count = await extractZipStream(streamOf(zip, 128), out); + + expect(count).toBe(1); + expect(readFileSync(join(out, "img.png"), "utf8")).toBe(body); + }); + + test("surfaces a write error without emitting unhandled rejections", async () => { + const out = tempDir(); + // Pre-create the entry's destination as a directory → write fails (EISDIR). + mkdirSync(join(out, "a.png")); + const zip = zipSync({ "a.png": strToU8("A"), "b.png": strToU8("B") }); + + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => unhandled.push(reason); + process.on("unhandledRejection", onUnhandled); + try { + await expect(extractZipStream(streamOf(zip), out)).rejects.toThrow(); + // Let any stray microtasks/timers surface a rejection if one leaked. + await new Promise((r) => setTimeout(r, 20)); + expect(unhandled).toEqual([]); + } finally { + process.off("unhandledRejection", onUnhandled); + } + }); }); From 1d2d37d87aae886f092af1433ec14d4944a95e13 Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Fri, 3 Jul 2026 07:30:03 +0000 Subject: [PATCH 3/4] fix(snapshots): close open write streams if extraction bails early MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If a push (malformed archive) or the source stream (network error mid-download) throws before `Promise.all(writes)`, the previously-opened write streams were left open, leaking file descriptors — a concern in long-lived library mode. Track open streams and destroy any unclosed ones in the finally when we didn't complete normally. Add a mid-stream source-error test. --- src/lib/snapshots/archive.ts | 13 +++++++++++++ test/lib/snapshots/archive.test.ts | 24 ++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/lib/snapshots/archive.ts b/src/lib/snapshots/archive.ts index 95909e7bda..ff13006aba 100644 --- a/src/lib/snapshots/archive.ts +++ b/src/lib/snapshots/archive.ts @@ -57,7 +57,9 @@ export async function extractZipStream( let written = 0; let failure: Error | null = null; + let completed = false; const writes: Promise[] = []; + const openStreams: ReturnType[] = []; const unzip = new Unzip((file) => { const dest = safeEntryDest(root, file.name); @@ -71,6 +73,7 @@ export async function extractZipStream( mkdirSync(dirname(dest), { recursive: true }); const stream = createWriteStream(dest); + openStreams.push(stream); // Never reject: a write error mid-loop must not become an unhandled // rejection (no handler is attached until Promise.all below). Record the // first error and resolve; it is surfaced after all writes settle. @@ -122,9 +125,19 @@ export async function extractZipStream( unzip.push(new Uint8Array(0), true); } await Promise.all(writes); + completed = true; } finally { // Cancel the source (e.g. the HTTP body) so a partial read doesn't leak. await iterator.return?.(); + // If we bailed early (e.g. unzip.push threw on a malformed archive), close + // any still-open write streams so their file descriptors aren't leaked. + if (!completed) { + for (const stream of openStreams) { + if (!stream.closed) { + stream.destroy(); + } + } + } } if (failure) { diff --git a/test/lib/snapshots/archive.test.ts b/test/lib/snapshots/archive.test.ts index 181b38d2a3..500abc3cfe 100644 --- a/test/lib/snapshots/archive.test.ts +++ b/test/lib/snapshots/archive.test.ts @@ -120,4 +120,28 @@ describe("extractZipStream", () => { process.off("unhandledRejection", onUnhandled); } }); + + test("propagates a mid-stream source error and cleans up", async () => { + const out = tempDir(); + const zip = zipSync({ "a.png": strToU8("A".repeat(2000)) }); + // Emit a partial chunk (opening a write stream) then fail, exercising the + // early-bail cleanup path (skips Promise.all). + async function* faulty(): AsyncIterable { + yield zip.subarray(0, 40); + throw new Error("network boom"); + } + + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => unhandled.push(reason); + process.on("unhandledRejection", onUnhandled); + try { + await expect(extractZipStream(faulty(), out)).rejects.toThrow( + "network boom" + ); + await new Promise((r) => setTimeout(r, 20)); + expect(unhandled).toEqual([]); + } finally { + process.off("unhandledRejection", onUnhandled); + } + }); }); From a0a7276fae0122569fc42ec2c3ef9b2fc117fbdf Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Fri, 3 Jul 2026 07:39:29 +0000 Subject: [PATCH 4/4] fix(snapshots): warn when a downloaded archive yields no images MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fflate's streaming parser is lenient — a corrupt/empty archive extracts 0 files instead of erroring. Network truncation is already caught (undici errors the body stream). Surface the 0-file case with a warning so it isn't silent. --- src/commands/snapshots/download.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/commands/snapshots/download.ts b/src/commands/snapshots/download.ts index c039051531..0c69f3eb13 100644 --- a/src/commands/snapshots/download.ts +++ b/src/commands/snapshots/download.ts @@ -228,6 +228,11 @@ export const downloadCommand = buildCommand({ response.body as unknown as AsyncIterable, output ); + if (imageCount === 0) { + log.warn( + `No images were extracted from snapshot ${snapshotId} — the archive may be empty or corrupt.` + ); + } yield new CommandOutput({ org,