From 6b38f64ad0ad98f738fec6c03a7b32336a2148b3 Mon Sep 17 00:00:00 2001 From: simpros <38320875+simpros@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:22:41 +0100 Subject: [PATCH] =?UTF-8?q?#294:=20sprout#294=20=E2=80=94=20preview=20imag?= =?UTF-8?q?e-repository=20override=20(build.image=5Frepo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/cli/src/commands/ci-identity.test.ts | 98 +++++++++++++++++++ apps/cli/src/commands/ci-identity.ts | 28 ++++-- apps/cli/src/commands/ci-preview.test.ts | 46 +++++++++ apps/cli/src/commands/ci-reseed.ts | 10 +- apps/cli/src/commands/ci-reset.test.ts | 41 ++++++++ .../commands/ci-teardown-reseed-logs.test.ts | 53 ++++++++++ .../cli/src/commands/ci-teardown-tags.test.ts | 41 +++++++- apps/cli/src/yaml.test.ts | 60 ++++++++++++ apps/cli/src/yaml.ts | 61 +++++++++--- docs/adopting-a-repo.md | 1 + docs/ci-integration.md | 23 ++++- docs/cli-reference.md | 2 +- docs/troubleshooting.md | 5 +- templates/README.md | 20 ++-- 14 files changed, 444 insertions(+), 45 deletions(-) diff --git a/apps/cli/src/commands/ci-identity.test.ts b/apps/cli/src/commands/ci-identity.test.ts index 780cf9a4..799a07b6 100644 --- a/apps/cli/src/commands/ci-identity.test.ts +++ b/apps/cli/src/commands/ci-identity.test.ts @@ -178,6 +178,42 @@ describe("resolveImageRef", () => { error: "cannot derive image ref (set CI_REGISTRY_IMAGE and CI_COMMIT_SHA)", }); }); + + test("uses the repository override in place of CI_REGISTRY_IMAGE", () => { + expect( + resolveImageRef( + { CI_REGISTRY_IMAGE: "registry.gitlab.com/group/repo" }, + { forge: "gitlab", commitSha: "abc" }, + "registry.gitlab.com/toptiere/dcos/product", + ), + ).toEqual({ + ok: true, + value: "registry.gitlab.com/toptiere/dcos/product:abc", + }); + }); + + test("uses the repository override without CI_REGISTRY_IMAGE set", () => { + expect( + resolveImageRef( + {}, + { forge: "github", commitSha: "def" }, + "ghcr.io/org/sub/app", + ), + ).toEqual({ ok: true, value: "ghcr.io/org/sub/app:def" }); + }); + + test("override still requires the forge SHA and names only that var", () => { + expect( + resolveImageRef( + { CI_REGISTRY_IMAGE: "registry.example/app" }, + { forge: "gitlab", commitSha: undefined }, + "registry.example/team/app", + ), + ).toEqual({ + ok: false, + error: "cannot derive image ref (set CI_COMMIT_SHA)", + }); + }); }); describe("resolveCiIdentity", () => { @@ -537,6 +573,38 @@ describe("resolveCiPreviewIdentity", () => { }); }); + test("resolves the image ref through build.image_repo", async () => { + expect( + await resolveCiPreviewIdentity( + deps( + { + CI_PROJECT_URL: "https://gitlab.com/group/repo", + CI_MERGE_REQUEST_IID: "17", + CI_PIPELINE_SOURCE: "merge_request_event", + CI_COMMIT_SHA: "abc123", + }, + { + readTextFile: async (path) => + path.endsWith(".sprout.yaml") + ? `slug: myapp +build: + image_repo: registry.gitlab.com/toptiere/dcos/product +preview: + hostname: "pr-{pr_id}.example.com" +` + : null, + }, + ), + ), + ).toMatchObject({ + ok: true, + value: { + imageRef: "registry.gitlab.com/toptiere/dcos/product:abc123", + hostname: "pr-17.example.com", + }, + }); + }); + test("errors when image ref cannot be derived", async () => { expect( await resolveCiPreviewIdentity( @@ -614,6 +682,36 @@ seed: }); }); + test("resolves push refs under build.image_repo when set", async () => { + expect( + await resolveCiPushedImageRefs( + deps( + env, + { + readTextFile: async (path) => + path.endsWith(".sprout.yaml") + ? `slug: myapp +build: + image_repo: registry.gitlab.com/toptiere/dcos/product +preview: + hostname: "pr-{pr_id}.example.com" +seed: + dockerfile: Dockerfile.seed +` + : null, + }, + ), + identity, + ), + ).toEqual({ + refs: [ + "registry.gitlab.com/toptiere/dcos/product:abc123", + "registry.gitlab.com/toptiere/dcos/product:abc123-seed", + ], + warnings: [], + }); + }); + test("never treats content-addressed seed tags as cleanup targets", async () => { const result = await resolveCiPushedImageRefs( deps( diff --git a/apps/cli/src/commands/ci-identity.ts b/apps/cli/src/commands/ci-identity.ts index 27c6ed90..7f1aa744 100644 --- a/apps/cli/src/commands/ci-identity.ts +++ b/apps/cli/src/commands/ci-identity.ts @@ -86,14 +86,18 @@ export function requireCiSource(env: NodeJS.ProcessEnv): Result { export function resolveImageRef( env: NodeJS.ProcessEnv, identity: Pick, + imageRepo?: string, ): Result { - const registry = env.CI_REGISTRY_IMAGE?.trim(); + const override = imageRepo?.trim(); + const registry = override || env.CI_REGISTRY_IMAGE?.trim(); const sha = identity.commitSha; if (!registry || !sha) { const shaVar = commitShaEnvVar(identity.forge); return { ok: false, - error: `cannot derive image ref (set CI_REGISTRY_IMAGE and ${shaVar})`, + error: override + ? `cannot derive image ref (set ${shaVar})` + : `cannot derive image ref (set CI_REGISTRY_IMAGE and ${shaVar})`, }; } return { ok: true, value: `${registry}:${sha}` }; @@ -149,12 +153,16 @@ export async function resolveCiPreviewIdentity( const base = await resolveCiIdentity(deps); if (!base.ok) return base; - const imageRef = resolveImageRef(deps.env, base.value); - if (!imageRef.ok) return imageRef; - const yaml = await loadYaml(deps); if (!yaml.ok) return yaml; + const imageRef = resolveImageRef( + deps.env, + base.value, + yaml.value.build?.image_repo, + ); + if (!imageRef.ok) return imageRef; + const hostname = resolveDeployHostname( yaml.value.preview.hostname, base.value.prId, @@ -183,10 +191,16 @@ export async function resolveCiPushedImageRefs( deps: CliDeps, identity: CiIdentity, ): Promise { - const app = resolveImageRef(deps.env, identity); + const yaml = await loadYaml(deps); + // An unreadable manifest cannot name an override repository, so fall back to + // the registry root exactly as a repo without `build.image_repo` does. + const app = resolveImageRef( + deps.env, + identity, + yaml.ok ? yaml.value.build?.image_repo : undefined, + ); if (!app.ok) return { refs: [], warnings: [] }; - const yaml = await loadYaml(deps); if (!yaml.ok) { return { refs: [app.value], diff --git a/apps/cli/src/commands/ci-preview.test.ts b/apps/cli/src/commands/ci-preview.test.ts index 0170e87e..4f6d4ca3 100644 --- a/apps/cli/src/commands/ci-preview.test.ts +++ b/apps/cli/src/commands/ci-preview.test.ts @@ -118,6 +118,24 @@ health: expect: 200 `; +const OVERRIDE_YAML = `slug: myapp +build: + dockerfile: Dockerfile + image_repo: registry.gitlab.com/toptiere/dcos/product +seed: + dockerfile: Dockerfile.seed +preview: + hostname: "pr-{pr_id}.myapp.preview.example.com" +health: + path: /health + interval: 2s + timeout: 120s + expect: 200 +`; + +const OVERRIDE_APP_REF = "registry.gitlab.com/toptiere/dcos/product:abc123"; +const OVERRIDE_SEED_REF = `${OVERRIDE_APP_REF}-seed`; + const SEEDED_INPUTS_YAML = `slug: myapp build: dockerfile: Dockerfile @@ -218,6 +236,34 @@ describe("sprout ci preview", () => { }); }); + test("build.image_repo pushes app and seed to the override repository", async () => { + const baseUrl = healthyGateway(); + const cwd = await withWorkspace(OVERRIDE_YAML, { + "Dockerfile.seed": SEED_DOCKERFILE, + }); + const code = await runCli( + ["ci", "preview"], + deps({ + cwd, + env: { SPROUT_URL: baseUrl, SPROUT_TOKEN: "t", ...GITLAB_MR_ENV }, + readTextFile: readRealFile, + }), + ); + expect(code).toBe(0); + expect(stderr).toEqual([]); + expect(dockerCalls).toEqual([ + ["docker", "build", "-f", "Dockerfile.seed", "-t", OVERRIDE_SEED_REF, "."], + ["docker", "push", OVERRIDE_SEED_REF], + ["docker", "build", "-f", "Dockerfile", "-t", OVERRIDE_APP_REF, "."], + ["docker", "push", OVERRIDE_APP_REF], + ]); + expect(captured).toHaveLength(1); + expect(captured[0]?.body).toMatchObject({ + app_image: OVERRIDE_APP_REF, + seed_image: OVERRIDE_SEED_REF, + }); + }); + test("without a seed block only the app image is built, no -s", async () => { const baseUrl = healthyGateway(); const cwd = await withWorkspace(MINIMAL_YAML); diff --git a/apps/cli/src/commands/ci-reseed.ts b/apps/cli/src/commands/ci-reseed.ts index 62eae585..baecb640 100644 --- a/apps/cli/src/commands/ci-reseed.ts +++ b/apps/cli/src/commands/ci-reseed.ts @@ -33,12 +33,16 @@ export async function runCiReseed( return fail(ctx.deps.io, "ci reseed requires -s "); } - const imageRef = resolveImageRef(ctx.deps.env, identity); - if (!imageRef.ok) return fail(ctx.deps.io, imageRef.error); - const yaml = await loadYaml(ctx.deps); if (!yaml.ok) return fail(ctx.deps.io, yaml.error); + const imageRef = resolveImageRef( + ctx.deps.env, + identity, + yaml.value.build?.image_repo, + ); + if (!imageRef.ok) return fail(ctx.deps.io, imageRef.error); + const assembled = buildReseedRequest(yaml.value, identity, { appImage: imageRef.value, seedImage: flags.value.seedImage, diff --git a/apps/cli/src/commands/ci-reset.test.ts b/apps/cli/src/commands/ci-reset.test.ts index 40ecf807..477d16b2 100644 --- a/apps/cli/src/commands/ci-reset.test.ts +++ b/apps/cli/src/commands/ci-reset.test.ts @@ -110,6 +110,21 @@ health: expect: 200 `; +const OVERRIDE_YAML = `slug: myapp +build: + dockerfile: Dockerfile + image_repo: registry.gitlab.com/toptiere/dcos/product +seed: + dockerfile: Dockerfile.seed +preview: + hostname: "pr-{pr_id}.myapp.preview.example.com" +health: + path: /health + interval: 2s + timeout: 120s + expect: 200 +`; + const GITLAB_MR_ENV = { CI_PROJECT_URL: "https://gitlab.com/group/repo", CI_MERGE_REQUEST_IID: "17", @@ -219,6 +234,32 @@ describe("sprout ci reset", () => { expect(posted).toContain("data wiped"); }); + test("with build.image_repo deploys from the override refs without rebuilding", async () => { + const baseUrl = resetGateway(); + const cwd = await withWorkspace(OVERRIDE_YAML, { + "Dockerfile.seed": "FROM oven/bun:1.4.0\n", + }); + const code = await runCli( + ["ci", "reset"], + deps({ + cwd, + env: { SPROUT_URL: baseUrl, SPROUT_TOKEN: "t", ...GITLAB_MR_ENV }, + readTextFile: readRealFile, + fetchFn: async (_url, init) => + (init?.method ?? "GET") === "GET" + ? Response.json([]) + : Response.json({ id: 1 }), + }), + ); + expect(code).toBe(0); + expect(stderr).toEqual([]); + expect(dockerCalls).toEqual([]); + expect(captured[1]?.body).toMatchObject({ + app_image: "registry.gitlab.com/toptiere/dcos/product:abc123", + seed_image: "registry.gitlab.com/toptiere/dcos/product:abc123-seed", + }); + }); + test("second reset on a healthy preview succeeds", async () => { const baseUrl = resetGateway(); const cwd = await withWorkspace(MINIMAL_YAML); diff --git a/apps/cli/src/commands/ci-teardown-reseed-logs.test.ts b/apps/cli/src/commands/ci-teardown-reseed-logs.test.ts index a6b07442..2616ac58 100644 --- a/apps/cli/src/commands/ci-teardown-reseed-logs.test.ts +++ b/apps/cli/src/commands/ci-teardown-reseed-logs.test.ts @@ -275,6 +275,59 @@ health: expect(captured[0]?.body).not.toHaveProperty("services"); }); + test("reseed deploys the app image from build.image_repo", async () => { + const baseUrl = startGateway(async (req, url) => { + if (url.pathname === "/v1/deploy" && req.method === "POST") { + captured.push({ + method: req.method, + path: url.pathname, + body: await req.json(), + authorization: req.headers.get("authorization"), + }); + } + return Response.json({ + ok: true, + status: "running", + preview_url: "https://pr-17.myapp.preview.example.com", + canonical_repo_id: "https://gitlab.com/group/repo", + pr_id: 17, + slug: "myapp", + db_name: "sprout_myapp_pr17", + hostname: "pr-17.myapp.preview.example.com", + }); + }); + const cwd = await withWorkspace(`slug: myapp +build: + image_repo: registry.gitlab.com/toptiere/dcos/product +preview: + hostname: "pr-{pr_id}.myapp.preview.example.com" +health: + path: /health + interval: 2s + timeout: 120s + expect: 200 +`); + const code = await runCli( + [ + "ci", + "reseed", + "-s", + "registry.gitlab.com/toptiere/dcos/product:abc123-seed", + ], + deps({ + cwd, + env: { SPROUT_URL: baseUrl, SPROUT_TOKEN: "t", ...GITLAB_MR_ENV }, + readTextFile: async (path) => Bun.file(path).text(), + }), + ); + expect(code).toBe(0); + expect(captured).toHaveLength(1); + expect(captured[0]?.body).toMatchObject({ + app_image: "registry.gitlab.com/toptiere/dcos/product:abc123", + seed_image: "registry.gitlab.com/toptiere/dcos/product:abc123-seed", + }); + }); + test("reseed reads SPROUT_APP_ENV blob and --seed-env-file like deploy", async () => { let polls = 0; const baseUrl = startGateway(async (req, url) => { diff --git a/apps/cli/src/commands/ci-teardown-tags.test.ts b/apps/cli/src/commands/ci-teardown-tags.test.ts index dfcd06ad..963b0a1b 100644 --- a/apps/cli/src/commands/ci-teardown-tags.test.ts +++ b/apps/cli/src/commands/ci-teardown-tags.test.ts @@ -27,6 +27,15 @@ seed: dockerfile: Dockerfile.seed `; +const OVERRIDE_YAML = `slug: myapp +build: + image_repo: registry.gitlab.com/toptiere/dcos/product +preview: + hostname: "pr-{pr_id}.myapp.preview.example.com" +seed: + dockerfile: Dockerfile.seed +`; + function startGateway(): string { server = Bun.serve({ port: 0, @@ -40,10 +49,11 @@ function startGateway(): string { function deps( env: NodeJS.ProcessEnv, fetchFn: (url: string, init?: RequestInit) => Promise, + yaml: string = YAML, ): CliDeps { return { cwd: "/", - readTextFile: async (path) => (path.endsWith(".sprout.yaml") ? YAML : null), + readTextFile: async (path) => (path.endsWith(".sprout.yaml") ? yaml : null), getGitRemoteUrl: () => null, createClient: (baseUrl, token) => createApiClient(baseUrl, { @@ -76,18 +86,19 @@ const GITLAB_ENV: NodeJS.ProcessEnv = { function gitlabFetch( calls: FetchCall[], deleteStatus: (url: string) => number = () => 204, + repositories: { id: number; path: string }[] = [{ id: 5, path: "group/repo" }], ) { return async (url: string, init?: RequestInit) => { const method = init?.method ?? "GET"; calls.push({ url, method, headers: headersOf(init) }); if (url.includes("/registry/repositories?")) { - return Response.json([{ id: 5, path: "group/repo" }]); + return Response.json(repositories); } if (url.includes("/merge_requests/")) { if (method === "GET") return Response.json([]); return Response.json({ id: 1 }); } - if (method === "DELETE" && url.includes("/registry/repositories/5/tags/")) { + if (method === "DELETE" && url.includes("/registry/repositories/")) { return new Response(null, { status: deleteStatus(url) }); } return new Response("not found", { status: 404 }); @@ -116,6 +127,30 @@ describe("ci teardown image tags", () => { expect(deletes[0]?.headers["job-token"]).toBe("job-token"); }); + test("with build.image_repo deletes exactly the override-pushed tags", async () => { + const calls: FetchCall[] = []; + const baseUrl = startGateway(); + const code = await runCli( + ["ci", "teardown"], + deps( + { ...GITLAB_ENV, SPROUT_URL: baseUrl }, + gitlabFetch(calls, () => 204, [ + { id: 5, path: "group/repo" }, + { id: 7, path: "toptiere/dcos/product" }, + ]), + OVERRIDE_YAML, + ), + ); + + expect(code).toBe(0); + expect(stderr).toEqual([]); + const deletes = calls.filter((call) => call.method === "DELETE"); + expect(deletes.map((call) => call.url)).toEqual([ + "https://gitlab.com/api/v4/projects/99/registry/repositories/7/tags/abc123", + "https://gitlab.com/api/v4/projects/99/registry/repositories/7/tags/abc123-seed", + ]); + }); + test("already-deleted tags warn and still exit 0", async () => { const calls: FetchCall[] = []; const baseUrl = startGateway(); diff --git a/apps/cli/src/yaml.test.ts b/apps/cli/src/yaml.test.ts index 09c8a3b4..902fdfa5 100644 --- a/apps/cli/src/yaml.test.ts +++ b/apps/cli/src/yaml.test.ts @@ -801,6 +801,66 @@ preview: }); }); + test("parses build.image_repo as the preview push target", () => { + const result = parseSproutYaml(` +slug: myapp +build: + dockerfile: docker/Dockerfile + image_repo: registry.gitlab.com/toptiere/dcos/product +preview: + hostname: "pr-{pr_id}.example.com" +`); + expect(result).toEqual({ + ok: true, + value: { + slug: "myapp", + preview: { hostname: "pr-{pr_id}.example.com" }, + build: { + dockerfile: "docker/Dockerfile", + image_repo: "registry.gitlab.com/toptiere/dcos/product", + }, + }, + }); + }); + + test("parses build.image_repo with a registry port", () => { + const result = parseSproutYaml(` +slug: myapp +build: + image_repo: localhost:5000/team/app +preview: + hostname: "pr-{pr_id}.example.com" +`); + expect(result).toMatchObject({ + ok: true, + value: { build: { image_repo: "localhost:5000/team/app" } }, + }); + }); + + test("rejects a build.image_repo carrying a tag, digest, or bare path", () => { + const base = (repo: string) => + parseSproutYaml( + `slug: myapp\npreview:\n hostname: "pr-{pr_id}.example.com"\nbuild:\n image_repo: "${repo}"\n`, + ); + const hint = + "build.image_repo must be a full repository (registry host + path, no tag or digest)"; + expect(base("registry.gitlab.com/team/app:abc123")).toEqual({ + ok: false, + error: hint, + }); + expect( + base( + "registry.gitlab.com/team/app@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + ), + ).toEqual({ ok: false, error: hint }); + expect(base("team/app")).toEqual({ ok: false, error: hint }); + expect(base("registry.gitlab.com/team/")).toEqual({ ok: false, error: hint }); + expect(base("")).toEqual({ + ok: false, + error: "build.image_repo is required", + }); + }); + test("empty build and seed blocks take conventional defaults", () => { const result = parseSproutYaml(` slug: myapp diff --git a/apps/cli/src/yaml.ts b/apps/cli/src/yaml.ts index 41d6b263..fe3cb029 100644 --- a/apps/cli/src/yaml.ts +++ b/apps/cli/src/yaml.ts @@ -60,7 +60,13 @@ export type SproutDockerfileBlock = { dockerfile: string; }; -export type SproutBuild = SproutDockerfileBlock; +export type SproutBuild = SproutDockerfileBlock & { + /** + * Full image repository (registry host + path, no tag) the preview app and + * seed tags are pushed to and deleted from; defaults to `CI_REGISTRY_IMAGE`. + */ + image_repo?: string; +}; export type SproutSeed = SproutDockerfileBlock & { inputs?: string[]; @@ -97,7 +103,7 @@ const TOP_KEYS = new Set(["slug", "preview", "health", "build", "seed", "db", "m const PREVIEW_KEYS = new Set(["hostname", "env", "app_env", "services", "labels", "volumes", "auth", "ttl", "idle_teardown"]); const HEALTH_KEYS = new Set(["path", "interval", "timeout", "expect"]); const SERVICE_KEYS = new Set(["name", "image", "hostname", "path", "port", "env", "labels"]); -const DOCKERFILE_KEYS = new Set(["dockerfile"]); +const BUILD_KEYS = new Set(["dockerfile", "image_repo"]); const SEED_KEYS = new Set(["dockerfile", "inputs", "env", "args"]); function isPlainObject(value: unknown): value is Record { @@ -263,25 +269,48 @@ function parseDockerfileField( return requireString(rawDockerfile, `${path}.dockerfile`); } -function parseDockerfileBlock( - raw: unknown, - path: string, - defaultDockerfile: string, -): Result { +const IMAGE_REPO_HINT = + "build.image_repo must be a full repository (registry host + path, no tag or digest)"; + +function parseImageRepoField(raw: unknown): Result { + if (raw === undefined) return { ok: true, value: undefined }; + const value = requireString(raw, "build.image_repo"); + if (!value.ok) return value; + const repo = value.value; + const hostEnd = repo.indexOf("/"); + const host = repo.slice(0, hostEnd); + const lastSlash = repo.lastIndexOf("/"); + const lastSegment = repo.slice(lastSlash + 1); + const registryHost = + host.includes(".") || host.includes(":") || host === "localhost"; + if ( + /\s/.test(repo) || + repo.includes("@") || + hostEnd <= 0 || + lastSlash === repo.length - 1 || + lastSegment.includes(":") || + !registryHost + ) { + return { ok: false, error: IMAGE_REPO_HINT }; + } + return { ok: true, value: repo }; +} + +function parseBuildBlock(raw: unknown): Result { if (raw === undefined) return { ok: true, value: undefined }; if (!isPlainObject(raw)) { - return { ok: false, error: `${path} must be a mapping` }; + return { ok: false, error: "build must be a mapping" }; } for (const key of Object.keys(raw)) { - if (!DOCKERFILE_KEYS.has(key)) return unknownKey(`${path}.${key}`); + if (!BUILD_KEYS.has(key)) return unknownKey(`build.${key}`); } - const dockerfile = parseDockerfileField( - raw.dockerfile, - path, - defaultDockerfile, - ); + const dockerfile = parseDockerfileField(raw.dockerfile, "build", "Dockerfile"); if (!dockerfile.ok) return dockerfile; - return { ok: true, value: { dockerfile: dockerfile.value } }; + const imageRepo = parseImageRepoField(raw.image_repo); + if (!imageRepo.ok) return imageRepo; + const value: SproutBuild = { dockerfile: dockerfile.value }; + if (imageRepo.value !== undefined) value.image_repo = imageRepo.value; + return { ok: true, value }; } function parseStringList( @@ -548,7 +577,7 @@ export function parseSproutYaml(raw: string): Result { ); if (!idleTeardown.ok) return idleTeardown; - const build = parseDockerfileBlock(parsed.build, "build", "Dockerfile"); + const build = parseBuildBlock(parsed.build); if (!build.ok) return build; const seed = parseSeedBlock(parsed.seed); diff --git a/docs/adopting-a-repo.md b/docs/adopting-a-repo.md index dd69c99c..86e72491 100644 --- a/docs/adopting-a-repo.md +++ b/docs/adopting-a-repo.md @@ -51,6 +51,7 @@ value grammar, merge order) are the contract. Seeding order lives in | `health.timeout` | when seeding | `120s` | How long the gateway polls before `health_timeout`. Never starts the seed. | | `health.expect` | when seeding | `200` | Expected status (100–599). Gates the after-healthy seed hook. | | `build.dockerfile` | no | `Dockerfile` | App Dockerfile for `sprout ci preview`. An empty `build: {}` takes the default. | +| `build.image_repo` | no | `CI_REGISTRY_IMAGE` | Full image repository for the preview app and seed tags (overrides `CI_REGISTRY_IMAGE`): registry host + path, no tag or digest (e.g. `registry.gitlab.com/toptiere/dcos/product`). The commit tag stays `:` (`-seed` for the commit-scoped seed tag, `seed-` for a content-addressed one), and teardown deletes from the same repository. Unset pushes to the project registry root exactly as before. | | `seed.dockerfile` | when `seed:` present | `Dockerfile.seed` | Seed Dockerfile. An empty `seed: {}` takes the default and enables seeding. | | `seed.inputs` | no | — (always rebuild) | Repo-relative paths whose contents key seed-image reuse (seed Dockerfile, entrypoint/script, migrations, lockfile, …). Sorted with paths folded into a sha256; the seed tag is `:seed-<12-hex>`. Without `inputs` the tag is commit-scoped (`-seed`) and the seed image is rebuilt on every run — set `inputs` explicitly to opt into reuse, listing every COPY source the seed image depends on. | | `seed.env` | no | — | Seed-only env (same grammar and layering as `preview.app_env`). | diff --git a/docs/ci-integration.md b/docs/ci-integration.md index eaba3645..b7f555c7 100644 --- a/docs/ci-integration.md +++ b/docs/ci-integration.md @@ -34,7 +34,8 @@ What the three jobs do: - `sprout-preview` (merge-request pipelines only): installs the pinned, checksum-verified `sprout` binary (version = component version), builds + - pushes the app image (`CI_REGISTRY_IMAGE:`) and — when `.sprout.yaml` + pushes the app image (`CI_REGISTRY_IMAGE:`, or `:` + when `.sprout.yaml` sets that key) and — when `.sprout.yaml` sets `seed` — the seed image (commit-scoped `-seed` tag rebuilt on every run, or — with explicit `seed.inputs` — a `seed-` tag content-addressed over those inputs, where an authenticated @@ -47,9 +48,11 @@ What the three jobs do: - `sprout-stop-preview` (`on_stop`, Stop button / MR close / merge / `auto_stop_in` expiry): `sprout ci teardown` (idempotent — exit 0 when already gone). Once the preview is gone it also deletes the commit's app - and commit-scoped seed tags from the project registry, using the same CI - job token / credentials the push used. Missing tags and missing delete - permission only warn (the forge expiration policy remains the backstop). + and commit-scoped seed tags from the repository the push used + (`build.image_repo` when set, else the project registry root), using the + same CI job token / credentials the push used. Missing tags and missing + delete permission only warn (the forge expiration policy remains the + backstop). - `sprout-reset` (manual, instant): `sprout ci reset` — wipe the preview database and redeploy + seed from scratch (data wiped). Press **Run** on it inside the MR pipeline for the reset *now* (GitLab has no @@ -59,6 +62,18 @@ What the three jobs do: - Prerequisites owned by the component: dind service, registry login, `apk` packages. Adopters declare no packages and no Docker setup. +### Image repository override + +By default the preview app and seed tags land in the project's registry +root (`CI_REGISTRY_IMAGE`). Set `build.image_repo` in `.sprout.yaml` to +push them into a sub-repository instead — e.g. +`registry.gitlab.com/toptiere/dcos/product` — when the root repository +holds nothing but throwaway preview tags. The value is a full repository +path with no tag or digest; the CLI appends `:` (and `:-seed` +for a commit-scoped seed), and teardown deletes from the same repository. +The key is manifest config, not a component input, so the preview, +teardown, reseed, and reset jobs all agree without extra CI wiring. + Prerequisites on the GitLab side: merge-request pipelines (`CI_PIPELINE_SOURCE=merge_request_event`; branch pipelines are refused with a named error) and a runner that can run privileged `docker:dind`. diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 68764600..a4f36444 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -44,7 +44,7 @@ auth so outside-pipeline errors win over missing-token. | | `--dotenv-file PATH` | Dotenv artifact the CLI writes `PREVIEW_URL=` to (default `sprout-preview.env`, relative to the workspace root). Emitted only once the preview is healthy. | | | `--reseed` | Force the gateway to re-run the seed against the existing database (requires a `seed` block) — re-seeds even when the seed image is unchanged. A changed seed image already re-seeds automatically; without seed changes, omit it — a reused image still seeds every fresh PR (`seeded_at` unset). | | `sprout ci teardown` | *(no flags — extra args are rejected)* | Tear down this MR's preview. Idempotent; rewrites the MR note in place ("preview was removed"). After the preview is gone, deletes the commit's app + commit-scoped seed image tags through the forge registry API (best effort: a missing tag or missing delete permission warns; the exit code stays 0). Note failures only warn so gateway success owns the exit code. | -| `sprout ci reseed` | `-s ` (required) | Re-run the seed job against the existing database (data kept; no image build; app tag from `CI_REGISTRY_IMAGE` + SHA). Body is a reseed request, so companions stay as last deployed by construction. | +| `sprout ci reseed` | `-s ` (required) | Re-run the seed job against the existing database (data kept; no image build; app tag from `CI_REGISTRY_IMAGE` + SHA, or `.sprout.yaml` `build.image_repo` + SHA when set). Body is a reseed request, so companions stay as last deployed by construction. | | | `--seed-env`, `--seed-env-file`, `--seed-arg`, `--app-env`, `--app-env-file` | Same env layering as `preview` (yaml + blob + files + flags). | | `sprout ci reset` | `--tail N`, `--dotenv-file PATH`, `--app-env[-file]`, `--seed-env[-file]`, `--seed-arg`, `--service`, `--clear-services` (same deploy flags as `preview`, no `--reseed`) | Wipe the preview database and any `preview.volumes` data volumes, then redeploy + seed from scratch (data wiped; no rebuild — reuses the already pushed images for the commit). The note gains a `Reset: at ` line. The component's `sprout-reset` manual job funnels here. | | `sprout ci logs` | `--tail N` | Preview container logs through the gateway (app, then seed when available). | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 0813ccf7..f2085cf4 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -9,11 +9,12 @@ echoing the value. | Symptom | Error (stderr) | Fix | |---|---|---| | Job runs on a branch pipeline, not an MR | `sprout ci refuses detached/non-MR pipelines (CI_PIPELINE_SOURCE=…); run from a merge-request pipeline` (GitHub: `GITHUB_EVENT_NAME=…`) | Gate the jobs on `$CI_MERGE_REQUEST_IID` (the component does this) or run from a `pull_request` workflow. Running both forges' claims at once is refused as ambiguous. | -| Registry/SHA missing so the image tag cannot be built | `cannot derive image ref (set CI_REGISTRY_IMAGE and CI_COMMIT_SHA)` | Run on a runner with the container registry enabled; on GitLab the component logs in with `CI_REGISTRY_USER`/`CI_REGISTRY_PASSWORD` automatically. | +| Registry/SHA missing so the image tag cannot be built | `cannot derive image ref (set CI_REGISTRY_IMAGE and CI_COMMIT_SHA)` — with `build.image_repo` set only the SHA is named (`cannot derive image ref (set CI_COMMIT_SHA)`) | Run on a runner with the container registry enabled; on GitLab the component logs in with `CI_REGISTRY_USER`/`CI_REGISTRY_PASSWORD` automatically. | +| `build.image_repo` rejected | `build.image_repo must be a full repository (registry host + path, no tag or digest)` | Give the full repository path including the registry host (e.g. `registry.gitlab.com/group/project/product`); the CLI appends the `` and `-seed`/`seed-` tags itself. | | Remote include without a version | `sprout_version input is empty/unpinned (remote includes must set sprout_version explicitly …)` | Set `sprout_version` to the tag in the `remote:` URL. Component includes pin it automatically. | | Downloaded release fails verification | `checksum entry missing for in /SHA256SUMS.txt …` or a `sha256sum -c` mismatch; `test "$(sprout --version)" = "…"` fails | Pin to a release that ships checksums (≥ the release that publishes `SHA256SUMS.txt`); do not hand-edit the install — the component verifies the downloaded asset. | | Hostname template rejected | `preview.hostname … must contain {pr_id}` / scheme/port/path/placeholder errors; service `preview.services[i].hostname` / `.path must start with /` | Keep the template a bare host with `{pr_id}` (`pr-{pr_id}.app.example.com`). Read the URL from `preview_url=` / `PREVIEW_URL` — never reconstruct it in CI. | -| Unknown manifest key | `unknown key: ` (top-level, `preview.*`, `health.*`, `seed.*`, `preview.env.*`) | Rename to a key in the [manifest table](adopting-a-repo.md#manifest-keys-sproutyaml); check `preview.env` against the canonical `PG*` set and services against `name/image/hostname/path/port/env/labels`. | +| Unknown manifest key | `unknown key: ` (top-level, `preview.*`, `health.*`, `build.*`, `seed.*`, `preview.env.*`) | Rename to a key in the [manifest table](adopting-a-repo.md#manifest-keys-sproutyaml); check `preview.env` against the canonical `PG*` set and services against `name/image/hostname/path/port/env/labels`. | | Seed configured without health | `health block required in .sprout.yaml when seed block is configured` (or `when -s is passed`) | Add the `health:` block ([Adopting a repo](adopting-a-repo.md#manifest-keys-sproutyaml) shows the shape). The gate runs before any `docker build`. | | Secret not supplied | deploy fails before the gateway call naming the key (declared `{ required: true }`, no file/flag provided it) | Provide it via the `SPROUT_APP_ENV` / `SPROUT_SEED_ENV` file-type variable or `--app-env[-file]` / `--seed-env[-file]`. Never commit the secret to the manifest. | | File-type CI variable passed via `app_env_file` / `seed_env_file` input (e.g. `inputs: { app_env_file: $MY_ENV_FILE }`) | `preview.app_env.: required value missing` (nothing points at the input) — had the flag been passed with a bad path, the CLI would say `cannot read --app-env-file: ` instead | Repo-relative dotenv paths only — never pass File vars via `inputs:`; map the blob at job runtime via `variables:` (`sprout-preview: { variables: { SPROUT_APP_ENV: $MY_ENV_FILE } }`, seed: `SPROUT_SEED_ENV: $MY_SEED_FILE`). Full diagnostic in [component Troubleshooting](../templates/README.md#troubleshooting). | diff --git a/templates/README.md b/templates/README.md index 8f3f36c3..00ec05eb 100644 --- a/templates/README.md +++ b/templates/README.md @@ -71,11 +71,13 @@ Prerequisites on the GitLab side: the bootstrap installs prerequisites with `apk`. - Container registry credentials come from the predefined `CI_REGISTRY_USER` / `CI_REGISTRY_PASSWORD`; the component logs in - automatically when they are present. The app tag is always - `CI_REGISTRY_IMAGE:`. Teardown deletes that tag and the seed tag - through the GitLab container registry API using `CI_JOB_TOKEN` (or - `GITLAB_TOKEN` with `api` scope when set); an instance that refuses the - delete only produces a warning. + automatically when they are present. The app tag is + `CI_REGISTRY_IMAGE:` unless `.sprout.yaml` sets + `build.image_repo`, which retargets both the app tag (`:`) + and the seed tag to that repository. Teardown deletes those tags from the + same repository through the GitLab container registry API using + `CI_JOB_TOKEN` (or `GITLAB_TOKEN` with `api` scope when set); an instance + that refuses the delete only produces a warning. ## Reset: manual job @@ -118,10 +120,10 @@ per-preview volume). | `tail` | `200` | Gateway log lines printed when `sprout ci preview` fails. | Image builds are driven by `.sprout.yaml` (`build.dockerfile`, -`seed.dockerfile` + `seed.env`/`seed.args`); the CLI owns Dockerfile -resolution — the component passes no Dockerfile paths and no free-form -extra args. Gaps belong behind explicit typed inputs (or CLI flags), not -shell guards or argv appenders. +`build.image_repo`, `seed.dockerfile` + `seed.env`/`seed.args`); the CLI +owns Dockerfile resolution and the push target — the component passes no +Dockerfile paths and no free-form extra args. Gaps belong behind explicit +typed inputs (or CLI flags), not shell guards or argv appenders. ## Troubleshooting