peppa/packages/runner/src/deploy-lag.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

142 lines
7.1 KiB
TypeScript
Raw 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-277: the production lags behind main. After the move to the server the platform deploy
// stopped silently more than once: merged stories lay in main while the site ran an old commit,
// and nobody knew for a day. Every 15 minutes the watchdog compares the commit of /api/health
// with main of the platform repo in Gitea; merged PRs older than 2 h that are not deployed —
// one personal message to the superadmins (not the platform channel) with the stories; again
// only on a new merged PR or after a day; caught up — «выкатка догнала main».
import { createHash } from "node:crypto";
import { asIs, m } from "@peppa/shared/i18n";
import { alertAdmins, deleteSetting, getSetting, giteaForBot, platformProjectKey, setSetting } from "@peppa/core";
import type { GiteaCommit } from "@peppa/core";
import type { Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
const MIN_MS = 60_000;
const DAY_MS = 24 * 3600_000;
const MERGE_RE = /^Merge pull request '([\s\S]*?)' \(#(\d+)\)/;
const everyMs = () => Math.max(1, Number(process.env.PEPPA_DEPLOY_LAG_EVERY_MIN ?? 15)) * MIN_MS;
const lagMs = () => Math.max(0, Number(process.env.PEPPA_DEPLOY_LAG_HOURS ?? 2)) * 3600_000;
/** /api/health of the running site: the explicit address, the public health address, or the web's. */
export function deployLagHealthUrl(): string | null {
const explicit = process.env.PEPPA_DEPLOY_LAG_HEALTH_URL || process.env.PEPPA_PUBLIC_HEALTH_URL;
if (explicit) return explicit;
const web = process.env.PEPPA_WEB_URL;
return web ? `${web.replace(/\/$/, "")}/api/health` : null;
}
/** The commit the site runs (null: no answer or no commit — the site's health is someone else's business). */
async function deployedCommit(url: string): Promise<string | null> {
try {
const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(10_000), headers: { "cache-control": "no-cache" } });
const body = (await res.json()) as { commit?: unknown };
return typeof body.commit === "string" && /^[0-9a-f]{7,40}$/i.test(body.commit) ? body.commit.toLowerCase() : null;
} catch {
return null;
}
}
export interface UndeployedMerge {
pr: number;
title: string;
sha: string;
/** Merge time, ms. */
at: number;
/** Platform stories named in the merge message. */
stories: string[];
}
/**
* Merged PRs of `commits` (newest first, as Gitea lists main) above the deployed commit. The deployed
* commit not among them — every merge of the list counts as not deployed.
*/
export function undeployedMerges(commits: GiteaCommit[], deployed: string, key = platformProjectKey()): UndeployedMerge[] {
const out: UndeployedMerge[] = [];
const re = new RegExp(`\\b${key}-(\\d+)\\b`, "gi");
for (const c of commits) {
if (c.sha.toLowerCase().startsWith(deployed)) break;
const mm = c.commit.message.match(MERGE_RE);
if (!mm) continue;
const stories = [...new Set([...c.commit.message.matchAll(re)].map((x) => `${key}-${Number(x[1])}`))];
out.push({ pr: Number(mm[2]), title: mm[1]!, sha: c.sha, at: Date.parse(c.commit.author.date), stories });
}
return out;
}
interface LagState {
alertedAt: number;
prs: number[];
head: string;
}
export type DeployLagResult =
| { state: "skipped" }
| { state: "fresh"; merges: number }
| { state: "lagging"; merges: UndeployedMerge[]; alerted: boolean }
| { state: "caught_up"; alerted: boolean };
export async function deployLagTick(db: Db, o: { now?: Date; force?: boolean; healthUrl?: string; log?: (s: string) => void } = {}): Promise<DeployLagResult> {
if (process.env.PEPPA_DEPLOY_LAG === "off") return { state: "skipped" };
const log = o.log ?? (() => {});
const now = (o.now ?? new Date()).getTime();
const last = await getSetting<number>(db, "deploy.lag.last");
if (!o.force && last != null && now - last < everyMs() && now >= last) return { state: "skipped" };
const url = o.healthUrl ?? deployLagHealthUrl();
if (!url) return { state: "skipped" };
await setSetting(db, "deploy.lag.last", now);
const deployed = await deployedCommit(url);
if (!deployed) return { state: "skipped" };
const [owner, repo] = loadEnv().GITEA_PLATFORM_REPO.split("/") as [string, string];
const commits = await giteaForBot().listCommits(owner, repo, "main", 100);
if (!commits.length) return { state: "skipped" };
const head = commits[0]!.sha;
const merges = undeployedMerges(commits, deployed);
const prev = await getSetting<LagState>(db, "deploy.lag");
if (!merges.length) {
if (!prev) return { state: "fresh", merges: 0 };
await deleteSetting(db, "deploy.lag");
const commit = deployed.slice(0, 7);
// glossary-ignore: сообщение читает администратор платформы
await alertAdmins(db, `deploy-lag:ok:${commit}:${now}`, m("✅ Выкатка догнала main: на сайте {commit}.", { commit }), log);
return { state: "caught_up", alerted: true };
}
const oldest = Math.min(...merges.map((x) => x.at));
if (now - oldest < lagMs()) return { state: "fresh", merges: merges.length };
const prs = merges.map((x) => x.pr).sort((a, b) => a - b);
const newPr = !prev || prs.some((n) => !prev.prs.includes(n));
if (!newPr && now - prev.alertedAt < DAY_MS) return { state: "lagging", merges, alerted: false };
await setSetting(db, "deploy.lag", { alertedAt: now, prs, head } satisfies LagState);
const stories = [...new Set(merges.flatMap((x) => (x.stories.length ? x.stories : [`#${x.pr}`])))].reverse();
const hours = Math.floor((now - oldest) / 3600_000);
// glossary-ignore: сообщение читает администратор платформы
const text = m("⚠️ Прод отстаёт от main на {hours} ч: на сайте {deployed}, в main {head}. Не выкачено слитых PR: {count} — {stories}. Выкатить — scripts/platform-deploy.sh.", {
hours,
deployed: deployed.slice(0, 7),
head: head.slice(0, 7),
count: merges.length,
stories: stories.join(", "),
});
await alertAdmins(db, `deploy-lag:${head.slice(0, 7)}:${now}`, text, log);
return { state: "lagging", merges, alerted: true };
}
/**
* PEP-310: the auto-deploy of `sha` did not go through; `reason` is the last line of
* scripts/platform-deploy.sh (red checks of main, the image build, the migration, a rollback).
* 26.11.2026 the build failed at 23:40 and nobody heard: the lag watch above speaks two hours later.
* The superadmins hear at once — one message per version and reason (the cron repeats every 10 minutes).
*/
export async function alertDeployFailed(db: Db, sha: string, reason: string, log: (s: string) => void = () => {}): Promise<number> {
const commit = sha.slice(0, 7);
const why = reason.replace(/\s+/g, " ").trim().slice(0, 300) || "?";
const kind = createHash("sha1").update(why.replace(/\d+/g, "#")).digest("hex").slice(0, 8);
// glossary-ignore: сообщение читает администратор платформы
const text = m("⚠️ Автовыкатка {commit} не прошла: {reason}. Прод остался на прежней версии.", { commit, reason: asIs(why) });
return alertAdmins(db, `deploy-failed:${commit}:${kind}`, text, log);
}