// glossary-ignore-file: обновление самой Peppa FACTORY ведёт суперадмин // Prod of Peppa itself (PEP-18). Peppa runs from ~/peppa/current, a release directory apart // from the development checkout. A release can't go through a CI job (a container can't // `launchctl`), so the PM's button queues a request on this host and the launchd agent // quest.telecom.peppa.release runs scripts/peppa-release.sh, which reports back through // `peppa release report` → recordRelease (same releases table and PM messages as projects). import { asIs, m } from "@peppa/shared/i18n"; import { askPmProject, configuredChecks, getProject, getSetting, setSetting, summarizeChecks, PeppaError, type Project } from "@peppa/core"; import { checkRuns, releases, type Db } from "@peppa/db"; import { peppaHome } from "@peppa/shared"; import { and, desc, eq } from "drizzle-orm"; import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { currentReleases, expireProdOffers, PROD_OPTION, type Release } from "./deploy.ts"; /** A `deploying` row older than this means the release script died without a report. */ const STALE_MS = 3600_000; /** Key of the project that is Peppa itself. */ export const platformKey = () => process.env.PEPPA_PLATFORM_KEY || "PEP"; export const isPlatform = (project: Project) => project.key === platformKey(); /** Where the PM's button leaves requests for the host listener. */ export const releaseQueueDir = () => process.env.PEPPA_RELEASE_QUEUE || join(peppaHome(), "release-queue"); export interface ReleaseRequest { releaseId: number; sha: string; by: string; } function projectChecks(project: Project): string[] { const f = join(project.workspacePath, ".peppa/project.json"); return configuredChecks(existsSync(f) ? readFileSync(f, "utf8") : null); } /** The commit of main with all configured checks green, newest first; null if none. */ async function greenMainSha(db: Db, project: Project, sha?: string): Promise { const configured = projectChecks(project); if (!configured.length) return null; const runs = await db .select() .from(checkRuns) .where(and(eq(checkRuns.projectId, project.id), eq(checkRuns.branch, "main"), sha ? eq(checkRuns.sha, sha) : undefined)) .orderBy(desc(checkRuns.updatedAt)); // Newest commit first: the order its runs were last updated in. const shas = [...new Set(runs.map((r) => r.sha))]; for (const s of shas) { if (summarizeChecks(configured, runs.filter((r) => r.sha === s), s).state === "success") return s; } return null; } /** What the PM's button would release now: the newest green main commit. */ export const platformReleaseCandidate = (db: Db, project: Project) => greenMainSha(db, project); const short = (sha: string | null | undefined) => (sha ? sha.slice(0, 7) : "—"); const OFFERS = "platform.release_offers"; /** * Whether Peppa offers "deploy to prod" after a green main (and shows the button). Off before the * official launch: Peppa then runs as `next dev` from the working copy and there is no prod yet. */ export async function platformReleaseOffers(db: Db): Promise { return (await getSetting(db, OFFERS)) ?? true; } export async function setPlatformReleaseOffers(db: Db, on: boolean): Promise { await setSetting(db, OFFERS, on); if (!on) await expireProdOffers(db, (await getProject(db, platformKey())).id, m("(выкатка в прод выключена до запуска)")); } /** A green report of main: offer the PM to release that commit (once per commit). */ export async function offerPlatformRelease(db: Db, project: Project, sha: string): Promise { if (!isPlatform(project) || !(await platformReleaseOffers(db)) || (await greenMainSha(db, project, sha)) !== sha) return false; const { prod } = await currentReleases(db, project.id); if (prod?.sha === sha) return false; await expireProdOffers(db, project.id); await askPmProject(db, project, { kind: "question", options: [PROD_OPTION], text: m("✅ {project}: main зелёный — {sha}. Выкатить в прод?", { project: asIs(project.name), sha: short(sha) }), }); return true; } /** "Deploy to prod" for Peppa: the newest green main commit goes to the host listener's queue. */ export async function deployPlatform(db: Db, project: Project, by: string, o: { now?: Date } = {}): Promise { const now = o.now ?? new Date(); const [running] = await db .select() .from(releases) .where(and(eq(releases.projectId, project.id), eq(releases.env, "prod"), eq(releases.status, "deploying"))) .orderBy(desc(releases.id)) .limit(1); if (running && now.getTime() - running.createdAt.getTime() < STALE_MS) throw new PeppaError(m("{project}: прод уже выкатывается ({sha})", { project: project.key, sha: short(running.sha) })); if (running) await db.update(releases).set({ status: "failed", reason: m("скрипт релиза не ответил за час") }).where(eq(releases.id, running.id)); const sha = await greenMainSha(db, project); if (!sha) throw new PeppaError(m("{project}: main без зелёных проверок — выкатывать нечего", { project: project.key })); const { prod } = await currentReleases(db, project.id); if (prod?.sha === sha) throw new PeppaError(m("{project}: {sha} уже в проде", { project: project.key, sha: short(sha) })); const [rel] = await db .insert(releases) .values({ projectId: project.id, env: "prod", sha, previousSha: prod?.sha ?? null, status: "deploying", deployedBy: by }) .returning(); const dir = releaseQueueDir(); mkdirSync(dir, { recursive: true, mode: 0o700 }); const req: ReleaseRequest = { releaseId: rel!.id, sha, by }; // Written beside the queue and renamed in: launchd starts the listener on any file there. const tmp = `${dir}.${rel!.id}.tmp`; writeFileSync(tmp, JSON.stringify(req)); renameSync(tmp, join(dir, `${rel!.id}.json`)); return rel!; }