227 lines
11 KiB
TypeScript
227 lines
11 KiB
TypeScript
// Deployments of factory projects (PEP-57). The project's deploy workflow does the work on
|
||
// the host (docker compose behind Traefik, health check, rollback) and reports each step
|
||
// here; Peppa keeps the releases, tells the PM, and starts prod by the PM's button — a
|
||
// `deploy-prod-*` tag at the healthy staging commit (Gitea 1.22 has no workflow_dispatch API).
|
||
import { answerQuestion, askPmProject, giteaForBot, PeppaError, runLink, type GiteaClient, type Project, type Question } from "@peppa/core";
|
||
import { projects, questions, releases, type Db } from "@peppa/db";
|
||
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
|
||
import { deployPlatform, isPlatform } from "./platform-release.ts";
|
||
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||
import { join } from "node:path";
|
||
import { peppaHome } from "@peppa/shared";
|
||
|
||
export type Release = typeof releases.$inferSelect;
|
||
export type ReleaseEnv = Release["env"];
|
||
export type ReleaseStatus = Release["status"];
|
||
|
||
/** The option of the "staging updated" message that sends the release to prod. */
|
||
export const PROD_OPTION = "🚀 Выкатить в прод";
|
||
|
||
export interface DeployReport {
|
||
env: ReleaseEnv;
|
||
sha: string;
|
||
previousSha?: string | null;
|
||
image?: string | null;
|
||
host?: string | null;
|
||
prNumber?: number | null;
|
||
status: ReleaseStatus;
|
||
reason?: string | null;
|
||
runUrl?: string | null;
|
||
commits?: string[];
|
||
logTail?: string | null;
|
||
}
|
||
|
||
/** Task keys of the project mentioned in commit subjects ("…from task/PAY-7 into main"). */
|
||
export function tasksInCommits(project: Project, commits: string[]): string[] {
|
||
const re = new RegExp(`\\b${project.key}-(\\d+)\\b`, "gi");
|
||
const out = new Set<string>();
|
||
for (const c of commits) for (const m of c.matchAll(re)) out.add(`${project.key}-${Number(m[1])}`);
|
||
return [...out].sort((a, b) => Number(a.split("-")[1]) - Number(b.split("-")[1]));
|
||
}
|
||
|
||
export async function listReleases(db: Db, projectId: number, limit = 20): Promise<Release[]> {
|
||
return db.select().from(releases).where(eq(releases.projectId, projectId)).orderBy(desc(releases.id)).limit(limit);
|
||
}
|
||
|
||
/** What runs in each environment now: the latest healthy (or rolled back to) release. */
|
||
export async function currentReleases(db: Db, projectId: number): Promise<Partial<Record<ReleaseEnv, Release>>> {
|
||
const out: Partial<Record<ReleaseEnv, Release>> = {};
|
||
for (const env of ["staging", "prod"] as const) {
|
||
const [r] = await db
|
||
.select()
|
||
.from(releases)
|
||
.where(and(eq(releases.projectId, projectId), eq(releases.env, env), eq(releases.status, "healthy")))
|
||
.orderBy(desc(releases.id))
|
||
.limit(1);
|
||
if (r) out[env] = r;
|
||
}
|
||
return out;
|
||
}
|
||
|
||
const short = (sha: string | null | undefined) => (sha ? sha.slice(0, 7) : "—");
|
||
|
||
/** Closes earlier unanswered "deploy to prod?" offers of the project: a newer staging is up. */
|
||
export async function expireProdOffers(db: Db, projectId: number, reason = "(неактуально: на staging новый релиз)") {
|
||
const open = await db
|
||
.select()
|
||
.from(questions)
|
||
.where(and(eq(questions.projectId, projectId), isNull(questions.taskId), isNull(questions.answeredAt), sql`exists (select 1 from json_each(${questions.options}) where value = ${PROD_OPTION})`));
|
||
for (const q of open) await answerQuestion(db, q.id, reason, "system").catch(() => {});
|
||
}
|
||
|
||
/** Records one step of a deploy and tells the PM what they need to know. */
|
||
export async function recordRelease(db: Db, project: Project, r: DeployReport): Promise<Release> {
|
||
const sameRun = and(
|
||
eq(releases.projectId, project.id),
|
||
eq(releases.env, r.env),
|
||
eq(releases.sha, r.sha),
|
||
eq(releases.status, "deploying"),
|
||
r.env === "preview" && r.prNumber ? eq(releases.prNumber, r.prNumber) : undefined,
|
||
);
|
||
const [open] = await db.select().from(releases).where(sameRun).orderBy(desc(releases.id)).limit(1);
|
||
const fromCommits = tasksInCommits(project, r.commits ?? []);
|
||
const values = {
|
||
previousSha: r.previousSha ?? open?.previousSha ?? null,
|
||
image: r.image ?? open?.image ?? null,
|
||
host: r.host ?? open?.host ?? null,
|
||
prNumber: r.prNumber ?? open?.prNumber ?? null,
|
||
tasks: open?.tasks.length ? open.tasks : fromCommits,
|
||
status: r.status,
|
||
reason: r.reason ?? null,
|
||
runUrl: r.runUrl ?? open?.runUrl ?? null,
|
||
logTail: r.logTail ?? open?.logTail ?? null,
|
||
};
|
||
let rel: Release;
|
||
if (r.status === "removed") {
|
||
// Preview torn down: every release of that PR's stand is gone.
|
||
await db
|
||
.update(releases)
|
||
.set({ status: "removed" })
|
||
.where(and(eq(releases.projectId, project.id), eq(releases.env, "preview"), eq(releases.prNumber, r.prNumber ?? -1), inArray(releases.status, ["deploying", "healthy"])));
|
||
[rel] = await db.select().from(releases).where(and(eq(releases.projectId, project.id), eq(releases.env, "preview"), eq(releases.prNumber, r.prNumber ?? -1))).orderBy(desc(releases.id)).limit(1);
|
||
if (rel!) return rel;
|
||
}
|
||
[rel] = open
|
||
? await db.update(releases).set(values).where(eq(releases.id, open.id)).returning()
|
||
: await db.insert(releases).values({ projectId: project.id, env: r.env, sha: r.sha, ...values }).returning();
|
||
await notifyRelease(db, project, rel!);
|
||
return rel!;
|
||
}
|
||
|
||
async function notifyRelease(db: Db, project: Project, rel: Release) {
|
||
const tasks = rel.tasks.length ? ` · стори: ${rel.tasks.join(", ")}` : "";
|
||
const log = runLink(rel.runUrl);
|
||
if (rel.status === "rolled_back" || rel.status === "failed") {
|
||
const back = rel.status === "rolled_back" ? ` — возвращён ${short(rel.previousSha)}` : "";
|
||
await askPmProject(db, project, {
|
||
kind: "attention",
|
||
text: `❌ ${project.name}: релиз ${short(rel.sha)} в ${rel.env} не прошёл${back}.\nПричина: ${rel.reason ?? "неизвестна"}${log ? `\nЛог: ${log}` : ""}`,
|
||
});
|
||
} else if (rel.status === "healthy" && rel.env === "staging") {
|
||
await expireProdOffers(db, project.id);
|
||
await askPmProject(db, project, {
|
||
kind: "question",
|
||
options: [PROD_OPTION],
|
||
text: `✅ ${project.name}: staging обновлён — ${short(rel.sha)}${tasks}${rel.host ? `\nhttps://${rel.host}` : ""}\nВыкатить этот релиз в прод?`,
|
||
});
|
||
} else if (rel.status === "healthy" && rel.env === "prod") {
|
||
await askPmProject(db, project, { kind: "attention", text: `🚀 ${project.name} в проде: ${short(rel.sha)}${tasks}${rel.host ? `\nhttps://${rel.host}` : ""}` });
|
||
}
|
||
}
|
||
|
||
/**
|
||
* "Deploy to prod" (web, Telegram, MCP): the image of the latest healthy staging release
|
||
* goes to prod — Peppa tags that commit `deploy-prod-<time>` and the workflow deploys it.
|
||
* Peppa itself has no staging: its green main goes to the host listener (PEP-18).
|
||
*/
|
||
export async function deployProd(db: Db, project: Project, by: string, client?: GiteaClient): Promise<Release> {
|
||
if (isPlatform(project)) return deployPlatform(db, project, by);
|
||
const gitea = client ?? giteaForBot();
|
||
const { staging, prod } = await currentReleases(db, project.id);
|
||
if (!staging) throw new PeppaError(`${project.key}: на staging нет здорового релиза — выкатывать нечего`);
|
||
const [running] = await db
|
||
.select()
|
||
.from(releases)
|
||
.where(and(eq(releases.projectId, project.id), eq(releases.env, "prod"), eq(releases.status, "deploying")))
|
||
.limit(1);
|
||
if (running) throw new PeppaError(`${project.key}: прод уже выкатывается (${short(running.sha)})`);
|
||
// Tasks since the last prod release: every healthy staging release after it.
|
||
const since = await db
|
||
.select()
|
||
.from(releases)
|
||
.where(and(eq(releases.projectId, project.id), eq(releases.env, "staging"), eq(releases.status, "healthy"), prod ? sql`${releases.id} > ${prod.id}` : undefined));
|
||
const taskKeys = [...new Set([...since.flatMap((r) => r.tasks), ...staging.tasks])].sort();
|
||
const tag = `deploy-prod-${new Date().toISOString().replace(/\D/g, "").slice(0, 17)}`;
|
||
await gitea.createTag(project.giteaOwner, project.giteaRepo, tag, staging.sha, `Прод по кнопке: ${by}`);
|
||
const [rel] = await db
|
||
.insert(releases)
|
||
.values({ projectId: project.id, env: "prod", sha: staging.sha, previousSha: prod?.sha ?? null, image: staging.image, tasks: taskKeys, status: "deploying", deployedBy: by })
|
||
.returning();
|
||
return rel!;
|
||
}
|
||
|
||
/** The PM pressed "deploy to prod" on a "staging updated" message (any channel). */
|
||
export async function onReleaseAnswer(db: Db, q: Question, answer: string, by: string): Promise<boolean> {
|
||
if (q.taskId || q.sessionId || !(q.options ?? []).includes(PROD_OPTION) || answer.trim() !== PROD_OPTION) return false;
|
||
const [project] = await db.select().from(projects).where(eq(projects.id, q.projectId));
|
||
if (!project) return false;
|
||
try {
|
||
await deployProd(db, project, by);
|
||
} catch (e) {
|
||
await askPmProject(db, project, { kind: "attention", text: `Прод не запущен: ${(e as Error).message}` });
|
||
}
|
||
return true;
|
||
}
|
||
|
||
/** PEP-44: limits for screenshots sent by the CI step. */
|
||
export const MAX_SCREENSHOTS = 6;
|
||
export const MAX_SCREENSHOT_BYTES = 3 * 1024 * 1024;
|
||
const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||
|
||
export interface ScreenshotReport {
|
||
sha: string;
|
||
prNumber: number | null;
|
||
shots: Array<{ path: string; png: string }>;
|
||
}
|
||
|
||
const screenshotDir = (projectId: number) => join(peppaHome(), "screenshots", String(projectId));
|
||
|
||
/**
|
||
* Screenshots of a preview stand (CI step after a healthy preview): PNG files under
|
||
* $PEPPA_HOME/screenshots/<project>/, listed on the preview release of that PR and commit.
|
||
* Not PNG, too big or too many → skipped. Returns how many were kept.
|
||
*/
|
||
export async function recordScreenshots(db: Db, project: Project, r: ScreenshotReport): Promise<{ release: number | null; saved: number }> {
|
||
const [rel] = await db
|
||
.select()
|
||
.from(releases)
|
||
.where(and(eq(releases.projectId, project.id), eq(releases.env, "preview"), eq(releases.sha, r.sha), r.prNumber ? eq(releases.prNumber, r.prNumber) : undefined))
|
||
.orderBy(desc(releases.id))
|
||
.limit(1);
|
||
if (!rel) return { release: null, saved: 0 };
|
||
const dir = screenshotDir(project.id);
|
||
mkdirSync(dir, { recursive: true });
|
||
const kept: Array<{ path: string; file: string }> = [];
|
||
for (const [i, s] of r.shots.slice(0, MAX_SCREENSHOTS).entries()) {
|
||
const buf = Buffer.from(s.png ?? "", "base64");
|
||
if (buf.length < PNG_MAGIC.length || buf.length > MAX_SCREENSHOT_BYTES || !buf.subarray(0, 8).equals(PNG_MAGIC)) continue;
|
||
const file = `r${rel.id}-${i}.png`;
|
||
writeFileSync(join(dir, file), buf);
|
||
kept.push({ path: String(s.path ?? "/").slice(0, 200), file });
|
||
}
|
||
await db.update(releases).set({ screenshots: kept }).where(eq(releases.id, rel.id));
|
||
return { release: rel.id, saved: kept.length };
|
||
}
|
||
|
||
/** PNG bytes of screenshot `n` of a release (null when absent). Access is checked by the caller. */
|
||
export async function releaseScreenshot(db: Db, releaseId: number, n: number): Promise<{ projectId: number; png: Buffer } | null> {
|
||
const [rel] = await db.select().from(releases).where(eq(releases.id, releaseId));
|
||
const s = rel?.screenshots[n];
|
||
if (!rel || !s || !/^r\d+-\d+\.png$/.test(s.file)) return null;
|
||
try {
|
||
return { projectId: rel.projectId, png: readFileSync(join(screenshotDir(rel.projectId), s.file)) };
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|