peppa/packages/runner/src/platform-build.ts
peppa-bot e2b06b5e80
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 52с
peppa/build build: success за 35с
peppa/test test: success за 1527с
peppa-ci / ci (pull_request) Successful in 27m32s
PEP-292: версия FORGE для канала — из коммита выкатки и истории main в Gitea, без git в контейнере
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:16:00 +00:00

100 lines
4.7 KiB
TypeScript

// New builds of FORGE (PEP-60). The watchdog checks the commit it runs about once a minute; a
// commit that differs from the last announced one and belongs to `main` is a release: posted to
// the platform channel with the stories from the commit messages.
//
// PEP-292: the platform runs from a Docker image without `.git` (PEP-230), so `git` is not called
// there. The commit is what the deploy built the image from (`PEPPA_COMMIT`, the full SHA behind
// `$PEPPA_HOME/platform.tag`); "is it on main" and the stories of the release come from the
// history of the main branch in Gitea. `git rev-parse` is used only next to a real `.git` (a
// working copy on the Mac).
import { existsSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { announcePlatformBuild, getPlatformBuild, giteaForBot, headCommit, peppaVersion, platformProjectKey } from "@peppa/core";
import type { GiteaCommit } from "@peppa/core";
import type { Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../..");
const PAGE = 50;
const PAGES = 4;
const RETRY_MS = 10 * 60_000;
/** The commit this platform runs: the deploy's build-arg, else HEAD of a real checkout; null when unknown. */
export function deployedCommit(root: string, env = process.env.PEPPA_COMMIT): string | null {
const c = env?.trim();
if (c && c !== "unknown") return c;
return existsSync(join(root, ".git")) ? headCommit(root) : null;
}
/** Platform stories mentioned in commit messages, sorted by number. */
export function storiesIn(messages: string[], key = platformProjectKey()): string[] {
const re = new RegExp(`\\b${key}-(\\d+)\\b`, "gi");
const nums = new Set<number>();
for (const msg of messages) for (const m of msg.matchAll(re)) nums.add(Number(m[1]));
return [...nums].sort((a, b) => a - b).map((n) => `${key}-${n}`);
}
const same = (a: string, b: string) => a.length >= 7 && b.length >= 7 && (a.startsWith(b) || b.startsWith(a));
/**
* Where `commit` sits on main in Gitea: its full SHA and the commits from it down to `prev`
* (exclusive; the whole window when `prev` is older). null — not on main within the window.
*/
export async function mainHistory(commit: string, prev: string | null): Promise<{ sha: string; between: GiteaCommit[] } | null> {
const [owner, repo] = loadEnv().GITEA_PLATFORM_REPO.split("/") as [string, string];
const branch = process.env.PEPPA_MAIN_BRANCH || "main";
const gitea = giteaForBot();
const window: GiteaCommit[] = [];
let at = -1;
for (let page = 1; page <= PAGES; page++) {
const list = await gitea.listCommits(owner, repo, branch, PAGE, page);
window.push(...list);
if (at < 0) at = window.findIndex((c) => same(c.sha, commit));
if (at >= 0 && (!prev || window.slice(at).some((c) => same(c.sha, prev)))) break;
if (list.length < PAGE) break;
}
if (at < 0) return null;
const rest = window.slice(at);
const end = prev ? rest.findIndex((c) => same(c.sha, prev)) : -1;
return { sha: window[at]!.sha, between: end >= 0 ? rest.slice(0, end) : rest };
}
let lastCheck = 0;
/** Commit → when it may be asked about again (not on main, or Gitea failed). */
const skipUntil = new Map<string, number>();
/** Watchdog: announces a new build of FORGE once (first run only remembers it). */
export async function platformBuildTick(
db: Db,
o: { root?: string; commit?: string; now?: Date; force?: boolean; log?: (m: string) => void } = {},
): Promise<boolean> {
const nowMs = (o.now ?? new Date()).getTime();
if (!o.force && Math.abs(nowMs - lastCheck) < 60_000) return false;
lastCheck = nowMs;
const root = o.root ?? process.env.PEPPA_ROOT ?? ROOT;
const commit = o.commit ?? deployedCommit(root);
if (!commit) return false;
const prev = await getPlatformBuild(db);
if (prev && same(prev.commit, commit)) return false;
if (!o.force && (skipUntil.get(commit) ?? 0) > nowMs) return false;
let history: Awaited<ReturnType<typeof mainHistory>>;
try {
history = await mainHistory(commit, prev?.commit ?? null);
} catch (e) {
skipUntil.set(commit, nowMs + RETRY_MS);
o.log?.(`platform build ${commit.slice(0, 7)}: Gitea history unavailable (${(e as Error).message}), retry later`);
return false;
}
if (!history) {
skipUntil.set(commit, nowMs + RETRY_MS);
return false;
}
skipUntil.delete(commit);
const tasks = prev ? storiesIn(history.between.map((c) => c.commit.message)) : [];
const posted = await announcePlatformBuild(db, { version: peppaVersion(root), commit: history.sha, tasks }, { now: o.now });
o.log?.(`platform build ${history.sha.slice(0, 7)}${tasks.length ? ` (${tasks.join(", ")})` : ""}${posted ? " → channel" : ""}`);
return posted;
}