{{ message }}
Repository navigation
Expand file tree
/
Copy pathsync-artifacts-catalog.ts
More file actions
1318 lines (1221 loc) · 50.8 KB
/
Copy pathsync-artifacts-catalog.ts
File metadata and controls
1318 lines (1221 loc) · 50.8 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
/**
* Pins `packages/stack/src/Artifacts.ts` to committed `supabase/slim-services` revisions. See
* `docs/adr/0026-slim-artifact-mirrors.md` for the catalog model and this script's three modes.
*/
import {
DIGEST_PATTERN,
InvalidPayloadError,
SOURCE_REGISTRY,
checksumFor,
escapeRegExp,
nativeFileNames,
nativeObjectUrl,
} from "./slim-mirror-payload.ts";
export const CATALOG_PATH = "packages/stack/src/Artifacts.ts";
const SLIM_IMAGE_PREFIX = `${SOURCE_REGISTRY}/`;
/** Native targets the catalog pins per revision, in `Artifacts.ts`'s serialization order. */
const NATIVE_TARGETS = ["darwin-arm64", "linux-amd64", "linux-arm64"] as const;
type NativeTargetName = (typeof NATIVE_TARGETS)[number];
/** Overridable so an integration test can point at a local fixture server instead of GitHub. */
const RELEASES_API =
process.env.SLIM_SERVICES_RELEASES_API ??
"https://api.github.com/repos/supabase/slim-services/releases";
const RELEASE_DOWNLOAD_BASE = "https://github.com/supabase/slim-services/releases/download";
/** Bounded retry for `waitForExpectedRelease`: 6 attempts, 10s apart, by default. */
const EXPECT_RELEASE_ATTEMPTS = 6;
const DEFAULT_EXPECT_RELEASE_INTERVAL_MS = 10_000;
/** ~10 min for `resolveRevisionPin`'s S3-mirror wait: `upload-natives-s3` for all three targets. */
const S3_WAIT_ATTEMPTS = 20;
const DEFAULT_S3_WAIT_INTERVAL_MS = 30_000;
const MAX_TIMER_DELAY_MS = 2 ** 31 - 1; // setTimeout's own ceiling.
/**
* Parses a millisecond wait-interval override from `envVar` fresh on every call, not once at
* module load, so a test can set it right before spawning. Unset keeps `fallback`; anything else
* must be a non-negative integer of at most `MAX_TIMER_DELAY_MS`, or this throws.
*/
function waitIntervalMs(envVar: string, fallback: number): number {
const raw = process.env[envVar];
if (raw === undefined) return fallback;
const value = Number(raw);
if (!/^(0|[1-9][0-9]*)$/.test(raw) || value > MAX_TIMER_DELAY_MS) {
throw new InvalidPayloadError(
`invalid ${envVar} ${JSON.stringify(raw)}: expected a non-negative integer of at most ${MAX_TIMER_DELAY_MS}`,
);
}
return value;
}
const expectReleaseIntervalMs = (): number =>
waitIntervalMs("SLIM_UPDATES_EXPECT_RELEASE_WAIT_MS", DEFAULT_EXPECT_RELEASE_INTERVAL_MS);
const s3WaitIntervalMs = (): number =>
waitIntervalMs("SLIM_UPDATES_S3_WAIT_MS", DEFAULT_S3_WAIT_INTERVAL_MS);
/** Real delay, for a caller that didn't override `wait`. */
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
type BoundedCheck<T> =
| { readonly kind: "done"; readonly value: T }
| { readonly kind: "retry" }
| { readonly kind: "failed"; readonly message: string };
type BoundedWaitOutcome<T> =
| { readonly status: "done"; readonly value: T }
| { readonly status: "timed-out" }
| { readonly status: "failed"; readonly message: string };
/** Calls `check` up to `attempts` times, waiting between, until it reports `done` or `failed`. */
async function boundedWait<T>(
check: () => Promise<BoundedCheck<T>>,
wait: (ms: number) => Promise<void>,
attempts: number,
intervalMs: number,
): Promise<BoundedWaitOutcome<T>> {
for (let attempt = 0; attempt < attempts; attempt++) {
const result = await check();
if (result.kind === "done") return { status: "done", value: result.value };
if (result.kind === "failed") return { status: "failed", message: result.message };
if (attempt < attempts - 1) await wait(intervalMs);
}
return { status: "timed-out" };
}
/**
* A GitHub Actions workflow-command line, `message` run through the workflow-command data
* encoding (`%` first, so encoding `\r`/`\n` never gets re-escaped) — the boundary every
* `::error ::`/`::warning ::` this script emits goes through.
*/
function workflowCommand(kind: "error" | "warning", message: string): string {
const encoded = message.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
return `::${kind} ::${encoded}`;
}
/** Leading numeric component, `v` stripped. Only postgres carries more than one line. */
function releaseLine(version: string): string {
const withoutPrefix = version.replace(/^[vV]/, "");
const separator = withoutPrefix.indexOf(".");
return separator === -1 ? withoutPrefix : withoutPrefix.slice(0, separator);
}
/**
* Matches a `<service>-<upstream>-r<N>` release tag. With `upstream` given, matches only that
* exact upstream (what `resolveRevisionPin` needs); with it omitted, captures any upstream as
* group 1 and the revision as group 2 (what the planner needs to enumerate every committed
* revision of every upstream a service carries). A tag with no `-r<N>` suffix — legacy — never
* matches either shape.
*/
function releaseTagPattern(service: string, upstream?: string): RegExp {
const upstreamPart = upstream === undefined ? "(.+)" : escapeRegExp(upstream);
return new RegExp(`^${escapeRegExp(service)}-${upstreamPart}-r(0|[1-9][0-9]*)$`);
}
/**
* Strips a leading `v`/`V` and one trailing `-sha-<hex>`, then parses the remainder as dot-
* separated integers. Returns undefined when the remainder isn't `^\d+(\.\d+)*$` — a version that
* isn't comparable this way, such as an OrioleDB-style suffix.
*/
function comparableVersion(version: string): ReadonlyArray<number> | undefined {
const stripped = version.replace(/^[vV]/, "").replace(/-sha-[0-9a-f]+$/i, "");
if (!/^\d+(\.\d+)*$/.test(stripped)) return undefined;
return stripped.split(".").map(Number);
}
/**
* Numeric ordering of two upstream versions: `-1` when `a` is older, `0` when neither is newer
* (including two versions that only differ in a stripped `-sha-<hex>` suffix, e.g. two Studio
* builds on the same date), `1` when `a` is newer. Undefined when either isn't comparable.
*/
function compareVersions(a: string, b: string): number | undefined {
const av = comparableVersion(a);
const bv = comparableVersion(b);
if (av === undefined || bv === undefined) return undefined;
const length = Math.max(av.length, bv.length);
for (let index = 0; index < length; index++) {
const left = av[index] ?? 0;
const right = bv[index] ?? 0;
if (left !== right) return left < right ? -1 : 1;
}
return 0;
}
export interface CatalogPinUpdate {
readonly service: string;
readonly version: string;
readonly revision: number;
readonly previousVersion: string;
readonly target: "default" | "additional";
}
/** Content pin for one resolved `<upstream>-r<N>` revision, without its `upstreamImage`. */
interface ResolvedPin {
readonly upstreamVersion: string;
readonly revision: number;
readonly image: string;
readonly natives: Readonly<
Record<NativeTargetName, { readonly archive: string; readonly manifest: string }>
>;
}
/** A `ResolvedPin` plus its `ArtifactPin.upstreamImage`, ready to serialize into the catalog. */
type CatalogPin = ResolvedPin & { readonly upstreamImage: string };
export type RevisionResolution =
| { readonly status: "resolved"; readonly pin: ResolvedPin }
| {
readonly status: "missing" | "incomplete" | "stale" | "lookup-failed";
readonly message: string;
};
/**
* Network ports the resolver needs: the release list (for revision allocation), a release's
* `SHA256SUMS` body, the GHCR manifest digest, and a byte source's sha256. Tests stub these
* directly.
*/
export interface RevisionIo {
/** Tags of every published, non-draft release — a draft is not yet a committed revision. */
readonly listReleaseTags: () => Promise<ReadonlyArray<string>>;
readonly fetchChecksums: (service: string, releaseVersion: string) => Promise<string | undefined>;
readonly imageDigest: (service: string, releaseVersion: string) => Promise<string | undefined>;
readonly s3Sha256: (url: string) => Promise<string | undefined>;
/** Overridable real delay between the S3-mirror wait's bounded attempts. */
readonly wait?: (ms: number) => Promise<void>;
/**
* Raw contents of a native target's `.manifest.json` release asset, for a derived service's
* `upstream_image` (or `source_image` on an image-derived build, e.g. postgrest's Linux
* targets).
*/
readonly fetchManifest: (
service: string,
releaseVersion: string,
target: NativeTargetName,
) => Promise<string | undefined>;
/**
* Raw contents of a mirrored service's `<service>-<upstreamVersion>.oci-provenance.json`
* release asset, whose `source` field is the mirrored upstream image.
*/
readonly fetchProvenance: (
service: string,
releaseVersion: string,
upstreamVersion: string,
) => Promise<string | undefined>;
}
function desiredImage(service: string, releaseVersion: string, digest: string): string {
if (!DIGEST_PATTERN.test(digest)) {
throw new InvalidPayloadError(`missing slim digest for ${service}:${releaseVersion}`);
}
return `${SLIM_IMAGE_PREFIX}${service}:${releaseVersion}@${digest}`;
}
/**
* Resolves `service`'s committed `<upstream>-r<N>` revision, pinned by content: the GHCR
* manifest digest, and every native target's archive and manifest sha256, cross-checked against
* the S3 mirror copy.
*
* With `requiredRevision` given (`--release`), that revision must already be committed; it is
* never "highest at apply time". Without it, the highest committed revision of `upstream` is used.
*/
export async function resolveRevisionPin(
service: string,
upstream: string,
io: RevisionIo,
requiredRevision?: number,
): Promise<RevisionResolution> {
const tagPattern = releaseTagPattern(service, upstream);
const seenRevisions = new Set<number>();
let highest: number | undefined;
for (const tag of await io.listReleaseTags()) {
const match = tagPattern.exec(tag);
if (match === null) continue;
const revision = Number(match[1]);
seenRevisions.add(revision);
if (highest === undefined || revision > highest) highest = revision;
}
let target: number;
if (requiredRevision !== undefined) {
if (!seenRevisions.has(requiredRevision)) {
return {
status: "missing",
message: `${service}:${upstream}-r${requiredRevision} is not a committed slim-services release.`,
};
}
target = requiredRevision;
} else {
if (highest === undefined) {
return {
status: "missing",
message: `${service}:${upstream} has no published slim-services revision.`,
};
}
target = highest;
}
const releaseVersion = `${upstream}-r${target}`;
const checksums = await io.fetchChecksums(service, releaseVersion);
if (checksums === undefined) {
return {
status: "incomplete",
message: `${service}-${releaseVersion} has no SHA256SUMS asset.`,
};
}
const natives: Record<string, { archive: string; manifest: string }> = {};
for (const target of NATIVE_TARGETS) {
const files = nativeFileNames(service, releaseVersion, target);
const archive = checksumFor(checksums, files.archive);
const manifest = checksumFor(checksums, files.manifest);
if (archive === undefined || manifest === undefined) {
return {
status: "incomplete",
message: `${service}-${releaseVersion} SHA256SUMS has no line for ${
archive === undefined ? files.archive : files.manifest
}.`,
};
}
natives[target] = { archive, manifest };
}
const digest = await io.imageDigest(service, releaseVersion);
if (digest === undefined || !DIGEST_PATTERN.test(digest)) {
return {
status: "lookup-failed",
message: `${SLIM_IMAGE_PREFIX}${service}:${releaseVersion} has no published manifest.`,
};
}
// `mirror-slim-image.yml`'s S3 upload runs in parallel, best-effort, so a freshly committed
// revision's S3 copy can briefly lag GitHub: a missing object waits, bounded; a present object
// with the wrong bytes fails immediately instead of waiting.
for (const target of NATIVE_TARGETS) {
const files = nativeFileNames(service, releaseVersion, target);
for (const part of ["archive", "manifest"] as const) {
const url = nativeObjectUrl(service, releaseVersion, files[part]);
const expected = natives[target]?.[part] as string;
const outcome = await boundedWait<true>(
async () => {
const actual = await io.s3Sha256(url);
if (actual === undefined) {
console.log(
`Waiting for the S3 mirror of ${service}-${releaseVersion} ${target} (${part})...`,
);
return { kind: "retry" };
}
if (actual !== expected) {
return {
kind: "failed",
message: `S3 copy of ${releaseVersion} ${target} (${part}) is stale (digest mismatch); run the slim-services mirror backfill.`,
};
}
return { kind: "done", value: true };
},
io.wait ?? sleep,
S3_WAIT_ATTEMPTS,
s3WaitIntervalMs(),
);
if (outcome.status === "failed") {
return { status: "stale", message: outcome.message };
}
if (outcome.status === "timed-out") {
return {
status: "stale",
message: `S3 copy of ${releaseVersion} ${target} (${part}) never appeared; the S3 mirror hasn't finished — check mirror-slim-image.yml for this release, backfill if needed, and re-run.`,
};
}
}
}
return {
status: "resolved",
pin: {
upstreamVersion: upstream,
revision: target,
image: desiredImage(service, releaseVersion, digest),
natives: natives as Record<NativeTargetName, { archive: string; manifest: string }>,
},
};
}
/**
* Services slim-services mirrors from an unmodified upstream image rather than building from
* source: their `upstreamImage` comes from the release's `oci-provenance.json` `source` field,
* not a native target's manifest. Keep this in sync with `SlimServicesSource`'s mirror-mode
* services.
*/
const MIRROR_MODE_SOURCE_SERVICES: ReadonlySet<string> = new Set(["vector", "mailpit", "imgproxy"]);
function parseJsonRecord(raw: string): Record<string, unknown> | undefined {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return undefined;
}
return typeof parsed === "object" && parsed !== null
? (parsed as Record<string, unknown>)
: undefined;
}
function stringField(record: Record<string, unknown> | undefined, key: string): string | undefined {
const value = record?.[key];
return typeof value === "string" && value.length > 0 ? value : undefined;
}
/** Strips a `docker.io/` prefix and any `@sha256:…` digest, to match the Dockerfile's `FROM` form. */
function normalizeUpstreamImage(image: string): string {
const withoutDigest = image.split("@")[0] ?? image;
return withoutDigest.startsWith("docker.io/")
? withoutDigest.slice("docker.io/".length)
: withoutDigest;
}
/**
* A normalized `upstreamImage`: one or more lowercase `registry`/`repository` path segments
* (each `[a-z0-9]`, optionally separated internally by `.`/`_`/`-`), a `:`, and a tag matching
* Docker's own tag grammar. Anchored, so no whitespace, quote, or template/expression syntax can
* slip through — this value gets embedded as a TypeScript string literal in `Artifacts.ts`.
*/
const IMAGE_REFERENCE_PATTERN =
/^[a-z0-9]+(?:[._-][a-z0-9]+)*(?:\/[a-z0-9]+(?:[._-][a-z0-9]+)*)*:[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$/;
/** Validates a normalized `upstreamImage` before it's ever written to `Artifacts.ts`. */
function validateUpstreamImage(image: string, context: string): string {
if (!IMAGE_REFERENCE_PATTERN.test(image)) {
throw new InvalidPayloadError(
`${context} has an invalid upstreamImage ${JSON.stringify(image)}.`,
);
}
return image;
}
/**
* Resolves `service`'s `upstreamImage` for the release `releaseVersion` (`<upstream>-r<N>`):
* a mirrored service's `oci-provenance.json` `source`, or a derived service's per-target
* manifest `upstream_image` (falling back to `source_image` for an image-derived build, e.g.
* postgrest's Linux targets) — cross-checked across every native target, so a derived service
* whose manifests disagree fails instead of silently picking one. Only manual mode
* (`refreshCatalogPin`) calls this.
*/
async function resolveUpstreamImage(
service: string,
releaseVersion: string,
upstreamVersion: string,
io: RevisionIo,
): Promise<string> {
if (MIRROR_MODE_SOURCE_SERVICES.has(service)) {
const provenance = await io.fetchProvenance(service, releaseVersion, upstreamVersion);
if (provenance === undefined) {
throw new InvalidPayloadError(`${service}-${releaseVersion} has no oci-provenance asset.`);
}
const source = stringField(parseJsonRecord(provenance), "source");
if (source === undefined) {
throw new InvalidPayloadError(
`${service}-${releaseVersion} oci-provenance has no 'source' field.`,
);
}
return validateUpstreamImage(normalizeUpstreamImage(source), `${service}-${releaseVersion}`);
}
const values = new Set<string>();
for (const target of NATIVE_TARGETS) {
const manifest = await io.fetchManifest(service, releaseVersion, target);
if (manifest === undefined) {
throw new InvalidPayloadError(
`${service}-${releaseVersion}-${target} has no manifest asset.`,
);
}
const record = parseJsonRecord(manifest);
const value = stringField(record, "upstream_image") ?? stringField(record, "source_image");
if (value === undefined) {
throw new InvalidPayloadError(
`${service}-${releaseVersion}-${target} manifest has neither 'upstream_image' nor 'source_image'.`,
);
}
values.add(normalizeUpstreamImage(value));
}
if (values.size !== 1) {
throw new InvalidPayloadError(
`${service}-${releaseVersion} manifests disagree on the upstream image: ${[...values]
.sort()
.map((value) => JSON.stringify(value))
.join(", ")}.`,
);
}
return validateUpstreamImage([...values][0] as string, `${service}-${releaseVersion}`);
}
/**
* Serializes a resolved pin into the object literal `Artifacts.ts` embeds, in catalog order.
* Every string field goes through `JSON.stringify`, not manual `"${…}"` interpolation — this
* text is written straight into TypeScript source that later gets imported, so an unescaped
* quote or template expression in any field (release metadata included) would inject code.
*/
function serializePin(pin: CatalogPin): string {
const natives = NATIVE_TARGETS.map((target) => {
const native = pin.natives[target];
return `${JSON.stringify(target)}: { archive: ${JSON.stringify(native.archive)}, manifest: ${JSON.stringify(native.manifest)} }`;
}).join(", ");
return `{ upstreamVersion: ${JSON.stringify(pin.upstreamVersion)}, revision: ${pin.revision}, image: ${JSON.stringify(pin.image)}, upstreamImage: ${JSON.stringify(pin.upstreamImage)}, natives: { ${natives} } }`;
}
interface PinSpan {
readonly start: number;
readonly end: number;
readonly version: string;
/**
* Span of an additional (release-line-keyed) pin's own string key, content only (no quotes).
* Absent for the default pin, which carries no separate key to keep in sync.
*/
readonly key?: { readonly start: number; readonly end: number };
}
/**
* Index right after the matching close-bracket for the open-bracket character at `openIndex`
* (which must itself be `open`). Skips string contents, so a formatter's line-wrapping, trailing
* commas, or reordered properties never confuse the boundary — only bracket balance matters.
*/
function scanBalanced(source: string, openIndex: number, open: string, close: string): number {
let depth = 0;
let index = openIndex;
for (; index < source.length; index++) {
const ch = source[index];
if (ch === '"' || ch === "'" || ch === "`") {
const quote = ch;
index++;
while (index < source.length && source[index] !== quote) {
if (source[index] === "\\") index++;
index++;
}
continue;
}
if (ch === open) depth++;
else if (ch === close) {
depth--;
if (depth === 0) return index + 1;
}
}
throw new InvalidPayloadError(`unterminated '${open}' while parsing ${CATALOG_PATH}`);
}
/** Loosely finds `upstreamVersion` anywhere inside a resolved pin literal's text. */
const PIN_UPSTREAM_VERSION = /upstreamVersion:\s*"([^"]+)"/;
/** Loosely finds `revision` anywhere inside a resolved pin literal's text. */
const PIN_REVISION = /revision:\s*(\d+)/;
/**
* Matches a resolved `ArtifactPin` object literal that starts at `index`. The span is found
* by bracket balance, then the version is pulled out with a loose field search — so a formatter's
* whitespace, line breaks, trailing commas, or property order never break matching, only the
* literal shape itself would.
*/
function matchPinAt(source: string, index: number): PinSpan | undefined {
if (source[index] === "{") {
const end = scanBalanced(source, index, "{", "}");
const version = PIN_UPSTREAM_VERSION.exec(source.slice(index, end))?.[1];
return version === undefined ? undefined : { start: index, end, version };
}
return undefined;
}
interface ServicePins {
readonly defaultPin: PinSpan;
readonly additional: ReadonlyArray<PinSpan>;
}
/**
* Finds every pin expression `service` carries in `source`: the `definition("<service>", <pin>,
* ...)` default pin, plus any additional (release-line-keyed) pins in its trailing object
* argument. Both `selectEntry` and `planSlimUpdates` build on this single traversal.
*/
function collectServicePins(source: string, service: string): ServicePins | undefined {
const prefix = new RegExp(`definition\\(\\s*"${escapeRegExp(service)}"\\s*,\\s*`);
const prefixMatch = prefix.exec(source);
if (prefixMatch === null) return undefined;
const pinIndex = prefixMatch.index + prefixMatch[0].length;
const defaultPin = matchPinAt(source, pinIndex);
if (defaultPin === undefined) return undefined;
const openParenIndex = prefixMatch.index + prefixMatch[0].indexOf("(");
const callEnd = scanBalanced(source, openParenIndex, "(", ")");
const additional: PinSpan[] = [];
const keyPattern = /"([^"]+)"\s*:\s*/g;
keyPattern.lastIndex = defaultPin.end;
for (
let keyMatch = keyPattern.exec(source);
keyMatch !== null;
keyMatch = keyPattern.exec(source)
) {
if (keyMatch.index >= callEnd) break;
const valueStart = keyMatch.index + keyMatch[0].length;
const pin = matchPinAt(source, valueStart);
if (pin === undefined) {
keyPattern.lastIndex = valueStart;
continue;
}
const keyText = keyMatch[1] ?? "";
const keyStart = keyMatch.index + keyMatch[0].indexOf(keyText);
additional.push({ ...pin, key: { start: keyStart, end: keyStart + keyText.length } });
keyPattern.lastIndex = pin.end;
}
return { defaultPin, additional };
}
type SelectedEntry =
| { readonly kind: "default" | "additional"; readonly version: string; readonly span: PinSpan }
| { readonly kind: "unmodelled-service" }
| { readonly kind: "unmodelled-release-line"; readonly known: ReadonlyArray<string> };
/**
* Locates `service`'s pin expression in `source`: the `definition("<service>", <pin>, ...)`
* default pin, and, when `version` is given, whichever pin (default or additional) sits on its
* release line. With no `version`, returns the default pin unconditionally.
*/
function selectEntry(source: string, service: string, version: string | undefined): SelectedEntry {
const pins = collectServicePins(source, service);
if (pins === undefined) return { kind: "unmodelled-service" };
const { defaultPin, additional } = pins;
if (version === undefined) {
return { kind: "default", version: defaultPin.version, span: defaultPin };
}
const bumpsDefault =
additional.length === 0 || releaseLine(version) === releaseLine(defaultPin.version);
if (bumpsDefault) {
return { kind: "default", version: defaultPin.version, span: defaultPin };
}
const sameLine = additional.find((pin) => releaseLine(pin.version) === releaseLine(version));
if (sameLine === undefined) {
return {
kind: "unmodelled-release-line",
known: [defaultPin.version, ...additional.map((pin) => pin.version)],
};
}
return { kind: "additional", version: sameLine.version, span: sameLine };
}
/** The `{service, upstream_version, revision, release_version}` payload a `slim-release-published` dispatch carries. */
export interface SlimReleasePublishedPayload {
readonly service: string;
readonly upstream_version: string;
readonly revision: number;
readonly release_version: string;
}
/** Every upstream tag format the catalog carries, including Studio's `2026.09.04-sha-5a67366`. */
const UPSTREAM_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
const SERVICE_NAME_PATTERN = /^[a-z0-9-]+$/;
const RELEASE_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*-r(0|[1-9][0-9]*)$/;
/**
* Validates an untrusted `slim-release-published` dispatch payload before any of its fields are
* written anywhere (a `$GITHUB_OUTPUT` line, a branch name, a PR title, …). Every field is checked
* against an anchored charset — `upstream_version` and `release_version` included, not just
* `service` and `revision` — so a value carrying a newline or shell/Actions metacharacter is
* rejected here instead of being echoed downstream.
*/
export function validateSlimReleasePublishedPayload(input: {
readonly service: string;
readonly upstream_version: string;
readonly revision: string;
readonly release_version: string;
}): SlimReleasePublishedPayload {
if (!SERVICE_NAME_PATTERN.test(input.service)) {
throw new InvalidPayloadError(`invalid service: ${JSON.stringify(input.service)}`);
}
if (!UPSTREAM_VERSION_PATTERN.test(input.upstream_version)) {
throw new InvalidPayloadError(
`invalid upstream_version: ${JSON.stringify(input.upstream_version)}`,
);
}
if (!/^(0|[1-9][0-9]*)$/.test(input.revision)) {
throw new InvalidPayloadError(`invalid revision: ${JSON.stringify(input.revision)}`);
}
if (!RELEASE_VERSION_PATTERN.test(input.release_version)) {
throw new InvalidPayloadError(
`invalid release_version: ${JSON.stringify(input.release_version)}`,
);
}
const revision = Number(input.revision);
const expected = `${input.upstream_version}-r${revision}`;
if (input.release_version !== expected) {
throw new InvalidPayloadError(
`release_version ${JSON.stringify(input.release_version)} does not match derived ${JSON.stringify(expected)}`,
);
}
return {
service: input.service,
upstream_version: input.upstream_version,
revision,
release_version: input.release_version,
};
}
const normalizeText = (text: string): string => text.replace(/\s+/g, " ").trim();
/**
* Writes `pin` over `entry`'s span in `source`, or leaves it unchanged when it already matches.
* An additional (release-line-keyed) pin also gets its own string key rewritten to `pin`'s
* `upstreamVersion` when it moves to a different upstream version, so the key an additional pin
* is looked up by never drifts from the `upstreamVersion` its resolved pin literal carries.
*/
function writePin(
source: string,
entry: Extract<SelectedEntry, { kind: "default" | "additional" }>,
pin: CatalogPin,
): { readonly source: string; readonly changed: boolean } {
const desired = serializePin(pin);
const current = source.slice(entry.span.start, entry.span.end);
let next = source;
let changed = false;
if (normalizeText(current) !== normalizeText(desired)) {
next = next.slice(0, entry.span.start) + desired + next.slice(entry.span.end);
changed = true;
}
const key = entry.span.key;
if (key !== undefined && source.slice(key.start, key.end) !== pin.upstreamVersion) {
next = next.slice(0, key.start) + pin.upstreamVersion + next.slice(key.end);
changed = true;
}
return { source: next, changed };
}
/**
* One hotfix or upgrade a `slim-release-published` run should apply, on one of `service`'s
* release lines. `line` is the leading numeric component (`releaseLine`), present only when the
* service carries more than one line (only postgres does today) — it's already folded into
* `branch`, so a caller never needs to consume it separately.
*/
export interface SlimUpdate {
readonly kind: "hotfix" | "upgrade";
readonly line?: string;
readonly branch: string;
readonly title: string;
/** The release version pinned before this update, e.g. `v2.195.0-r0`. */
readonly fromRelease: string;
readonly toUpstream: string;
/** The release version this update pins, e.g. `v2.195.0-r1`. */
readonly toRelease: string;
}
/**
* Builds one `SlimUpdate`, validating every value it emits — `service`, `toUpstream` and
* `toRelease` — against the same anchored patterns `validateSlimReleasePublishedPayload` uses,
* before any of them reaches a branch name or PR title. Release tag names (the ultimate source of
* `toUpstream`) come from an external API, so this check applies even to values derived from the
* catalog itself (`fromRelease`'s upstream), not only to values freshly parsed from a tag.
*/
function buildUpdate(
kind: "hotfix" | "upgrade",
service: string,
line: string,
hasLines: boolean,
pinned: { readonly upstream: string; readonly revision: number },
toUpstream: string,
toRevision: number,
): SlimUpdate {
if (!SERVICE_NAME_PATTERN.test(service)) {
throw new InvalidPayloadError(`invalid service: ${JSON.stringify(service)}`);
}
if (!UPSTREAM_VERSION_PATTERN.test(toUpstream)) {
throw new InvalidPayloadError(`invalid upstream version: ${JSON.stringify(toUpstream)}`);
}
const toRelease = `${toUpstream}-r${toRevision}`;
if (!RELEASE_VERSION_PATTERN.test(toRelease)) {
throw new InvalidPayloadError(`invalid release version: ${JSON.stringify(toRelease)}`);
}
const fromRelease = `${pinned.upstream}-r${pinned.revision}`;
const suffix = hasLines ? `-${line}` : "";
const branch =
kind === "hotfix" ? `slim-hotfix/${service}${suffix}` : `slim-bump/${service}${suffix}`;
const title =
kind === "hotfix"
? `chore(stack): pin ${service} ${toRelease}`
: `chore(stack): bump ${service} to ${toRelease}`;
return {
kind,
line: hasLines ? line : undefined,
branch,
title,
fromRelease,
toUpstream,
toRelease,
};
}
export interface PlanSlimUpdatesResult {
readonly updates: ReadonlyArray<SlimUpdate>;
/** `::warning ::…` workflow-command lines, for the caller to print to stdout. */
readonly warnings: ReadonlyArray<string>;
}
/** Groups every candidate release tag under one bucket, for a service with no additional pins. */
const SINGLE_LINE_KEY = "*";
/**
* The upgrade or hotfix each of `service`'s release lines should get, planned against `catalog`'s
* pins and the committed (non-draft) `releaseTags`; the rules are in ADR 0026, "Hotfix and upgrade
* pickup". Never logs: `plan-updates` writes `updates` to a file the workflow parses as records,
* so diagnostics come back in `warnings`.
*/
export function planSlimUpdates(
catalog: string,
service: string,
releaseTags: ReadonlyArray<string>,
): PlanSlimUpdatesResult {
const warnings: string[] = [];
const pins = collectServicePins(catalog, service);
if (pins === undefined) {
warnings.push(
workflowCommand(
"warning",
`${CATALOG_PATH} has no slim entry for ${service}; nothing to plan.`,
),
);
return { updates: [], warnings };
}
const allPins = [pins.defaultPin, ...pins.additional];
const hasLines = pins.additional.length > 0;
const pinnedByLine = new Map<string, { readonly upstream: string; readonly revision: number }>();
for (const span of allPins) {
const line = hasLines ? releaseLine(span.version) : SINGLE_LINE_KEY;
const text = catalog.slice(span.start, span.end);
const revisionMatch = PIN_REVISION.exec(text);
if (revisionMatch === null) {
throw new InvalidPayloadError(
`${CATALOG_PATH} has no revision for ${service} ${span.version}; a committed catalog always pins a resolved revision.`,
);
}
pinnedByLine.set(line, { upstream: span.version, revision: Number(revisionMatch[1]) });
}
const tagPattern = releaseTagPattern(service);
const candidatesByLine = new Map<string, Array<{ upstream: string; revision: number }>>();
for (const tag of releaseTags) {
const match = tagPattern.exec(tag);
if (match === null) continue; // not this service, or a legacy tag with no `-rN`: ignored.
const upstream = match[1] as string;
const revision = Number(match[2]);
let line: string;
if (hasLines) {
line = releaseLine(upstream);
if (!pinnedByLine.has(line)) {
warnings.push(
workflowCommand(
"warning",
`${service} ${upstream} is not on a release line ${CATALOG_PATH} carries for it; ignoring ${tag}.`,
),
);
continue;
}
} else {
line = SINGLE_LINE_KEY;
}
const list = candidatesByLine.get(line) ?? [];
list.push({ upstream, revision });
candidatesByLine.set(line, list);
}
const updates: SlimUpdate[] = [];
for (const [line, pinned] of pinnedByLine) {
const candidates = candidatesByLine.get(line) ?? [];
const sameUpstreamRevisions = candidates
.filter((candidate) => candidate.upstream === pinned.upstream)
.map((candidate) => candidate.revision);
const hotfixRevision =
sameUpstreamRevisions.length > 0 ? Math.max(...sameUpstreamRevisions) : undefined;
const highestRevisionByUpstream = new Map<string, number>();
for (const candidate of candidates) {
const current = highestRevisionByUpstream.get(candidate.upstream);
if (current === undefined || candidate.revision > current) {
highestRevisionByUpstream.set(candidate.upstream, candidate.revision);
}
}
let bestUpstream: string | undefined;
for (const upstream of highestRevisionByUpstream.keys()) {
const comparedToPinned = compareVersions(upstream, pinned.upstream);
if (comparedToPinned === undefined) {
warnings.push(
workflowCommand(
"warning",
`${service} ${upstream} is not a comparable version; ignoring.`,
),
);
continue;
}
if (bestUpstream === undefined || (compareVersions(upstream, bestUpstream) ?? 0) > 0) {
bestUpstream = upstream;
}
}
if (bestUpstream !== undefined && compareVersions(bestUpstream, pinned.upstream) === 1) {
const revision = highestRevisionByUpstream.get(bestUpstream) as number;
updates.push(buildUpdate("upgrade", service, line, hasLines, pinned, bestUpstream, revision));
if (hotfixRevision !== undefined && hotfixRevision > pinned.revision) {
const skippedRelease = `${pinned.upstream}-r${hotfixRevision}`;
warnings.push(
workflowCommand(
"warning",
`${service} ${skippedRelease} hotfix skipped because this line is upgrading to ${bestUpstream}-r${revision}; run --service ${service} --release ${skippedRelease} to pin the hotfix alone.`,
),
);
}
} else if (hotfixRevision !== undefined && hotfixRevision > pinned.revision) {
updates.push(
buildUpdate("hotfix", service, line, hasLines, pinned, pinned.upstream, hotfixRevision),
);
}
}
return { updates, warnings };
}
/**
* Reads every committed release tag through `listReleaseTags` and plans against `catalog`. The
* injectable lister is the seam a dry run or an end-to-end test uses to exercise the whole
* `plan-updates` transport — this function plus the CLI's file/stdout wiring — without a network
* call, the same pattern `RevisionIo.listReleaseTags` already uses.
*/
export async function planUpdatesForService(input: {
readonly catalog: string;
readonly service: string;
readonly listReleaseTags: () => Promise<ReadonlyArray<string>>;
}): Promise<PlanSlimUpdatesResult> {
const releaseTags = await input.listReleaseTags();
return planSlimUpdates(input.catalog, input.service, releaseTags);
}
export interface WaitForExpectedReleaseResult {
readonly visible: boolean;
/** The last listing `listReleaseTags` returned, whichever attempt it came from. */
readonly tags: ReadonlyArray<string>;
}
/**
* Eventual-consistency handling of the releases API lagging behind the `slim-release-published`
* dispatch that triggered this run: re-lists up to `attempts` times, `io.wait`-ing between
* attempts, until `<service>-<releaseVersion>` appears. Not a test retry — a real, bounded wait
* for an external API to catch up. `io.wait` is the seam a unit test overrides to skip the real
* delay; an integration test instead shrinks the real delay via `SLIM_UPDATES_EXPECT_RELEASE_WAIT_MS`
* (parsed fresh by `expectReleaseIntervalMs` on every call this default reaches), since a
* subprocess can't be handed a function.
*/
export async function waitForExpectedRelease(
service: string,
releaseVersion: string,
io: {
readonly listReleaseTags: () => Promise<ReadonlyArray<string>>;
readonly wait: (ms: number) => Promise<void>;
},
attempts: number = EXPECT_RELEASE_ATTEMPTS,
intervalMs: number = expectReleaseIntervalMs(),
): Promise<WaitForExpectedReleaseResult> {
const expectedTag = `${service}-${releaseVersion}`;
let tags: ReadonlyArray<string> = [];
const outcome = await boundedWait<true>(
async () => {
tags = await io.listReleaseTags();
return tags.includes(expectedTag) ? { kind: "done", value: true } : { kind: "retry" };
},
io.wait,
attempts,
intervalMs,
);
return { visible: outcome.status === "done", tags };
}
export interface CatalogRefreshResult {
readonly source: string;
readonly update?: CatalogPinUpdate;
}
/**
* Refreshes one catalog entry: to the committed release named by `release` (`<U>-r<N>`,
* required to already be committed — never "highest at apply time"), or to the highest committed
* revision of `upstream` (or, when both are omitted, of the entry's currently pinned upstream
* version). `upstream` and `release` are mutually exclusive. Pure aside from `io`: callers own
* reading and writing `Artifacts.ts`.
*/
export async function refreshCatalogPin(input: {
readonly catalog: string;
readonly service: string;
readonly upstream?: string;
readonly release?: string;
readonly io: RevisionIo;
}): Promise<CatalogRefreshResult> {
if (input.upstream !== undefined && input.release !== undefined) {
throw new InvalidPayloadError("--upstream and --release are mutually exclusive.");
}
if (input.upstream !== undefined && !UPSTREAM_VERSION_PATTERN.test(input.upstream)) {
throw new InvalidPayloadError(`invalid --upstream '${input.upstream}'`);
}
let upstream = input.upstream;
let requiredRevision: number | undefined;
if (input.release !== undefined) {
if (!RELEASE_VERSION_PATTERN.test(input.release)) {
throw new InvalidPayloadError(`invalid --release '${input.release}'`);
}
const match = /^(.+)-r(0|[1-9][0-9]*)$/.exec(input.release) as RegExpExecArray;
upstream = match[1];
requiredRevision = Number(match[2]);
}
const entry = selectEntry(input.catalog, input.service, upstream);
if (entry.kind === "unmodelled-service") {
throw new InvalidPayloadError(`${CATALOG_PATH} has no slim entry for ${input.service}.`);
}
if (entry.kind === "unmodelled-release-line") {
throw new InvalidPayloadError(
`${input.service} ${upstream ?? ""} is not on a release line ${CATALOG_PATH} carries (${entry.known.join(", ")}).`,
);
}
const resolvedUpstream = upstream ?? entry.version;
const resolution = await resolveRevisionPin(
input.service,
resolvedUpstream,
input.io,
requiredRevision,
);
if (resolution.status !== "resolved") {
throw new InvalidPayloadError(resolution.message);
}
const pin: CatalogPin = {
...resolution.pin,
You can’t perform that action at this time.
