// PEP-145: the product of a project always opens by a link — the watchdog side. Per project // (not Peppa itself): the system story «Продукт должен открываться по ссылке» when accepted // stories have nowhere to be seen or the last update of the version to check did not come up; // «Показывать всем: сам» carried through when stories are accepted after the deploy; and the // one-time offer of that mode to projects created before it existed. import { m } from "@peppa/shared/i18n"; import { archivedLog, askPmProject, createTask, getProductLinkState, getPublishChoice, getSetting, listPlatformDelays, listProjects, logEvent, openProductLinkTask, productLinkDescription, PRODUCT_LINK_TITLE, PUBLISH_AUTO_OPTION, PUBLISH_BUTTON_OPTION, reorderTask, setIntakeState, setProductLinkState, setPublishMode, setSetting, type GiteaClient, type Project, type Question, pausedProjectIds, } from "@peppa/core"; import { projects, releases, tasks, type Db } from "@peppa/db"; import { and, desc, eq, isNull } from "drizzle-orm"; import { autoPublish, currentReleases } from "./deploy.ts"; import { isPlatform } from "./platform-release.ts"; import { onAnswer } from "./sessions.ts"; export interface ProductLinkTickOptions { now?: Date; log?: (m: string) => void; client?: GiteaClient; } /** A deploy that said «начато» and nothing since does not hold the story back for ever. */ const DEPLOYING_MS = 30 * 60_000; const minGapMs = () => Math.max(0, Number(process.env.PEPPA_PRODUCT_LINK_HOURS ?? 24)) * 3_600_000; const offeredKey = (projectId: number) => `product.publish.offered:${projectId}`; export async function productLinkTick(db: Db, o: ProductLinkTickOptions = {}): Promise { if (process.env.PEPPA_PRODUCT_LINK === "off") return; const log = o.log ?? (() => {}); const paused = await pausedProjectIds(db); for (const project of await listProjects(db)) { // PEP-174: no system story and no publishing while the project is on pause. if (isPlatform(project) || paused.has(project.id)) continue; try { await ensureProductLinkTask(db, project, o); await offerPublishMode(db, project); await autoPublish(db, project, o); } catch (e) { log(`product link ${project.key}: ${(e as Error).message}`); } } } /** * Files the system story when the project has accepted stories and no healthy version to check, * or the last finished update failed or was rolled back. One open story per project, not more * often than once a day. Returns the new story's key, or null. */ export async function ensureProductLinkTask(db: Db, project: Project, o: ProductLinkTickOptions = {}): Promise { const now = (o.now ?? new Date()).getTime(); if (await openProductLinkTask(db, project.id)) return null; // PEP-158: the failed version to check is with the agent of its story already. if ((await listPlatformDelays(db)).some((d) => d.projectId === project.id && d.taskId != null && d.reason === "deploy" && !d.exhausted && d.state.startsWith("staging:"))) return null; const state = await getProductLinkState(db, project.id); if (state && now - state.at < minGapMs()) return null; const recent = await db.select().from(releases).where(and(eq(releases.projectId, project.id), eq(releases.env, "staging"))).orderBy(desc(releases.id)).limit(10); // An update is on its way: its result decides. if (recent.some((r) => r.status === "deploying" && now - r.createdAt.getTime() < DEPLOYING_MS)) return null; const last = recent.find((r) => r.status !== "deploying" && r.status !== "removed"); const failed = last && (last.status === "failed" || last.status === "rolled_back") ? last : null; const done = await db.select({ id: tasks.id }).from(tasks).where(and(eq(tasks.projectId, project.id), eq(tasks.status, "done"), isNull(tasks.archivedAt))); const healthy = recent.some((r) => r.status === "healthy") || !!(await currentReleases(db, project.id)).staging; if (!failed && (healthy || done.length === 0)) return null; const description = productLinkDescription({ doneStories: done.length, failed: failed ? { status: failed.status, sha: failed.sha, reason: failed.reason, logTail: failed.logTail ?? archivedLog("releases", failed.id, failed.updatedAt), runUrl: failed.runUrl } : null }); const ref = await createTask(db, { projectId: project.id, title: PRODUCT_LINK_TITLE, description, origin: "acceptance", severity: "breakage" }); // Already formulated: «продакт» and «аналитик» of the intake skip it. await setIntakeState(db, ref.task.id, { stage: "done", original: { title: PRODUCT_LINK_TITLE, description }, attempts: 0, note: "заведена FORGE: продукт не открывается по ссылке" }); await reorderTask(db, ref, { to: "top" }); await setProductLinkState(db, project.id, { taskId: ref.task.id, at: now }); await logEvent(db, { projectId: project.id, taskId: ref.task.id, type: "product_link_task", payload: { key: ref.key, failed: failed ? { sha: failed.sha, status: failed.status, reason: failed.reason } : null, doneStories: done.length } }); o.log?.(`product link ${project.key}: filed ${ref.key}${failed ? ` (${failed.status} ${failed.sha.slice(0, 7)})` : " (no version to check)"}`); return ref.key; } /** * A project created before «Показывать всем» existed stays «по кнопке»; once it has a version * to check, its people get one message with two buttons. */ export async function offerPublishMode(db: Db, project: Project): Promise { if ((await getPublishChoice(db, project.id)) || (await getSetting(db, offeredKey(project.id)))) return false; if (!(await currentReleases(db, project.id)).staging) return false; const q = await askPmProject(db, project, { kind: "question", options: [PUBLISH_AUTO_OPTION, PUBLISH_BUTTON_OPTION], text: [ m("💡 {project}: показывать новые версии продукта всем пользователям сразу?", { project: project.name }), m("Сейчас новую версию сначала видите только вы, а всем она открывается по кнопке «Показать всем». Можно иначе: как только задачи приняты, FORGE сама обновляет продукт для всех."), m("Изменить выбор можно в настройках проекта."), ].join("\n"), }); await setSetting(db, offeredKey(project.id), { questionId: q.id, at: Date.now() }); return true; } /** The answer to the offer above (`onAnswer` registry). */ export async function onPublishAnswer(db: Db, q: Question, answer: string): Promise { if (q.taskId || q.sessionId || !(q.options ?? []).includes(PUBLISH_AUTO_OPTION)) return false; const a = answer.trim(); if (a !== PUBLISH_AUTO_OPTION && a !== PUBLISH_BUTTON_OPTION) return false; const [project] = await db.select().from(projects).where(eq(projects.id, q.projectId)); if (!project) return false; await setPublishMode(db, project.id, a === PUBLISH_AUTO_OPTION ? "auto" : "button"); if (a === PUBLISH_AUTO_OPTION) await autoPublish(db, project).catch(() => false); return true; } onAnswer(onPublishAnswer);