Merge pull request 'Выключатель «Выкатить в прод?» для Пеппы до запуска' (#38) from pep18/release-offers-switch into main
This commit is contained in:
commit
dbd9b04b70
@ -35,7 +35,7 @@
|
||||
- **CD проектов (PEP-57)**: шаблон — `.gitea/workflows/deploy.yml` + `.gitea/peppa-deploy.sh` + `deploy/compose.yml` (метки Traefik, сеть `traefik_default`) + `deploy/Dockerfile.*`; настройки — `deploy` в `.peppa/project.json`. Образ `peppa/<slug>:<sha>` на docker хоста, `docker compose -p <slug>-<env>`, хосты `<slug>-pr<N>` / `<slug>-staging` / `<slug>-prod` `.telecom.quest` (один уровень: сертификат Cloudflare). Health до 2 мин изнутри сети Traefik, провал → откат на образ, работавший до этого. Шаг шлёт `X-Peppa-Event: deploy` → `recordRelease` (runner/deploy.ts, таблица `releases`, задачи — из сообщений коммитов). Staging здоров → PM вопрос с кнопкой «🚀 Выкатить в прод»; откат/провал → сообщение с причиной и логом. Прод: `deployProd` (веб «Релизы» на странице проекта, Telegram-кнопка через `answerAndDeliver` → `onReleaseAnswer`, MCP `deploy`, CLI `peppa deploy prod`) ставит тег `deploy-prod-<время>` на здоровый staging-коммит (в Gitea 1.22 нет API workflow_dispatch). В тестах docker — `mock-docker` первым в PATH
|
||||
- `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта
|
||||
- Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем
|
||||
- **До официального запуска (сейчас)**: всё в деве. `peppa.telecom.quest` — `next dev` (HMR) из рабочей копии `/Users/telecom/Dev/Peppa`: правки этой сессии сразу видны вживую, без сборки и релиза; бот, вачдог и `~/.local/bin` — тоже из рабочей копии; агента `release` нет. Установка: `PEPPA_WEB_MODE=dev scripts/install-launchd.sh watchdog web bot && scripts/install-bins.sh`. Cloudflare превращает `no-cache` в 4-часовой кэш браузера, а dev-чанки не меняют имён — поэтому `next.config.ts` в dev отдаёт `/_next/static` с `private, no-store`. Новые колонки в схеме = сразу `peppa db backup && peppa db migrate` (живой веб читает схему из рабочей копии). Что выкачено = что лежит в рабочей копии (ветка, незакоммиченное), поэтому после работы возвращаться на `main`. Официальный прод будет отдельно на другом домене — по схеме PEP-18 ниже
|
||||
- **До официального запуска (сейчас)**: всё в деве. `peppa.telecom.quest` — `next dev` (HMR) из рабочей копии `/Users/telecom/Dev/Peppa`: правки этой сессии сразу видны вживую, без сборки и релиза; бот, вачдог и `~/.local/bin` — тоже из рабочей копии; агента `release` нет. Установка: `PEPPA_WEB_MODE=dev scripts/install-launchd.sh watchdog web bot && scripts/install-bins.sh`. Cloudflare превращает `no-cache` в 4-часовой кэш браузера, а dev-чанки не меняют имён — поэтому `next.config.ts` в dev отдаёт `/_next/static` с `private, no-store`. Новые колонки в схеме = сразу `peppa db backup && peppa db migrate` (живой веб читает схему из рабочей копии). Что выкачено = что лежит в рабочей копии (ветка, незакоммиченное), поэтому после работы возвращаться на `main`. Вопрос «Выкатить в прод?» после зелёного main выключен (`peppa platform release-offers off`, настройка `platform.release_offers`; кнопка в «Релизах» тоже скрыта) — включить при запуске. Официальный прод будет отдельно на другом домене — по схеме PEP-18 ниже
|
||||
- **Прод Пеппы (PEP-18, для будущего официального прода)**: сервисы и `~/.local/bin` работают из `~/peppa/current` — симлинк на `~/peppa/releases/<sha>` (git worktree от bare-клона `~/peppa/repo.git`, `.env` → `~/peppa/shared/.env`), не из рабочей копии `/Users/telecom/Dev/Peppa`. Релиз — `scripts/peppa-release.sh <sha>`: install → `next build` → `peppa db backup` (VACUUM INTO + `quick_check`, `~/.peppa/backups/release-*`) → `peppa db migrate` → `current` → `launchctl kickstart -k` web/bot/watchdog → health (`/api/health` с коммитом релиза, свежие heartbeat) → иначе откат `current` и kickstart; журнал `~/peppa/logs`, отчёты `peppa release report` в `releases` (проект PEP, env prod). Кнопка PM: после зелёного main — вопрос «🚀 Выкатить в прод»; `deployProd` для `PEPPA_PLATFORM_KEY` (PEP) → `deployPlatform` (runner/platform-release.ts) кладёт запрос в `~/.peppa/release-queue`, launchd `quest.telecom.peppa.release` (QueueDirectories) запускает `peppa-release.sh --queue`. `peppa-release.sh --check` — здоровье текущего. bin-обёртки берут логический корень (хуки и `credential.helper` → `~/peppa/current`), агенты launchd получают `PEPPA_ROOT`
|
||||
- `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (watchdog/web/bot/release; ждёт выгрузки после `bootout`), peppa-release.sh
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { ExternalLink, Plus, Rocket } from "lucide-react";
|
||||
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, platformReleaseCandidate, type Release } from "@peppa/runner";
|
||||
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, platformReleaseCandidate, platformReleaseOffers, type Release } from "@peppa/runner";
|
||||
import { getIncidentSettings, listErrorSources, listIncidents, listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
@ -73,7 +73,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
currentReleases(db, p.id),
|
||||
]);
|
||||
// Peppa itself has no staging: its prod candidate is the newest green main (PEP-18).
|
||||
const prodCandidate = isPlatform(p) ? await platformReleaseCandidate(db, p) : (current.staging?.sha ?? null);
|
||||
const prodCandidate = isPlatform(p) ? ((await platformReleaseOffers(db)) ? await platformReleaseCandidate(db, p) : null) : (current.staging?.sha ?? null);
|
||||
const collaborators = new Set((repo.collaborators ?? []).map((l) => l.toLowerCase()));
|
||||
// Members who are not repo collaborators (only known when Gitea listed them; owners of the namespace see it anyway).
|
||||
const noRepoAccess = (login: string) =>
|
||||
|
||||
@ -42,7 +42,7 @@ import {
|
||||
type TaskStatus,
|
||||
} from "@peppa/core";
|
||||
import { createDb, migrateDb } from "@peppa/db";
|
||||
import { answerAndDeliver, connectCi, deployProd, listReleases, recordRelease, type ReleaseStatus, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
||||
import { answerAndDeliver, connectCi, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
@ -73,6 +73,7 @@ const USAGE = `peppa — Peppa software factory CLI
|
||||
peppa session stop <id>
|
||||
peppa session resume <id> [-p <extra prompt>] (new generation, claude --resume)
|
||||
peppa platform allowlist | allow <login> | deny <login> (who may log into Peppa)
|
||||
peppa platform release-offers [on|off] ("deploy to prod?" after a green main of Peppa; off before launch)
|
||||
peppa platform admins [login,… | -] (who gets service alerts; default: the allowlist)
|
||||
peppa status (services, outbox, runners, questions, admins)
|
||||
peppa telegram pair <login> | status | unpair <login> (users normally pair in web Settings)
|
||||
@ -407,6 +408,13 @@ async function main(): Promise<void> {
|
||||
console.log(`${u.login} (#${u.id})`);
|
||||
break;
|
||||
}
|
||||
case "platform release-offers": {
|
||||
// PEP-18: "deploy to prod?" after a green main of Peppa; off before the official launch.
|
||||
if (args[0] === "on" || args[0] === "off") await setPlatformReleaseOffers(db, args[0] === "on");
|
||||
else if (args[0]) throw new PeppaError("usage: peppa platform release-offers [on|off]");
|
||||
console.log(`выкатка Пеппы в прод: ${(await platformReleaseOffers(db)) ? "предлагается" : "выключена"}`);
|
||||
break;
|
||||
}
|
||||
case "user egov": {
|
||||
// PEP-65: link (or unlink with "-") the IIN a user logs in with through eGov QR.
|
||||
if (!args[0] || !args[1]) throw new PeppaError("usage: peppa user egov <login> <ИИН|->");
|
||||
|
||||
@ -58,12 +58,12 @@ export async function currentReleases(db: Db, projectId: number): Promise<Partia
|
||||
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) {
|
||||
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, "(неактуально: на staging новый релиз)", "system").catch(() => {});
|
||||
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. */
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
// `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 { askPmProject, configuredChecks, summarizeChecks, PeppaError, type Project } from "@peppa/core";
|
||||
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";
|
||||
@ -54,9 +54,24 @@ export const platformReleaseCandidate = (db: Db, project: Project) => greenMainS
|
||||
|
||||
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<boolean> {
|
||||
return (await getSetting<boolean>(db, OFFERS)) ?? true;
|
||||
}
|
||||
|
||||
export async function setPlatformReleaseOffers(db: Db, on: boolean): Promise<void> {
|
||||
await setSetting(db, OFFERS, on);
|
||||
if (!on) await expireProdOffers(db, (await getProject(db, platformKey())).id, "(выкатка в прод выключена до запуска)");
|
||||
}
|
||||
|
||||
/** 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<boolean> {
|
||||
if (!isPlatform(project) || (await greenMainSha(db, project, sha)) !== sha) return false;
|
||||
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);
|
||||
|
||||
@ -258,4 +258,23 @@ describe("Прод из релизного каталога", () => {
|
||||
symlinkSync(viaCurrent, join(localBin, "probe"));
|
||||
assert.equal(execFileSync("bash", [join(localBin, "probe")], { encoding: "utf8" }).trim(), join(RELEASES, "current"));
|
||||
});
|
||||
|
||||
test("Scenario: Выключено — после зелёного main вопроса нет, открытый закрыт; включено — снова есть", async () => {
|
||||
const offers = async () => (await core.pendingQuestions(db, proj.id)).filter((q) => q.options?.includes(runner.PROD_OPTION));
|
||||
const first = merge(`${pep.key}-offers-1`);
|
||||
await greenMain(first);
|
||||
assert.equal((await offers()).length, 1);
|
||||
|
||||
await runner.setPlatformReleaseOffers(db, false);
|
||||
assert.equal(await runner.platformReleaseOffers(db), false);
|
||||
assert.equal((await offers()).length, 0, "the open offer is closed");
|
||||
const second = merge(`${pep.key}-offers-2`);
|
||||
await greenMain(second);
|
||||
assert.equal((await offers()).length, 0, "no offer while off");
|
||||
|
||||
await runner.setPlatformReleaseOffers(db, true);
|
||||
const third = merge(`${pep.key}-offers-3`);
|
||||
await greenMain(third);
|
||||
assert.equal((await offers()).length, 1);
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
Reference in New Issue
Block a user