diff --git a/.craft.yml b/.craft.yml index 8fcda72ec..c5e7596ff 100644 --- a/.craft.yml +++ b/.craft.yml @@ -40,6 +40,7 @@ workspaces: artifacts: Build: - "/^sentry-.*$/" + - "/^zst-.*$/" - "npm-package" - "npm-package-sentry-cli" - "/^pypi-wheel-.*$/" diff --git a/.github/workflows/cli-build.yml b/.github/workflows/cli-build.yml index c79a224ab..2b54074a2 100644 --- a/.github/workflows/cli-build.yml +++ b/.github/workflows/cli-build.yml @@ -149,11 +149,19 @@ jobs: path: | packages/cli/dist-bin/sentry-* !packages/cli/dist-bin/*.gz + !packages/cli/dist-bin/*.zst - name: Upload compressed artifact uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: sentry-${{ matrix.target }}-gz path: packages/cli/dist-bin/*.gz + # Named outside the `sentry-*` artifact globs on purpose: the binpatch + # steps treat every non-.gz file they download as a binary to diff. + - name: Upload zstd artifact + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: zst-${{ matrix.target }} + path: packages/cli/dist-bin/*.zst # PyPI `sentry-cli` (the v3 package name) ships one wheel per binary but musl. - name: Build PyPI wheel if: ${{ !matrix.skip-wheel }} diff --git a/apps/cli-docs/src/content/docs/getting-started.mdx b/apps/cli-docs/src/content/docs/getting-started.mdx index 28f94daba..9e0606f00 100644 --- a/apps/cli-docs/src/content/docs/getting-started.mdx +++ b/apps/cli-docs/src/content/docs/getting-started.mdx @@ -178,8 +178,9 @@ on Alpine Linux. The `sentry` PyPI package (self-hosted Sentry) also installs a Each release's binaries are attached to its [GitHub release](https://github.com/getsentry/toolkit/releases) and served from `https://downloads.sentry-cdn.com/sentry-cli//`, as -`sentry--` (`.exe` on Windows) and gzipped as `.gz`. Musl-based Linux, -such as Alpine, uses `sentry-linux--musl`. For example: +`sentry--` (`.exe` on Windows) and gzipped as `.gz`. The GitHub +release also has a zstd copy, `.zst`, about 28% smaller than the `.gz`. +Musl-based Linux, such as Alpine, uses `sentry-linux--musl`. For example: ```bash curl -fsSL https://downloads.sentry-cdn.com/sentry-cli/latest/sentry-linux-x64.gz | gunzip > sentry diff --git a/packages/cli/install b/packages/cli/install index a011fb3f9..f8db5bf11 100755 --- a/packages/cli/install +++ b/packages/cli/install @@ -57,13 +57,15 @@ asset="" # release file name, such as sentry-linux-x64-musl version="" # the exact version being installed gz_url="" # release downloads and their SHA-256 checksums gz_sha="" +zst_url="" # set only from the registry: GitHub fallbacks use gzip +zst_sha="" raw_url="" raw_sha="" registry_status="" # HTTP status of the release registry lookup # Download paths, all in the install directory. plan_download_paths sets them. binary="" # the downloaded binary -blob_file="" # the downloaded .gz, before unpacking +blob_file="" # the downloaded .zst or .gz, before unpacking init_binary="" # hard link to the binary for `sentry init` main() { @@ -378,6 +380,11 @@ gzip_intact() { gunzip -t "$1" 2>/dev/null } +# Usage: zstd_intact . +zstd_intact() { + zstd -tq "$1" 2>/dev/null +} + # Usage: checksum_matches . A missing checksum or a # missing hash tool counts as a match. A mismatch records the actual hash in # bad_checksum. @@ -448,12 +455,16 @@ require_good_checksum() { || die "Checksum mismatch for ${asset} ${version}: expected $1, got ${bad_checksum}" "checksum" } -# Usage: unpack_binary . Unpacks the download to binary, then -# deletes the archive. gzip_intact has already checked the archive, so a -# failure here means the binary could not be written. +# Usage: unpack_binary [command...]. Unpacks the download to binary +# with (`gunzip -c` by default), then deletes the archive. The +# archive has already passed its intact check, so a failure here means the +# binary could not be written. unpack_binary() { - gunzip -c "$1" > "$binary" || die "$no_room_message" "unpack" - rm -f "$1" + local archive=$1 + shift + (( $# )) || set -- gunzip -c + "$@" "$archive" > "$binary" || die "$no_room_message" "unpack" + rm -f "$archive" } # --------------------------------------------------------------------------- @@ -516,6 +527,7 @@ fetch_registry_release() { fi version="$registry_version" + { read -r zst_url; read -r zst_sha; } <<< "$(registry_file "$metadata" "${asset}.zst")" || true { read -r gz_url; read -r gz_sha; } <<< "$(registry_file "$metadata" "${asset}.gz")" || true { read -r raw_url; read -r raw_sha; } <<< "$(registry_file "$metadata" "$asset")" || true if [[ -z "$gz_url" && -z "$raw_url" ]]; then @@ -551,12 +563,22 @@ registry_file() { }' <<< "$1" } -# Prefers the gzip asset (~37 MB instead of ~99 MB) and falls back to the raw -# binary when it is missing or unusable. A checksum mismatch on both tries is +# Prefers the zstd asset when zstd is installed (~28% smaller than gzip), then +# the gzip asset (~37 MB instead of ~99 MB), and falls back to the raw binary +# when those are missing or unusable. A checksum mismatch on both tries is # fatal, never a reason to fall back. download_stable() { muted "Downloading sentry v${version}..." + if [[ -n "$zst_url" ]] && command -v zstd >/dev/null 2>&1; then + if download_verified "$blob_file" "$zst_url" "$zst_sha" zstd_intact; then + unpack_binary "$blob_file" zstd -dcq + return + fi + require_good_checksum "$zst_sha" + rm -f "$blob_file" + fi + if [[ -n "$gz_url" ]] \ && download_verified "$blob_file" "$gz_url" "$gz_sha" gzip_intact; then unpack_binary "$blob_file" diff --git a/packages/cli/script/build.ts b/packages/cli/script/build.ts index de537b14c..00ffb3811 100644 --- a/packages/cli/script/build.ts +++ b/packages/cli/script/build.ts @@ -37,7 +37,7 @@ import { createRequire } from "node:module"; import { basename } from "node:path"; import { buildCarExtract } from "./build-car-extract.js"; import { promisify } from "node:util"; -import { gzip } from "node:zlib"; +import { constants as zlibConstants, gzip, zstdCompress } from "node:zlib"; import { type BuildOptions, build as esbuild } from "esbuild"; import { fossilize } from "fossilize"; import { @@ -59,6 +59,17 @@ import { textImportPlugin } from "./text-import-plugin.js"; import { logger } from "../src/lib/logger.js"; const gzipAsync = promisify(gzip); +const zstdCompressAsync = promisify(zstdCompress); + +/** + * zstd settings for release downloads: level 19 with a 128 MiB window. The + * window spans (nearly) the whole binary, and 2^27 is the largest window + * that the `zstd` CLI and `node:zlib` decode without extra flags. + */ +const ZSTD_PARAMS = { + [zlibConstants.ZSTD_c_compressionLevel]: 19, + [zlibConstants.ZSTD_c_windowLog]: 27, +}; const pkg = JSON.parse(await readFile("package.json", "utf-8")); const VERSION: string = pkg.version; @@ -471,17 +482,31 @@ async function postProcessTarget(target: BuildTarget): Promise { logger.log(` -> ${outfile}`); - // On main and release branches (RELEASE_BUILD=1), create gzip-compressed - // copies for release downloads / GHCR nightly (~70% smaller with hole-punch). + // On main and release branches (RELEASE_BUILD=1), create compressed copies + // for downloads. `.gz` serves GHCR nightlies, the CDN, Homebrew, and hosts + // without zstd; `.zst` is ~28% smaller and preferred by `install` and + // `cli upgrade`. if (process.env["RELEASE_BUILD"]) { const binary = await readFile(outfile); - const compressed = await gzipAsync(Buffer.from(binary), { level: 6 }); - await writeFile(`${outfile}.gz`, compressed); - const ratio = ( - (1 - compressed.byteLength / binary.byteLength) * - 100 - ).toFixed(0); - logger.log(` -> ${outfile}.gz (${ratio}% smaller)`); + const [gz, zst] = await Promise.all([ + gzipAsync(binary, { level: 6 }), + zstdCompressAsync(binary, { params: ZSTD_PARAMS }), + ]); + await Promise.all( + ( + [ + [".gz", gz], + [".zst", zst], + ] as const + ).map(async ([ext, compressed]) => { + await writeFile(`${outfile}${ext}`, compressed); + const ratio = ( + (1 - compressed.byteLength / binary.byteLength) * + 100 + ).toFixed(0); + logger.log(` -> ${outfile}${ext} (${ratio}% smaller)`); + }), + ); } } diff --git a/packages/cli/src/lib/upgrade.ts b/packages/cli/src/lib/upgrade.ts index ecdc17884..e038a9e29 100644 --- a/packages/cli/src/lib/upgrade.ts +++ b/packages/cli/src/lib/upgrade.ts @@ -18,7 +18,9 @@ import { import { writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import { dirname, isAbsolute, join, sep } from "node:path"; +import { Duplex } from "node:stream"; import { setTimeout } from "node:timers/promises"; +import { createZstdDecompress } from "node:zlib"; import { prerelease as semverPrerelease, valid as semverValid } from "semver"; import { sentry } from "./app-identity.js"; import { @@ -906,6 +908,29 @@ function writeChunkSync(fd: number, chunk: Uint8Array): void { } } +/** Creates a fresh web-stream decompressor for one download. */ +type Decompressor = () => ReadableWritablePair< + Uint8Array, + Uint8Array +>; + +const gunzip: Decompressor = () => new DecompressionStream("gzip"); + +/** + * zstd decompressor, or `undefined` on runtimes without zstd in `node:zlib` + * (Node < 22.15), where downloads use gzip instead. + */ +const unzstd: Decompressor | undefined = + typeof createZstdDecompress === "function" + ? () => { + const { readable, writable } = Duplex.toWeb(createZstdDecompress()); + return { + readable: readable as ReadableStream>, + writable, + }; + } + : undefined; + /** * Drain a decompressed body into `fd`, awaiting the underlying stream * pipeline. Returns the terminal stream error (if any) and any error @@ -916,6 +941,7 @@ async function drainBodyToFd( body: ReadableStream>, fd: number, onBytes: (n: number) => void, + decompress: Decompressor, ): Promise<{ streamError: Error | undefined; writeError: Error | undefined; @@ -923,9 +949,7 @@ async function drainBodyToFd( let writeError: Error | undefined; let streamError: Error | undefined; try { - for await (const chunk of body.pipeThrough( - new DecompressionStream("gzip"), - )) { + for await (const chunk of body.pipeThrough(decompress())) { if (writeError) { break; } @@ -960,11 +984,13 @@ async function drainBodyToFd( * * @param body - Readable stream from a fetch response * @param destPath - File path to write the decompressed output + * @param decompress - Decompressor for the body's format (gzip by default) */ async function streamDecompressToFile( body: ReadableStream>, destPath: string, setMessage?: SetMessage, + decompress: Decompressor = gunzip, ): Promise { // Indeterminate byte counter: the decompressed size isn't known ahead of // time (Content-Length covers only the compressed stream), so we show a live @@ -975,8 +1001,11 @@ async function streamDecompressToFile( // Drain the body to the fd. Awaited so we know before closeSync whether // the drain terminated with an error. - const { streamError, writeError } = await drainBodyToFd(body, fd, (n) => - progress.onProgress(n), + const { streamError, writeError } = await drainBodyToFd( + body, + fd, + (n) => progress.onProgress(n), + decompress, ); progress.done(); @@ -1061,13 +1090,14 @@ async function downloadNightlyToPath( /** * Download a stable binary from GitHub Releases and write it to `destPath`. * - * Tries the gzip-compressed URL first (`{url}.gz`, ~37 MB vs ~99 MB), - * falling back to the raw binary URL on any failure. The compressed - * download is streamed through DecompressionStream for minimal memory usage. + * Tries the compressed URLs first, zstd (`{url}.zst`) when the runtime + * supports it and then gzip (`{url}.gz`), falling back to the raw binary + * URL when both fail. Compressed downloads are streamed through a + * decompressor for minimal memory usage. * * @param version - Stable version string (without 'v' prefix) - * @param destPath - File path to write the binary (decompressed if gzip) - * @throws {UpgradeError} When both download attempts fail + * @param destPath - File path to write the binary (decompressed if compressed) + * @throws {UpgradeError} When every download attempt fails */ async function downloadStableToPath( version: string, @@ -1078,20 +1108,41 @@ async function downloadStableToPath( const url = getBinaryDownloadUrl(version, source); const headers = getGitHubHeaders(); - // Try gzip-compressed download first (~60% smaller) - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. - try { - const gzResponse = await fetchWithUpgradeError( - `${url}.gz`, - { headers }, - "GitHub", - ); - if (gzResponse.ok && gzResponse.body) { - await streamDecompressToFile(gzResponse.body, destPath, setMessage); - return; + /** Downloads `{url}{ext}` into `destPath`; false when it is unavailable. */ + const tryCompressed = async ( + ext: string, + decompress: Decompressor, + ): Promise => { + try { + const response = await fetchWithUpgradeError( + `${url}${ext}`, + { headers }, + "GitHub", + ); + if (response.ok && response.body) { + await streamDecompressToFile( + response.body, + destPath, + setMessage, + decompress, + ); + return true; + } + log.debug(`${ext} download returned HTTP ${response.status}`); + } catch (error) { + log.debug(`${ext} download failed, trying the next format`, error); } - } catch { - // Fall through to raw download + return false; + }; + + // Try compressed downloads first: zstd is ~28% smaller than gzip, and + // gzip is ~60% smaller than the raw binary. Releases published before an + // asset existed return 404 for it and fall through to the next one. + if (unzstd && (await tryCompressed(".zst", unzstd))) { + return; + } + if (await tryCompressed(".gz", gunzip)) { + return; } // Fall back to raw (uncompressed) binary diff --git a/packages/cli/test/lib/install-scenarios.ts b/packages/cli/test/lib/install-scenarios.ts index 33b1700b1..fea7fcd5d 100644 --- a/packages/cli/test/lib/install-scenarios.ts +++ b/packages/cli/test/lib/install-scenarios.ts @@ -34,6 +34,8 @@ export interface ServedAsset { name: string; gz: Buffer; raw: string | Buffer; + /** zstd download, listed in the registry only when set (bash only). */ + zst?: Buffer; } type RegistryResponse = @@ -67,6 +69,9 @@ export function registryTemplate( const entries: [string, string | Buffer][] = options.missing ? [["sentry-other-platform", "other"]] : [ + ...(served.zst + ? [[`${served.name}.zst`, served.zst] as [string, Buffer]] + : []), [`${served.name}.gz`, served.gz], [served.name, served.raw], ]; diff --git a/packages/cli/test/lib/install-script.test.ts b/packages/cli/test/lib/install-script.test.ts index 9817499fc..fbea20883 100644 --- a/packages/cli/test/lib/install-script.test.ts +++ b/packages/cli/test/lib/install-script.test.ts @@ -18,7 +18,7 @@ import { createServer } from "node:http"; import type { AddressInfo } from "node:net"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { gzipSync } from "node:zlib"; +import { gzipSync, zstdCompressSync } from "node:zlib"; import { afterEach, beforeEach, describe, expect, test } from "vitest"; import { applyScenario, @@ -141,6 +141,9 @@ case "$url" in https://o1.ingest.us.sentry.io/api/*/envelope/) printf '%s\\n' "$data" > "$SENTRY_TEST_DIR/error-report" ;; + https://github.com/*/releases/download/*.zst) + emit < "$SENTRY_TEST_ZST_FILE" + ;; https://github.com/*/releases/download/*.gz) if [[ "\${SENTRY_TEST_GZ_MISSING:-}" == "1" ]]; then exit 22; fi if (( $(nth gz) <= \${SENTRY_TEST_GZ_CORRUPT:-0} )); then @@ -221,6 +224,74 @@ esac ); }); + describe("zstd downloads", () => { + // Stands in for the zstd CLI, so the test runs on hosts without it. + // SENTRY_TEST_ZSTD_FAIL=1 makes every call fail, like a corrupt archive. + function installFakeZstd(): void { + writeFileSync( + join(binDir, "zstd"), + `#!${process.execPath} +const { readFileSync } = require("node:fs"); +const { zstdDecompressSync } = require("node:zlib"); +if (process.env.SENTRY_TEST_ZSTD_FAIL === "1") process.exit(1); +const out = zstdDecompressSync(readFileSync(process.argv.at(-1))); +if (!process.argv.includes("-tq")) process.stdout.write(out); +`, + ); + chmodSync(join(binDir, "zstd"), 0o755); + } + + function serveZst(): void { + const zst = zstdCompressSync(downloadedExecutable); + const zstFile = join(testDir, "served-asset.zst"); + writeFileSync(zstFile, zst); + env["SENTRY_TEST_ZST_FILE"] = zstFile; + writeFileSync( + env["SENTRY_TEST_REGISTRY_BODY"] as string, + registryTemplate({ ...served, zst }, {}), + ); + } + + test("prefers the zstd asset when zstd is installed", () => { + installFakeZstd(); + serveZst(); + const result = spawnSync("bash", [installScript, "--no-modify-path"], { + env, + encoding: "utf8", + timeout: 10_000, + }); + + expect(result.status, result.stdout + result.stderr).toBe(0); + expect(recorded("curl-urls").slice(1)).toEqual([ + toolkitDownload(LATEST_VERSION, `${hostAsset}.zst`), + ]); + expect(readFileSync(join(installDir, "sentry"), "utf8")).toBe( + downloadedExecutable, + ); + expect(installerTempFiles()).toEqual([]); + }); + + test("falls back to the gzip asset when the zstd archive is unusable", () => { + installFakeZstd(); + serveZst(); + env["SENTRY_TEST_ZSTD_FAIL"] = "1"; + const result = spawnSync("bash", [installScript, "--no-modify-path"], { + env, + encoding: "utf8", + timeout: 10_000, + }); + + expect(result.status, result.stdout + result.stderr).toBe(0); + expect(recorded("curl-urls").slice(1)).toEqual([ + toolkitDownload(LATEST_VERSION, `${hostAsset}.zst`), + toolkitDownload(LATEST_VERSION, `${hostAsset}.zst`), + toolkitDownload(LATEST_VERSION, `${hostAsset}.gz`), + ]); + expect(existsSync(join(installDir, "sentry"))).toBe(true); + expect(installerTempFiles()).toEqual([]); + }); + }); + function recorded(name: string): string[] { const path = join(testDir, name); return existsSync(path) diff --git a/packages/cli/test/lib/upgrade.test.ts b/packages/cli/test/lib/upgrade.test.ts index 5c4b7bb6f..e2504a1b5 100644 --- a/packages/cli/test/lib/upgrade.test.ts +++ b/packages/cli/test/lib/upgrade.test.ts @@ -28,7 +28,7 @@ import { import { homedir, platform } from "node:os"; import { join, sep } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; -import { gzipSync } from "node:zlib"; +import { gzipSync, zstdCompressSync } from "node:zlib"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; // --------------------------------------------------------------------------- @@ -1942,14 +1942,54 @@ describe("executeUpgrade with curl method", () => { expect(new Uint8Array(content)).toEqual(mockBinaryContent); }); - test("falls back to raw binary when .gz URL returns 404", async () => { + test("prefers the .zst download over .gz", async () => { + const mockBinaryContent = new Uint8Array([0x7f, 0x45, 0x4c, 0x46]); + const requested: string[] = []; + + mockFetch(async (url) => { + const urlStr = extractInputUrl(url); + requested.push(urlStr); + if (urlStr.endsWith(".zst")) { + return new Response(zstdCompressSync(mockBinaryContent), { + status: 200, + }); + } + return new Response("Not Found", { status: 404 }); + }); + + const result = await executeUpgrade("curl", "1.0.0"); + + expect(requested).toHaveLength(1); + expect(requested[0]).toMatch(/\.zst$/); + const content = await readFile(result!.tempBinaryPath); + expect(new Uint8Array(content)).toEqual(mockBinaryContent); + }); + + test("falls back to .gz when the .zst asset is missing", async () => { + const mockBinaryContent = new Uint8Array([0x7f, 0x45, 0x4c, 0x46]); + + mockFetch(async (url) => { + if (extractInputUrl(url).endsWith(".gz")) { + return new Response(gzipSync(mockBinaryContent), { status: 200 }); + } + return new Response("Not Found", { status: 404 }); + }); + + const result = await executeUpgrade("curl", "1.0.0"); + + const content = await readFile(result!.tempBinaryPath); + expect(new Uint8Array(content)).toEqual(mockBinaryContent); + }); + + test("falls back to raw binary when compressed URLs return 404", async () => { const mockBinaryContent = new Uint8Array([0x7f, 0x45, 0x4c, 0x46]); // ELF magic bytes let callCount = 0; - // Mock fetch: first call (for .gz) returns 404, second returns raw binary - mockFetch(async () => { + // Mock fetch: compressed assets return 404, raw URL returns the binary + mockFetch(async (url) => { callCount += 1; - if (callCount === 1) { + const urlStr = extractInputUrl(url); + if (urlStr.endsWith(".zst") || urlStr.endsWith(".gz")) { return new Response("Not Found", { status: 404 }); } return new Response(mockBinaryContent, { status: 200 }); @@ -1958,7 +1998,7 @@ describe("executeUpgrade with curl method", () => { const result = await executeUpgrade("curl", "1.0.0"); expect(result).not.toBeNull(); - expect(callCount).toBe(2); // Both .gz and raw URL were tried + expect(callCount).toBe(3); // .zst, .gz, and raw URL were tried // Verify the binary was downloaded expect( @@ -1971,14 +2011,15 @@ describe("executeUpgrade with curl method", () => { expect(new Uint8Array(content)).toEqual(mockBinaryContent); }); - test("falls back to raw binary when .gz fetch throws network error", async () => { + test("falls back to raw binary when compressed fetches throw network errors", async () => { const mockBinaryContent = new Uint8Array([0x7f, 0x45, 0x4c, 0x46]); let callCount = 0; - // Mock fetch: first call throws, second returns raw binary - mockFetch(async () => { + // Mock fetch: compressed downloads throw, raw URL returns the binary + mockFetch(async (url) => { callCount += 1; - if (callCount === 1) { + const urlStr = extractInputUrl(url); + if (urlStr.endsWith(".zst") || urlStr.endsWith(".gz")) { throw new TypeError("fetch failed"); } return new Response(mockBinaryContent, { status: 200 }); @@ -1987,7 +2028,7 @@ describe("executeUpgrade with curl method", () => { const result = await executeUpgrade("curl", "1.0.0"); expect(result).not.toBeNull(); - expect(callCount).toBe(2); + expect(callCount).toBe(3); const content = await readFile(result!.tempBinaryPath); expect(new Uint8Array(content)).toEqual(mockBinaryContent);