peppa/packages/runner/src/rollout.ts
peppa-bot 70de049164
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 56с
peppa/build build: success за 38с
peppa/test test: success за 1772с
peppa-ci / ci (pull_request) Successful in 32m15s
PEP-305: «Принято, ждёт обновления» снимается, когда одна версия несёт несколько задач
В образе платформы нет рабочей копии git: `git merge-base --is-ancestor` падал, ошибка читалась
как «коммит не входит», и «Готово» получала только задача, чей коммит слияния совпал с коммитом
живого веба. 26.11 версия 1dc99c5b принесла PEP-301 и PEP-268 — PEP-301 осталась ждать навсегда.

- core/rollout.ts: `commitIn` различает «не предок» (false) и «git не знает» (null);
  `rolledOutWhere` при «не знает» спрашивает вызывающего (`inLive`).
- runner/rollout.ts: `liveCarries` — коммиты, достижимые из коммита живого веба, у Gitea
  (`commits?sha=`, страницами); список одного коммита веба читается один раз и только до времени
  самого коммита задачи (`rollout.wait.shaAt`). Gitea не отвечает — следующий проход.
- GiteaClient.listCommits: страница; мок Gitea: страницы, предел 50, время коммита.
- Тесты: каталог без git, две задачи одной версией — обе «Готово» (падал до исправления);
  ответы git «не предок» / «неизвестно».

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

130 lines
5.3 KiB
TypeScript

// PEP-278: accepted stories wait for the version that carries them (core/rollout.ts). Once a minute
// the watchdog learns each waiting story's merge commit from Gitea and lifts the mark when that
// commit runs — the story is «Готово» for real, one line goes to its chat thread.
import {
clearRolloutWait,
giteaForBot,
listRolloutWaits,
logEvent,
notify,
rolledOutWhere,
setRolloutWait,
taskPrNumber,
type GiteaClient,
type GiteaCommit,
type RolloutWait,
} from "@peppa/core";
import { projects, tasks, type Db } from "@peppa/db";
import { eq } from "drizzle-orm";
/** The commit that brought the story into the main branch; null — not known (yet), "none" — nothing was merged. */
async function mergeCommit(gitea: GiteaClient, project: { giteaOwner: string; giteaRepo: string }, n: number): Promise<string | "none"> {
const pull = await gitea.getPullRequest(project.giteaOwner, project.giteaRepo, n);
if (pull.merged) return pull.merge_commit_sha || pull.head.sha;
// PEP-93: closed without a merge because all its commits were in the base already.
if (pull.state === "closed") return pull.head.sha;
return "none";
}
// PEP-305: the platform runs from an image without a git checkout, so «does the live commit carry
// this merge?» is asked of Gitea: the commits reachable from the live one, newest first, by pages.
const PAGE = 50; // the largest page Gitea gives
const MAX_PAGES = 40; // a safety net: the time bound below stops the reading long before
const SLACK_MS = 10 * 60_000; // clocks of the machines that made the commits
const WEEK_MS = 7 * 86_400_000;
interface Reach {
key: string;
shas: Set<string>;
/** The oldest commit time read so far (ms). */
oldest: number;
next: number;
end: boolean;
}
let reach: Reach | null = null;
const commitTime = (c: GiteaCommit) => Date.parse(c.created ?? c.commit.committer?.date ?? c.commit.author.date);
/**
* Is `commit` (made at `at`, ms) among the commits `live` carries? The list of one live commit is
* read once and kept; it is continued only while it has not gone below the commit's own time —
* a merge that is not rolled out yet costs one page, not the whole history.
*/
export async function liveCarries(gitea: GiteaClient, repo: { giteaOwner: string; giteaRepo: string }, live: string, commit: string, at: number): Promise<boolean> {
const key = `${repo.giteaOwner}/${repo.giteaRepo}@${live}`;
if (reach?.key !== key) reach = { key, shas: new Set(), oldest: Infinity, next: 1, end: false };
const r = reach;
while (!r.shas.has(commit) && !r.end && r.oldest >= at - SLACK_MS && r.next <= MAX_PAGES) {
const page = await gitea.listCommits(repo.giteaOwner, repo.giteaRepo, live, PAGE, r.next);
r.next++;
if (!page.length) r.end = true;
for (const c of page) {
r.shas.add(c.sha);
const t = commitTime(c);
if (t < r.oldest) r.oldest = t;
}
}
return r.shas.has(commit);
}
export async function rolloutTick(db: Db, o: { gitea?: GiteaClient; root?: string; log?: (m: string) => void } = {}): Promise<number> {
if (process.env.PEPPA_ROLLOUT === "off") return 0;
const waits = await listRolloutWaits(db);
let done = 0;
for (const [taskId, w0] of waits) {
let w: RolloutWait = w0;
const [task] = await db.select().from(tasks).where(eq(tasks.id, taskId));
// The story left «Готово» (or is archived, or gone): nothing to wait for.
if (!task || task.status !== "done" || task.archivedAt) {
await clearRolloutWait(db, taskId);
continue;
}
const [project] = await db.select().from(projects).where(eq(projects.id, task.projectId));
if (!project) continue;
if (!w.sha) {
const n = taskPrNumber(project, task.prUrl);
let sha: string | "none" | null = n ? null : "none";
if (n) {
try {
sha = await mergeCommit(o.gitea ?? giteaForBot(), project, n);
} catch {
continue; // Gitea is down — the next minute
}
}
if (sha === "none") {
// Moved to «Готово» by hand with an unmerged result: there is no commit to wait for.
await clearRolloutWait(db, taskId);
await notify(db, { type: "task_updated", taskId });
continue;
}
w = { ...w, sha };
await setRolloutWait(db, taskId, w);
}
const where = await rolledOutWhere(db, project, w, {
root: o.root,
inLive: async (commit, live) => {
try {
const gitea = o.gitea ?? giteaForBot();
if (w.shaAt == null) {
const [c] = await gitea.listCommits(project.giteaOwner, project.giteaRepo, commit, 1);
if (!c) return false;
const t = commitTime(c);
w = { ...w, shaAt: Number.isFinite(t) ? t : w.at - WEEK_MS };
await setRolloutWait(db, taskId, w);
}
return await liveCarries(gitea, project, live, commit, w.shaAt!);
} catch {
return false; // Gitea is down or does not know the commit — the next minute
}
},
});
if (!where) continue;
await clearRolloutWait(db, taskId);
await logEvent(db, { projectId: project.id, taskId, type: "task_rolled_out", payload: { env: where, sha: w.sha } });
await notify(db, { type: "task_updated", taskId });
o.log?.(`rollout: ${w.key} runs (${where}, ${w.sha?.slice(0, 7)})`);
done++;
}
return done;
}