// PEP-18, spec platform-release: FORGE's own prod from ~/peppa/current, the PM's button, the // release script with backup and rollback, install-launchd without the bootout race. // scripts/peppa-release.sh and install-launchd.sh run for real against mock-launchctl and // mock-pnpm (first on PATH), a local git repo instead of Gitea and a mock /api/health that // answers with the commit `current` points to; the CLI, the DB and recordRelease are real. import assert from "node:assert/strict"; import { execFile, execFileSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, symlinkSync, writeFileSync } from "node:fs"; import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; import { tmpdir } from "node:os"; import { basename, 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"; const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); const TMP = mkdtempSync(join(tmpdir(), "peppa-release-")); const RELEASES = join(TMP, "peppa"); const QUEUE = join(process.env.PEPPA_HOME!, "release-queue"); const LAUNCHD = join(TMP, "launchd"); const PNPM_LOG = join(TMP, "pnpm.log"); process.env.PEPPA_RELEASE_QUEUE = QUEUE; // launchctl, pnpm → mocks, first on PATH for the scripts. const BIN = join(TMP, "bin"); mkdirSync(BIN); symlinkSync(join(ROOT, "packages/testkit/bin/mock-launchctl"), join(BIN, "launchctl")); symlinkSync(join(ROOT, "packages/testkit/bin/mock-pnpm"), join(BIN, "pnpm")); // The "Gitea" repo of FORGE: commits are merges of PEP-like task branches. const REMOTE = join(TMP, "remote"); const git = (...a: string[]) => execFileSync("git", ["-C", REMOTE, "-c", "user.name=t", "-c", "user.email=t@t", ...a], { encoding: "utf8" }).trim(); mkdirSync(REMOTE); git("init", "-q", "-b", "main"); function merge(task: string): string { writeFileSync(join(REMOTE, `${task}.txt`), task); git("add", "-A"); git("commit", "-qm", `Merge pull request '${task}' (#1) from task/${task} into main`); return git("rev-parse", "HEAD"); } let server: Server; let healthUrl = ""; /** Commits whose web never gets healthy. */ const bad = new Set(); const currentSha = () => (existsSync(join(RELEASES, "current")) ? basename(readlinkSync(join(RELEASES, "current"))) : null); let pep: Awaited>; let proj: Awaited>; before(async () => { server = createServer((req, res) => { const sha = currentSha(); if (req.url !== "/api/health" || !sha || bad.has(sha)) return void res.writeHead(503).end(JSON.stringify({ ok: false })); const now = new Date().toISOString(); res.writeHead(200).end(JSON.stringify({ ok: true, commit: sha.slice(0, 7), services: [{ service: "bot", lastHeartbeat: now }, { service: "watchdog", lastHeartbeat: now }] })); }); await new Promise((r) => server.listen(0, "127.0.0.1", r)); healthUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/health`; // The platform project: its workspace .peppa/project.json has the checks of main. pep = await project({ turns: [] }); process.env.PEPPA_PLATFORM_KEY = pep.key; proj = await core.getProject(db, pep.key); writeFileSync(join(pep.dir, ".peppa/project.json"), JSON.stringify({ slug: proj.slug, key: pep.key, name: pep.key, checks: { typecheck: "x", test: "x", build: "x" } })); // Prod services are loaded in (mock) launchd; the release dir has its one .env. mkdirSync(join(LAUNCHD, "loaded"), { recursive: true }); for (const s of ["web", "bot", "watchdog"]) writeFileSync(join(LAUNCHD, "loaded", `quest.telecom.peppa.${s}`), ""); mkdirSync(join(RELEASES, "shared"), { recursive: true }); writeFileSync(join(RELEASES, "shared/.env"), ""); }); after(async () => { server.close(); await teardown(); }); const scriptEnv = (extra: Record = {}) => ({ ...process.env, PATH: `${BIN}:${process.env.PATH}`, MOCK_LAUNCHCTL_STATE: LAUNCHD, MOCK_PNPM_LOG: PNPM_LOG, PEPPA_RELEASES_DIR: RELEASES, PEPPA_RELEASE_REMOTE: REMOTE, PEPPA_RELEASE_CLI: join(ROOT, "packages/cli/bin/peppa"), PEPPA_RELEASE_HEALTH_URL: healthUrl, PEPPA_RELEASE_HEALTH_TIMEOUT: "2", PEPPA_RELEASE_HEALTH_INTERVAL: "0.3", ...extra, }); function sh(script: string, args: string[], env: NodeJS.ProcessEnv): Promise<{ code: number; out: string }> { return new Promise((done) => execFile("bash", [join(ROOT, "scripts", script), ...args], { env, encoding: "utf8" }, (err, stdout, stderr) => done({ code: err ? Number((err as { code?: number }).code ?? 1) : 0, out: stdout + stderr }), ), ); } const release = (args: string[], extra: Record = {}) => sh("peppa-release.sh", args, scriptEnv(extra)); const kickstarts = () => (existsSync(join(LAUNCHD, "kickstarts.log")) ? readFileSync(join(LAUNCHD, "kickstarts.log"), "utf8").trim().split("\n").filter(Boolean) : []); const releaseBackups = () => (existsSync(join(process.env.PEPPA_HOME!, "backups")) ? readdirSync(join(process.env.PEPPA_HOME!, "backups")).filter((f) => f.startsWith("release-")) : []); const latestRelease = async () => (await runner.listReleases(db, proj.id, 1))[0]!; const messages = async () => (await core.pendingQuestions(db, proj.id)).map((q) => q.text); async function greenMain(sha: string) { for (const check of ["typecheck", "test", "build"]) await runner.recordCheck(db, proj, { sha, branch: "main", check, state: "success" }); } describe("Деплой FORGE по кнопке PM", () => { test("Scenario: Зелёный main — предложение PM", async () => { const sha = merge(`${pep.key}-5`); await runner.recordCheck(db, proj, { sha, branch: "main", check: "typecheck", state: "success" }); assert.ok(!(await core.pendingQuestions(db, proj.id)).some((q) => q.options?.includes(runner.PROD_OPTION)), "no offer until every check is green"); await greenMain(sha); const offers = (await core.pendingQuestions(db, proj.id)).filter((q) => q.options?.includes(runner.PROD_OPTION)); assert.equal(offers.length, 1); assert.match(offers[0]!.text, new RegExp(`main зелёный — ${sha.slice(0, 7)}\\. Выкатить в прод\\?`)); }); test("Scenario: Кнопка ставит запрос слушателю", async () => { const offer = (await core.pendingQuestions(db, proj.id)).find((q) => q.options?.includes(runner.PROD_OPTION))!; assert.equal(await runner.onReleaseAnswer(db, offer, runner.PROD_OPTION, "PM (telegram)"), true); const rel = await latestRelease(); assert.equal(rel.env, "prod"); assert.equal(rel.status, "deploying"); assert.equal(rel.deployedBy, "PM (telegram)"); const req = JSON.parse(readFileSync(join(QUEUE, `${rel.id}.json`), "utf8")); assert.deepEqual(req, { releaseId: rel.id, sha: rel.sha, by: "PM (telegram)" }); }); test("Scenario: Второй запрос во время деплоя", async () => { const rel = await latestRelease(); await assert.rejects(runner.deployProd(db, proj, "mock-pm"), new RegExp(`прод уже выкатывается \\(${rel.sha.slice(0, 7)}\\)`)); }); test("Scenario: Красный main не выкатывается", async () => { const other = await project({ turns: [] }); const p = await core.getProject(db, other.key); writeFileSync(join(other.dir, ".peppa/project.json"), JSON.stringify({ slug: p.slug, key: other.key, name: other.key, checks: { typecheck: "x", test: "x" } })); process.env.PEPPA_PLATFORM_KEY = other.key; try { await runner.recordCheck(db, p, { sha: "e4f5a6b0", branch: "main", check: "typecheck", state: "success" }); await runner.recordCheck(db, p, { sha: "e4f5a6b0", branch: "main", check: "test", state: "failure" }); await assert.rejects(runner.deployProd(db, p, "mock-pm"), /main без зелёных проверок — выкатывать нечего/); assert.equal((await runner.listReleases(db, p.id)).length, 0); } finally { process.env.PEPPA_PLATFORM_KEY = pep.key; } }); }); describe("Релиз с бэкапом и автооткатом", () => { test("Scenario: Успешный релиз — запрос из очереди, бэкап до миграции, current на новом коммите", async () => { const rel = await latestRelease(); const r = await release(["--queue"]); assert.equal(r.code, 0, r.out); assert.equal(currentSha(), rel.sha); assert.deepEqual(readdirSync(QUEUE), [], "the request left the queue"); assert.deepEqual(kickstarts(), ["quest.telecom.peppa.web kickstarted", "quest.telecom.peppa.bot kickstarted", "quest.telecom.peppa.watchdog kickstarted"]); assert.equal(releaseBackups().length, 1, "a checked backup before the migration"); const done = await latestRelease(); assert.equal(done.id, rel.id, "the button's release row is the one completed"); assert.equal(done.status, "healthy"); assert.deepEqual(done.tasks, [`${pep.key}-5`]); assert.ok((await messages()).some((t) => t.includes("ваш продукт обновлён и открыт для всех")), "the PM is told"); // The worktree is the commit; .env is the shared one. assert.equal(readlinkSync(join(RELEASES, "releases", rel.sha, ".env")), join(RELEASES, "shared/.env")); assert.ok(existsSync(join(RELEASES, "releases", rel.sha, "apps/web/.next/BUILD_ID"))); }); test("Scenario: Нездоровый релиз откатывается", async () => { const prev = currentSha()!; const sha = merge(`${pep.key}-6`); bad.add(sha); const before = kickstarts().length; const r = await release([sha]); assert.equal(r.code, 1, r.out); assert.equal(currentSha(), prev, "current is back on the previous release"); assert.equal(kickstarts().length - before, 6, "restarted on the new release, then on the old one"); const rel = await latestRelease(); assert.equal(rel.sha, sha); assert.equal(rel.status, "rolled_back"); assert.equal(rel.previousSha, prev); assert.match(rel.reason ?? "", /релиз нездоров: веб не отвечает/); assert.ok(rel.logTail, "the log tail is kept"); // PEP-150: a failed update is the superadmin's to see (a delay of the project), not a message to the owner. const failed = `обновление ${sha.slice(0, 7)} (prod) не прошло проверку — возвращена прежняя версия ${prev.slice(0, 7)}`; assert.ok(!(await messages()).some((t) => t.includes(failed)), "nothing for the owner"); assert.ok((await core.listPlatformDelays(db)).some((d) => d.projectId === proj.id && d.reason === "deploy" && d.details.includes(failed))); }); test("Scenario: Сборка упала — прод не тронут", async () => { const prev = currentSha()!; const sha = merge(`${pep.key}-8`); const [k, b] = [kickstarts().length, releaseBackups().length]; const r = await release([sha], { MOCK_PNPM_FAIL: "build" }); assert.equal(r.code, 1, r.out); assert.equal(currentSha(), prev); assert.equal(kickstarts().length, k, "no service restarted"); assert.equal(releaseBackups().length, b, "no backup, no migration"); const rel = await latestRelease(); assert.equal(rel.status, "failed"); assert.match(rel.reason ?? "", /next build/); assert.match(rel.logTail ?? "", /Failed to compile/); }); test("Scenario: --check — здоровье текущего релиза", async () => { const r = await release(["--check"]); assert.equal(r.code, 0, r.out); assert.match(r.out, new RegExp(`healthy ${currentSha()!.slice(0, 7)}`)); }); }); describe("Установка launchd без гонки", () => { const install = (args: string[]) => { const home = join(TMP, "home"); mkdirSync(home, { recursive: true }); return sh("install-launchd.sh", args, { ...scriptEnv(), HOME: home, PEPPA_HOME: join(home, ".peppa"), PEPPA_LAUNCHD_WAIT_SEC: "3", PEPPA_NODE: process.execPath }); }; test("Scenario: Переустановка работающего агента", async () => { // Loaded and slow to unload: `print` still finds it twice after bootout. writeFileSync(join(LAUNCHD, "calls.log"), ""); const r = await install(["web"]); assert.equal(r.code, 0, r.out); assert.doesNotMatch(r.out, /Bootstrap failed/); const calls = readFileSync(join(LAUNCHD, "calls.log"), "utf8").trim().split("\n"); const iOut = calls.findIndex((c) => c.startsWith("launchctl bootout")); const iIn = calls.findIndex((c) => c.startsWith("launchctl bootstrap")); assert.ok(iOut >= 0 && iIn > iOut, calls.join("\n")); assert.equal(calls.slice(iOut + 1, iIn).filter((c) => c.startsWith("launchctl print")).length, 3, "waited until print no longer found it"); const plist = readFileSync(join(LAUNCHD, "loaded/quest.telecom.peppa.web"), "utf8"); assert.match(plist, new RegExp(`PEPPA_ROOT${ROOT}`)); assert.match(plist, /KeepAlive<\/key>/); }); test("Scenario: Слушатель релизов — запуск по очереди запросов", async () => { const r = await install(["release"]); assert.equal(r.code, 0, r.out); const plist = readFileSync(join(LAUNCHD, "loaded/quest.telecom.peppa.release"), "utf8"); assert.match(plist, /QueueDirectories<\/key>.*\/\.peppa\/release-queue<\/string><\/array>/); assert.match(plist, /scripts\/peppa-release\.sh<\/string>\s*--queue<\/string>/); assert.doesNotMatch(plist, /KeepAlive/); }); }); describe("Прод из релизного каталога", () => { test("Scenario: Хук раннера переживает смену релиза — корень по пути current, не по релизу", () => { // The wrappers' root lines, run as a bin inside the current release. const wrapper = readFileSync(join(ROOT, "packages/runner/bin/peppa-hook"), "utf8"); const rootLines = wrapper.split("\n").filter((l) => l.startsWith("_b=") || l.startsWith("PEPPA_ROOT=")); assert.equal(rootLines.length, 2, wrapper); const binDir = join(RELEASES, "releases", currentSha()!, "packages/runner/bin"); mkdirSync(binDir, { recursive: true }); writeFileSync(join(binDir, "probe"), `${rootLines.join("\n")}\necho "$PEPPA_ROOT"\n`); const viaCurrent = join(RELEASES, "current/packages/runner/bin/probe"); assert.equal(execFileSync("bash", [viaCurrent], { encoding: "utf8" }).trim(), join(RELEASES, "current")); // ~/.local/bin/ → ~/peppa/current/…: still current, not releases/. const localBin = join(TMP, "local-bin"); mkdirSync(localBin); symlinkSync(viaCurrent, join(localBin, "probe")); assert.equal(execFileSync("bash", [join(localBin, "probe")], { encoding: "utf8" }).trim(), join(RELEASES, "current")); }); test("Scenario: Выключено — после зелёного main вопроса нет, открытый закрыт; включено — снова есть", async () => { const offers = async () => (await core.pendingQuestions(db, proj.id)).filter((q) => q.options?.includes(runner.PROD_OPTION)); const first = merge(`${pep.key}-offers-1`); await greenMain(first); assert.equal((await offers()).length, 1); await runner.setPlatformReleaseOffers(db, false); assert.equal(await runner.platformReleaseOffers(db), false); assert.equal((await offers()).length, 0, "the open offer is closed"); const second = merge(`${pep.key}-offers-2`); await greenMain(second); assert.equal((await offers()).length, 0, "no offer while off"); await runner.setPlatformReleaseOffers(db, true); const third = merge(`${pep.key}-offers-3`); await greenMain(third); assert.equal((await offers()).length, 1); }); });