peppa/packages/testkit/test/deploy.test.ts
Асель 2677f1ad84 PEP-129: tests follow the reworded messages
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 09:52:35 +05:00

349 lines
19 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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<string>();
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' /<project>/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<void>((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<string, string> = {}) =>
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, state };
}
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("PEP-112 Scenario: Выкатка с секретами — секреты проекта доходят до контейнера продукта, значений нет в логе", async () => {
process.env.PEPPA_SECRET ??= "mock-secret-for-tests";
const d = await deployable();
const pm = await core.upsertUserFromGitea(db, { id: 1301, login: "mock-pm-secrets" }, { access_token: "x" });
await core.setProjectOwner(db, d.proj.id, pm.id);
const pem = "-----BEGIN KEY-----\nline two\n-----END KEY-----";
await core.setProjectSecret(db, pm.id, d.proj.id, "ANTHROPIC_API_KEY", "sk-ant-mock$HOME-1");
await core.setProjectSecret(db, pm.id, d.proj.id, "SIGNING_KEY", pem);
const sha = d.merge(`${d.p.key}-3`);
const r = await d.run("staging", sha);
assert.equal(r.code, 0, r.out);
assert.match(r.out, /секретов проекта передано сервису web: 2/);
assert.ok(!r.out.includes("sk-ant-mock") && !r.out.includes("line two"), "values never reach the log");
const override = JSON.parse(readFileSync(join(d.state, `env-${d.proj.slug}-staging.json`), "utf8"));
// «$» is doubled for compose (it would interpolate a variable otherwise); the container gets one.
assert.deepEqual(override, { services: { web: { environment: { ANTHROPIC_API_KEY: "sk-ant-mock$$HOME-1", SIGNING_KEY: pem } } } });
assert.match(d.calls(), /docker compose -p \S+-staging -f deploy\/compose\.yml -f \S*peppa-env\.\S+ up -d/);
const [rel] = await releases(d.proj.id);
assert.equal(rel!.status, "healthy");
assert.ok(!(rel!.logTail ?? "").includes("sk-ant-mock"));
// A restart of the same commit (Peppa's deploy-staging-* tag after a secret changed).
await core.deleteProjectSecret(db, pm.id, d.proj.id, "SIGNING_KEY");
const again = await d.run("staging", sha);
assert.equal(again.code, 0, again.out);
assert.match(again.out, /секретов проекта передано сервису web: 1/);
assert.equal(d.calls().match(/docker build/g)?.length, 1, "the image is not rebuilt");
const last = (await releases(d.proj.id)).at(-1)!;
assert.equal(last.previousSha, sha);
const note = (await core.pendingQuestions(db, d.proj.id)).at(-1)!;
assert.match(note.text, /версия для проверки перезапущена с новыми настройками/);
});
test("PEP-112: a project without secrets deploys as before — no override file", async () => {
const d = await deployable();
const r = await d.run("staging", d.merge(`${d.p.key}-4`));
assert.equal(r.code, 0, r.out);
assert.match(r.out, /секретов проекта нет/);
assert.ok(!existsSync(join(d.state, `env-${d.proj.slug}-staging.json`)));
});
test("no healthy staging: nothing to deploy to prod", async () => {
const d = await deployable();
await assert.rejects(runner.deployProd(db, d.proj, "mock-pm"), /в версии для проверки нет работающих изменений/);
});
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, "сборка образа не удалась");
});
});
// PEP-44, spec delivery-pipeline: «Превью на ревью».
describe("Превью на ревью", () => {
async function storyWithPr(d: Awaited<ReturnType<typeof deployable>>, pr: number) {
const ref = await core.resolveTask(db, d.p.taskKey);
await core.updateTask(db, ref, { prUrl: `${gitea.url}/${d.proj.giteaOwner}/${d.proj.giteaRepo}/pulls/${pr}` });
return core.resolveTask(db, d.p.taskKey);
}
test("Scenario: Стенд поднят — ссылка «Посмотреть», дифф и проверки; Scenario: Скриншоты — снимок в карточке", async () => {
const d = await deployable();
const ref = await storyWithPr(d, 3);
const sha = d.merge(`${d.p.key}-1`);
const r = await d.run("preview", sha, { PEPPA_PR: "3" });
assert.equal(r.code, 0, r.out);
assert.match(r.out, /скриншот \/ снят/);
const [rel] = await releases(d.proj.id);
assert.equal(rel!.status, "healthy");
assert.equal(rel!.screenshots.length, 1);
assert.equal(rel!.screenshots[0]!.path, "/");
const shot = await runner.releaseScreenshot(db, rel!.id, 0);
assert.ok(shot && shot.png.subarray(1, 4).toString() === "PNG", "a PNG is kept");
assert.equal(shot!.projectId, d.proj.id);
assert.equal(await runner.releaseScreenshot(db, rel!.id, 5), null);
const p = await core.reviewPreview(db, ref);
assert.equal(p.previewUrl, `https://${d.proj.slug}-pr3.telecom.quest`);
assert.equal(p.releaseId, rel!.id);
assert.deepEqual(p.screenshots, [{ n: 0, path: "/" }]);
assert.match(p.diffUrl!, /\/pulls\/3\/files$/);
const note = core.reviewPreviewNote(p);
assert.match(note, new RegExp(`Посмотреть: https://${d.proj.slug}-pr3\\.telecom\\.quest`));
assert.match(note, /Изменения: .*\/pulls\/3\/files/);
assert.match(note, /Проверки/);
// The card (getTaskDetails) carries the same summary.
assert.equal((await core.getTaskDetails(db, ref)).preview.previewUrl, p.previewUrl);
});
test("Scenario: Скриншоты не сняты — превью здоровое, ссылка без скриншотов", async () => {
const d = await deployable();
const ref = await storyWithPr(d, 4);
const r = await d.run("preview", d.merge(`${d.p.key}-1`), { PEPPA_PR: "4", MOCK_DOCKER_SCREENSHOT_FAIL: "1" });
assert.equal(r.code, 0, r.out);
assert.match(r.out, /скриншот \/ не снят/);
const [rel] = await releases(d.proj.id);
assert.equal(rel!.status, "healthy");
assert.deepEqual(rel!.screenshots, []);
const p = await core.reviewPreview(db, ref);
assert.ok(p.previewUrl);
assert.deepEqual(p.screenshots, []);
});
test("screenshots are opt-out (deploy.screenshots: []) and only for previews; junk is not stored", async () => {
const d = await deployable({ compose: "deploy/compose.yml", service: "web", port: 3000, health: "/healthz", screenshots: [] });
const sha = d.merge(`${d.p.key}-1`);
assert.equal((await d.run("preview", sha, { PEPPA_PR: "5" })).code, 0);
assert.equal((await d.run("staging", sha)).code, 0);
assert.ok(!d.calls().includes("docker run"), "no screenshot container started");
const [rel] = (await releases(d.proj.id)).filter((x) => x.env === "preview");
const out = await runner.recordScreenshots(db, d.proj, { sha, prNumber: 5, shots: [{ path: "/", png: Buffer.from("not a png").toString("base64") }] });
assert.deepEqual(out, { release: rel!.id, saved: 0 });
// Unsigned report is refused.
const bad = await runner.handleGiteaHook(db, { event: "screenshots", signature: "x", body: JSON.stringify({ repository: `${d.proj.giteaOwner}/${d.proj.giteaRepo}`, sha, shots: [] }) });
assert.equal(bad.status, 401);
});
});