From abe585afb6d5af89b99bca1e48611ac76a8c9eca Mon Sep 17 00:00:00 2001 From: simpros <38320875+simpros@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:29:09 +0100 Subject: [PATCH] OTHER-3: Sprout image-cleanup consolidation --- apps/cli/src/commands/ci-identity.test.ts | 9 +- apps/cli/src/commands/ci-identity.ts | 15 +- apps/cli/src/commands/ci-note-wiring.test.ts | 4 +- .../cli/src/commands/ci-teardown-tags.test.ts | 98 +++++ apps/cli/src/commands/ci-teardown.ts | 27 +- apps/cli/src/commands/forge-http.ts | 28 ++ apps/cli/src/commands/forge-note.ts | 32 +- apps/cli/src/commands/image-cleanup.ts | 379 +++++++++--------- apps/cli/src/commands/seed-image.ts | 9 +- apps/cli/src/identity.ts | 33 +- 10 files changed, 384 insertions(+), 250 deletions(-) create mode 100644 apps/cli/src/commands/forge-http.ts diff --git a/apps/cli/src/commands/ci-identity.test.ts b/apps/cli/src/commands/ci-identity.test.ts index 780cf9a4..c2d625f2 100644 --- a/apps/cli/src/commands/ci-identity.test.ts +++ b/apps/cli/src/commands/ci-identity.test.ts @@ -641,12 +641,17 @@ seed: expect(result.refs).toEqual(["registry.gitlab.com/group/repo:abc123"]); }); - test("skips silently when the commit's image ref cannot be derived", async () => { + test("warns instead of skipping silently when the commit's image ref cannot be derived", async () => { expect( await resolveCiPushedImageRefs( deps({ CI_COMMIT_SHA: "abc123" }, { readTextFile: async () => null }), identity, ), - ).toEqual({ refs: [], warnings: [] }); + ).toEqual({ + refs: [], + warnings: [ + "registry cleanup: image ref not resolved (cannot derive image ref (set CI_REGISTRY_IMAGE and CI_COMMIT_SHA))", + ], + }); }); }); diff --git a/apps/cli/src/commands/ci-identity.ts b/apps/cli/src/commands/ci-identity.ts index 27c6ed90..dcb70823 100644 --- a/apps/cli/src/commands/ci-identity.ts +++ b/apps/cli/src/commands/ci-identity.ts @@ -9,7 +9,7 @@ import { } from "../identity.ts"; import { resolveDeployHostname } from "../hostname.ts"; import type { Result } from "../result.ts"; -import { resolveSeedTarget } from "./seed-image.ts"; +import { resolveSeedTarget, isSharedSeedTarget } from "./seed-image.ts"; export type CiSource = | { forge: "gitlab"; pipelineSource: "merge_request_event" } @@ -184,7 +184,12 @@ export async function resolveCiPushedImageRefs( identity: CiIdentity, ): Promise { const app = resolveImageRef(deps.env, identity); - if (!app.ok) return { refs: [], warnings: [] }; + if (!app.ok) { + return { + refs: [], + warnings: [`registry cleanup: image ref not resolved (${app.error})`], + }; + } const yaml = await loadYaml(deps); if (!yaml.ok) { @@ -195,6 +200,9 @@ export async function resolveCiPushedImageRefs( } if (!yaml.value.seed) return { refs: [app.value], warnings: [] }; + if (isSharedSeedTarget(yaml.value.seed)) { + return { refs: [app.value], warnings: [] }; + } const seed = await resolveSeedTarget( yaml.value.seed, app.value, @@ -207,8 +215,5 @@ export async function resolveCiPushedImageRefs( warnings: [`registry cleanup: seed tag not resolved (${seed.error})`], }; } - // Content-addressed seed tags are shared cache across previews, so only the - // commit-scoped seed tag is a per-run artifact this teardown may delete. - if (seed.value.allowReuse) return { refs: [app.value], warnings: [] }; return { refs: [app.value, seed.value.ref], warnings: [] }; } diff --git a/apps/cli/src/commands/ci-note-wiring.test.ts b/apps/cli/src/commands/ci-note-wiring.test.ts index 42e304e3..a1f46863 100644 --- a/apps/cli/src/commands/ci-note-wiring.test.ts +++ b/apps/cli/src/commands/ci-note-wiring.test.ts @@ -211,7 +211,9 @@ preview: }, ); expect(code).toBe(0); - expect(stderr).toEqual([]); + expect(stderr).toEqual([ + "warning: registry cleanup: image ref not resolved (cannot derive image ref (set CI_REGISTRY_IMAGE and CI_COMMIT_SHA))", + ]); expect(forgeCalls[1]?.method).toBe("PUT"); const posted = JSON.stringify(forgeCalls[1]?.body ?? ""); expect(posted).toContain("removed"); diff --git a/apps/cli/src/commands/ci-teardown-tags.test.ts b/apps/cli/src/commands/ci-teardown-tags.test.ts index dfcd06ad..1296ef9f 100644 --- a/apps/cli/src/commands/ci-teardown-tags.test.ts +++ b/apps/cli/src/commands/ci-teardown-tags.test.ts @@ -116,6 +116,44 @@ describe("ci teardown image tags", () => { expect(deletes[0]?.headers["job-token"]).toBe("job-token"); }); + test("lists the GitLab repository index once and reports what it deleted", async () => { + const calls: FetchCall[] = []; + const baseUrl = startGateway(); + const code = await runCli( + ["ci", "teardown"], + deps({ ...GITLAB_ENV, SPROUT_URL: baseUrl }, gitlabFetch(calls)), + ); + + expect(code).toBe(0); + expect(stdout).toEqual(["deleted 2 registry tag(s)"]); + expect( + calls.filter((call) => call.url.includes("/registry/repositories?")), + ).toHaveLength(1); + expect(calls.filter((call) => call.method === "DELETE")).toHaveLength(2); + }); + + test("warns when the image ref cannot be resolved instead of exiting silently", async () => { + const calls: FetchCall[] = []; + const baseUrl = startGateway(); + const code = await runCli( + ["ci", "teardown"], + deps( + { + ...GITLAB_ENV, + CI_REGISTRY_IMAGE: undefined, + SPROUT_URL: baseUrl, + }, + gitlabFetch(calls), + ), + ); + + expect(code).toBe(0); + expect(stderr).toEqual([ + "warning: registry cleanup: image ref not resolved (cannot derive image ref (set CI_REGISTRY_IMAGE and CI_COMMIT_SHA))", + ]); + expect(calls.filter((call) => call.method === "DELETE")).toEqual([]); + }); + test("already-deleted tags warn and still exit 0", async () => { const calls: FetchCall[] = []; const baseUrl = startGateway(); @@ -253,6 +291,66 @@ describe("ci teardown image tags", () => { expect(deletes[0]?.headers.authorization).toBe("Bearer gh-token"); }); + test("resolves each GHCR package and version list once for the run's tags", async () => { + const calls: FetchCall[] = []; + const baseUrl = startGateway(); + const fetchFn = async (url: string, init?: RequestInit) => { + const method = init?.method ?? "GET"; + calls.push({ url, method, headers: headersOf(init) }); + if (url.includes("/issues/42/comments")) { + if (method === "GET") return Response.json([]); + return Response.json({ id: 1 }); + } + if (url === "https://api.github.com/users/org") { + return Response.json({ type: "Organization" }); + } + if ( + method === "GET" && + url.includes("/orgs/org/packages/container/repo/versions") + ) { + return Response.json([ + { id: 11, metadata: { container: { tags: ["def456"] } } }, + { id: 12, metadata: { container: { tags: ["def456-seed"] } } }, + ]); + } + if (method === "DELETE" && url.includes("/versions/")) { + return new Response(null, { status: 204 }); + } + return new Response("not found", { status: 404 }); + }; + + const code = await runCli( + ["ci", "teardown"], + deps( + { + SPROUT_URL: baseUrl, + SPROUT_TOKEN: "t", + GITHUB_EVENT_NAME: "pull_request", + GITHUB_REF: "refs/pull/42/merge", + GITHUB_REPOSITORY: "org/repo", + GITHUB_SHA: "def456", + GITHUB_TOKEN: "gh-token", + CI_REGISTRY_IMAGE: "ghcr.io/org/repo", + }, + fetchFn, + ), + ); + + expect(code).toBe(0); + expect(stdout).toEqual(["deleted 2 registry tag(s)"]); + expect( + calls.filter((call) => call.url === "https://api.github.com/users/org"), + ).toHaveLength(1); + expect( + calls.filter( + (call) => + call.method === "GET" && + call.url.includes("/packages/container/"), + ), + ).toHaveLength(1); + expect(calls.filter((call) => call.method === "DELETE")).toHaveLength(2); + }); + test("GHCR retries a refused delete with the job token", async () => { const calls: FetchCall[] = []; const baseUrl = startGateway(); diff --git a/apps/cli/src/commands/ci-teardown.ts b/apps/cli/src/commands/ci-teardown.ts index 06ccaf85..874811e3 100644 --- a/apps/cli/src/commands/ci-teardown.ts +++ b/apps/cli/src/commands/ci-teardown.ts @@ -1,6 +1,7 @@ import type { CliContext } from "../context.ts"; import { fail } from "../context.ts"; import { parseFlags } from "../flags.ts"; +import type { Result } from "../result.ts"; import { resolveCiPushedImageRefs, type CiIdentity, @@ -27,24 +28,36 @@ export async function runCiTeardown( const result = await teardownPreview(ctx.client, identity); if (!result.ok) return fail(ctx.deps.io, result.error); + const imagesPromise = resolveCiPushedImageRefs(ctx.deps, identity); + const cleanupPromise = imagesPromise.then((images) => + cleanupPushedImageRefs(ctx.deps, identity, images.refs), + ); + const notePromise = publishTeardownNote(ctx.deps, identity).catch( + (err): Result => ({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }), + ); + + let note: Result; try { - const images = await resolveCiPushedImageRefs(ctx.deps, identity); + const [images, cleanup] = await Promise.all([imagesPromise, cleanupPromise]); for (const warning of images.warnings) { ctx.deps.io.stderr(`warning: ${warning}`); } - const cleanup = await cleanupPushedImageRefs( - ctx.deps, - identity, - images.refs, - ); for (const warning of cleanup.warnings) { ctx.deps.io.stderr(`warning: ${warning}`); } + if (cleanup.deleted.length > 0) { + ctx.deps.io.stdout(`deleted ${cleanup.deleted.length} registry tag(s)`); + } + note = await notePromise; } catch (err) { const detail = err instanceof Error ? err.message : String(err); ctx.deps.io.stderr(`warning: registry tag cleanup skipped: ${detail}`); + note = await notePromise; } - warnForgeNote(ctx.deps.io, await publishTeardownNote(ctx.deps, identity)); + warnForgeNote(ctx.deps.io, note); return 0; } diff --git a/apps/cli/src/commands/forge-http.ts b/apps/cli/src/commands/forge-http.ts new file mode 100644 index 00000000..566b8869 --- /dev/null +++ b/apps/cli/src/commands/forge-http.ts @@ -0,0 +1,28 @@ +import type { CliDeps } from "../context.ts"; + +export function fetchFor( + deps: CliDeps, +): (url: string, init?: RequestInit) => Promise { + return deps.fetchFn ?? globalThis.fetch; +} + +export function stripTrailingSlash(url: string): string { + return url.replace(/\/+$/, ""); +} + +export async function readErrorBody(res: Response): Promise { + try { + const text = (await res.text()).trim(); + return text ? text.slice(0, 300) : res.statusText || "unknown error"; + } catch { + return res.statusText || "unknown error"; + } +} + +export function githubHeaders(token: string): Record { + return { + Authorization: `Bearer ${token}`, + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + }; +} diff --git a/apps/cli/src/commands/forge-note.ts b/apps/cli/src/commands/forge-note.ts index 8f0503a9..2e815045 100644 --- a/apps/cli/src/commands/forge-note.ts +++ b/apps/cli/src/commands/forge-note.ts @@ -2,18 +2,16 @@ import type { CliDeps, CliIo } from "../context.ts"; import type { Result } from "../result.ts"; import type { DeploySettled } from "./deploy-outcome.ts"; import type { CiIdentity } from "./ci-identity.ts"; +import { + fetchFor as fetchFn, + githubHeaders as githubWriteHeaders, + readErrorBody, + stripTrailingSlash, +} from "./forge-http.ts"; /** Hidden marker keying one sprout note per MR; re-runs edit in place. */ export const SPROUT_NOTE_MARKER = ""; -function fetchFn(deps: CliDeps): (url: string, init?: RequestInit) => Promise { - return deps.fetchFn ?? globalThis.fetch; -} - -function stripTrailingSlash(url: string): string { - return url.replace(/\/+$/, ""); -} - function shortSha(sha: string | undefined): string | undefined { const trimmed = sha?.trim(); if (!trimmed) return undefined; @@ -124,14 +122,6 @@ function repoPathFromCanonical(repo: string, host: string): string | null { } } -function githubWriteHeaders(token: string): Record { - return { - Authorization: `Bearer ${token}`, - Accept: "application/vnd.github+json", - "X-GitHub-Api-Version": "2022-11-28", - }; -} - function resolveForgeTarget( env: NodeJS.ProcessEnv, identity: CiIdentity, @@ -197,16 +187,6 @@ function resolveForgeTarget( }; } -async function readErrorBody(res: Response): Promise { - try { - const text = await res.text(); - const trimmed = text.trim(); - return trimmed ? trimmed.slice(0, 500) : res.statusText || "unknown error"; - } catch { - return res.statusText || "unknown error"; - } -} - type ForgeNote = { id: number; body: string }; async function forgeRequest( diff --git a/apps/cli/src/commands/image-cleanup.ts b/apps/cli/src/commands/image-cleanup.ts index 8e33257c..6805445b 100644 --- a/apps/cli/src/commands/image-cleanup.ts +++ b/apps/cli/src/commands/image-cleanup.ts @@ -1,6 +1,12 @@ import type { CliDeps } from "../context.ts"; import type { CiIdentity } from "./ci-identity.ts"; import type { Result } from "../result.ts"; +import { + fetchFor, + githubHeaders, + readErrorBody, + stripTrailingSlash, +} from "./forge-http.ts"; export type ParsedImageRef = { registry: string; @@ -16,14 +22,6 @@ export type ImageCleanupReport = { const MAX_GITLAB_REPOSITORIES_PAGES = 10; const MAX_GHCR_VERSION_PAGES = 100; -function fetchFor(deps: CliDeps): (url: string, init?: RequestInit) => Promise { - return deps.fetchFn ?? globalThis.fetch; -} - -function stripTrailingSlash(url: string): string { - return url.replace(/\/+$/, ""); -} - export function parseImageRef(ref: string): ParsedImageRef | null { const trimmed = ref.trim(); const slash = trimmed.lastIndexOf("/"); @@ -35,27 +33,14 @@ export function parseImageRef(ref: string): ParsedImageRef | null { const hostEnd = name.indexOf("/"); if (hostEnd <= 0) return null; const registry = name.slice(0, hostEnd); - if ( - !registry.includes(".") && - !registry.includes(":") && - registry !== "localhost" - ) { - return null; - } + const namedRegistry = + registry.includes(".") || registry.includes(":") || registry === "localhost"; + if (!namedRegistry) return null; const repository = name.slice(hostEnd + 1); - if (!repository || tag.includes("/")) return null; + if (!repository) return null; return { registry, repository, tag }; } -async function readErrorBody(res: Response): Promise { - try { - const text = (await res.text()).trim(); - return text ? text.slice(0, 300) : res.statusText || "unknown error"; - } catch { - return res.statusText || "unknown error"; - } -} - function unauthorizedStatus(status: number): boolean { return status === 401 || status === 403; } @@ -117,7 +102,8 @@ function gitlabHeaders(target: GitlabTarget): Record { async function listGitlabRepositories( doFetch: (url: string, init?: RequestInit) => Promise, target: GitlabTarget, -): Promise>> { + wanted: ReadonlySet, +): Promise; exhausted: boolean }>> { const repositories = new Map(); for (let page = 1; page <= MAX_GITLAB_REPOSITORIES_PAGES; page++) { let res: Response; @@ -161,9 +147,14 @@ async function listGitlabRepositories( repositories.set(record.path.toLowerCase(), record.id); } } - if (data.length < 100) break; + if ([...wanted].every((path) => repositories.has(path))) { + return { ok: true, value: { repositories, exhausted: false } }; + } + if (data.length < 100) { + return { ok: true, value: { repositories, exhausted: false } }; + } } - return { ok: true, value: repositories }; + return { ok: true, value: { repositories, exhausted: true } }; } type DeleteOutcome = @@ -172,23 +163,19 @@ type DeleteOutcome = | { status: "unauthorized" } | { status: "failed"; detail: string }; -async function deleteGitlabTag( +async function deleteResource( doFetch: (url: string, init?: RequestInit) => Promise, - target: GitlabTarget, - repositoryId: number, - tag: string, + url: string, + headers: Record, ): Promise { let res: Response; try { - res = await doFetch( - `${target.api}/projects/${target.project}/registry/repositories/${repositoryId}/tags/${encodeURIComponent(tag)}`, - { method: "DELETE", headers: gitlabHeaders(target) }, - ); + res = await doFetch(url, { method: "DELETE", headers }); } catch (err) { const detail = err instanceof Error ? err.message : String(err); return { status: "failed", detail }; } - if (res.ok || res.status === 202) return { status: "deleted" }; + if (res.ok) return { status: "deleted" }; if (res.status === 404) return { status: "missing" }; if (unauthorizedStatus(res.status)) return { status: "unauthorized" }; return { @@ -197,10 +184,46 @@ async function deleteGitlabTag( }; } +function deleteGitlabTag( + doFetch: (url: string, init?: RequestInit) => Promise, + target: GitlabTarget, + repositoryId: number, + tag: string, +): Promise { + return deleteResource( + doFetch, + `${target.api}/projects/${target.project}/registry/repositories/${repositoryId}/tags/${encodeURIComponent(tag)}`, + gitlabHeaders(target), + ); +} + function unauthorizedWarning(scope: string): string { return `registry tag delete is not authorized (missing ${scope} scope); leaving the tags to the forge expiration policy`; } +type CleanupTally = ImageCleanupReport & { sawUnauthorized: boolean }; + +function recordOutcome( + tally: CleanupTally, + ref: string, + outcome: DeleteOutcome, +): void { + switch (outcome.status) { + case "deleted": + tally.deleted.push(ref); + break; + case "missing": + tally.warnings.push(`registry tag already absent: ${ref}`); + break; + case "unauthorized": + tally.sawUnauthorized = true; + break; + case "failed": + tally.warnings.push(`registry tag delete failed for ${ref}: ${outcome.detail}`); + break; + } +} + async function cleanupGitlab( deps: CliDeps, refs: string[], @@ -216,7 +239,9 @@ async function cleanupGitlab( }); if (parsed.length === 0) return { deleted: [], warnings: [] }; - const repositories = await listGitlabRepositories(fetchFor(deps), target.value); + const doFetch = fetchFor(deps); + const wanted = new Set(parsed.map(({ image }) => image.repository.toLowerCase())); + const repositories = await listGitlabRepositories(doFetch, target.value, wanted); if (!repositories.ok) { const unauthorized = repositories.error.includes("unauthorized"); return { @@ -229,38 +254,27 @@ async function cleanupGitlab( }; } - const deleted: string[] = []; - const warnings: string[] = []; - let sawUnauthorized = false; - for (const { ref, image } of parsed) { - const repositoryId = repositories.value.get(image.repository.toLowerCase()); - if (repositoryId === undefined) { - warnings.push(`registry tag already absent: ${ref}`); + const tally: CleanupTally = { deleted: [], warnings: [], sawUnauthorized: false }; + const index = repositories.value; + const deletions = parsed.map(async ({ ref, image }) => { + const repositoryId = index.repositories.get(image.repository.toLowerCase()); + if (repositoryId === undefined) return { ref, image, outcome: null }; + const outcome = await deleteGitlabTag(doFetch, target.value, repositoryId, image.tag); + return { ref, image, outcome }; + }); + for (const { ref, image, outcome } of await Promise.all(deletions)) { + if (outcome === null) { + tally.warnings.push( + index.exhausted + ? `GitLab registry repository list page cap reached for ${image.repository}; ${image.tag} not resolved` + : `registry tag already absent: ${ref}`, + ); continue; } - const outcome = await deleteGitlabTag( - fetchFor(deps), - target.value, - repositoryId, - image.tag, - ); - switch (outcome.status) { - case "deleted": - deleted.push(ref); - break; - case "missing": - warnings.push(`registry tag already absent: ${ref}`); - break; - case "unauthorized": - sawUnauthorized = true; - break; - case "failed": - warnings.push(`registry tag delete failed for ${ref}: ${outcome.detail}`); - break; - } + recordOutcome(tally, ref, outcome); } - if (sawUnauthorized) warnings.push(unauthorizedWarning("api")); - return { deleted, warnings }; + if (tally.sawUnauthorized) tally.warnings.push(unauthorizedWarning("api")); + return { deleted: tally.deleted, warnings: tally.warnings }; } type GithubTarget = { api: string; token: string; fallbackToken?: string }; @@ -293,14 +307,6 @@ function resolveGithubTarget(env: NodeJS.ProcessEnv): Result { }; } -function githubHeaders(token: string): Record { - return { - Authorization: `Bearer ${token}`, - Accept: "application/vnd.github+json", - "X-GitHub-Api-Version": "2022-11-28", - }; -} - type GithubPackage = { packageBase: string; packageName: string }; async function resolveGithubPackage( @@ -368,12 +374,15 @@ function nextLink(link: string | null): string | null { type GithubVersion = { id: number; tags: string[] }; -async function findGithubVersion( +async function findGithubVersions( doFetch: (url: string, init?: RequestInit) => Promise, target: GithubTarget, pkg: GithubPackage, - tag: string, -): Promise> { + wanted: ReadonlySet, +): Promise< + Result<{ versions: Map; exhausted: boolean }> +> { + const versions = new Map(); let url = `${target.api}/${pkg.packageBase}/${encodeURIComponent(pkg.packageName)}/versions?per_page=100`; for (let page = 0; page < MAX_GHCR_VERSION_PAGES; page++) { let res: Response; @@ -408,52 +417,36 @@ async function findGithubVersion( metadata?: { container?: { tags?: unknown } }; }; const tags = record.metadata?.container?.tags; - if ( - typeof record.id === "number" && - Array.isArray(tags) && - tags.includes(tag) - ) { - return { - ok: true, - value: { - id: record.id, - tags: tags.filter((item): item is string => typeof item === "string"), - }, - }; + if (typeof record.id !== "number" || !Array.isArray(tags)) continue; + const tagList = tags.filter((tag): tag is string => typeof tag === "string"); + for (const tag of tagList) { + if (!wanted.has(tag) || versions.has(tag)) continue; + versions.set(tag, { id: record.id, tags: tagList }); } } + if (versions.size === wanted.size) { + return { ok: true, value: { versions, exhausted: false } }; + } const next = nextLink(res.headers.get("link")); - if (!next) return { ok: true, value: null }; + if (!next) return { ok: true, value: { versions, exhausted: false } }; url = next; } - return { ok: true, value: null }; + return { ok: true, value: { versions, exhausted: true } }; } -async function deleteGithubVersionWithToken( +function deleteGithubVersionWithToken( doFetch: (url: string, init?: RequestInit) => Promise, target: GithubTarget, token: string, pkg: GithubPackage, versionId: number, ): Promise { - let res: Response; - try { - res = await doFetch( - `${target.api}/${pkg.packageBase}/${encodeURIComponent(pkg.packageName)}/versions/${versionId}`, - { method: "DELETE", headers: githubHeaders(token) }, - ); - } catch (err) { - const detail = err instanceof Error ? err.message : String(err); - return { status: "failed", detail }; - } - if (res.ok || res.status === 204) return { status: "deleted" }; - if (res.status === 404) return { status: "missing" }; - if (unauthorizedStatus(res.status)) return { status: "unauthorized" }; - return { - status: "failed", - detail: `${res.status} ${await readErrorBody(res)}`, - }; + return deleteResource( + doFetch, + `${target.api}/${pkg.packageBase}/${encodeURIComponent(pkg.packageName)}/versions/${versionId}`, + githubHeaders(token), + ); } /** The registry login token often lacks delete:packages; the job token can delete. */ @@ -480,6 +473,12 @@ async function deleteGithubVersion( ); } +type GithubGroup = { + image: ParsedImageRef; + tags: Set; + refs: Array<{ ref: string; tag: string }>; +}; + async function cleanupGithub( deps: CliDeps, refs: string[], @@ -489,110 +488,98 @@ async function cleanupGithub( return { deleted: [], warnings: [`registry tag cleanup skipped: ${target.error}`] }; } - type GithubEntry = - | { ref: string; warning: string } - | { ref: string; image: ParsedImageRef }; - const parsed: GithubEntry[] = refs.map((ref) => { + const tally: CleanupTally = { deleted: [], warnings: [], sawUnauthorized: false }; + const groups = new Map(); + for (const ref of refs) { const image = parseImageRef(ref); if (!image) { - return { - ref, - warning: `registry tag cleanup skipped for ${ref}: unsupported image reference`, - }; + tally.warnings.push( + `registry tag cleanup skipped for ${ref}: unsupported image reference`, + ); + continue; } if (image.registry.toLowerCase() !== "ghcr.io") { - return { - ref, - warning: `registry tag cleanup skipped for ${ref}: only ghcr.io is supported on GitHub`, - }; + tally.warnings.push( + `registry tag cleanup skipped for ${ref}: only ghcr.io is supported on GitHub`, + ); + continue; + } + const group = groups.get(image.repository); + if (group) { + group.tags.add(image.tag); + group.refs.push({ ref, tag: image.tag }); + } else { + groups.set(image.repository, { + image, + tags: new Set([image.tag]), + refs: [{ ref, tag: image.tag }], + }); } - return { ref, image }; - }); - - const targetTags = new Map>(); - for (const entry of parsed) { - if (!("image" in entry)) continue; - const tags = targetTags.get(entry.image.repository) ?? new Set(); - tags.add(entry.image.tag); - targetTags.set(entry.image.repository, tags); } - const deleted: string[] = []; - const warnings: string[] = []; - let sawUnauthorized = false; - for (const entry of parsed) { - if ("warning" in entry) { - warnings.push(entry.warning); - continue; - } - const pkg = await resolveGithubPackage( - fetchFor(deps), - target.value, - entry.image, - ); - if (!pkg.ok) { - if (unauthorizedDetail(pkg.error)) { - sawUnauthorized = true; - } else { - warnings.push( - `registry tag cleanup skipped for ${entry.ref}: ${pkg.error}`, - ); + const doFetch = fetchFor(deps); + const packages = await Promise.all( + [...groups].map(async ([repository, group]) => ({ + repository, + group, + pkg: await resolveGithubPackage(doFetch, target.value, group.image), + })), + ); + + for (const { repository, group, pkg } of packages) { + const skip = (error: string) => { + if (unauthorizedDetail(error)) { + tally.sawUnauthorized = true; + return; } + for (const { ref } of group.refs) { + tally.warnings.push(`registry tag cleanup skipped for ${ref}: ${error}`); + } + }; + if (!pkg.ok) { + skip(pkg.error); continue; } - const version = await findGithubVersion( - fetchFor(deps), + const versions = await findGithubVersions( + doFetch, target.value, pkg.value, - entry.image.tag, + group.tags, ); - if (!version.ok) { - if (unauthorizedDetail(version.error)) { - sawUnauthorized = true; - } else { - warnings.push( - `registry tag cleanup skipped for ${entry.ref}: ${version.error}`, - ); - } - continue; - } - if (version.value === null) { - warnings.push(`registry tag already absent: ${entry.ref}`); - continue; - } - const wanted = targetTags.get(entry.image.repository) ?? new Set(); - const extraTags = version.value.tags.filter((tag) => !wanted.has(tag)); - if (extraTags.length > 0) { - warnings.push( - `registry tag delete skipped for ${entry.ref}: GHCR version ${version.value.id} also carries ${extraTags.join(", ")}`, - ); + if (!versions.ok) { + skip(versions.error); continue; } - const outcome = await deleteGithubVersion( - fetchFor(deps), - target.value, - pkg.value, - version.value.id, - ); - switch (outcome.status) { - case "deleted": - deleted.push(entry.ref); - break; - case "missing": - warnings.push(`registry tag already absent: ${entry.ref}`); - break; - case "unauthorized": - sawUnauthorized = true; - break; - case "failed": - warnings.push( - `registry tag delete failed for ${entry.ref}: ${outcome.detail}`, + for (const { ref, tag } of group.refs) { + const version = versions.value.versions.get(tag); + if (!version) { + tally.warnings.push( + versions.value.exhausted + ? `GHCR version list page cap reached for ${repository}; ${tag} not resolved` + : `registry tag already absent: ${ref}`, + ); + continue; + } + const extraTags = version.tags.filter((item) => !group.tags.has(item)); + if (extraTags.length > 0) { + tally.warnings.push( + `registry tag delete skipped for ${ref}: GHCR version ${version.id} also carries ${extraTags.join(", ")}`, ); - break; + continue; + } + const outcome = await deleteGithubVersion( + doFetch, + target.value, + pkg.value, + version.id, + ); + recordOutcome(tally, ref, outcome); } } - if (sawUnauthorized) warnings.push(unauthorizedWarning("delete:packages")); - return { deleted, warnings }; + if (tally.sawUnauthorized) { + tally.warnings.push(unauthorizedWarning("delete:packages")); + } + return { deleted: tally.deleted, warnings: tally.warnings }; } export async function cleanupPushedImageRefs( diff --git a/apps/cli/src/commands/seed-image.ts b/apps/cli/src/commands/seed-image.ts index 489dbc2d..76fa2add 100644 --- a/apps/cli/src/commands/seed-image.ts +++ b/apps/cli/src/commands/seed-image.ts @@ -104,13 +104,20 @@ async function seedImageExists( export type SeedTarget = { ref: string; allowReuse: boolean }; +/** Content-addressed seeds (`inputs`) are shared cache; only commit-scoped tags are per-run. */ +export function isSharedSeedTarget( + seed: Pick, +): seed is Pick & { inputs: string[] } { + return seed.inputs !== undefined; +} + export async function resolveSeedTarget( seed: SproutSeed, appImageRef: string, cwd: string, readFile: (path: string) => Promise, ): Promise> { - if (seed.inputs === undefined) { + if (!isSharedSeedTarget(seed)) { const ref = resolveCommitSeedImageRef(appImageRef); if (!ref.ok) return ref; return { ok: true, value: { ref: ref.value, allowReuse: false } }; diff --git a/apps/cli/src/identity.ts b/apps/cli/src/identity.ts index fab7e116..00aa2622 100644 --- a/apps/cli/src/identity.ts +++ b/apps/cli/src/identity.ts @@ -98,18 +98,28 @@ export function resolveCanonicalRepoId(input: { }; } +function pullRequestRecord( + eventPayload: unknown, +): Record | null { + if (typeof eventPayload !== "object" || eventPayload === null) return null; + const pullRequest = (eventPayload as { pull_request?: unknown }).pull_request; + if (typeof pullRequest !== "object" || pullRequest === null) return null; + return pullRequest as Record; +} + function readGithubPrId( env: NodeJS.ProcessEnv, eventPayload?: unknown, ): number | null { - if (eventPayload && typeof eventPayload === "object") { - const record = eventPayload as Record; - const fromPr = record.pull_request; - if (fromPr && typeof fromPr === "object") { - const n = positiveInt((fromPr as { number?: unknown }).number); - if (n !== null) return n; - } - const fromNumber = positiveInt(record.number); + const pullRequest = pullRequestRecord(eventPayload); + if (pullRequest) { + const fromPr = positiveInt(pullRequest.number); + if (fromPr !== null) return fromPr; + } + if (typeof eventPayload === "object" && eventPayload !== null) { + const fromNumber = positiveInt( + (eventPayload as Record).number, + ); if (fromNumber !== null) return fromNumber; } @@ -177,10 +187,9 @@ export function resolveCommitSha( export function resolvePullRequestHeadSha( eventPayload: unknown, ): string | undefined { - if (typeof eventPayload !== "object" || eventPayload === null) return undefined; - const pullRequest = (eventPayload as { pull_request?: unknown }).pull_request; - if (typeof pullRequest !== "object" || pullRequest === null) return undefined; - const head = (pullRequest as { head?: unknown }).head; + const pullRequest = pullRequestRecord(eventPayload); + if (!pullRequest) return undefined; + const head = pullRequest.head; if (typeof head !== "object" || head === null) return undefined; const sha = (head as { sha?: unknown }).sha; return typeof sha === "string" ? sha.trim() || undefined : undefined;