В образе платформы нет рабочей копии 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>
115 lines
5.6 KiB
TypeScript
115 lines
5.6 KiB
TypeScript
// PEP-278: «Готово» only when the changes work. An accepted story (status `done`) whose result is
|
|
// in the project's code waits for the version that carries it: the mark `rollout.wait:<taskId>`
|
|
// sits on top of `done` (the status itself stays — everything that reads `done` works as before),
|
|
// screens say «Принято, ждёт обновления», and the watchdog (runner/rollout.ts) lifts the mark
|
|
// once the merge commit runs — the platform: it is in the live web's commit (`/api/health`);
|
|
// a project: a healthy staging or prod version has the story or the commit.
|
|
import { execFileSync } from "node:child_process";
|
|
import { dirname, join } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { keyPrefix, releases, settings, type Db } from "@peppa/db";
|
|
import { m } from "@peppa/shared/i18n";
|
|
import { and, eq, gte, inArray } from "drizzle-orm";
|
|
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
|
|
|
export interface RolloutWait {
|
|
/** When the story became done (ms). */
|
|
at: number;
|
|
/** The story's key («PEP-7»): release task lists carry keys. */
|
|
key: string;
|
|
/** Commit that brought the story into the main branch; null until the watchdog has asked Gitea. */
|
|
sha?: string | null;
|
|
/** PEP-305: when that commit was made (ms) — how deep the watchdog looks for it under the live commit. */
|
|
shaAt?: number | null;
|
|
}
|
|
|
|
const PREFIX = "rollout.wait:";
|
|
const waitKey = (taskId: number) => `${PREFIX}${taskId}`;
|
|
|
|
/** What the owner sees on an accepted story that does not work yet. */
|
|
export const ROLLOUT_LABEL = m("Принято, ждёт обновления");
|
|
|
|
const platformKey = () => process.env.PEPPA_PLATFORM_KEY || "PEP";
|
|
|
|
export const getRolloutWait = (db: Db, taskId: number) => getSetting<RolloutWait>(db, waitKey(taskId));
|
|
export const setRolloutWait = (db: Db, taskId: number, w: RolloutWait) => setSetting(db, waitKey(taskId), w);
|
|
export const clearRolloutWait = (db: Db, taskId: number) => deleteSetting(db, waitKey(taskId));
|
|
|
|
/** All waiting stories: task id → wait. */
|
|
export async function listRolloutWaits(db: Db): Promise<Map<number, RolloutWait>> {
|
|
const rows = await db.select().from(settings).where(keyPrefix(settings.key, PREFIX));
|
|
return new Map(rows.map((r) => [Number(r.key.slice(PREFIX.length)), r.value as RolloutWait]));
|
|
}
|
|
|
|
/** Ids of the stories (of `ids`, or all) that are accepted but do not work yet. */
|
|
export async function awaitingRollout(db: Db, ids?: number[]): Promise<Set<number>> {
|
|
const all = await listRolloutWaits(db);
|
|
return new Set(ids ? ids.filter((id) => all.has(id)) : all.keys());
|
|
}
|
|
|
|
/**
|
|
* Are the project's changes rolled out at all? The platform — always; a project — once it has had a
|
|
* healthy staging or prod version. A project without one has nothing to wait for: done is done.
|
|
*/
|
|
export async function rolloutTracked(db: Db, project: { id: number; key: string }): Promise<boolean> {
|
|
if (project.key === platformKey()) return true;
|
|
const [r] = await db
|
|
.select({ id: releases.id })
|
|
.from(releases)
|
|
.where(and(eq(releases.projectId, project.id), inArray(releases.env, ["staging", "prod"]), eq(releases.status, "healthy")))
|
|
.limit(1);
|
|
return !!r;
|
|
}
|
|
|
|
/**
|
|
* Is `commit` in `live` (equal or an ancestor) by the git checkout `root`? null — git cannot tell:
|
|
* `root` is not a checkout (the platform image has none, PEP-305) or does not know the commits.
|
|
*/
|
|
export function commitIn(root: string, commit: string, live: string): boolean | null {
|
|
if (commit === live) return true;
|
|
try {
|
|
execFileSync("git", ["merge-base", "--is-ancestor", commit, live], { cwd: root, stdio: "ignore" });
|
|
return true;
|
|
} catch (e) {
|
|
// Exit code 1 is git's «not an ancestor»; anything else (128: no repository, unknown commit) is no answer.
|
|
return (e as { status?: number | null }).status === 1 ? false : null;
|
|
}
|
|
}
|
|
|
|
// A version reported a little before the accept may carry the story (merged by hand, webhook late).
|
|
const EARLY_MS = 6 * 3600_000;
|
|
|
|
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../..");
|
|
export const platformRoot = () => process.env.PEPPA_ROOT || ROOT;
|
|
|
|
/** Commit the live web runs (its heartbeat; the same commit `/api/health` reports). */
|
|
export async function liveWebCommit(db: Db): Promise<string | null> {
|
|
const hb = await getSetting<{ commit?: string | null }>(db, "heartbeat:web");
|
|
return hb?.commit || null;
|
|
}
|
|
|
|
/**
|
|
* Does the waiting story work now? A healthy staging/prod version created after the accept carries
|
|
* its key or its commit; for the platform also — the live web's commit contains the merge commit.
|
|
* Returns where it works («live», «staging», «prod») or null.
|
|
* `inLive` answers «is this commit in the live one?» when the local git cannot (PEP-305): the
|
|
* watchdog asks Gitea. Without it an unknown answer counts as «not yet».
|
|
*/
|
|
export async function rolledOutWhere(
|
|
db: Db,
|
|
project: { id: number; key: string },
|
|
w: RolloutWait,
|
|
o: { root?: string; inLive?: (commit: string, live: string) => Promise<boolean> } = {},
|
|
): Promise<string | null> {
|
|
const rows = await db
|
|
.select({ env: releases.env, sha: releases.sha, tasks: releases.tasks })
|
|
.from(releases)
|
|
.where(and(eq(releases.projectId, project.id), inArray(releases.env, ["staging", "prod"]), eq(releases.status, "healthy"), gte(releases.createdAt, new Date(w.at - EARLY_MS))));
|
|
for (const r of rows) if ((r.tasks ?? []).includes(w.key) || (w.sha && r.sha === w.sha)) return r.env;
|
|
if (project.key === platformKey() && w.sha) {
|
|
const live = await liveWebCommit(db);
|
|
if (live && (commitIn(o.root ?? platformRoot(), w.sha, live) ?? (await o.inLive?.(w.sha, live)) ?? false)) return "live";
|
|
}
|
|
return null;
|
|
}
|