// PEP-276: after the move to the server nothing ran the platform deploy — prod stayed on e694f4c3 while // 11 PRs were merged. The script failed at once without hand-set paths («.env: No such file»); now it // finds the server layout itself and `--auto` (cron every 10 min) deploys main's head when prod lags. import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, test } from "node:test"; const path = (p: string) => new URL(`../../../${p}`, import.meta.url).pathname; /** `touch -t` stamp (local time): YYYYMMDDhhmm. */ const stamp = (d: Date) => `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, "0")}${String(d.getDate()).padStart(2, "0")}${String(d.getHours()).padStart(2, "0")}${String(d.getMinutes()).padStart(2, "0")}`; const deploy = readFileSync(path("scripts/platform-deploy.sh"), "utf8"); describe("PEP-276: выкатка платформы сама", () => { test("Сценарий: раскладка сервера (~/peppa/src, ~/peppa/.env, ~/peppa/home) находится без переменных", () => { const base = realpathSync(mkdtempSync(join(tmpdir(), "autodeploy-"))); try { mkdirSync(join(base, "peppa", "src", "scripts"), { recursive: true }); mkdirSync(join(base, "peppa", "home"), { recursive: true }); mkdirSync(join(base, "user")); writeFileSync(join(base, "peppa", ".env"), "X=1\n"); writeFileSync(join(base, "peppa", "home", "peppa.db"), "x"); // Только разбор аргументов и умолчания путей — до блокировки и любых действий. const head = deploy.slice(0, deploy.indexOf('URL="${PEPPA_WEB_URL')); const script = join(base, "peppa", "src", "scripts", "platform-deploy.sh"); writeFileSync(script, `${head}\necho "$PEPPA_HOME|$ENV_FILE|$AUTO"\n`); const env = { PATH: process.env.PATH!, HOME: join(base, "user") }; const out = execFileSync("bash", [script, "--auto"], { env }).toString().trim(); assert.equal(out, `${join(base, "peppa", "home")}|${join(base, "peppa", ".env")}|1`); // 24.11: на сервере появился пустой ~/.peppa — раскладка сервера всё равно важнее. mkdirSync(join(base, "user", ".peppa")); const stray = execFileSync("bash", [script, "--auto"], { env }).toString().trim(); assert.equal(stray, `${join(base, "peppa", "home")}|${join(base, "peppa", ".env")}|1`); // Mac: базы рядом с копией нет — ~/.peppa (с базой) и .env в корне копии, как раньше. rmSync(join(base, "peppa", "home"), { recursive: true }); writeFileSync(join(base, "user", ".peppa", "peppa.db"), "x"); writeFileSync(join(base, "peppa", "src", ".env"), "X=1\n"); const mac = execFileSync("bash", [script], { env }).toString().trim(); assert.equal(mac, `${join(base, "user", ".peppa")}|${join(base, "peppa", "src", ".env")}|0`); // Нет базы — выкатка не начинается (сервисы на пустой базе = пропавшие данные). rmSync(join(base, "user", ".peppa", "peppa.db")); assert.throws(() => execFileSync("bash", [script], { env, stdio: "pipe" }), /нет базы/); } finally { rmSync(base, { recursive: true, force: true }); } }); test("Сценарий: --auto — прод на HEAD main или проверки идут → тихо выходит; упавшая цель не повторяется по кругу", () => { execFileSync("bash", ["-n", path("scripts/platform-deploy.sh")]); const auto = deploy.slice(deploy.indexOf('if [ "$AUTO" = 1 ]; then\n LIVE=')); assert.match(auto, /case "\$TARGET" in "\$\{LIVE:-—\}"\*\) exit 0;; esac/); assert.match(auto, /failed_recently "\$PEPPA_HOME\/platform-deploy\.failed" "\$TARGET" && exit 0/); assert.match(deploy, /\[ "\$AUTO" = 1 \] && exit 0 # проверки ещё идут/); // Метка неудачи ставится до сборки и снимается только после проверки страниц. assert.ok(deploy.indexOf('>"$PEPPA_HOME/platform-deploy.failed"') < deploy.indexOf("docker build")); assert.ok(deploy.indexOf('rm -f "$PEPPA_HOME/platform-deploy.failed"') > deploy.indexOf("for p in / /projects")); // Сначала свежий скрипт из main, потом блокировка; брошенная блокировка старше 2 ч снимается. assert.ok(deploy.indexOf("PEPPA_AUTODEPLOY_FRESH=1 exec") < deploy.indexOf('mkdir "$LOCK"')); assert.match(deploy, /-mmin \+120/); }); // PEP-310: 26.11.2026 the image build failed at 23:40 («permission denied» in ~/.docker). The cron // marked the version as failed and never tried it again; nobody heard until someone looked. test("PEP-310: неудачная цель пропускается час, потом пробуется снова; другая цель — сразу", () => { const base = realpathSync(mkdtempSync(join(tmpdir(), "deploy-failed-"))); try { const mark = join(base, "platform-deploy.failed"); const lib = path("scripts/lib/deploy-failed.sh"); const recent = (target: string, env: Record = {}) => { try { execFileSync("bash", ["-c", `. "${lib}"; failed_recently "${mark}" "${target}"`], { env: { PATH: process.env.PATH!, ...env } }); return true; } catch { return false; } }; assert.equal(recent("aaa"), false, "no mark — nothing failed"); writeFileSync(mark, "aaa\n"); assert.equal(recent("aaa"), true, "failed a moment ago — the cron skips it"); assert.equal(recent("bbb"), false, "a new commit is tried at once"); // 61 minutes later the same version is tried again. execFileSync("touch", ["-t", stamp(new Date(Date.now() - 61 * 60_000)), mark]); assert.equal(recent("aaa"), false, "an hour passed — try again"); assert.equal(recent("aaa", { PEPPA_AUTODEPLOY_RETRY_MIN: "120" }), true, "the pause is a setting"); } finally { rmSync(base, { recursive: true, force: true }); } }); test("PEP-310: о неудаче --auto вачдог сообщает суперадминам; root не пишет в ~/.docker учётки", () => { // `die` of an automatic run calls the running watchdog — only when the target is known. assert.match(deploy, /alert_failed\(\) \{\n \[ "\$AUTO" = 1 \] && \[ -n "\$\{SHORT:-\}" \] && \[ -z "\$\{PEPPA_PLATFORM_DRY:-\}" \] \|\| return 0\n docker exec peppa-watchdog peppa platform deploy-failed "\$SHORT" "\$1"/); assert.match(deploy, /die\(\) \{ say "STOP — \$\*"; alert_failed "\$\*"; exit 1; \}/); // The alert never breaks the script, and a rollback names its cause in the line the alert carries. assert.match(deploy, /deploy-failed "\$SHORT" "\$1" >\/dev\/null 2>&1 \|\| true/); assert.match(deploy, /die "откатились, сайт работает на \$PREV — \$1"/); // sudo keeps root's files out of the account's home; files left there earlier are given back before the build. assert.match(deploy, /sudo -E -H "\$DOCKER_BIN"/); assert.ok(deploy.indexOf("run fix_docker_home") > 0 && deploy.indexOf("run fix_docker_home") < deploy.indexOf("run docker build")); // fix_docker_home on a folder of the user's own files does nothing and does not call sudo. const base = realpathSync(mkdtempSync(join(tmpdir(), "docker-home-"))); try { mkdirSync(join(base, "buildx"), { recursive: true }); writeFileSync(join(base, "buildx", ".lock"), ""); const fn = deploy.slice(deploy.indexOf("fix_docker_home() {"), deploy.indexOf("run fix_docker_home")); const out = execFileSync("bash", ["-c", `say() { echo "$*"; }; sudo() { echo SUDO; }; ${fn}\nfix_docker_home; echo done`], { env: { PATH: process.env.PATH!, DOCKER_CONFIG: base, HOME: base } }).toString(); assert.equal(out.trim(), "done"); } finally { rmSync(base, { recursive: true, force: true }); } }); test("Сценарий: cron ставится один раз и снимается", () => { const inst = readFileSync(path("scripts/install-autodeploy.sh"), "utf8"); execFileSync("bash", ["-n", path("scripts/install-autodeploy.sh")]); assert.match(inst, /\*\/10 \* \* \* \* cd \$ROOT && scripts\/platform-deploy\.sh --auto/); assert.match(inst, /grep -vF "\$MARK"/); }); });