peppa/packages/runner/src/deploy-lag.ts
peppa-bot 546027bb4e
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 34с
peppa/test test: success за 1471с
peppa-ci / ci (pull_request) Successful in 29m20s
PEP-277: сторож «прод отстаёт от main» — сообщение суперадминам
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:40:49 +00:00

126 lines
6.0 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-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 { 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 };
}