// 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(); 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 { 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>> { const out: Partial> = {}; 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 { 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-