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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions apps/cli/src/commands/ci-identity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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))",
],
});
});
});
15 changes: 10 additions & 5 deletions apps/cli/src/commands/ci-identity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down Expand Up @@ -184,7 +184,12 @@ export async function resolveCiPushedImageRefs(
identity: CiIdentity,
): Promise<CiPushedImageRefs> {
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) {
Expand All @@ -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,
Expand All @@ -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: [] };
}
4 changes: 3 additions & 1 deletion apps/cli/src/commands/ci-note-wiring.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
98 changes: 98 additions & 0 deletions apps/cli/src/commands/ci-teardown-tags.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down
27 changes: 20 additions & 7 deletions apps/cli/src/commands/ci-teardown.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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<void> => ({
ok: false,
error: err instanceof Error ? err.message : String(err),
}),
);

let note: Result<void>;
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;
}
28 changes: 28 additions & 0 deletions apps/cli/src/commands/forge-http.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type { CliDeps } from "../context.ts";

export function fetchFor(
deps: CliDeps,
): (url: string, init?: RequestInit) => Promise<Response> {
return deps.fetchFn ?? globalThis.fetch;
}

export function stripTrailingSlash(url: string): string {
return url.replace(/\/+$/, "");
}

export async function readErrorBody(res: Response): Promise<string> {
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<string, string> {
return {
Authorization: `Bearer ${token}`,
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
};
}
32 changes: 6 additions & 26 deletions apps/cli/src/commands/forge-note.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "<!-- sprout-preview-note -->";

function fetchFn(deps: CliDeps): (url: string, init?: RequestInit) => Promise<Response> {
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;
Expand Down Expand Up @@ -124,14 +122,6 @@ function repoPathFromCanonical(repo: string, host: string): string | null {
}
}

function githubWriteHeaders(token: string): Record<string, string> {
return {
Authorization: `Bearer ${token}`,
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
};
}

function resolveForgeTarget(
env: NodeJS.ProcessEnv,
identity: CiIdentity,
Expand Down Expand Up @@ -197,16 +187,6 @@ function resolveForgeTarget(
};
}

async function readErrorBody(res: Response): Promise<string> {
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(
Expand Down
Loading
Loading