// PEP-57, spec delivery-pipeline: «Деплой по окружениям» и «Проверка здоровья и откат». // The template's .gitea/peppa-deploy.sh runs for real against mock-docker (docker CLI on // PATH) and a mock health endpoint; it reports to Peppa through handleGiteaHook. import assert from "node:assert/strict"; import { execFile, execFileSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs"; import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { after, before, describe, test } from "node:test"; import { core, db, project, runner, teardown } from "./helpers.ts"; import { MockGitea } from "../src/mock-gitea.ts"; const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); const TMP = mkdtempSync(join(tmpdir(), "peppa-deploy-")); process.env.PEPPA_SECRET = "mock-secret-for-tests"; const gitea = new MockGitea(join(TMP, "gitea")); const BOT = { id: 81, login: "peppa-bot", token: "mock-token-bot" }; const SCRIPT = join(ROOT, "template/.gitea/peppa-deploy.sh"); // docker → mock-docker, first on PATH for the script. const BIN = join(TMP, "bin"); mkdirSync(BIN); symlinkSync(join(ROOT, "packages/testkit/bin/mock-docker"), join(BIN, "docker")); let server: Server; let base = ""; /** Images whose app fails its health check. */ const badImages = new Set(); before(async () => { await gitea.start(); process.env.GITEA_URL = gitea.url; process.env.GITEA_TOKEN = BOT.token; gitea.addUser(BOT); // One server: Peppa's /api/hooks/gitea and the deployed apps' //healthz. server = createServer((req, res) => { let body = ""; req.on("data", (c) => (body += c)); req.on("end", async () => { if (req.url === "/api/hooks/gitea") { const r = await runner.handleGiteaHook(db, { event: String(req.headers["x-peppa-event"]), signature: String(req.headers["x-gitea-signature"]), body }); res.writeHead(r.status).end(JSON.stringify(r.body)); return; } const [, stateDir, proj] = decodeURIComponent(req.url ?? "").match(/^\/state:([^:]+):([^/]+)\/healthz$/) ?? []; const f = stateDir && join(stateDir, "containers", `${proj}-web-1`); const image = f && existsSync(f) ? readFileSync(f, "utf8").trim() : null; res.writeHead(image && !badImages.has(image) ? 200 : 503).end(); }); }); await new Promise((r) => server.listen(0, "127.0.0.1", r)); base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); after(async () => { server.close(); await gitea.stop(); await teardown(); }); /** A project with deploy settings, its repo checked out as the CI job sees it. */ async function deployable(deploy: object | null = { compose: "deploy/compose.yml", service: "web", port: 3000, health: "/healthz" }) { const p = await project({ turns: [] }); const proj = await core.getProject(db, p.key); const work = join(TMP, `work-${p.key}`); const state = join(TMP, `docker-${p.key}`); mkdirSync(join(work, ".peppa"), { recursive: true }); mkdirSync(join(work, "deploy")); writeFileSync(join(work, "deploy/compose.yml"), readFileSync(join(ROOT, "template/deploy/compose.yml"))); writeFileSync(join(work, "Dockerfile"), "FROM scratch\n"); writeFileSync(join(work, ".peppa/project.json"), JSON.stringify({ slug: proj.slug, key: p.key, name: p.key, peppaUrl: base, ...(deploy ? { deploy } : {}) })); const git = (...a: string[]) => execFileSync("git", ["-C", work, "-c", "user.name=t", "-c", "user.email=t@t", ...a], { encoding: "utf8" }).trim(); git("init", "-q", "-b", "main"); git("add", "-A"); git("commit", "-qm", "init"); const repo = gitea.addRepo(proj.giteaOwner, proj.giteaRepo); repo.collaborators[BOT.login] = "write"; /** A merge of a task branch into main, pushed to Gitea; returns its SHA. */ const merge = (task: string) => { writeFileSync(join(work, `${task}.txt`), task); git("add", "-A"); git("commit", "-qm", `Merge pull request '${task}' (#1) from task/${task} into main`); git("push", "-q", repo.path, "main"); return git("rev-parse", "HEAD"); }; const run = (mode: string, sha: string, extra: Record = {}) => new Promise<{ code: number; out: string }>((done) => { git("checkout", "-q", sha); const env = { ...process.env, PATH: `${BIN}:${process.env.PATH}`, MOCK_DOCKER_STATE: state, PEPPA_SHA: sha, PEPPA_CI_SECRET: core.projectHookSecret(proj.id), PEPPA_HEALTH_BASE: `${base}/state:${state}:{project}`, PEPPA_HEALTH_TIMEOUT: "2", PEPPA_HEALTH_INTERVAL: "0.3", GITHUB_REPOSITORY: `${proj.giteaOwner}/${proj.giteaRepo}`, GITHUB_RUN_NUMBER: "5", ...extra, }; execFile("bash", [SCRIPT, mode], { cwd: work, env, encoding: "utf8" }, (err, stdout, stderr) => { git("checkout", "-q", "main"); done({ code: err ? Number((err as { code?: number }).code ?? 1) : 0, out: stdout + stderr }); }); }); const container = (env: string) => { const f = join(state, "containers", `${proj.slug}-${env}-web-1`); return existsSync(f) ? readFileSync(f, "utf8").trim() : null; }; const calls = () => (existsSync(join(state, "calls.log")) ? readFileSync(join(state, "calls.log"), "utf8") : ""); return { p, proj, merge, run, container, calls }; } async function releases(projectId: number) { return (await runner.listReleases(db, projectId, 50)).reverse(); } describe("Деплой по окружениям", () => { test("Scenario: Staging после мержа — образ с тегом коммита на staging, релиз со списком задач", async () => { const d = await deployable(); const sha = d.merge(`${d.p.key}-7`); const r = await d.run("staging", sha); assert.equal(r.code, 0, r.out); assert.equal(d.container("staging"), `peppa/${d.proj.slug}:${sha}`); const [rel] = await releases(d.proj.id); assert.equal(rel!.env, "staging"); assert.equal(rel!.status, "healthy"); assert.equal(rel!.sha, sha); assert.equal(rel!.host, `${d.proj.slug}-staging.telecom.quest`); assert.deepEqual(rel!.tasks, [`${d.p.key}-7`]); const offer = (await core.pendingQuestions(db, d.proj.id)).find((q) => q.options?.includes(runner.PROD_OPTION)); assert.ok(offer, "the PM is offered to deploy to prod"); assert.equal(offer.taskId, null); }); test("Scenario: Прод по кнопке — тот же образ в проде, релиз прода с автором PM", async () => { const d = await deployable(); const sha = d.merge(`${d.p.key}-7`); assert.equal((await d.run("staging", sha)).code, 0); const rel = await runner.deployProd(db, d.proj, "mock-pm"); assert.equal(rel.status, "deploying"); const tag = gitea.repo(d.proj.giteaOwner, d.proj.giteaRepo).tags.at(-1)!; assert.match(tag.name, /^deploy-prod-\d{17}$/); assert.equal(tag.target, sha, "Peppa tags the healthy staging commit"); // The tag starts the deploy workflow in prod mode. const r = await d.run("prod", sha, { GITHUB_REF: `refs/tags/${tag.name}` }); assert.equal(r.code, 0, r.out); assert.equal(d.container("prod"), `peppa/${d.proj.slug}:${sha}`); assert.equal(d.calls().match(/docker build/g)?.length, 1, "prod reuses the staging image"); const prod = (await releases(d.proj.id)).filter((x) => x.env === "prod"); assert.equal(prod.length, 1); assert.equal(prod[0]!.status, "healthy"); assert.equal(prod[0]!.deployedBy, "mock-pm"); assert.deepEqual(prod[0]!.tasks, [`${d.p.key}-7`]); await assert.rejects(runner.deployProd(db, d.proj, "mock-pm").then(() => runner.deployProd(db, d.proj, "mock-pm")), /уже выкатывается/); }); test("Telegram button: answering the staging message with «Выкатить в прод» starts prod", async () => { const d = await deployable(); assert.equal((await d.run("staging", d.merge(`${d.p.key}-2`))).code, 0); const offer = (await core.pendingQuestions(db, d.proj.id)).find((q) => q.options?.includes(runner.PROD_OPTION))!; await runner.answerAndDeliver(db, offer.id, runner.PROD_OPTION, "telegram"); const [prod] = (await releases(d.proj.id)).filter((x) => x.env === "prod"); assert.equal(prod?.status, "deploying"); assert.equal(prod?.deployedBy, "PM (telegram)"); }); test("no healthy staging: nothing to deploy to prod", async () => { const d = await deployable(); await assert.rejects(runner.deployProd(db, d.proj, "mock-pm"), /на staging нет здорового релиза/); }); test("preview on a PR, removed when the PR is closed", async () => { const d = await deployable(); const sha = d.merge(`${d.p.key}-3`); assert.equal((await d.run("preview", sha, { PEPPA_PR: "3" })).code, 0); assert.equal(d.container("pr3"), `peppa/${d.proj.slug}:${sha}`); let [rel] = await releases(d.proj.id); assert.equal(rel!.host, `${d.proj.slug}-pr3.telecom.quest`); assert.equal(rel!.status, "healthy"); assert.equal((await d.run("preview-down", sha, { PEPPA_PR: "3" })).code, 0); assert.equal(d.container("pr3"), null); [rel] = await releases(d.proj.id); assert.equal(rel!.status, "removed"); }); test("project without deploy settings: the step is skipped", async () => { const d = await deployable(null); const r = await d.run("staging", d.merge("x")); assert.equal(r.code, 0); assert.match(r.out, /деплой не настроен/); assert.equal((await releases(d.proj.id)).length, 0); }); }); describe("Проверка здоровья и откат", () => { test("Scenario: Неудачный релиз — прод возвращён на предыдущий, релиз помечен «откат», PM получает причину и лог", async () => { const d = await deployable(); const good = d.merge(`${d.p.key}-1`); assert.equal((await d.run("prod", good)).code, 0); const bad = d.merge(`${d.p.key}-2`); badImages.add(`peppa/${d.proj.slug}:${bad}`); const r = await d.run("prod", bad); assert.equal(r.code, 1); assert.equal(d.container("prod"), `peppa/${d.proj.slug}:${good}`, "prod is back on the previous release"); const rel = (await releases(d.proj.id)).find((x) => x.sha === bad)!; assert.equal(rel.status, "rolled_back"); assert.equal(rel.previousSha, good); assert.match(rel.reason ?? "", /проверка \/healthz не прошла за 2 с/); assert.deepEqual(rel.tasks, [`${d.p.key}-2`], "only what was merged since the previous release"); const msg = (await core.pendingQuestions(db, d.proj.id)).find((q) => q.text.includes(bad.slice(0, 7)) && q.text.includes("не прошёл"))!; assert.ok(msg, "the PM got a message"); assert.match(msg.text, new RegExp(`возвращён ${good.slice(0, 7)}`)); assert.match(msg.text, /Причина: проверка \/healthz/); assert.match(msg.text, new RegExp(`Лог: ${gitea.url}/test/${d.proj.giteaRepo}/actions/runs/5`)); assert.equal((await runner.currentReleases(db, d.proj.id)).prod?.sha, good); }); test("first release fails its health check: nothing to roll back to, release failed", async () => { const d = await deployable(); const sha = d.merge("first"); badImages.add(`peppa/${d.proj.slug}:${sha}`); assert.equal((await d.run("staging", sha)).code, 1); const [rel] = await releases(d.proj.id); assert.equal(rel!.status, "failed"); assert.match(rel!.reason ?? "", /откатывать не на что/); }); test("image build fails: release failed, the running stand is untouched", async () => { const d = await deployable(); const good = d.merge("a"); assert.equal((await d.run("staging", good)).code, 0); const r = await d.run("staging", d.merge("b"), { MOCK_DOCKER_BUILD_FAIL: "1" }); assert.equal(r.code, 1); assert.equal(d.container("staging"), `peppa/${d.proj.slug}:${good}`); assert.equal((await releases(d.proj.id)).at(-1)!.reason, "сборка образа не удалась"); }); });