peppa/packages/runner/src/deploy-lag.ts
peppa-bot ce03df667c
Some checks failed
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 55с
peppa/build build: success за 35с
peppa/test test: failure за 1720с
peppa-ci / ci (pull_request) Failing after 31m5s
PEP-272: /api/health анониму — только ok; без X-Powered-By, script-src в CSP, аватар по https
- /api/health без ключа X-Peppa-Health (HMAC от PEPPA_SECRET, принимается и PREVIOUS) отдаёт только {ok};
  ключ шлют сторож адреса, сторож отставания выкатки, healthcheck контейнеров, скрипты выкатки
- poweredByHeader: false; CSP: script-src 'self' 'unsafe-inline' (unsafe-eval только в dev), worker-src 'self'
- httpsAvatar: http → https при записи и показе
- тест health-anon.test.ts, change archived

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 20:36:06 +00:00

142 lines
7.2 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, healthHeaders, 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", ...healthHeaders() } });
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);
}