@astrofoundry/pi-astro 0.35.0 → 0.36.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,115 @@
1
+ import { UsageError } from "./errors.ts";
2
+ import { parseTag, type UpdateRow } from "./image-updates.ts";
3
+ import { parseImageRef } from "./registry.ts";
4
+
5
+ /** Stacks whose updates wait for a person, tracked in the root of the GitOps repository: `{ "<stack>": "<reason>" }`. */
6
+ export const HOLDS_FILE = "update-holds.json";
7
+ const STACK = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
8
+
9
+ /** The held stacks with their reasons; a malformed file is an error, never "nothing held". */
10
+ export function parseHolds(text: string): Record<string, string> {
11
+ let value: unknown;
12
+ try {
13
+ value = JSON.parse(text);
14
+ } catch {
15
+ throw new UsageError(`${HOLDS_FILE} is not JSON`);
16
+ }
17
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new UsageError(`${HOLDS_FILE} must be an object of stack name to reason`);
18
+ const holds: Record<string, string> = {};
19
+ for (const [stack, reason] of Object.entries(value)) {
20
+ if (!STACK.test(stack) || typeof reason !== "string" || reason.trim().length === 0) throw new UsageError(`${HOLDS_FILE}: "${stack.slice(0, 40)}" needs a stack name and a non-empty reason`);
21
+ holds[stack] = reason.trim().slice(0, 200);
22
+ }
23
+ return holds;
24
+ }
25
+
26
+ /** True when the update moves to a newer major version, read from the first number of both release tags. */
27
+ export function crossesMajor(running: string, latest: string): boolean {
28
+ const a = parseTag(running);
29
+ const b = parseTag(latest);
30
+ return a !== null && b !== null && b.nums[0] > a.nums[0];
31
+ }
32
+
33
+ /** The rows of one stack that an update changes. */
34
+ export function pendingRows(rows: readonly UpdateRow[]): UpdateRow[] {
35
+ return rows.filter((r) => r.status === "update" || r.status === "release" || r.status === "rebuild");
36
+ }
37
+
38
+ /**
39
+ * The image reference a pinned row moves to: the newer tag for `edit tag`, the
40
+ * newer digest for `edit digest`; null for rows a redeploy with a pull applies.
41
+ */
42
+ export function nextImageRef(row: UpdateRow): string | null {
43
+ if (row.action === "edit tag") {
44
+ const ref = parseImageRef(row.ref);
45
+ if (ref.digest || !ref.tag || !parseTag(row.latest)) throw new UsageError(`${row.service}: cannot move ${row.ref} to tag ${row.latest}`);
46
+ if (!row.ref.endsWith(`:${ref.tag}`)) throw new UsageError(`${row.service}: ${row.ref} does not end with its tag`);
47
+ return `${row.ref.slice(0, row.ref.length - ref.tag.length)}${row.latest}`;
48
+ }
49
+ if (row.action === "edit digest") {
50
+ const at = row.ref.indexOf("@");
51
+ if (at < 0 || !row.latestDigest || !/^sha256:[0-9a-f]{64}$/.test(row.latestDigest)) throw new UsageError(`${row.service}: cannot move ${row.ref} to a new digest`);
52
+ return `${row.ref.slice(0, at)}@${row.latestDigest}`;
53
+ }
54
+ return null;
55
+ }
56
+
57
+ function escapeRegExp(text: string): string {
58
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
59
+ }
60
+
61
+ /**
62
+ * The Compose file with every `image:` line that names exactly `oldRef`
63
+ * (quoted or not, with an optional trailing comment) changed to `newRef`.
64
+ * Any other mention of the reference, or a longer reference that starts with
65
+ * it, stays as it is. Refuses a file without such a line.
66
+ */
67
+ export function replaceImageRef(compose: string, oldRef: string, newRef: string): string {
68
+ const line = new RegExp(`^(\\s*image:\\s*)(["']?)${escapeRegExp(oldRef)}\\2(\\s*(?:#.*)?)$`, "gm");
69
+ let count = 0;
70
+ const next = compose.replace(line, (_all, head: string, quote: string, tail: string) => {
71
+ count++;
72
+ return `${head}${quote}${newRef}${quote}${tail}`;
73
+ });
74
+ if (count === 0) throw new UsageError(`the Compose file has no "image: ${oldRef}" line`);
75
+ return next;
76
+ }
77
+
78
+ export type StackStatus = "updated" | "rolled back" | "failed" | "nothing to do";
79
+
80
+ export interface ServiceResult {
81
+ service: string;
82
+ ref: string;
83
+ from: string;
84
+ to: string;
85
+ /** `pull` (redeploy with a pull) or the reference written into the Compose file. */
86
+ applied: string;
87
+ /** After the update: current, still behind, or not checked. */
88
+ result: "current" | "behind" | "unchecked";
89
+ }
90
+
91
+ /** One container of the stack after a redeploy, as `containers get` reports it. */
92
+ export interface StackContainer {
93
+ name: string;
94
+ running: boolean | null;
95
+ state: string | null;
96
+ exitCode: number | null;
97
+ health: string;
98
+ }
99
+
100
+ /**
101
+ * Why the stack is not healthy yet, or null when every container runs (or, as
102
+ * a one-shot job, exited with code 0) and none is unhealthy or still starting.
103
+ */
104
+ export function containersProblem(containers: readonly StackContainer[], expected: number): string | null {
105
+ if (containers.length < expected) return `${containers.length} of ${expected} services have a container`;
106
+ const down = containers.filter((c) => c.running !== true && !(c.state === "exited" && c.exitCode === 0)).map((c) => c.name);
107
+ if (down.length > 0) return `not running: ${down.join(", ")}`;
108
+ const sick = containers.filter((c) => c.health === "unhealthy" || c.health === "starting").map((c) => `${c.name} (${c.health})`);
109
+ return sick.length > 0 ? `health: ${sick.join(", ")}` : null;
110
+ }
111
+
112
+ /** A commit subject that names the stack and every reference it changes. */
113
+ export function commitMessage(stack: string, edits: readonly { service: string; from: string; to: string }[]): string {
114
+ return `${stack}: ${edits.map((e) => `${e.service} ${e.from} -> ${e.to}`).join(", ")}`.slice(0, 200);
115
+ }
@@ -44,6 +44,7 @@ describe("arcane wrapper", () => {
44
44
  expect(await arcaneCommand(["--help"])).toBe(0);
45
45
  expect(String(write.mock.calls[0][0])).toContain("git write");
46
46
  expect(String(write.mock.calls[0][0])).toContain("git show");
47
+ expect(String(write.mock.calls[0][0])).toContain("stack-update <stack> [--confirm]");
47
48
  expect(String(write.mock.calls[0][0])).not.toMatch(/^\s+gitops /m);
48
49
  write.mockRestore();
49
50
  });