peppa/packages/testkit/test/server-deploy.test.ts
peppa-bot 2c582e190d
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 57с
peppa/build build: success за 39с
peppa/test test: success за 1693с
peppa-ci / ci (pull_request) Successful in 31m19s
PEP-310: автовыкатка сообщает о неудаче сразу и пробует ту же версию снова через час
26.11 в 23:40 сборка образа упала («permission denied» в ~/.docker): учётке сервера дали прямой
доступ к docker, скрипт перестал звать sudo, а служебные файлы остались за root от прежних
`sudo -E docker`. Автовыкатка записала версию как неудачную и больше её не пробовала; никому
ничего не пришло — сторож отставания (PEP-277) говорит только через два часа.

- scripts/platform-deploy.sh: `die` при --auto зовёт работающий вачдог
  (`peppa platform deploy-failed <sha> <причина>`); неудачная цель пропускается час, потом пробуется
  снова (scripts/lib/deploy-failed.sh, PEPPA_AUTODEPLOY_RETRY_MIN); `sudo -E -H` — root не пишет в
  ~/.docker учётки; `fix_docker_home` возвращает учётке оставшиеся там чужие файлы до сборки; откат
  называет причину в последней строке.
- runner/deploy-lag.ts: `alertDeployFailed` — суперадминам одно сообщение на версию и причину.
- CLI `peppa platform deploy-failed`; переводы en/kk.
- AGENTS.md: заметки PEP-308, PEP-309 и PEP-310 (три исправления сливаются одним заходом).
- Тесты: autodeploy.test.ts (метка неудачи, сообщение, ~/.docker), deploy-lag.test.ts (одно сообщение).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 01:00:26 +05:00

63 lines
4.2 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-240: the first platform deploy on the server and the Bugsink move showed what the scripts must
// do themselves: docker through sudo (never the whole script as root), a database copy without a host
// sqlite3, Bugsink reachable by its container name, a verified copy with a way back.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { describe, test } from "node:test";
const path = (p: string) => new URL(`../../../${p}`, import.meta.url).pathname;
const read = (p: string) => readFileSync(path(p), "utf8");
describe("PEP-240: выкатка платформы на сервере", () => {
const deploy = read("scripts/platform-deploy.sh");
test("Сценарий: у пользователя нет доступа к сокету docker — docker через sudo, сервисы не от root", () => {
execFileSync("bash", ["-n", path("scripts/platform-deploy.sh")]);
assert.match(deploy, /\[ ! -w \/var\/run\/docker\.sock \] && \[ "\$\(id -u\)" != 0 \]/);
assert.match(deploy, /docker\(\) \{ sudo -E -H "\$DOCKER_BIN" "\$@"; \}/);
// uid сервисов берётся до любого sudo — от пользователя, запустившего выкатку.
assert.ok(deploy.indexOf("PEPPA_UID=") < deploy.indexOf("sudo -E"), "PEPPA_UID must be set before docker goes through sudo");
});
test("Сценарий: на хосте нет sqlite3 — копия базы утилитой из образа цели, без копии миграции нет", () => {
const fn = deploy.slice(deploy.indexOf("backup_db() {"), deploy.indexOf("run backup_db"));
assert.match(fn, /command -v sqlite3/);
assert.match(fn, /docker run --rm --user .* "peppa\/platform:\$SHORT" sqlite3 .*VACUUM INTO/);
assert.match(fn, /\[ -s "\$out" \]/, "an empty copy is a failed copy");
assert.ok(deploy.indexOf("run backup_db || die") < deploy.indexOf("peppa db migrate"), "the copy comes before the migration");
});
});
describe("PEP-240: Bugsink на сервере", () => {
const move = read("scripts/server-move/bugsink-move.sh");
test("Сценарий: запрос по имени контейнера — имя есть в ALLOWED_HOSTS", () => {
const compose = read("infra/docker-compose.yml");
const bugsink = compose.slice(compose.indexOf("\n bugsink:"), compose.indexOf("\n cloudflared:"));
assert.match(bugsink, /ALLOWED_HOSTS: \$\{BUGSINK_HOST:-bugsink\.telecom\.quest\},peppa-bugsink,localhost,127\.0\.0\.1/);
});
test("Сценарий: данные после копии не совпали — перенос останавливается, Bugsink снова на прежнем месте", () => {
execFileSync("bash", ["-n", path("scripts/server-move/bugsink-move.sh")]);
const stop = move.indexOf("docker stop peppa-bugsink >/dev/null");
assert.ok(move.indexOf("уже есть контейнер или том Bugsink") < stop, "the server is checked before anything stops");
assert.ok(move.indexOf("trap back ERR") > stop && move.indexOf("trap back ERR") < move.indexOf("том → сервер"));
assert.match(move, /back\(\) \{[^}]*docker start peppa-bugsink/);
assert.match(move, /\[ "\$A" = "\$B" \] \|\| \{[^}]*false; \}/);
});
test("Сценарий: адрес Bugsink в настройках меняется только после ответа по новому адресу", () => {
const put = move.indexOf("put_env BUGSINK_URL http://peppa-bugsink:8000");
const probe = move.indexOf('fetch(\\"http://peppa-bugsink:8000/accounts/login/\\")');
assert.ok(probe > 0 && probe < put, "the name is probed before BUGSINK_URL changes");
assert.equal(move.match(/put_env BUGSINK_URL/g)?.length, 1);
});
test("Сценарий: вебхуки после переноса — адрес веба в сети docker, проекты переписаны", () => {
assert.match(move, /put_env BUGSINK_WEBHOOK_BASE http:\/\/peppa-web:3100/);
assert.match(move, /peppa project errors \$k/);
assert.ok(move.lastIndexOf("\nwebhooks\n") > move.indexOf("mac-route.sh"), "webhooks are rewritten at the end of the move");
});
});