peppa/packages/runner/src/deploy.ts
2026-11-16 23:13:34 +05:00

364 lines
21 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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 { asIs, m } from "@peppa/shared/i18n";
import { clearPlatformDelay, getPlatformDelay, platformDelay, taskForCheck, answerQuestion, askPmProject, deleteSetting, getPublishMode, getSetting, setSetting, resolveTask, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question, platformFailure, isProjectPaused } from "@peppa/core";
import { projects, questions, releases, settings, 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 = m("🚀 Показать всем");
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 = m("(неактуально: в версии для проверки появились новые изменения)")) {
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,
// PEP-112: the product's own output may print a key — never keep it readable.
logTail: r.logTail ? (await projectSecretMasker(db, project.id))(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!);
// PEP-112: the product agent looks at what was deployed (not at Peppa itself).
if (rel!.status === "healthy" && !isPlatform(project)) await queueProductReview(db, project.id, rel!);
return rel!;
}
async function notifyRelease(db: Db, project: Project, rel: Release) {
if (rel.status === "healthy") {
// PEP-150: a healthy version of the same environment ends the delay of a failed one.
const ref = rel.env === "preview" ? await taskForCheck(db, project, null, rel.prNumber).catch(() => null) : null;
const scope = { projectId: project.id, taskId: ref?.task.id ?? null };
if (ref || (await getPlatformDelay(db, scope, "deploy"))?.state.startsWith(`${rel.env}:`)) await clearPlatformDelay(db, scope, "deploy");
}
const tasks = rel.tasks.join(", ");
const v = { project: asIs(project.name), sha: short(rel.sha), tasks };
const log = runLink(rel.runUrl);
if (rel.status === "rolled_back" || rel.status === "failed") {
const head =
rel.status === "rolled_back"
? m("❌ {project}: обновление {sha} ({env}) не прошло проверку — возвращена прежняя версия {prev}.", { ...v, env: rel.env, prev: short(rel.previousSha) })
: m("❌ {project}: обновление {sha} ({env}) не прошло проверку.", { ...v, env: rel.env });
// PEP-150: a failed update is not the owner's to fix — the superadmin gets one message per
// failed version; the story of a preview shows the delay line until a healthy one comes.
const ref = rel.env === "preview" ? await taskForCheck(db, project, null, rel.prNumber).catch(() => null) : null;
await platformDelay(db, { projectId: project.id, taskId: ref?.task.id ?? null }, {
reason: "deploy",
state: `${rel.env}:${rel.sha}`,
exhausted: true,
details: `${head}\n${m("Причина: {reason}", { reason: rel.reason ? asIs(rel.reason) : m("неизвестна") })}${log ? `\n${m("Подробности: {url}", { url: log })}` : ""}`,
});
} else if (rel.status === "healthy" && rel.env !== "preview" && rel.previousSha === rel.sha) {
// PEP-112: the same version started again (the project's secrets changed) — not a new one.
const open = await openNeeds(db, project.id);
await askPmProject(db, project, {
kind: "attention",
text: `${rel.env === "prod" ? m("🔑 {project}: ваш продукт перезапущен с новыми настройками", v) : m("🔑 {project}: версия для проверки перезапущена с новыми настройками", v)}${rel.host ? `\n${m("Открыть: {url}", { url: `https://${rel.host}` })}` : ""}${open.length ? `\n${m("Ещё работает в демо-режиме, нужно: {needs}", { needs: needsLine(open, asIs) })}` : ""}`,
});
} else if (rel.status === "healthy" && rel.env === "staging") {
await expireProdOffers(db, project.id);
// PEP-145: «Показывать всем: сам» — the version goes to everyone without a question.
if (await autoPublish(db, project).catch(() => false)) return;
await askPmProject(db, project, {
kind: "question",
options: [PROD_OPTION],
// PEP-111: said for a product manager — what it is, where to look, what the button does.
text: [
rel.tasks.length ? m("✅ {project}: новая версия готова к проверке · задачи: {tasks}", v) : m("✅ {project}: новая версия готова к проверке", v),
...(rel.host ? [m("Посмотреть: {url}", { url: `https://${rel.host}` })] : []),
m("Это версия только для вас. Показать её всем пользователям?"),
].join("\n"),
});
} else if (rel.status === "healthy" && rel.env === "prod") {
const storiesIn = rel.tasks.length ? ` · ${m("задачи: {tasks}", v)}` : "";
await askPmProject(db, project, {
kind: "attention",
text: `${m("🚀 {project}: ваш продукт обновлён и открыт для всех", v)}${rel.host ? `\n${m("Открыть: {url}", { url: `https://${rel.host}` })}` : ""}${storiesIn}\n${m("Что дальше: опишите следующую задачу аналитику в чате проекта — {url}", { url: `${process.env.PEPPA_WEB_URL ?? ""}/chats/${project.key}` })}`,
});
}
}
/**
* "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(m("{project}: в версии для проверки нет работающих изменений — показывать нечего", { project: project.key }));
const [running] = await db
.select()
.from(releases)
.where(and(eq(releases.projectId, project.id), eq(releases.env, "prod"), eq(releases.status, "deploying")))
.limit(1);
// PEP-146: a second press of «Показать всем» while the update is on its way is not an error —
// the person gets the update that is already running.
if (running) return running;
// 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!;
}
const publishedKey = (projectId: number) => `product.published:${projectId}`;
/** A failed automatic start is tried again not sooner than this. */
const AUTO_PUBLISH_RETRY_MS = 10 * 60_000;
/**
* PEP-145: «Показывать всем: сам». The healthy version to check, newer than the working one and
* with every story accepted, becomes the working version without anyone pressing a button.
* Called when a staging deploy turns healthy and from the watchdog (stories accepted later).
* Returns true when the update of the working version was started.
*/
export async function autoPublish(db: Db, project: Project, o: { now?: Date; client?: GiteaClient; log?: (m: string) => void } = {}): Promise<boolean> {
if (isPlatform(project) || (await getPublishMode(db, project.id)) !== "auto") return false;
const { staging, prod } = await currentReleases(db, project.id);
if (!staging || prod?.sha === staging.sha) return false;
const now = (o.now ?? new Date()).getTime();
const tried = await getSetting<{ sha: string; at: number; ok: boolean }>(db, publishedKey(project.id));
if (tried?.sha === staging.sha && (tried.ok || now - tried.at < AUTO_PUBLISH_RETRY_MS)) return false;
const [running] = await db.select({ id: releases.id }).from(releases).where(and(eq(releases.projectId, project.id), eq(releases.env, "prod"), eq(releases.status, "deploying"))).limit(1);
if (running) return false;
// Every story that would reach everyone is accepted: this version and the ones skipped before it.
const since = await db
.select({ tasks: releases.tasks })
.from(releases)
.where(and(eq(releases.projectId, project.id), eq(releases.env, "staging"), eq(releases.status, "healthy"), prod ? sql`${releases.id} > ${prod.id}` : undefined));
for (const key of new Set([...since.flatMap((r) => r.tasks), ...staging.tasks])) {
const ref = await resolveTask(db, key, project.key).catch(() => null);
if (ref && ref.project.id === project.id && ref.task.status !== "done" && !ref.task.archivedAt) return false;
}
try {
await deployProd(db, project, "Peppa FACTORY", o.client);
} catch (e) {
await setSetting(db, publishedKey(project.id), { sha: staging.sha, at: now, ok: false });
o.log?.(`auto publish ${project.key}: ${(e as Error).message}`);
return false;
}
await setSetting(db, publishedKey(project.id), { sha: staging.sha, at: now, ok: true });
await expireProdOffers(db, project.id, m("(неактуально: Peppa FACTORY сама показывает эту версию всем)"));
await logEvent(db, { projectId: project.id, type: "product_auto_published", payload: { sha: staging.sha, tasks: staging.tasks } });
o.log?.(`auto publish ${project.key}: ${staging.sha.slice(0, 7)}`);
return true;
}
const REDEPLOY_PREFIX = "product.redeploy:";
/**
* PEP-112: the project's secrets changed → its deployed versions start again with the new
* environment. Peppa tags the commit each healthy version runs (`deploy-prod-*` /
* `deploy-staging-*`), the project's workflow redeploys it; the image is already built. Waits
* for a quiet spell so a series of edits makes one restart. Returns the tags it created.
*/
export async function productRedeployTick(db: Db, o: { now?: Date; client?: GiteaClient; log?: (m: string) => void } = {}): Promise<string[]> {
if (process.env.PEPPA_SECRETS_REDEPLOY === "off") return [];
const now = (o.now ?? new Date()).getTime();
const quietMs = Math.max(0, Number(process.env.PEPPA_SECRETS_REDEPLOY_DELAY_SEC ?? 120)) * 1000;
const created: string[] = [];
const rows = await db.select().from(settings).where(sql`${settings.key} like ${`${REDEPLOY_PREFIX}%`}`);
for (const row of rows) {
const at = (row.value as { at?: number } | null)?.at ?? 0;
if (now - at < quietMs) continue;
// PEP-174: the restart waits for «Продолжить».
if (await isProjectPaused(db, Number(row.key.slice(REDEPLOY_PREFIX.length)))) continue;
await deleteSetting(db, row.key);
const [project] = await db.select().from(projects).where(eq(projects.id, Number(row.key.slice(REDEPLOY_PREFIX.length))));
if (!project || isPlatform(project)) continue;
const current = await currentReleases(db, project.id);
const stamp = new Date(now).toISOString().replace(/\D/g, "").slice(0, 17);
const tags: string[] = [];
for (const env of ["staging", "prod"] as const) {
const rel = current[env];
if (!rel) continue;
const [running] = await db.select({ id: releases.id }).from(releases).where(and(eq(releases.projectId, project.id), eq(releases.env, env), eq(releases.status, "deploying"))).limit(1);
if (running) continue; // that deploy picks the new secrets up itself
const tag = `deploy-${env}-${stamp}`;
try {
await (o.client ?? giteaForBot()).createTag(project.giteaOwner, project.giteaRepo, tag, rel.sha, "Перезапуск: изменились секреты проекта");
tags.push(tag);
} catch (e) {
o.log?.(`secrets redeploy ${project.key} ${env}: ${(e as Error).message}`);
}
}
if (tags.length) {
await markSecretsRestart(db, project.id, now);
await logEvent(db, { projectId: project.id, type: "secrets_redeploy", payload: { tags } });
created.push(...tags);
}
}
return created;
}
/** Local PNG files of a release's screenshots (PEP-112: the product agent reads them). */
export function releaseScreenshotFiles(rel: Pick<Release, "projectId" | "screenshots">): string[] {
return rel.screenshots.filter((s) => /^r\d+-\d+\.png$/.test(s.file)).map((s) => join(screenshotDir(rel.projectId), s.file));
}
/** 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) {
const text = m("Обновление рабочей версии не запущено: {error}", { error: (e as Error).message });
// A condition the owner understands is the answer to their own press; an error of the
// platform is not theirs (PEP-150): the superadmin and Bugsink.
if (e instanceof PeppaError) await askPmProject(db, project, { kind: "attention", text });
else await platformDelay(db, { projectId: project.id }, { reason: "deploy", state: `prod-start:${Date.now()}`, exhausted: true, details: `${project.key}: ${text}`, error: e, ttlMin: 24 * 60 });
}
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;
}
}