Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .craft.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
artifacts:
Build:
- "/^sentry-.*$/"
- "/^zst-.*$/"

Check warning on line 43 in .craft.yml

View check run for this annotation

@sentry/warden / warden: code-review

Registry includeNames still excludes .zst, so install never prefers zstd

Craft now collects `zst-*` build artifacts, but `app:sentry` still publishes only `/^sentry-.*\.gz$/`, so the installer never receives a `.zst` URL/checksum and always falls back to gzip. Update that includeNames (e.g. `/^sentry-.*\.(gz|zst)$/`) so registry releases list the new assets.
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved
- "npm-package"
- "npm-package-sentry-cli"
- "/^pypi-wheel-.*$/"
Expand Down
8 changes: 8 additions & 0 deletions .github/workflows/cli-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
Expand Down
5 changes: 3 additions & 2 deletions apps/cli-docs/src/content/docs/getting-started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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/<version>/`, as
`sentry-<os>-<arch>` (`.exe` on Windows) and gzipped as `.gz`. Musl-based Linux,
such as Alpine, uses `sentry-linux-<arch>-musl`. For example:
`sentry-<os>-<arch>` (`.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-<arch>-musl`. For example:

```bash
curl -fsSL https://downloads.sentry-cdn.com/sentry-cli/latest/sentry-linux-x64.gz | gunzip > sentry
Expand Down
38 changes: 30 additions & 8 deletions packages/cli/install
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -378,6 +380,11 @@ gzip_intact() {
gunzip -t "$1" 2>/dev/null
}

# Usage: zstd_intact <zst-file>.
zstd_intact() {
zstd -tq "$1" 2>/dev/null
}

# Usage: checksum_matches <file> <expected-hex>. A missing checksum or a
# missing hash tool counts as a match. A mismatch records the actual hash in
# bad_checksum.
Expand Down Expand Up @@ -448,12 +455,16 @@ require_good_checksum() {
|| die "Checksum mismatch for ${asset} ${version}: expected $1, got ${bad_checksum}" "checksum"
}

# Usage: unpack_binary <gz-file>. 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 <archive> [command...]. Unpacks the download to binary
# with <command> (`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"
}

# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
45 changes: 35 additions & 10 deletions packages/cli/script/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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;
Expand Down Expand Up @@ -471,17 +482,31 @@ async function postProcessTarget(target: BuildTarget): Promise<void> {

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)`);
}),
);
}
}

Expand Down
97 changes: 74 additions & 23 deletions packages/cli/src/lib/upgrade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -906,6 +908,29 @@ function writeChunkSync(fd: number, chunk: Uint8Array): void {
}
}

/** Creates a fresh web-stream decompressor for one download. */
type Decompressor = () => ReadableWritablePair<
Uint8Array<ArrayBuffer>,
Uint8Array<ArrayBuffer>
>;

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<Uint8Array<ArrayBuffer>>,
writable,
};
}
: undefined;

/**
* Drain a decompressed body into `fd`, awaiting the underlying stream
* pipeline. Returns the terminal stream error (if any) and any error
Expand All @@ -916,16 +941,15 @@ async function drainBodyToFd(
body: ReadableStream<Uint8Array<ArrayBuffer>>,
fd: number,
onBytes: (n: number) => void,
decompress: Decompressor,
): Promise<{
streamError: Error | undefined;
writeError: Error | undefined;
}> {
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;
}
Expand Down Expand Up @@ -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<Uint8Array<ArrayBuffer>>,
destPath: string,
setMessage?: SetMessage,
decompress: Decompressor = gunzip,
): Promise<void> {
// Indeterminate byte counter: the decompressed size isn't known ahead of
// time (Content-Length covers only the compressed stream), so we show a live
Expand All @@ -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();

Expand Down Expand Up @@ -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,
Expand All @@ -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<boolean> => {
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
Expand Down
5 changes: 5 additions & 0 deletions packages/cli/test/lib/install-scenarios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down Expand Up @@ -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],
];
Expand Down
Loading
Loading