-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdelta-upgrade.ts
More file actions
1346 lines (1228 loc) · 39.7 KB
/
delta-upgrade.ts
File metadata and controls
1346 lines (1228 loc) · 39.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Delta Upgrade Module
*
* Discovers and applies binary delta patches for CLI self-upgrades.
* Instead of downloading the full ~30 MB gzipped binary, downloads
* tiny patches (50-500 KB) and applies them to the currently installed
* binary using the TRDIFF10 format (zig-bsdiff with zstd compression).
*
* Supports two channels:
* - **Stable**: patches stored as GitHub Release assets with predictable names
* - **Nightly**: patches stored in GHCR with `:patch-<version>` tags
*
* Falls back to full download when:
* - No patch is available (404)
* - Chain of patches exceeds 60% of the full download size
* - Chain exceeds the maximum depth (10 steps)
* - Any error occurs during patch download or application
*/
import { unlinkSync } from "node:fs";
// biome-ignore lint/performance/noNamespaceImport: Sentry SDK recommends namespace import
import * as Sentry from "@sentry/node-core/light";
import {
GITHUB_RELEASES_URL,
getPlatformBinaryName,
isDowngrade,
isNightlyVersion,
} from "./binary.js";
import { applyPatch } from "./bspatch.js";
import { CLI_VERSION } from "./constants.js";
import { customFetch } from "./custom-ca.js";
import { formatBytes } from "./formatters/numbers.js";
import {
downloadLayerBlob,
fetchManifest,
getAnonymousToken,
listTags,
type OciManifest,
} from "./ghcr.js";
import { logger } from "./logger.js";
import { loadCachedChain, savePatchesToCache } from "./patch-cache.js";
import { withTracing, withTracingSpan } from "./telemetry.js";
/** Scoped logger for delta upgrade operations */
const log = logger.withTag("delta-upgrade");
/**
* Maximum number of stable patches to chain before falling back to full download.
* Also controls the GitHub Releases `per_page` in {@link fetchRecentReleases}.
*/
const MAX_STABLE_CHAIN_DEPTH = 10;
/**
* Maximum number of nightly patches to chain before falling back to full download.
* Matches the GHCR cleanup `KEEP_COUNT` (30 retained nightly tags) so every
* retained patch tag is usable. Acts as a safety net against unbounded manifest
* fan-out — the size budget ({@link SIZE_THRESHOLD_RATIO}) is the primary guard.
*/
const MAX_NIGHTLY_CHAIN_DEPTH = 30;
/**
* Maximum ratio of total patch chain size to full download size.
* If the sum of patches exceeds this fraction of the `.gz` download,
* we fall back to full download since the savings are too small.
*/
const SIZE_THRESHOLD_RATIO = 0.6;
/** Pattern to extract hex from a GitHub asset digest like "sha256:<hex>" */
const SHA256_DIGEST_PATTERN = /^sha256:([0-9a-f]+)$/i;
/** A single link in the patch chain */
type PatchLink = {
/** Raw patch file data */
data: Uint8Array;
/** Byte size of the patch */
size: number;
};
/** A resolved chain of patches from current version to target version */
export type PatchChain = {
/** Ordered list of patches to apply (oldest first) */
patches: PatchLink[];
/** Total size of all patches in the chain (bytes) */
totalSize: number;
/** Expected SHA-256 hex digest of the final output binary */
expectedSha256: string;
/**
* Version step pairs in apply order (oldest first).
* Present when the chain was resolved from network — used for cache storage.
*/
steps?: { fromVersion: string; toVersion: string }[];
};
/** Result of a successful delta upgrade */
export type DeltaResult = {
/** SHA-256 hex digest of the output binary */
sha256: string;
/** Total bytes downloaded for the patch chain */
patchBytes: number;
/** Number of patches in the chain (1 = direct, >1 = multi-hop) */
chainLength: number;
};
/**
* Check whether delta upgrade can be attempted.
*
* Conditions that prevent delta upgrade:
* - Running a dev build (CLI_VERSION = "0.0.0-dev")
* - Cross-channel upgrade (stable→nightly or nightly→stable)
* - Current executable path is not readable
*
* @param targetVersion - Version to upgrade to
* @returns true if delta upgrade should be attempted
*/
export function canAttemptDelta(targetVersion: string): boolean {
// Dev builds have no known base version to patch from
if (CLI_VERSION === "0.0.0-dev") {
return false;
}
// Cross-channel upgrades are rare one-off operations; skip delta
if (isNightlyVersion(CLI_VERSION) !== isNightlyVersion(targetVersion)) {
return false;
}
// Downgrades have no forward patch path — skip immediately
if (isDowngrade(CLI_VERSION, targetVersion)) {
return false;
}
return true;
}
// Stable channel: GitHub Releases
/** GitHub Release asset metadata (subset of API response) */
export type GitHubAsset = {
name: string;
size: number;
/** SHA-256 digest in the form "sha256:<hex>" */
digest?: string;
browser_download_url: string;
};
/** GitHub Release metadata (subset of API response) */
export type GitHubRelease = {
tag_name: string;
assets: GitHubAsset[];
/** Markdown release notes body. May be empty or absent for pre-releases. */
body?: string;
};
/**
* Fetch recent releases from GitHub, ordered newest-first.
*
* A single API call returns full release metadata including assets,
* eliminating the need for per-release fetches during chain resolution.
*
* @returns Array of releases (newest first), or empty array on failure
*/
export async function fetchRecentReleases(
signal?: AbortSignal
): Promise<GitHubRelease[]> {
const perPage = MAX_STABLE_CHAIN_DEPTH + 2;
let response: Response;
try {
response = await customFetch(`${GITHUB_RELEASES_URL}?per_page=${perPage}`, {
headers: {
Accept: "application/vnd.github.v3+json",
"User-Agent": "sentry-cli",
},
signal,
});
} catch (error) {
log.debug("Failed to fetch recent releases from GitHub", error);
return [];
}
if (!response.ok) {
return [];
}
return (await response.json()) as GitHubRelease[];
}
/**
* Extract SHA-256 hex digest from a GitHub asset's digest field.
*
* GitHub provides digests as "sha256:<hex>". This strips the prefix.
*
* @param asset - GitHub Release asset
* @returns Hex digest string, or null if no digest available
*/
export function extractSha256(asset: GitHubAsset): string | null {
if (!asset.digest) {
return null;
}
const match = SHA256_DIGEST_PATTERN.exec(asset.digest);
// Normalize to lowercase — Bun.CryptoHasher.digest("hex") returns lowercase
return match ? (match[1]?.toLowerCase() ?? null) : null;
}
/**
* Download a patch file from a GitHub Release asset URL.
*
* @param url - Browser download URL for the asset
* @returns Patch file data, or null on failure
*/
export async function downloadStablePatch(
url: string,
signal?: AbortSignal
): Promise<Uint8Array | null> {
let response: Response;
try {
response = await customFetch(url, {
headers: { "User-Agent": "sentry-cli" },
signal,
});
} catch (error) {
log.debug("Failed to download stable patch", error);
return null;
}
if (!response.ok) {
return null;
}
return new Uint8Array(await response.arrayBuffer());
}
/**
* Extract the target binary SHA-256 from a GitHub Release.
*
* @param release - GitHub Release metadata
* @param binaryName - Platform binary name (e.g., "sentry-linux-x64")
* @returns Hex SHA-256 digest, or null if unavailable
*/
export function getStableTargetSha256(
release: GitHubRelease,
binaryName: string
): string | null {
const binaryAsset = release.assets.find((a) => a.name === binaryName);
if (!binaryAsset) {
return null;
}
return extractSha256(binaryAsset);
}
/** Options for extracting the stable version chain from a release list */
export type ExtractStableChainOpts = {
releases: GitHubRelease[];
currentVersion: string;
targetVersion: string;
binaryName: string;
fullGzSize: number;
};
/** Extracted stable chain info (patch URLs in apply order + target hash) */
export type StableChainInfo = {
/** Patch download URLs in apply order (oldest patch first) */
patchUrls: string[];
/** Expected SHA-256 of the final target binary */
expectedSha256: string;
/** Version step pairs in apply order (oldest first) */
steps: { fromVersion: string; toVersion: string }[];
};
/**
* Extract the chain of patch URLs from an already-fetched release list.
*
* Pure computation over the release array — no HTTP calls. Validates that
* every release in the chain has a patch asset and that the cumulative
* size stays under the threshold.
*
* @returns Chain info with URLs in apply order, or null if unavailable
*/
export function extractStableChain(
opts: ExtractStableChainOpts
): StableChainInfo | null {
const { releases, currentVersion, targetVersion, binaryName, fullGzSize } =
opts;
const patchAssetName = `${binaryName}.patch`;
// Releases are newest-first; find target and current positions
const targetIdx = releases.findIndex((r) => r.tag_name === targetVersion);
const currentIdx = releases.findIndex((r) => r.tag_name === currentVersion);
if (targetIdx === -1 || currentIdx === -1 || targetIdx >= currentIdx) {
return null;
}
// Chain: [target, ..., current+1] (newest first, excludes current)
const chainReleases = releases.slice(targetIdx, currentIdx);
if (chainReleases.length > MAX_STABLE_CHAIN_DEPTH) {
log.debug(
`Stable chain depth ${chainReleases.length} exceeds limit ${MAX_STABLE_CHAIN_DEPTH}`
);
return null;
}
// SHA-256 comes from the target release's binary asset
const targetRelease = chainReleases[0];
if (!targetRelease) {
return null;
}
const expectedSha256 = getStableTargetSha256(targetRelease, binaryName) ?? "";
if (!expectedSha256) {
return null;
}
// Collect patch URLs and validate size threshold
const patchUrls: string[] = [];
let totalSize = 0;
for (const release of chainReleases) {
const patchAsset = release.assets.find((a) => a.name === patchAssetName);
if (!patchAsset) {
return null;
}
patchUrls.push(patchAsset.browser_download_url);
totalSize += patchAsset.size;
if (totalSize > fullGzSize * SIZE_THRESHOLD_RATIO) {
log.debug(
`Stable chain size ${totalSize} exceeds ${Math.round(SIZE_THRESHOLD_RATIO * 100)}% of full download ${fullGzSize}`
);
return null;
}
}
// Reverse to get apply order: oldest patch first
patchUrls.reverse();
// Build version steps in apply order (oldest first, matching patchUrls)
const reversedReleases = [...chainReleases].reverse();
const steps: { fromVersion: string; toVersion: string }[] = [];
let prevVersion = currentVersion;
for (const release of reversedReleases) {
steps.push({ fromVersion: prevVersion, toVersion: release.tag_name });
prevVersion = release.tag_name;
}
return { patchUrls, expectedSha256, steps };
}
/**
* Resolve a chain of stable patches from current to target version.
*
* 1. Single API call: fetch recent releases (includes full asset metadata)
* 2. Extract chain info from the list (pure computation, no I/O)
* 3. Parallel: download all patch files concurrently
*
* @param currentVersion - Currently installed version
* @param targetVersion - Version to upgrade to
* @returns Resolved patch chain, or null if unavailable
*/
export async function resolveStableChain(
currentVersion: string,
targetVersion: string,
signal?: AbortSignal
): Promise<PatchChain | null> {
const binaryName = getPlatformBinaryName();
const releases = await withTracing("fetch-releases", "http.client", () =>
fetchRecentReleases(signal)
);
// Get .gz size from the target release for threshold calculation
const targetRelease = releases.find((r) => r.tag_name === targetVersion);
if (!targetRelease) {
return null;
}
const gzAsset = targetRelease.assets.find(
(a) => a.name === `${binaryName}.gz`
);
if (!gzAsset) {
return null;
}
const chainInfo = extractStableChain({
releases,
currentVersion,
targetVersion,
binaryName,
fullGzSize: gzAsset.size,
});
if (!chainInfo) {
return null;
}
// Parallel patch download
const downloadResults = await withTracing(
"download-patches",
"http.client",
() =>
Promise.all(
chainInfo.patchUrls.map((url) => downloadStablePatch(url, signal))
)
);
const patches: PatchLink[] = [];
let totalSize = 0;
for (const data of downloadResults) {
if (!data) {
return null;
}
patches.push({ data, size: data.byteLength });
totalSize += data.byteLength;
}
return {
patches,
totalSize,
expectedSha256: chainInfo.expectedSha256,
steps: chainInfo.steps,
};
}
// Nightly channel: GHCR
/**
* Extract the `from-version` annotation from a patch manifest.
*
* @param manifest - OCI manifest for a `:patch-<version>` tag
* @returns The base version this patch applies to, or null if missing
*/
export function getPatchFromVersion(manifest: OciManifest): string | null {
return manifest.annotations?.["from-version"] ?? null;
}
/**
* Extract the SHA-256 annotation for a specific platform from a patch manifest.
*
* Annotations are stored as `sha256-<binaryName>=<hex>`.
*
* @param manifest - OCI manifest for a `:patch-<version>` tag
* @param binaryName - Platform binary name (e.g., "sentry-linux-x64")
* @returns Hex digest string, or null if not found
*/
export function getPatchTargetSha256(
manifest: OciManifest,
binaryName: string
): string | null {
return manifest.annotations?.[`sha256-${binaryName}`] ?? null;
}
/** GHCR tag prefix for patch manifests */
export const PATCH_TAG_PREFIX = "patch-";
/**
* Filter patch tags to only those in the upgrade chain from current to target,
* and sort them in apply order (oldest first).
*
* Since nightly patches are sequential (each `patch-<V_n>` patches from V_{n-1}),
* the chain tags are those where the version is strictly greater than
* currentVersion and less than or equal to targetVersion.
*
* @param allTags - All patch tags from GHCR (e.g., `["patch-0.14.0-dev.100", ...]`)
* @param currentVersion - Version to upgrade from
* @param targetVersion - Version to upgrade to
* @returns Sorted tag names in apply order, or empty array if none match
*/
export function filterAndSortChainTags(
allTags: string[],
currentVersion: string,
targetVersion: string
): string[] {
const chainTags: { tag: string; version: string }[] = [];
for (const tag of allTags) {
const version = tag.slice(PATCH_TAG_PREFIX.length);
// Include tags where: currentVersion < version <= targetVersion
if (
Bun.semver.order(version, currentVersion) === 1 &&
Bun.semver.order(version, targetVersion) !== 1
) {
chainTags.push({ tag, version });
}
}
// Sort by version (chronological for nightlies)
chainTags.sort((a, b) => Bun.semver.order(a.version, b.version));
return chainTags.map((t) => t.tag);
}
/** Result of validating a nightly chain of manifests */
type NightlyChainValidation = {
/** Layer digests in apply order (oldest first) */
digests: string[];
/** Total size of all patch layers */
totalSize: number;
/** Expected SHA-256 of the final target binary */
expectedSha256: string;
};
/** Options for validating a nightly chain */
type ValidateChainOpts = {
manifests: OciManifest[];
chainTags: string[];
currentVersion: string;
targetVersion: string;
patchLayerName: string;
binaryName: string;
fullGzSize: number;
};
/** Reason a chain step failed validation */
type ChainStepFailure =
| { reason: "version-mismatch"; expected: string; actual: string | null }
| { reason: "missing-layer"; layerName: string }
| { reason: "size-exceeded"; layerSize: number; budget: number };
/** Result of validating a single chain step */
type ChainStepResult =
| { ok: true; digest: string; size: number }
| { ok: false; failure: ChainStepFailure };
/**
* Validate a single step in the nightly chain.
*
* Checks three conditions in order:
* 1. Manifest's `from-version` annotation matches the expected previous version
* 2. A layer with the expected platform title exists in the manifest
* 3. The layer's size fits within the remaining download budget
*
* @returns Layer digest and size on success, or a typed failure reason
*/
export function validateChainStep(
manifest: OciManifest,
opts: { expectedFrom: string; patchLayerName: string; sizeLimit: number }
): ChainStepResult {
const fromVersion = getPatchFromVersion(manifest);
if (fromVersion !== opts.expectedFrom) {
return {
ok: false,
failure: {
reason: "version-mismatch",
expected: opts.expectedFrom,
actual: fromVersion,
},
};
}
const layer = manifest.layers.find((l) => {
const title = l.annotations?.["org.opencontainers.image.title"];
return title === opts.patchLayerName;
});
if (!layer) {
return {
ok: false,
failure: { reason: "missing-layer", layerName: opts.patchLayerName },
};
}
if (layer.size > opts.sizeLimit) {
return {
ok: false,
failure: {
reason: "size-exceeded",
layerSize: layer.size,
budget: opts.sizeLimit,
},
};
}
return { ok: true, digest: layer.digest, size: layer.size };
}
/** Format a chain step failure reason for debug logging */
function formatStepFailure(failure: ChainStepFailure): string {
switch (failure.reason) {
case "version-mismatch":
return `version mismatch (expected=${failure.expected}, actual=${failure.actual ?? "missing"})`;
case "missing-layer":
return `platform layer not found (expected=${failure.layerName})`;
case "size-exceeded":
return `patch too large (size=${failure.layerSize}, budget=${failure.budget})`;
default:
return "unknown failure";
}
}
/**
* Validate a chain of manifests and extract patch layer info.
*
* Checks that each manifest's `from-version` links to the previous step,
* that the platform patch layer exists, and that cumulative size stays
* under the threshold.
*
* @returns Validated chain info, or null if the chain is invalid
*/
function validateNightlyChain(
opts: ValidateChainOpts
): NightlyChainValidation | null {
const {
manifests,
chainTags,
currentVersion,
targetVersion,
patchLayerName,
binaryName,
fullGzSize,
} = opts;
const digests: string[] = [];
let totalSize = 0;
let prevVersion = currentVersion;
for (let i = 0; i < manifests.length; i++) {
const manifest = manifests[i];
const tag = chainTags[i];
if (!(manifest && tag)) {
return null;
}
const remainingBudget = fullGzSize * SIZE_THRESHOLD_RATIO - totalSize;
const result = validateChainStep(manifest, {
expectedFrom: prevVersion,
patchLayerName,
sizeLimit: remainingBudget,
});
if (!result.ok) {
log.debug(
`Nightly chain step ${i + 1} failed: ${formatStepFailure(result.failure)}`
);
return null;
}
digests.push(result.digest);
totalSize += result.size;
prevVersion = tag.slice(PATCH_TAG_PREFIX.length);
if (i === manifests.length - 1) {
// Verify the last tag actually corresponds to the target version.
// Without this check, a missing patch-<targetVersion> tag could
// cause the chain to silently stop at an intermediate version.
if (prevVersion !== targetVersion) {
return null;
}
const sha256 = getPatchTargetSha256(manifest, binaryName) ?? "";
if (!sha256) {
return null;
}
return { digests, totalSize, expectedSha256: sha256 };
}
}
return null;
}
/** Options for fetching chain manifests */
type FetchManifestsOpts = {
token: string;
tags: string[];
allTagCount: number;
chainTagCount: number;
signal?: AbortSignal;
};
/**
* Fetch manifests for the given chain tags.
*
* @returns Map from tag → manifest for the tags that were fetched
*/
async function fetchChainManifests(
opts: FetchManifestsOpts
): Promise<Map<string, OciManifest>> {
const { token, tags, allTagCount, chainTagCount, signal } = opts;
const fetchedManifests = new Map<string, OciManifest>();
const results = await withTracingSpan(
"fetch-chain-manifests",
"http.client",
(span) => {
span.setAttribute("chain.tags_total", allTagCount);
span.setAttribute("chain.tags_filtered", chainTagCount);
span.setAttribute("chain.fetched_count", tags.length);
return Promise.all(
tags.map(async (tag) => {
try {
const manifest = await fetchManifest(token, tag, signal);
return { tag, manifest };
} catch {
return { tag, manifest: null };
}
})
);
}
);
for (const { tag, manifest } of results) {
if (manifest) {
fetchedManifests.set(tag, manifest);
}
}
return fetchedManifests;
}
/**
* Resolve a chain of nightly patches from current to target version.
*
* Uses a lazy approach that only fetches manifests actually needed:
* 1. Single API call: list all `patch-*` tags (cheap — just names)
* 2. Filter to tags in the upgrade range and sort by version
* 3. Fetch manifests for chain tags (typically 1-2 HTTP calls)
* 4. Validate chain linkage and size threshold
* 5. Parallel: download all patch layer blobs concurrently
*
* @param opts.token - GHCR anonymous bearer token
* @param opts.currentVersion - Currently installed nightly version
* @param opts.targetVersion - Target nightly version
* @param opts.fullGzSize - Size of the full .gz layer for threshold calculation
* @param opts.preloadedTags - Pre-fetched patch tags from `listTags`. When provided,
* skips the `listTags` call. Used by `resolveNightlyDelta` to run the tag
* listing in parallel with the target manifest fetch.
* @returns Resolved patch chain, or null if unavailable
*/
export async function resolveNightlyChain(opts: {
token: string;
currentVersion: string;
targetVersion: string;
fullGzSize: number;
preloadedTags?: string[];
signal?: AbortSignal;
}): Promise<PatchChain | null> {
const {
token,
currentVersion,
targetVersion,
fullGzSize,
preloadedTags,
signal,
} = opts;
const binaryName = getPlatformBinaryName();
const patchLayerName = `${binaryName}.patch`;
// Step 1: Use pre-fetched tags or fetch them (for backward compat / direct callers)
const allTags =
preloadedTags ?? (await listTags(token, PATCH_TAG_PREFIX, signal));
// Step 2: Extract versions, filter to chain range, sort chronologically
const chainTags = filterAndSortChainTags(
allTags,
currentVersion,
targetVersion
);
if (chainTags.length === 0 || chainTags.length > MAX_NIGHTLY_CHAIN_DEPTH) {
log.debug(
chainTags.length === 0
? "No patch tags found in version range"
: `Nightly chain depth ${chainTags.length} exceeds limit ${MAX_NIGHTLY_CHAIN_DEPTH}`
);
return null;
}
// Step 3: Fetch manifests for chain tags
const fetchedManifests = await fetchChainManifests({
token,
tags: chainTags,
allTagCount: allTags.length,
chainTagCount: chainTags.length,
signal,
});
// Build ordered manifests — any missing manifest means chain is broken
const manifests: (OciManifest | undefined)[] = chainTags.map((tag) =>
fetchedManifests.get(tag)
);
if (manifests.some((m) => !m)) {
return null;
}
// Step 4: Validate chain and collect patch info
const validation = validateNightlyChain({
manifests: manifests as OciManifest[],
chainTags,
currentVersion,
targetVersion,
patchLayerName,
binaryName,
fullGzSize,
});
if (!validation) {
return null;
}
// Step 5: Parallel blob download
const downloadResults = await withTracing(
"download-patches",
"http.client",
() =>
Promise.all(
validation.digests.map((digest) =>
downloadLayerBlob(token, digest, signal).then(
(buf) => new Uint8Array(buf)
)
)
)
);
const patches: PatchLink[] = [];
let downloadedSize = 0;
for (const data of downloadResults) {
patches.push({ data, size: data.byteLength });
downloadedSize += data.byteLength;
}
// Build version steps from chain tags (oldest first)
const steps: { fromVersion: string; toVersion: string }[] = [];
let prevVersion = currentVersion;
for (const tag of chainTags) {
const toVersion = tag.slice(PATCH_TAG_PREFIX.length);
steps.push({ fromVersion: prevVersion, toVersion });
prevVersion = toVersion;
}
return {
patches,
totalSize: downloadedSize,
expectedSha256: validation.expectedSha256,
steps,
};
}
/**
* Attempt to download and apply delta patches instead of a full binary.
*
* This is the main entry point called by `downloadBinaryToTemp()` in
* upgrade.ts. It discovers available patches, resolves a chain, downloads
* the patches, applies them sequentially, and verifies the result.
*
* @param targetVersion - Version to upgrade to
* @param oldBinaryPath - Path to the currently running binary (used as patch base)
* @param destPath - Path to write the patched binary
* @returns Delta result with SHA-256 and size info, or null if delta is unavailable
*/
export function attemptDeltaUpgrade(
targetVersion: string,
oldBinaryPath: string,
destPath: string,
offline?: boolean
): Promise<DeltaResult | null> {
if (!canAttemptDelta(targetVersion)) {
return Promise.resolve(null);
}
const channel = isNightlyVersion(targetVersion) ? "nightly" : "stable";
return withTracingSpan(
"delta-upgrade",
"upgrade.delta",
async (span) => {
span.setAttribute("delta.from_version", CLI_VERSION);
span.setAttribute("delta.to_version", targetVersion);
log.debug(
`Attempting delta upgrade from ${CLI_VERSION} to ${targetVersion}`
);
try {
const result =
channel === "nightly"
? await resolveNightlyDelta(
targetVersion,
oldBinaryPath,
destPath,
offline
)
: await resolveStableDelta(
targetVersion,
oldBinaryPath,
destPath,
offline
);
if (result) {
span.setAttribute("delta.patch_bytes", result.patchBytes);
span.setAttribute("delta.chain_length", result.chainLength);
span.setAttribute("delta.sha256", result.sha256.slice(0, 12));
span.setStatus({ code: 1 }); // OK
Sentry.metrics.distribution(
"upgrade.delta.patch_bytes",
result.patchBytes,
{
attributes: { channel },
}
);
Sentry.metrics.distribution(
"upgrade.delta.chain_length",
result.chainLength,
{
attributes: { channel },
}
);
} else {
// No patch available — not an error, just unavailable
span.setAttribute("delta.result", "unavailable");
span.setStatus({ code: 1 }); // OK — graceful fallback
}
return result;
} catch (error) {
// Record the error in Sentry so we can see delta failures in telemetry.
// Marked non-fatal: the upgrade continues via full download.
Sentry.captureException(error, {
level: "warning",
tags: {
"delta.from_version": CLI_VERSION,
"delta.to_version": targetVersion,
"delta.channel": channel,
},
contexts: {
delta_upgrade: {
from_version: CLI_VERSION,
to_version: targetVersion,
channel,
old_binary_path: oldBinaryPath,
},
},
});
const msg = error instanceof Error ? error.message : String(error);
log.warn(
`Delta upgrade failed (${msg}), falling back to full download`
);
span.setStatus({ code: 2 }); // Error
span.setAttribute("delta.result", "error");
span.setAttribute("delta.error", msg);
return null;
}
},
{ "delta.channel": channel }
);
}
/**
* Build a cache key for Sentry Cache Insights instrumentation.
* Format: `patch-chain:{from}-{to}` (e.g., `patch-chain:0.13.0-0.14.0`).
*/
function patchCacheKey(fromVersion: string, toVersion: string): string {
return `patch-chain:${fromVersion}-${toVersion}`;
}
/**
* Try to load a cached patch chain, catching and suppressing errors.
*
* Emits a `cache.get` span with standard Sentry Cache Module attributes
* so the operation appears in the Cache Insights dashboard.
*
* @returns Cached chain data, or null if unavailable or on any error
*/
async function tryLoadCachedChain(
currentVersion: string,
targetVersion: string
): Promise<PatchChain | null> {
const key = patchCacheKey(currentVersion, targetVersion);
try {
return await withTracingSpan(key, "cache.get", async (span) => {
span.setAttribute("cache.key", [key]);
const result = await loadCachedChain(currentVersion, targetVersion);
const hit = result !== null;
span.setAttribute("cache.hit", hit);
if (hit) {
span.setAttribute("cache.item_size", result.totalSize);
}
return result;
});
} catch {
return null;
}
}
/**
* Apply a cached or network-resolved chain and return the delta result.
*/
async function applyChainAndReturn(
chain: PatchChain,
oldBinaryPath: string,
destPath: string
): Promise<DeltaResult> {
const sha256 = await withTracing(
"apply-patch-chain",
"upgrade.delta.apply",
() => applyPatchChain(chain, oldBinaryPath, destPath)
);
return {
sha256,
patchBytes: chain.totalSize,
chainLength: chain.patches.length,
};
}
/** Options for the shared cache-first resolve + apply logic */
type ResolveAndApplyOpts = {
targetVersion: string;
oldBinaryPath: string;
destPath: string;
/** Channel-specific chain resolution callback */
resolveFromNetwork: () => Promise<PatchChain | null>;
/** Channel label for log messages (e.g., "stable", "nightly") */
channel: string;
/** When true, skip the network fallback — only use cached patches */
offline?: boolean;
};