peppa/packages/testkit/test/deploy.test.ts
peppa-bot b02c41ec80
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 53с
peppa/build build: success за 36с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1773с
peppa-ci / ci (pull_request) Successful in 32m0s
PEP-314: замечания координатора — база у агента без записи в passwd (nss_wrapper), Dockerfile.golang, адрес базы ${ROUTER}-db, «go 1.27» = последний выпуск, stop без адреса, оценка времени
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 11:31:46 +00:00

482 lines
27 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 FORGE through handleGiteaHook.
import { stripAsIs } from "@peppa/shared/i18n";
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, superadmin, 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: FORGE'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, "deploy/compose.postgres.yml"), readFileSync(join(ROOT, "template/deploy/compose.postgres.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, "FORGE 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`]);
// PEP-146: a second press while the update is running is not an error — the same update comes back.
const first = await runner.deployProd(db, d.proj, "mock-pm");
const second = await runner.deployProd(db, d.proj, "mock-pm");
assert.equal(second.id, first.id, "no second update is started");
assert.equal((await releases(d.proj.id)).filter((x) => x.env === "prod" && x.status === "deploying").length, 1);
});
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 (FORGE'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: Неудачный релиз — прод возвращён на предыдущий, релиз помечен «откат», суперадмин получает причину и лог", async () => {
const sent = await superadmin();
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");
// PEP-150: a failed update is not the owner's to fix — the superadmin gets the reason and the log.
assert.equal((await core.pendingQuestions(db, d.proj.id)).some((q) => q.text.includes("не прошло проверку")), false, "the owner is not told");
const text = (await sent()).find((x) => x.includes(bad.slice(0, 7)) && x.includes("не прошло проверку"))!;
assert.ok(text, "the superadmin got a message");
assert.match(text, new RegExp(`возвращена прежняя версия ${good.slice(0, 7)}`));
assert.match(stripAsIs(text), /Причина: проверка \/healthz/);
assert.match(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);
});
});
// PEP-314, spec delivery-pipeline «База продукта на стенде» и «Миграция без оболочки».
const DB_DEPLOY = { compose: "deploy/compose.postgres.yml", service: "web", port: 3000, health: "/healthz", database: { service: "db" }, migrate: ["/app/server", "migrate"] };
describe("База продукта на стенде", () => {
const passwords = (state: string, project: string) =>
existsSync(join(state, `dbpw-${project}`)) ? readFileSync(join(state, `dbpw-${project}`), "utf8").split("\n").filter(Boolean) : [];
test("Scenario: Пароль переживает повторную выкатку", async () => {
const d = await deployable(DB_DEPLOY);
const first = await d.run("staging", d.merge(`${d.p.key}-1`));
assert.equal(first.code, 0, first.out);
const second = await d.run("staging", d.merge(`${d.p.key}-2`));
assert.equal(second.code, 0, second.out);
const pw = [...new Set(passwords(d.state, `${d.proj.slug}-staging`))];
assert.equal(pw.length, 1, `one password for the stand: ${pw}`);
assert.match(pw[0]!, /^[0-9a-f]{48}$/);
for (const out of [first.out, second.out]) assert.ok(!out.includes(pw[0]!), "the password is not in the log");
for (const rel of await releases(d.proj.id)) assert.ok(!(rel.logTail ?? "").includes(pw[0]!), "nor in the report to FORGE");
// the volume is made with compose's labels, so compose takes it as its own
const labels = readFileSync(join(d.state, "volumes", `${d.proj.slug}-staging_db-data`, "labels"), "utf8");
assert.match(labels, new RegExp(`com\\.docker\\.compose\\.project=${d.proj.slug}-staging`));
assert.match(labels, /com\.docker\.compose\.volume=db-data/);
});
test("Scenario: Свой пароль у каждого стенда", async () => {
const d = await deployable(DB_DEPLOY);
assert.equal((await d.run("staging", d.merge(`${d.p.key}-1`))).code, 0);
assert.equal((await d.run("preview", d.merge(`${d.p.key}-3`), { PEPPA_PR: "3" })).code, 0);
const staging = passwords(d.state, `${d.proj.slug}-staging`)[0];
const preview = passwords(d.state, `${d.proj.slug}-pr3`)[0];
assert.ok(staging && preview);
assert.notEqual(staging, preview);
});
test("Scenario: Миграция для образа distroless", async () => {
const d = await deployable(DB_DEPLOY);
const r = await d.run("staging", d.merge(`${d.p.key}-1`));
assert.equal(r.code, 0, r.out);
assert.match(d.calls(), / run --rm web \/app\/server migrate$/m);
assert.doesNotMatch(d.calls(), /sh -c/);
});
test("строковая миграция идёт через sh -c, как раньше", async () => {
const d = await deployable({ compose: "deploy/compose.yml", service: "web", port: 3000, migrate: "pnpm db:migrate" });
assert.equal((await d.run("staging", d.merge(`${d.p.key}-1`))).code, 0);
assert.match(d.calls(), / run --rm web sh -c pnpm db:migrate$/m);
});
test("Scenario: Копия базы перед миграцией", async () => {
const d = await deployable(DB_DEPLOY);
assert.equal((await d.run("staging", d.merge(`${d.p.key}-1`))).code, 0);
assert.doesNotMatch(d.calls(), / exec -T db /, "the first deploy has nothing to copy");
const r = await d.run("staging", d.merge(`${d.p.key}-2`));
assert.equal(r.code, 0, r.out);
assert.match(r.out, /копия базы снята/);
const lines = d.calls().split("\n");
const dump = lines.findLastIndex((l) => / exec -T db sh -c .*pg_dump/s.test(l) || l.includes(" exec -T db "));
const migrate = lines.findLastIndex((l) => l.includes("run --rm web /app/server migrate"));
assert.ok(dump >= 0 && dump < migrate, "pg_dump goes before the migration");
});
test("Scenario: Копия не снялась", async () => {
const d = await deployable(DB_DEPLOY);
assert.equal((await d.run("staging", d.merge(`${d.p.key}-1`))).code, 0);
const before = d.calls().split("\n").length;
const r = await d.run("staging", d.merge(`${d.p.key}-2`), { MOCK_DOCKER_PGDUMP_FAIL: "1" });
assert.equal(r.code, 1);
const rel = (await releases(d.proj.id)).at(-1)!;
assert.equal(rel.status, "failed");
assert.equal(rel.reason, "копия базы не снята");
const after = d.calls().split("\n").slice(before - 1).join("\n");
assert.doesNotMatch(after, /\/app\/server migrate/, "no migration after a failed copy");
});
test("Scenario: Закрытый PR удаляет тома превью", async () => {
const d = await deployable(DB_DEPLOY);
const sha = d.merge(`${d.p.key}-3`);
assert.equal((await d.run("preview", sha, { PEPPA_PR: "3" })).code, 0);
assert.doesNotMatch(d.calls(), / exec -T db /, "a preview makes no copy");
assert.ok(existsSync(join(d.state, "volumes", `${d.proj.slug}-pr3_db-data`)));
assert.equal((await d.run("preview-down", sha, { PEPPA_PR: "3" })).code, 0);
assert.match(d.calls(), / down -v --remove-orphans$/m);
assert.ok(!existsSync(join(d.state, "volumes", `${d.proj.slug}-pr3_db-data`)));
});
test("Scenario: Проект без базы — как раньше", async () => {
const d = await deployable();
const sha = d.merge(`${d.p.key}-3`);
assert.equal((await d.run("staging", sha)).code, 0);
assert.equal((await d.run("preview", sha, { PEPPA_PR: "3" })).code, 0);
assert.equal((await d.run("preview-down", sha, { PEPPA_PR: "3" })).code, 0);
assert.ok(passwords(d.state, `${d.proj.slug}-staging`).every((p) => p === ""), "no PEPPA_DB_PASSWORD");
assert.ok(!existsSync(join(d.state, "volumes")), "no volumes made by the script");
assert.doesNotMatch(d.calls(), / down -v/);
assert.doesNotMatch(d.calls(), /docker volume|exec -T/);
});
});
describe("Шаблон стенда с базой (PEP-314)", () => {
test("Scenario: Агент нового проекта ищет, как выкатить Go с базой", () => {
const compose = readFileSync(join(ROOT, "template/deploy/compose.postgres.yml"), "utf8");
// Service blocks by indentation (no YAML parser among the deps): « name:» up to the next one.
const block = (name: string) => (compose.match(new RegExp(`^ ${name}:\\n((?: .*\\n|\\s*\\n)*)`, "m")) ?? [])[1] ?? "";
const dbSvc = block("db");
assert.ok(dbSvc.includes("image: postgres:18"), dbSvc);
assert.doesNotMatch(dbSvc, /^ ports:/m, "the database publishes no ports");
assert.doesNotMatch(dbSvc, /traefik/, "the database is not in traefik_default");
assert.match(dbSvc, /^ networks:\n default:\n aliases:\n - \$\{ROUTER:\?\}-db\n/m, "a name unique to the stand");
assert.match(dbSvc, /^ - db-data:\/var\/lib\/postgresql$/m);
assert.match(dbSvc, /^ healthcheck:\n test: .*pg_isready/m);
const web = block("web");
assert.match(web, /depends_on:\n db:\n condition: service_healthy/);
assert.match(web, /DATABASE_URL: "postgres:\/\/app:\$\{PEPPA_DB_PASSWORD:\?\}@\$\{ROUTER:\?\}-db:5432\/app/);
assert.doesNotMatch(web, /@db:/, "not the short name «db» — web is in traefik_default too");
const docker = readFileSync(join(ROOT, "template/deploy/Dockerfile.golang"), "utf8");
assert.match(docker, /^FROM gcr\.io\/distroless\/static/m);
assert.match(docker, /^CMD \["\/app\/server"\]/m);
assert.doesNotMatch(docker, /^ENTRYPOINT/m);
const std = readFileSync(join(ROOT, "docs/standards/default-stack.md"), "utf8");
assert.match(std, /^## Данные продукта и копии$/m);
assert.ok(std.includes("source .gitea/peppa-tools.sh go postgres && go test ./..."));
});
});