PEP-60: platform Telegram channel — check, releases, outages/restarts, platform digest
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
781936478e
commit
82c003e209
@ -94,6 +94,7 @@ const PUSH_TITLE: Record<NotifyEvent, string> = {
|
||||
incidents: "Ошибка в проде",
|
||||
monitoring: "Мониторинг",
|
||||
digest: "Сводка",
|
||||
platform: "Обновления Пеппы",
|
||||
};
|
||||
|
||||
/** Browser notification text for a question. */
|
||||
|
||||
57
apps/web/app/(app)/platform/actions.ts
Normal file
57
apps/web/app/(app)/platform/actions.ts
Normal file
@ -0,0 +1,57 @@
|
||||
"use server";
|
||||
// «Платформа» (PEP-60): the platform's Telegram channel and digest — superadmin only.
|
||||
|
||||
import { checkPlatformChannel, parseChatId, PeppaError, platformDigestTick, PLATFORM_CHANNEL_EVENTS, requireSuperadmin, setPlatformChannel } from "@peppa/core";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { asWebActor, requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||
const BASE = "/platform";
|
||||
|
||||
async function attempt(fn: () => Promise<string | void>): Promise<never> {
|
||||
const user = asWebActor(await requireUser());
|
||||
let target = BASE;
|
||||
try {
|
||||
await requireSuperadmin(db, user);
|
||||
target = (await fn()) || target;
|
||||
} catch (e) {
|
||||
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
|
||||
target = `${BASE}?error=${encodeURIComponent(msg.slice(0, 300))}`;
|
||||
}
|
||||
revalidatePath(BASE);
|
||||
redirect(target);
|
||||
}
|
||||
|
||||
/** Saves the Chat ID (and checks the channel right away). */
|
||||
export async function saveChannelAction(f: FormData) {
|
||||
await attempt(async () => {
|
||||
const raw = str(f, "chatId");
|
||||
const c = await setPlatformChannel(db, { chatId: raw ? parseChatId(raw) : null });
|
||||
if (c.chatId != null) await checkPlatformChannel(db);
|
||||
});
|
||||
}
|
||||
|
||||
export async function checkChannelAction() {
|
||||
await attempt(async () => {
|
||||
await checkPlatformChannel(db);
|
||||
});
|
||||
}
|
||||
|
||||
export async function saveChannelSettingsAction(f: FormData) {
|
||||
await attempt(async () => {
|
||||
const events = Object.fromEntries(PLATFORM_CHANNEL_EVENTS.map((e) => [e, f.get(`event.${e}`) === "on"]));
|
||||
await setPlatformChannel(db, { events, digest: { time: str(f, "time"), timezone: str(f, "timezone"), users: f.get("users") === "on" } });
|
||||
});
|
||||
}
|
||||
|
||||
/** Sends the platform digest now (over the time since the previous one). */
|
||||
export async function sendDigestNowAction() {
|
||||
await attempt(async () => {
|
||||
const r = await platformDigestTick(db, { force: true });
|
||||
if (!r) throw new PeppaError("Некуда отправлять: канал не подключён и дайджест пользователям выключен");
|
||||
if (!r.channel && !r.users) return `${BASE}?sent=empty`;
|
||||
return `${BASE}?sent=${r.channel ? "channel" : ""}${r.users ? `,users:${r.users}` : ""}`;
|
||||
});
|
||||
}
|
||||
114
apps/web/app/(app)/platform/page.tsx
Normal file
114
apps/web/app/(app)/platform/page.tsx
Normal file
@ -0,0 +1,114 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { Megaphone, RefreshCw, Send } from "lucide-react";
|
||||
import { buildPlatformDigest, getPlatformBuild, getPlatformChannel, isSuperadmin, platformDigestEmpty, PLATFORM_CHANNEL_EVENT_NAMES, PLATFORM_CHANNEL_EVENTS, renderPlatformDigest } from "@peppa/core";
|
||||
import { ago, Flash, PageHeader, Section } from "@/components/common";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Input, Label } from "@/components/ui/input";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { checkChannelAction, saveChannelAction, saveChannelSettingsAction, sendDigestNowAction } from "./actions";
|
||||
|
||||
export const metadata = { title: "Платформа — Пеппа" };
|
||||
|
||||
/** Telegram HTML of the digest → plain text for the preview. */
|
||||
const plain = (html: string) => html.replace(/<[^>]+>/g, "").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
|
||||
|
||||
export default async function Platform({ searchParams }: { searchParams: Promise<{ error?: string; sent?: string }> }) {
|
||||
const user = await requireUser();
|
||||
if (!(await isSuperadmin(db, user))) notFound();
|
||||
const { error, sent } = await searchParams;
|
||||
const [c, build] = await Promise.all([getPlatformChannel(db), getPlatformBuild(db)]);
|
||||
const digest = await buildPlatformDigest(db, { since: new Date(Date.now() - 24 * 3600_000) });
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
{sent && <p className="mb-4 rounded-lg border px-4 py-3 text-sm">{sent === "empty" ? "Дайджест пуст — нечего отправлять." : `Дайджест отправлен: ${sent.replace("channel", "в канал").replace(",users:", " · пользователям: ")}`}</p>}
|
||||
<PageHeader title={<><Megaphone className="mr-1 inline size-5 text-primary" />Платформа</>}>
|
||||
Telegram-канал Пеппы: новые версии, падения и перезапуски сервисов и ежедневный дайджест — что нового в Пеппе и что происходит сейчас. Раздел видят только суперадмины.
|
||||
{build && <> Сейчас: v{build.version} · <span className="font-mono">{build.commit.slice(0, 7)}</span>.</>}
|
||||
</PageHeader>
|
||||
|
||||
<Section title="Канал">
|
||||
<Card className="gap-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{c.chatId == null ? (
|
||||
<Badge variant="secondary">канал не задан</Badge>
|
||||
) : !c.check ? (
|
||||
<Badge variant="info">не проверен</Badge>
|
||||
) : c.check.ok ? (
|
||||
<Badge variant="ok">канал подключён</Badge>
|
||||
) : (
|
||||
<Badge variant="danger">не работает</Badge>
|
||||
)}
|
||||
{c.check?.ok && c.title && <span className="font-semibold">{c.title}</span>}
|
||||
{c.check && <span className="ml-auto text-xs text-muted-foreground">проверен {ago(new Date(c.check.at))}</span>}
|
||||
</div>
|
||||
{c.check && !c.check.ok && <p className="m-0 text-sm text-destructive">{c.check.error}</p>}
|
||||
<form action={saveChannelAction} className="flex flex-wrap items-end gap-2">
|
||||
<Label className="min-w-56 flex-1">
|
||||
Chat ID канала
|
||||
<Input name="chatId" placeholder="-100… или @имя" defaultValue={c.chatId == null ? "" : String(c.chatId)} className="h-8 font-mono" />
|
||||
</Label>
|
||||
<Button size="sm">Сохранить и проверить</Button>
|
||||
</form>
|
||||
{c.chatId != null && (
|
||||
<form action={checkChannelAction}>
|
||||
<Button size="sm" variant="outline"><RefreshCw />Проверить ещё раз</Button>
|
||||
</form>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
Добавьте бота Пеппы в канал администратором с правом «Публикация сообщений». Пока проверка не прошла, Пеппа перепроверяет канал раз в час и ничего туда не пишет. Ответы в канале бот не читает.
|
||||
</p>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
<Section title="Что присылать">
|
||||
<Card>
|
||||
<form action={saveChannelSettingsAction} className="flex flex-col gap-3">
|
||||
{PLATFORM_CHANNEL_EVENTS.map((e) => (
|
||||
<label key={e} className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name={`event.${e}`} defaultChecked={c.events[e]} className="size-4 accent-primary" />
|
||||
{PLATFORM_CHANNEL_EVENT_NAMES[e]} — в канал
|
||||
</label>
|
||||
))}
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name="users" defaultChecked={c.digest.users} className="size-4 accent-primary" />
|
||||
Дайджест ещё и в личные чаты всем, кто привязал Telegram (отписка — «Настройки → Уведомления»)
|
||||
</label>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<Label>
|
||||
Время дайджеста
|
||||
<Input name="time" type="time" required defaultValue={c.digest.time} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
Таймзона
|
||||
<Input name="timezone" required defaultValue={c.digest.timezone} className="h-8 font-mono" />
|
||||
</Label>
|
||||
</div>
|
||||
<Button size="sm" className="self-start">Сохранить</Button>
|
||||
</form>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
title="Дайджест за сутки"
|
||||
actions={
|
||||
<form action={sendDigestNowAction}>
|
||||
<Button size="sm" variant="outline"><Send />Отправить сейчас</Button>
|
||||
</form>
|
||||
}
|
||||
>
|
||||
{platformDigestEmpty(digest) ? (
|
||||
<p className="m-0 text-sm text-muted-foreground">За сутки ничего нового и ничего не происходит — дайджест не уйдёт.</p>
|
||||
) : (
|
||||
<pre className="m-0 overflow-x-auto rounded-md bg-muted p-3 text-xs whitespace-pre-wrap">{plain(renderPlatformDigest(digest))}</pre>
|
||||
)}
|
||||
</Section>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
@ -82,6 +82,9 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
<Button asChild size="sm">
|
||||
<a href="/journal">Журнал</a>
|
||||
</Button>
|
||||
<Button asChild size="sm">
|
||||
<a href="/platform">Платформа</a>
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { Bot, Contact, FolderKanban, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
|
||||
import { Bot, Contact, FolderKanban, Megaphone, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
|
||||
import { Brand } from "@/components/Brand";
|
||||
import { ThemeToggle } from "@/components/ThemeToggle";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@ -28,6 +28,7 @@ const ITEMS: Item[] = [
|
||||
{ href: "/secrets", label: "Секреты", icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true },
|
||||
{ href: "/hosts", label: "Хосты", icon: Server, match: (p) => p.startsWith("/hosts"), admin: true },
|
||||
{ href: "/journal", label: "Журнал", icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true },
|
||||
{ href: "/platform", label: "Платформа", icon: Megaphone, match: (p) => p.startsWith("/platform"), admin: true },
|
||||
{ href: "/users", label: "Пользователи", icon: Users, match: (p) => p.startsWith("/users"), admin: true },
|
||||
{ href: "/settings", label: "Настройки", icon: Settings, match: (p) => p.startsWith("/settings") },
|
||||
];
|
||||
|
||||
66
openspec/changes/pep-60-platform-channel-digest/design.md
Normal file
66
openspec/changes/pep-60-platform-channel-digest/design.md
Normal file
@ -0,0 +1,66 @@
|
||||
# Design: PEP-60 — канал платформы и дайджест Пеппы
|
||||
|
||||
## Настройки (без миграций)
|
||||
|
||||
`settings` `platform.telegram_channel` (ключ уже есть в боевой базе: `{chatId, setAt}`) —
|
||||
`PlatformChannel` в `core/platform-channel.ts`, поверх умолчаний:
|
||||
|
||||
- `chatId`, `title`, `check: {ok, error, at}` — результат последней проверки;
|
||||
- `events: {releases, services, digest}` — всё включено;
|
||||
- `digest: {time "09:00", timezone (PEPPA_TZ/сервер), users: false}` — личные чаты включает
|
||||
суперадмин (без сюрприза всем пользователям в первый же день).
|
||||
|
||||
Менять может только суперадмин (`requireSuperadmin`): веб `/platform` и CLI
|
||||
`peppa platform channel chat=<chat_id|-> [releases=on|off …]` (отрицательный id — через `chat=`:
|
||||
`parseArgs` принимает `-100…` за флаг), `peppa platform channel check`, `peppa platform digest [now]`.
|
||||
|
||||
## Проверка канала
|
||||
|
||||
`checkPlatformChannel` — Bot API напрямую (как прямая доставка вачдога PEP-20):
|
||||
`getMe` → `getChat(chat_id)` → `getChatMember(chat_id, bot)`. `chat not found` / 403 →
|
||||
«бот не видит канал — добавьте его администратором»; не админ или `can_post_messages: false`
|
||||
(в канале) → «бот не может публиковать — дайте право «Публикация сообщений»». Удача —
|
||||
`title` канала. Проверка при сохранении, кнопкой и раз в час в вачдоге, пока не ок (PM
|
||||
добавит бота — канал заработает сам). Писать в канал только при `check.ok`.
|
||||
|
||||
## Отправка
|
||||
|
||||
`postToChannel(db, kind, dedupeKey, text)` → тот же `telegram_outbox` (повторы, 429). Ключи
|
||||
сервисных событий начинаются с `mon:` — их вачдог доставляет сам, когда упал бот. Канал не
|
||||
принимает ответов: кнопок нет, бот на сообщения канала не реагирует (updates `channel_post`
|
||||
он и так не обрабатывает).
|
||||
|
||||
## События
|
||||
|
||||
- **Сервисы** — в `checkServices` (PEP-20) рядом с алертом админам: одно сообщение о
|
||||
падении (без напоминаний) и одно о восстановлении с длительностью простоя; ключи от
|
||||
начала простоя, поэтому бот и вачдог вместе дают одно сообщение. **Перезапуск** — смена
|
||||
`heartbeat.startedAt` без простоя: «🔄 вачдог перезапущен (v0.15.0 · abc1234)».
|
||||
- **Релиз**. В heartbeat добавлен `commit` (`peppaCommit()`: `PEPPA_COMMIT` /
|
||||
`NEXT_PUBLIC_PEPPA_COMMIT_FULL` / `git rev-parse HEAD` корня). Вачдог раз в минуту
|
||||
(`platformBuildTick`, runner) берёт HEAD корня Пеппы; если он отличается от
|
||||
`platform.build` и входит в `main` (`git merge-base --is-ancestor HEAD main`) — это выкатка:
|
||||
«🚀 Peppa v0.16.0 · b1c2d3e» и стори из сообщений коммитов `prev..HEAD`
|
||||
(`PEP-N`, с названиями). Так работает и сейчас (dev из рабочей копии: ветка задачи не
|
||||
объявляется, возврат на обновлённый main — объявляется), и в проде PEP-18 (`current` —
|
||||
worktree релиза от `main`). Первый запуск только запоминает сборку.
|
||||
|
||||
## Дайджест платформы
|
||||
|
||||
`buildPlatformDigest(since, now)`: «Что нового» — стори проекта Пеппы (`PEPPA_PLATFORM_KEY`),
|
||||
ставшие `done` после `since`, и сборки, объявленные с тех пор; «Сейчас» — версия · коммит,
|
||||
сервисы, активные раннеры, открытые вопросы, лимиты подписок (`listAccountUsage`, ≥ 50% или
|
||||
«лимит до»). Пусто (нет нового, нет раннеров, нет вопросов, сервисы в порядке) — не
|
||||
отправляется. `platformDigestTick` в `tick` вачдога: в `digest.time` (окно 3 ч, раз в
|
||||
местные сутки, `platform.digest.last`), в канал и — если `digest.users` — каждому
|
||||
пользователю событием уведомлений `platform` («Обновления Пеппы»: Telegram вкл, push выкл).
|
||||
Отписка — «Настройки → Уведомления» (строка появляется сама из `NOTIFY_EVENTS`); личный
|
||||
дайджест по проектам (PEP-29, событие `digest`) не меняется.
|
||||
|
||||
## Решения
|
||||
|
||||
- Без миграций — всё в `settings`, как прочие настройки платформы.
|
||||
- Отдельная страница `/platform` для суперадмина (по образцу `/hosts`), пункт меню
|
||||
«Платформа»; не суперадмину — 404.
|
||||
- Окно сервиса «упал» — общий порог мониторинга (`PEPPA_MONITOR_STALE_MIN`), отдельный
|
||||
порог для канала не вводим.
|
||||
@ -1,16 +1,18 @@
|
||||
# Tasks: PEP-60
|
||||
|
||||
## 0. Перед стартом
|
||||
- [x] 0.1 Бот — админ канала (проверка `getChat`/тестовое сообщение по согласию PM); роль суперадмина из PEP-16 (иначе только CLI)
|
||||
- [x] 0.1 Проверка бота в канале: `getChat(-1004371018094)` → «chat not found» — бот ещё не админ; работаем, канал включится сам после проверки
|
||||
|
||||
## 1. Канал
|
||||
- [x] 1.1 core: настройки платформы (канал, события, расписание); CLI `peppa platform channel <chat_id>` и `platform status`
|
||||
- [x] 1.2 Веб: «Настройки платформы» для суперадмина с проверкой канала
|
||||
- [x] 1.3 События: релиз (из деплоя/CI, PEP-57; до него — при старте веба с новым коммитом), рестарт и падение/восстановление сервисов (heartbeat, PEP-20)
|
||||
- [x] 1.1 core `platform-channel.ts`: настройки, проверка канала (Bot API), `postToChannel`; CLI `peppa platform channel`
|
||||
- [x] 1.2 Веб `/platform` для суперадмина: Chat ID, проверка, события, расписание; пункт меню
|
||||
- [x] 1.3 События сервисов в `checkServices`: падение/восстановление/перезапуск; `commit` в heartbeat
|
||||
- [x] 1.4 Релиз: `platformBuildTick` (runner) — новая сборка из `main` со списком стори
|
||||
|
||||
## 2. Дайджест
|
||||
- [x] 2.1 Сбор: смерженные PR/задачи PEP с прошлого дайджеста, версия, сервисы, раннеры, вопросы, лимиты; пропуск, если пусто
|
||||
- [x] 2.2 Расписание и отправка в канал; личный дайджест пользователям (после PEP-2) и отписка в Настройках
|
||||
- [x] 2.1 `buildPlatformDigest` + рендер; пропуск, если пусто
|
||||
- [x] 2.2 `platformDigestTick` в вачдоге: канал + пользователи (событие `platform`, отписка в Настройках); перепроверка канала раз в час
|
||||
|
||||
## 3. Проверка
|
||||
- [x] 3.1 Тесты на mock-telegram — по сценарию спецификации на каждый; весь e2e зелёный; `openspec validate`
|
||||
- [ ] 3.1 e2e `platform-channel.test.ts` на mock-telegram по сценариям спеки; весь e2e и typecheck зелёные; `openspec validate`
|
||||
- [ ] 3.2 Документация: AGENTS.md, `/help`
|
||||
|
||||
@ -71,6 +71,7 @@ import {
|
||||
import { createDb, migrateDb } from "@peppa/db";
|
||||
import { checkHost, ensureSshKey, pushImage, sshArgs } from "@peppa/runner";
|
||||
import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runnerServiceAlive, setRunnerClient, recentRunnerCommands, getWatchdogSettings, setWatchdogSettings } from "@peppa/runner";
|
||||
import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core";
|
||||
import { createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
|
||||
import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core";
|
||||
import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
||||
@ -121,6 +122,9 @@ const USAGE = `peppa — Peppa software factory CLI
|
||||
(PEP-10/27: system → project → story; a story overrides mode/context only)
|
||||
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 channel [chat=<chat_id|->|@name|check] [releases|services|digest=on|off time=HH:MM tz=<IANA> users=on|off]
|
||||
(PEP-60: Telegram channel of the platform — events and the platform digest)
|
||||
peppa platform digest [now] (PEP-60: show the platform digest; now — send it to the channel/users)
|
||||
peppa platform admins [login,… | -] (who gets service alerts; default: the allowlist)
|
||||
peppa platform watchdog [key=value… | key=- | reset] (PEP-28: restartMax restartWindowMin restartDelaysMin=1,5,15
|
||||
stallRestartMin remindMin escalateMin idleStopHours; 0 = off)
|
||||
@ -641,6 +645,7 @@ async function main(): Promise<void> {
|
||||
const paired = new Set((await adminRecipients(db)).map((u) => u.login));
|
||||
const admins = (await platformAdmins(db)).map((l) => `${l}${paired.has(l) ? " (Telegram)" : " (без Telegram)"}`);
|
||||
console.log(`админы: ${admins.join(", ") || "нет"}`);
|
||||
console.log(`канал платформы: ${describeChannel(await getPlatformChannel(db))}`);
|
||||
break;
|
||||
}
|
||||
case "telegram pair": {
|
||||
@ -674,6 +679,42 @@ async function main(): Promise<void> {
|
||||
console.log(`${u.login} (#${u.id})`);
|
||||
break;
|
||||
}
|
||||
case "platform channel": {
|
||||
// PEP-60: the platform's Telegram channel (superadmin's setting; the CLI is an admin tool).
|
||||
const patch: PlatformChannelPatch = {};
|
||||
let check = false;
|
||||
for (const a of args) {
|
||||
if (a === "check") check = true;
|
||||
else if (a === "-") patch.chatId = null;
|
||||
else if (!a.includes("=")) patch.chatId = parseChatId(a);
|
||||
else {
|
||||
const [k, v] = [a.slice(0, a.indexOf("=")), a.slice(a.indexOf("=") + 1)];
|
||||
const on = v === "on" ? true : v === "off" ? false : null;
|
||||
if (k === "chat") patch.chatId = v === "-" ? null : parseChatId(v);
|
||||
else if ((PLATFORM_CHANNEL_EVENTS as readonly string[]).includes(k) && on != null) patch.events = { ...patch.events, [k]: on };
|
||||
else if (k === "users" && on != null) patch.digest = { ...patch.digest, users: on };
|
||||
else if (k === "time") patch.digest = { ...patch.digest, time: v };
|
||||
else if (k === "tz") patch.digest = { ...patch.digest, timezone: v };
|
||||
else throw new PeppaError(`unknown setting ${a}: chat=<id>, releases|services|digest|users=on|off, time=HH:MM, tz=<IANA>`);
|
||||
}
|
||||
}
|
||||
let c = Object.keys(patch).length ? await setPlatformChannel(db, patch) : await getPlatformChannel(db);
|
||||
if (c.chatId != null && (check || patch.chatId !== undefined)) c = await checkPlatformChannel(db);
|
||||
console.log(describeChannel(c));
|
||||
console.log(`события: ${PLATFORM_CHANNEL_EVENTS.map((e) => `${e}=${c.events[e] ? "on" : "off"}`).join(" ")}`);
|
||||
console.log(`дайджест: ${c.digest.time} ${c.digest.timezone}, пользователям ${c.digest.users ? "да" : "нет"}`);
|
||||
break;
|
||||
}
|
||||
case "platform digest": {
|
||||
if (args[0] === "now") {
|
||||
const r = await platformDigestTick(db, { force: true, log: console.log });
|
||||
if (!r) console.log("некуда отправлять: канал не подключён и дайджест пользователям выключен");
|
||||
break;
|
||||
}
|
||||
const { buildPlatformDigest, renderPlatformDigest } = await import("@peppa/core");
|
||||
console.log(renderPlatformDigest(await buildPlatformDigest(db, { since: new Date(Date.now() - 24 * 3600_000) })).replace(/<[^>]+>/g, ""));
|
||||
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");
|
||||
|
||||
@ -28,6 +28,7 @@ export * from "./reviews.ts";
|
||||
export * from "./webpush.ts";
|
||||
export * from "./notifications.ts";
|
||||
export * from "./digest.ts";
|
||||
export * from "./platform-channel.ts";
|
||||
export * from "./autonomy.ts";
|
||||
export * from "./openspec.ts";
|
||||
export * from "./steps.ts";
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
// Service monitoring (PEP-20): web, bot and watchdog write heartbeats into `settings`; the
|
||||
// watchdog and the bot check each other (and the web) and alert the platform admins in
|
||||
// Telegram through the outbox when a service goes quiet, without spamming.
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { hostname } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
@ -9,6 +10,7 @@ import { telegramOutbox, users, type Db } from "@peppa/db";
|
||||
import { and, count, eq, inArray, isNotNull, sql } from "drizzle-orm";
|
||||
import { allowedLogins } from "./access.ts";
|
||||
import { deliverToUser } from "./notifications.ts";
|
||||
import { getPlatformChannel, postToChannel } from "./platform-channel.ts";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
import type { User } from "./users.ts";
|
||||
|
||||
@ -23,6 +25,8 @@ export interface Heartbeat {
|
||||
pid: number;
|
||||
host: string;
|
||||
version: string;
|
||||
/** Commit the process runs (PEP-60); absent in heartbeats of older processes. */
|
||||
commit?: string | null;
|
||||
}
|
||||
|
||||
export interface ServiceState {
|
||||
@ -38,6 +42,8 @@ interface AlertState {
|
||||
alerted: boolean;
|
||||
reminders: number;
|
||||
lastAlertAt: string | null;
|
||||
/** PEP-60: the outage was posted to the platform channel (then its recovery is too). */
|
||||
channelPosted?: boolean;
|
||||
}
|
||||
|
||||
export interface MonitorOptions {
|
||||
@ -60,14 +66,33 @@ const startedAt = new Date().toISOString();
|
||||
export const defaultStaleMs = () => Number(process.env.PEPPA_MONITOR_STALE_MIN ?? 5) * MIN;
|
||||
|
||||
/** Peppa version from the root package.json (bot, watchdog, CLI run from the checkout). */
|
||||
export function peppaVersion(): string {
|
||||
export function peppaVersion(root = join(dirname(fileURLToPath(import.meta.url)), "../../..")): string {
|
||||
try {
|
||||
return (JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../../../package.json"), "utf8")) as { version?: string }).version ?? "0.0.0";
|
||||
return (JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version?: string }).version ?? "0.0.0";
|
||||
} catch {
|
||||
return "0.0.0";
|
||||
}
|
||||
}
|
||||
|
||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../..");
|
||||
|
||||
/** HEAD of Peppa's checkout right now (null outside git). */
|
||||
export function headCommit(root = ROOT): string | null {
|
||||
try {
|
||||
return execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
let processCommit: string | null | undefined;
|
||||
|
||||
/** Commit this process runs: PEPPA_COMMIT, the web's build-time commit, or HEAD at first call. */
|
||||
export function peppaCommit(): string | null {
|
||||
if (processCommit === undefined) processCommit = process.env.PEPPA_COMMIT || process.env.NEXT_PUBLIC_PEPPA_COMMIT_FULL || headCommit();
|
||||
return processCommit;
|
||||
}
|
||||
|
||||
/** "I'm alive": called every 30–60 s by each service. */
|
||||
export async function beat(db: Db, service: Service, o: { now?: Date; version?: string } = {}): Promise<void> {
|
||||
const hb: Heartbeat = {
|
||||
@ -76,6 +101,7 @@ export async function beat(db: Db, service: Service, o: { now?: Date; version?:
|
||||
pid: process.pid,
|
||||
host: hostname(),
|
||||
version: o.version ?? peppaVersion(),
|
||||
commit: peppaCommit(),
|
||||
};
|
||||
await setSetting(db, hbKey(service), hb);
|
||||
}
|
||||
@ -162,23 +188,39 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
|
||||
const cooldownMs = o.cooldownMs ?? 15 * MIN;
|
||||
const log = o.log ?? (() => {});
|
||||
let queued = 0;
|
||||
const channel = await getPlatformChannel(db);
|
||||
for (const s of await serviceStatus(db, { now, staleMs: o.staleMs })) {
|
||||
if (s.service === o.self || !s.heartbeat) continue;
|
||||
const name = SERVICE_NAMES[s.service];
|
||||
const st = await getSetting<AlertState>(db, alertKey(s.service));
|
||||
if (s.ok) {
|
||||
if (!st?.since) continue;
|
||||
const restarted = await noteProcess(db, s.service, s.heartbeat);
|
||||
if (!st?.since) {
|
||||
// PEP-60: a new process without an outage = a restart (an outage ends with «снова на связи»).
|
||||
if (restarted) {
|
||||
const build = `v${s.heartbeat.version}${s.heartbeat.commit ? ` · ${s.heartbeat.commit.slice(0, 7)}` : ""}`;
|
||||
await postToChannel(db, "services", `mon:ch:${s.service}:restart:${s.heartbeat.host}:${s.heartbeat.pid}`, `🔄 Пеппа: ${name} перезапущен (${build}).`, channel);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// lastAlertAt survives the recovery: it is what the cooldown against flapping counts from.
|
||||
await setSetting(db, alertKey(s.service), { since: null, alerted: false, reminders: 0, lastAlertAt: st.lastAlertAt });
|
||||
const quiet = minutes(Date.parse(s.heartbeat.at) - Date.parse(st.since));
|
||||
if (st.alerted) {
|
||||
const quiet = minutes(Date.parse(s.heartbeat.at) - Date.parse(st.since));
|
||||
queued += await alertAdmins(db, `mon:${s.service}:up:${st.since}`, `✅ Пеппа: ${name} снова на связи (молчал ${quiet} мин).`, log);
|
||||
}
|
||||
if (st.channelPosted && (await postToChannel(db, "services", `mon:ch:${s.service}:up:${st.since}`, `✅ Пеппа: ${name} снова работает — простой ${quiet} мин.`, channel))) queued++;
|
||||
continue;
|
||||
}
|
||||
// Down. A new outage starts when the last heartbeat differs from the remembered one.
|
||||
const cur: AlertState =
|
||||
st?.since === s.heartbeat.at ? st : { since: s.heartbeat.at, alerted: false, reminders: 0, lastAlertAt: st?.lastAlertAt ?? null };
|
||||
// PEP-60: the channel hears about an outage once (no reminders, no cooldown games).
|
||||
if (!cur.channelPosted && (await postToChannel(db, "services", `mon:ch:${s.service}:down:${cur.since}`, `⚠️ Пеппа: ${name} не отвечает с ${hhmm(s.heartbeat.at)}.`, channel))) {
|
||||
cur.channelPosted = true;
|
||||
queued++;
|
||||
if (cur === st) await setSetting(db, alertKey(s.service), cur);
|
||||
}
|
||||
const sinceLast = cur.lastAlertAt ? now.getTime() - Date.parse(cur.lastAlertAt) : Infinity;
|
||||
const due = cur.alerted ? sinceLast >= remindMs : sinceLast >= cooldownMs;
|
||||
if (due) {
|
||||
@ -192,6 +234,16 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
|
||||
return queued;
|
||||
}
|
||||
|
||||
/** Remembers the service's process; true when it differs from a previously seen one. */
|
||||
async function noteProcess(db: Db, service: Service, hb: Heartbeat): Promise<boolean> {
|
||||
const key = `monitor.process:${service}`;
|
||||
const id = `${hb.host}:${hb.pid}:${hb.startedAt}`;
|
||||
const prev = await getSetting<string>(db, key);
|
||||
if (prev === id) return false;
|
||||
await setSetting(db, key, id);
|
||||
return prev != null;
|
||||
}
|
||||
|
||||
/** Monitor messages not delivered yet (the watchdog sends them itself when the bot is down). */
|
||||
export async function pendingMonitorMessages(db: Db) {
|
||||
return db
|
||||
|
||||
@ -8,7 +8,7 @@ import type { Question } from "./tasks.ts";
|
||||
import type { User } from "./users.ts";
|
||||
import { enqueuePush, type PushPayload } from "./webpush.ts";
|
||||
|
||||
export const NOTIFY_EVENTS = ["questions", "review", "failures", "releases", "incidents", "monitoring", "digest"] as const;
|
||||
export const NOTIFY_EVENTS = ["questions", "review", "failures", "releases", "incidents", "monitoring", "digest", "platform"] as const;
|
||||
export type NotifyEvent = (typeof NOTIFY_EVENTS)[number];
|
||||
|
||||
export const NOTIFY_EVENT_NAMES: Record<NotifyEvent, string> = {
|
||||
@ -19,6 +19,7 @@ export const NOTIFY_EVENT_NAMES: Record<NotifyEvent, string> = {
|
||||
incidents: "Ошибки из прода",
|
||||
monitoring: "Мониторинг Пеппы (админам)",
|
||||
digest: "Ежедневный дайджест",
|
||||
platform: "Дайджест обновлений Пеппы",
|
||||
};
|
||||
|
||||
export interface Channels {
|
||||
@ -47,7 +48,7 @@ export const serverTimezone = () => process.env.PEPPA_TZ || Intl.DateTimeFormat(
|
||||
export function defaultPrefs(): NotifyPrefs {
|
||||
const on = { telegram: true, push: true };
|
||||
return {
|
||||
events: { questions: on, review: on, failures: on, releases: on, incidents: on, monitoring: on, digest: { telegram: true, push: false } },
|
||||
events: { questions: on, review: on, failures: on, releases: on, incidents: on, monitoring: on, digest: { telegram: true, push: false }, platform: { telegram: true, push: false } },
|
||||
quiet: null,
|
||||
timezone: serverTimezone(),
|
||||
digestTime: "09:00",
|
||||
|
||||
371
packages/core/src/platform-channel.ts
Normal file
371
packages/core/src/platform-channel.ts
Normal file
@ -0,0 +1,371 @@
|
||||
// Platform channel and Peppa's own digest (PEP-60): a Telegram channel set by a superadmin
|
||||
// gets platform events (releases, service outages, restarts) and the daily platform digest;
|
||||
// paired users get the platform digest too (notification event «platform»). No migrations:
|
||||
// everything lives in `settings`; messages go through the Telegram outbox with retries.
|
||||
import { projects, questions, sessions, tasks, users, type Db } from "@peppa/db";
|
||||
import { formatTaskKey, loadEnv } from "@peppa/shared";
|
||||
import { and, asc, eq, gte, isNotNull, isNull, notInArray } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { deliverToUser, hhmmToMinutes, isValidTimezone, localClock, serverTimezone } from "./notifications.ts";
|
||||
import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
|
||||
import { getSetting, setSetting } from "./settings.ts";
|
||||
import { enqueueTelegram } from "./telegram.ts";
|
||||
import { describeAccount, listAccountUsage } from "./usage.ts";
|
||||
|
||||
export const PLATFORM_CHANNEL_EVENTS = ["releases", "services", "digest"] as const;
|
||||
export type PlatformChannelEvent = (typeof PLATFORM_CHANNEL_EVENTS)[number];
|
||||
|
||||
export const PLATFORM_CHANNEL_EVENT_NAMES: Record<PlatformChannelEvent, string> = {
|
||||
releases: "Новые версии Пеппы",
|
||||
services: "Падение, восстановление и перезапуск сервисов",
|
||||
digest: "Ежедневный дайджест",
|
||||
};
|
||||
|
||||
export interface ChannelCheck {
|
||||
ok: boolean;
|
||||
/** Human-readable reason when not ok. */
|
||||
error: string | null;
|
||||
at: string;
|
||||
}
|
||||
|
||||
export interface PlatformChannel {
|
||||
/** Telegram Chat ID of the channel («-100…» or «@name»); null = no channel. */
|
||||
chatId: number | string | null;
|
||||
/** Channel title from the last good check. */
|
||||
title: string | null;
|
||||
check: ChannelCheck | null;
|
||||
events: Record<PlatformChannelEvent, boolean>;
|
||||
digest: { time: string; timezone: string; users: boolean };
|
||||
setAt?: string;
|
||||
}
|
||||
|
||||
const KEY = "platform.telegram_channel";
|
||||
const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
|
||||
|
||||
export function defaultPlatformChannel(): PlatformChannel {
|
||||
return {
|
||||
chatId: null,
|
||||
title: null,
|
||||
check: null,
|
||||
events: { releases: true, services: true, digest: true },
|
||||
digest: { time: "09:00", timezone: serverTimezone(), users: false },
|
||||
};
|
||||
}
|
||||
|
||||
/** Saved channel settings merged over the defaults. */
|
||||
export async function getPlatformChannel(db: Db): Promise<PlatformChannel> {
|
||||
const d = defaultPlatformChannel();
|
||||
const s = (await getSetting<Partial<PlatformChannel>>(db, KEY)) ?? {};
|
||||
const events = { ...d.events };
|
||||
for (const e of PLATFORM_CHANNEL_EVENTS) if (typeof s.events?.[e] === "boolean") events[e] = s.events[e];
|
||||
return {
|
||||
chatId: s.chatId ?? null,
|
||||
title: s.title ?? null,
|
||||
check: s.check ?? null,
|
||||
events,
|
||||
digest: {
|
||||
time: s.digest?.time && HHMM.test(s.digest.time) ? s.digest.time : d.digest.time,
|
||||
timezone: s.digest?.timezone && isValidTimezone(s.digest.timezone) ? s.digest.timezone : d.digest.timezone,
|
||||
users: s.digest?.users ?? d.digest.users,
|
||||
},
|
||||
...(s.setAt ? { setAt: s.setAt } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** «-1004371018094» → number, «@name» stays a string; anything else is refused. */
|
||||
export function parseChatId(raw: string): number | string {
|
||||
const s = raw.trim();
|
||||
if (/^-?\d{5,20}$/.test(s)) return Number(s);
|
||||
if (/^@[A-Za-z][A-Za-z0-9_]{3,}$/.test(s)) return s;
|
||||
throw new PeppaError("Chat ID канала — число вида -100… или @имя_канала");
|
||||
}
|
||||
|
||||
export interface PlatformChannelPatch {
|
||||
chatId?: number | string | null;
|
||||
events?: Partial<Record<PlatformChannelEvent, boolean>>;
|
||||
digest?: Partial<PlatformChannel["digest"]>;
|
||||
}
|
||||
|
||||
/** Changes the settings; a new Chat ID drops the previous check result. */
|
||||
export async function setPlatformChannel(db: Db, patch: PlatformChannelPatch): Promise<PlatformChannel> {
|
||||
const cur = await getPlatformChannel(db);
|
||||
const next: PlatformChannel = { ...cur, events: { ...cur.events, ...patch.events }, digest: { ...cur.digest, ...patch.digest } };
|
||||
if (!HHMM.test(next.digest.time)) throw new PeppaError("Время дайджеста: формат ЧЧ:ММ");
|
||||
if (!isValidTimezone(next.digest.timezone)) throw new PeppaError(`Неизвестная таймзона: ${next.digest.timezone}`);
|
||||
if (patch.chatId !== undefined && String(patch.chatId) !== String(cur.chatId)) {
|
||||
Object.assign(next, { chatId: patch.chatId, title: null, check: null, setAt: new Date().toISOString() });
|
||||
}
|
||||
await setSetting(db, KEY, next);
|
||||
return next;
|
||||
}
|
||||
|
||||
// ── check ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface BotApiAccess {
|
||||
token?: string;
|
||||
apiUrl?: string;
|
||||
}
|
||||
|
||||
export const CHANNEL_NOT_VISIBLE = "бот не видит канал — добавьте его администратором";
|
||||
export const CHANNEL_NO_POST = "бот не может публиковать — дайте ему право «Публикация сообщений»";
|
||||
|
||||
type ApiResult<T> = { ok: true; result: T } | { ok: false; error_code?: number; description?: string };
|
||||
|
||||
async function botApi<T>(tg: BotApiAccess, method: string, params: Record<string, unknown>): Promise<ApiResult<T>> {
|
||||
const token = tg.token ?? process.env.TELEGRAM_BOT_TOKEN;
|
||||
if (!token) return { ok: false, description: "TELEGRAM_BOT_TOKEN не задан" };
|
||||
const base = tg.apiUrl ?? process.env.TELEGRAM_API_URL ?? "https://api.telegram.org";
|
||||
try {
|
||||
const res = await fetch(`${base}/bot${token}/${method}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(params),
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
});
|
||||
return (await res.json()) as ApiResult<T>;
|
||||
} catch (e) {
|
||||
return { ok: false, description: (e as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the bot can post to the channel: getMe → getChat → getChatMember. Saves the result
|
||||
* (and the channel title) into the settings and returns them.
|
||||
*/
|
||||
export async function checkPlatformChannel(db: Db, tg: BotApiAccess = {}, o: { now?: Date } = {}): Promise<PlatformChannel> {
|
||||
const cur = await getPlatformChannel(db);
|
||||
if (cur.chatId == null) throw new PeppaError("Канал платформы не задан");
|
||||
const at = (o.now ?? new Date()).toISOString();
|
||||
const verdict = async (): Promise<{ ok: boolean; error: string | null; title: string | null }> => {
|
||||
const me = await botApi<{ id: number }>(tg, "getMe", {});
|
||||
if (!me.ok) return { ok: false, error: `Telegram: ${me.description ?? "нет ответа"}`, title: null };
|
||||
const chat = await botApi<{ title?: string; type: string }>(tg, "getChat", { chat_id: cur.chatId });
|
||||
if (!chat.ok) {
|
||||
const gone = chat.error_code === 400 || chat.error_code === 403 || /chat not found|not a member|kicked/i.test(chat.description ?? "");
|
||||
return { ok: false, error: gone ? CHANNEL_NOT_VISIBLE : `Telegram: ${chat.description ?? "нет ответа"}`, title: null };
|
||||
}
|
||||
const title = chat.result.title ?? null;
|
||||
const member = await botApi<{ status: string; can_post_messages?: boolean }>(tg, "getChatMember", { chat_id: cur.chatId, user_id: me.result.id });
|
||||
if (!member.ok) return { ok: false, error: `Telegram: ${member.description ?? "нет ответа"}`, title };
|
||||
const m = member.result;
|
||||
const canPost = chat.result.type === "channel" ? m.status === "creator" || (m.status === "administrator" && m.can_post_messages !== false) : m.status !== "left" && m.status !== "kicked";
|
||||
return canPost ? { ok: true, error: null, title } : { ok: false, error: m.status === "left" || m.status === "kicked" ? CHANNEL_NOT_VISIBLE : CHANNEL_NO_POST, title };
|
||||
};
|
||||
const v = await verdict();
|
||||
const next: PlatformChannel = { ...cur, title: v.title ?? cur.title, check: { ok: v.ok, error: v.error, at } };
|
||||
await setSetting(db, KEY, next);
|
||||
return next;
|
||||
}
|
||||
|
||||
/** «канал подключён — Peppa News» / the reason / «не проверен». */
|
||||
export function describeChannel(c: PlatformChannel): string {
|
||||
if (c.chatId == null) return "канал не задан";
|
||||
if (!c.check) return `${c.chatId}: не проверен`;
|
||||
return c.check.ok ? `канал подключён${c.title ? ` — ${c.title}` : ""}` : `${c.chatId}: ${c.check.error}`;
|
||||
}
|
||||
|
||||
/** Watchdog: re-checks a channel that isn't working yet at most once an hour. */
|
||||
export async function recheckPlatformChannel(db: Db, o: { now?: Date; tg?: BotApiAccess; log?: (m: string) => void } = {}): Promise<boolean> {
|
||||
const c = await getPlatformChannel(db);
|
||||
const now = o.now ?? new Date();
|
||||
if (c.chatId == null || c.check?.ok) return false;
|
||||
if (c.check && now.getTime() - Date.parse(c.check.at) < 3600_000) return false;
|
||||
const r = await checkPlatformChannel(db, o.tg, { now });
|
||||
if (r.check?.ok) o.log?.(`platform channel: ${describeChannel(r)}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── posting ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
|
||||
/**
|
||||
* Queues a message to the platform channel if it is connected and the event is on. Service
|
||||
* events use `mon:` keys so the watchdog delivers them itself when the bot is down.
|
||||
*/
|
||||
export async function postToChannel(db: Db, event: PlatformChannelEvent, dedupeKey: string, html: string, channel?: PlatformChannel): Promise<boolean> {
|
||||
const c = channel ?? (await getPlatformChannel(db));
|
||||
if (c.chatId == null || !c.check?.ok || !c.events[event]) return false;
|
||||
return enqueueTelegram(db, {
|
||||
dedupeKey,
|
||||
method: "sendMessage",
|
||||
params: { chat_id: c.chatId, text: html, parse_mode: "HTML", link_preview_options: { is_disabled: true } },
|
||||
});
|
||||
}
|
||||
|
||||
// ── builds and releases ────────────────────────────────────────────────────────────
|
||||
|
||||
/** Key of the project that is Peppa itself. */
|
||||
export const platformProjectKey = () => process.env.PEPPA_PLATFORM_KEY || "PEP";
|
||||
|
||||
export interface PlatformBuild {
|
||||
version: string;
|
||||
commit: string;
|
||||
at: string;
|
||||
/** Platform stories found in the commits since the previous build. */
|
||||
tasks: string[];
|
||||
}
|
||||
|
||||
const BUILD = "platform.build";
|
||||
const BUILDS = "platform.builds";
|
||||
|
||||
export const getPlatformBuild = (db: Db) => getSetting<PlatformBuild>(db, BUILD);
|
||||
|
||||
/** Announced builds, newest last (the digest lists the ones since its previous run). */
|
||||
export async function recentPlatformBuilds(db: Db): Promise<PlatformBuild[]> {
|
||||
return (await getSetting<PlatformBuild[]>(db, BUILDS)) ?? [];
|
||||
}
|
||||
|
||||
const short = (sha: string) => sha.slice(0, 7);
|
||||
|
||||
/** Titles of the platform's stories by key (missing ones are left out). */
|
||||
async function storyTitles(db: Db, keys: string[]): Promise<Map<string, string>> {
|
||||
const pk = platformProjectKey();
|
||||
const [p] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, pk));
|
||||
const out = new Map<string, string>();
|
||||
if (!p || !keys.length) return out;
|
||||
const rows = await db.select({ number: tasks.number, title: tasks.title }).from(tasks).where(eq(tasks.projectId, p.id));
|
||||
for (const r of rows) out.set(formatTaskKey(pk, r.number), r.title);
|
||||
return out;
|
||||
}
|
||||
|
||||
function storyLine(webUrl: string, key: string, title: string | undefined): string {
|
||||
return ` • <a href="${esc(`${webUrl}/t/${key}`)}">${esc(key)}</a>${title ? ` ${esc(title.length > 70 ? `${title.slice(0, 70)}…` : title)}` : ""}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A new build of Peppa is live (watchdog, runner/platform-build.ts). The first one is only
|
||||
* remembered; later ones are posted to the channel: «🚀 Peppa v0.16.0 · b1c2d3e» + stories.
|
||||
*/
|
||||
export async function announcePlatformBuild(db: Db, b: Omit<PlatformBuild, "at">, o: { now?: Date } = {}): Promise<boolean> {
|
||||
const prev = await getPlatformBuild(db);
|
||||
if (prev?.commit === b.commit) return false;
|
||||
const build: PlatformBuild = { ...b, at: (o.now ?? new Date()).toISOString() };
|
||||
await setSetting(db, BUILD, build);
|
||||
if (!prev) return false;
|
||||
await setSetting(db, BUILDS, [...(await recentPlatformBuilds(db)), build].slice(-20));
|
||||
return postToChannel(db, "releases", `pch:release:${b.commit}`, renderBuild(build, await storyTitles(db, build.tasks)));
|
||||
}
|
||||
|
||||
export function renderBuild(b: PlatformBuild, titles: Map<string, string> = new Map()): string {
|
||||
const webUrl = loadEnv().PEPPA_WEB_URL;
|
||||
const lines = [`🚀 <b>Peppa v${esc(b.version)} · ${esc(short(b.commit))}</b>`];
|
||||
if (b.tasks.length) lines.push(`Стори: ${b.tasks.map(esc).join(", ")}`, ...b.tasks.slice(0, 15).map((k) => storyLine(webUrl, k, titles.get(k))));
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
// ── platform digest ────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface PlatformDigest {
|
||||
since: Date;
|
||||
build: PlatformBuild | null;
|
||||
/** Builds announced since the previous digest. */
|
||||
builds: PlatformBuild[];
|
||||
/** Platform stories finished since the previous digest. */
|
||||
done: { key: string; title: string }[];
|
||||
services: { name: string; ok: boolean; state: string }[];
|
||||
runners: number;
|
||||
questions: number;
|
||||
rateLimited: number;
|
||||
limits: string[];
|
||||
}
|
||||
|
||||
/** Changes of Peppa since `since` and the current state of the platform. */
|
||||
export async function buildPlatformDigest(db: Db, o: { since: Date; now?: Date }): Promise<PlatformDigest> {
|
||||
const now = o.now ?? new Date();
|
||||
const { serviceStatus, describeState, SERVICE_NAMES } = await import("./monitor.ts");
|
||||
const pk = platformProjectKey();
|
||||
const [p] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, pk));
|
||||
const done = p
|
||||
? (
|
||||
await db
|
||||
.select({ number: tasks.number, title: tasks.title })
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.projectId, p.id), eq(tasks.status, "done"), gte(tasks.updatedAt, o.since)))
|
||||
.orderBy(asc(tasks.number))
|
||||
).map((t) => ({ key: formatTaskKey(pk, t.number), title: t.title }))
|
||||
: [];
|
||||
const live = await db.select({ status: sessions.status }).from(sessions).where(notInArray(sessions.status, FINISHED_SESSION_STATUSES));
|
||||
const open = await db.select({ id: questions.id }).from(questions).where(isNull(questions.answeredAt));
|
||||
const services = (await serviceStatus(db, { now })).filter((s) => s.heartbeat).map((s) => ({ name: SERVICE_NAMES[s.service], ok: s.ok, state: describeState(s) }));
|
||||
const limits = (await listAccountUsage(db, { now: now.getTime() }))
|
||||
.filter((a) => a.limitedUntil || (a.fiveHour?.pct ?? 0) >= 50 || (a.sevenDay?.pct ?? 0) >= 50)
|
||||
.map(describeAccount);
|
||||
return {
|
||||
since: o.since,
|
||||
build: await getPlatformBuild(db),
|
||||
builds: (await recentPlatformBuilds(db)).filter((b) => Date.parse(b.at) >= o.since.getTime()),
|
||||
done,
|
||||
services,
|
||||
runners: live.length,
|
||||
questions: open.length,
|
||||
rateLimited: live.filter((s) => s.status === "rate_limited").length,
|
||||
limits,
|
||||
};
|
||||
}
|
||||
|
||||
/** Nothing new and nothing going on: the digest isn't sent. */
|
||||
export const platformDigestEmpty = (d: PlatformDigest) => !d.done.length && !d.builds.length && !d.runners && !d.questions && d.services.every((s) => s.ok);
|
||||
|
||||
export function renderPlatformDigest(d: PlatformDigest): string {
|
||||
const webUrl = loadEnv().PEPPA_WEB_URL;
|
||||
const lines = ["🐷 <b>Дайджест Пеппы</b>"];
|
||||
if (d.done.length || d.builds.length) {
|
||||
lines.push("", "<b>Что нового</b>");
|
||||
for (const b of d.builds) lines.push(`🚀 v${esc(b.version)} · ${esc(short(b.commit))}`);
|
||||
if (d.done.length) lines.push(`✅ Сделано: ${d.done.map((t) => esc(t.key)).join(", ")}`, ...d.done.slice(0, 12).map((t) => storyLine(webUrl, t.key, t.title)));
|
||||
if (d.done.length > 12) lines.push(` …и ещё ${d.done.length - 12}`);
|
||||
}
|
||||
lines.push("", "<b>Сейчас</b>");
|
||||
if (d.build) lines.push(`Версия: v${esc(d.build.version)} · ${esc(short(d.build.commit))}`);
|
||||
if (d.services.length) lines.push(`Сервисы: ${d.services.map((s) => `${s.ok ? "✅" : "⚠️"} ${esc(s.name)}${s.ok ? "" : ` (${esc(s.state)})`}`).join(", ")}`);
|
||||
lines.push(`Раннеров: ${d.runners}${d.rateLimited ? ` (ждут сброса лимита: ${d.rateLimited})` : ""}`, `Вопросов: ${d.questions}`);
|
||||
if (d.limits.length) lines.push(`Лимиты: ${d.limits.map(esc).join("; ")}`);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
const LAST = "platform.digest.last";
|
||||
const WINDOW_MIN = 180;
|
||||
|
||||
/**
|
||||
* Watchdog tick: at the platform's digest time (once a local day) builds the digest over the
|
||||
* time since the previous one and sends it to the channel and, when enabled, to every paired
|
||||
* user who keeps the «platform» notification on. Returns where it went.
|
||||
*/
|
||||
export async function platformDigestTick(db: Db, o: { now?: Date; force?: boolean; log?: (m: string) => void } = {}): Promise<{ channel: boolean; users: number } | null> {
|
||||
const now = o.now ?? new Date();
|
||||
const c = await getPlatformChannel(db);
|
||||
const clock = localClock(now, c.digest.timezone);
|
||||
const target = hhmmToMinutes(c.digest.time);
|
||||
const last = await getSetting<{ date: string; at: string }>(db, LAST);
|
||||
if (!o.force) {
|
||||
if (clock.minutes < target || clock.minutes >= target + WINDOW_MIN) return null;
|
||||
if (last?.date === clock.date) return null;
|
||||
}
|
||||
const toChannel = c.chatId != null && !!c.check?.ok && c.events.digest;
|
||||
if (!toChannel && !c.digest.users) return null;
|
||||
await setSetting(db, LAST, { date: clock.date, at: now.toISOString() });
|
||||
const since = last ? new Date(last.at) : new Date(now.getTime() - 24 * 3600_000);
|
||||
const d = await buildPlatformDigest(db, { since, now });
|
||||
if (platformDigestEmpty(d)) {
|
||||
o.log?.("platform digest: nothing to report");
|
||||
return { channel: false, users: 0 };
|
||||
}
|
||||
const text = renderPlatformDigest(d);
|
||||
const channel = toChannel && (await postToChannel(db, "digest", `pch:digest:${clock.date}`, text, c));
|
||||
let sent = 0;
|
||||
if (c.digest.users) {
|
||||
const paired = (await db.select().from(users).where(isNotNull(users.telegramChatId))).filter((u) => !u.disabledAt);
|
||||
for (const u of paired) {
|
||||
const r = await deliverToUser(db, u, {
|
||||
event: "platform",
|
||||
dedupeKey: `pdigest:${clock.date}:${u.telegramChatId}`,
|
||||
telegram: { params: { text, parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
|
||||
now,
|
||||
});
|
||||
if (r.telegram) sent++;
|
||||
}
|
||||
}
|
||||
o.log?.(`platform digest: channel ${channel ? "yes" : "no"}, users ${sent}`);
|
||||
return { channel, users: sent };
|
||||
}
|
||||
@ -17,6 +17,7 @@ export * from "./triage.ts";
|
||||
export * from "./ci-feedback.ts";
|
||||
export * from "./deploy.ts";
|
||||
export * from "./platform-release.ts";
|
||||
export * from "./platform-build.ts";
|
||||
export * from "./code.ts";
|
||||
export * from "./agents-md.ts";
|
||||
export * from "./terminal.ts";
|
||||
|
||||
57
packages/runner/src/platform-build.ts
Normal file
57
packages/runner/src/platform-build.ts
Normal file
@ -0,0 +1,57 @@
|
||||
// New builds of Peppa (PEP-60). The watchdog looks at HEAD of Peppa's checkout about once a
|
||||
// minute; a commit that differs from the last announced one and belongs to `main` is a
|
||||
// release: posted to the platform channel with the stories from the commit messages. Works
|
||||
// now (dev from the working copy: a story branch isn't announced, returning to an updated
|
||||
// main is) and in prod (PEP-18: ~/peppa/current is a worktree of a `main` commit).
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { announcePlatformBuild, getPlatformBuild, headCommit, peppaVersion, platformProjectKey } from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
|
||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../..");
|
||||
|
||||
const git = (root: string, args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
|
||||
|
||||
/** True when `commit` is reachable from the branch (default `main`). */
|
||||
export function onMainBranch(root: string, commit: string, branch = process.env.PEPPA_MAIN_BRANCH || "main"): boolean {
|
||||
try {
|
||||
git(root, ["merge-base", "--is-ancestor", commit, branch]);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Platform stories mentioned in the commits `prev..commit` (all of HEAD's history is too much: none then). */
|
||||
export function storiesBetween(root: string, prev: string | null, commit: string, key = platformProjectKey()): string[] {
|
||||
if (!prev) return [];
|
||||
let log = "";
|
||||
try {
|
||||
log = git(root, ["log", "--format=%s%n%b", `${prev}..${commit}`]);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const re = new RegExp(`\\b${key}-(\\d+)\\b`, "gi");
|
||||
const nums = new Set<number>();
|
||||
for (const m of log.matchAll(re)) nums.add(Number(m[1]));
|
||||
return [...nums].sort((a, b) => a - b).map((n) => `${key}-${n}`);
|
||||
}
|
||||
|
||||
let lastCheck = 0;
|
||||
|
||||
/** Watchdog: announces a new build of Peppa once (first run only remembers it). */
|
||||
export async function platformBuildTick(db: Db, o: { root?: string; now?: Date; force?: boolean; log?: (m: string) => void } = {}): Promise<boolean> {
|
||||
const nowMs = (o.now ?? new Date()).getTime();
|
||||
if (!o.force && Math.abs(nowMs - lastCheck) < 60_000) return false;
|
||||
lastCheck = nowMs;
|
||||
const root = o.root ?? process.env.PEPPA_ROOT ?? ROOT;
|
||||
const commit = headCommit(root);
|
||||
if (!commit) return false;
|
||||
const prev = await getPlatformBuild(db);
|
||||
if (prev?.commit === commit || !onMainBranch(root, commit)) return false;
|
||||
const tasks = storiesBetween(root, prev?.commit ?? null, commit);
|
||||
const posted = await announcePlatformBuild(db, { version: peppaVersion(root), commit, tasks }, { now: o.now });
|
||||
o.log?.(`platform build ${commit.slice(0, 7)}${tasks.length ? ` (${tasks.join(", ")})` : ""}${posted ? " → channel" : ""}`);
|
||||
return posted;
|
||||
}
|
||||
@ -5,6 +5,8 @@ import { createHash } from "node:crypto";
|
||||
import {
|
||||
backupDb,
|
||||
digestTick,
|
||||
platformDigestTick,
|
||||
recheckPlatformChannel,
|
||||
getBudgetState,
|
||||
runAsActor,
|
||||
expireSessionQuestions,
|
||||
@ -23,6 +25,7 @@ import { hostTick } from "./hosts.ts";
|
||||
import { getSubscription, isUsable } from "@peppa/core";
|
||||
import { planRotation, rotationEnabled, tryRotate, usageWarning } from "./rotation.ts";
|
||||
import { monitorTick } from "./monitor.ts";
|
||||
import { platformBuildTick } from "./platform-build.ts";
|
||||
import { incidentTick } from "./incidents.ts";
|
||||
import { pollChecks } from "./ci-feedback.ts";
|
||||
import { reviewTick } from "./reviewer.ts";
|
||||
@ -83,6 +86,11 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise<void> {
|
||||
await incidentTick(db, { now: opts.now, log }).catch((e) => log(`incidents: ${(e as Error).message}`));
|
||||
// Daily digest at each user's time (PEP-29); a no-op outside their window.
|
||||
await digestTick(db, { now: opts.now, log }).catch((e) => log(`digest: ${(e as Error).message}`));
|
||||
// PEP-60: platform channel — re-check a channel that isn't working yet, new builds, the
|
||||
// platform digest at its time.
|
||||
await recheckPlatformChannel(db, { now: opts.now, log }).catch((e) => log(`platform channel: ${(e as Error).message}`));
|
||||
await platformBuildTick(db, { now: opts.now, log }).catch((e) => log(`platform build: ${(e as Error).message}`));
|
||||
await platformDigestTick(db, { now: opts.now, log }).catch((e) => log(`platform digest: ${(e as Error).message}`));
|
||||
}
|
||||
|
||||
async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: WatchdogSettings, log: (m: string) => void) {
|
||||
|
||||
@ -32,8 +32,15 @@ export class MockTelegram {
|
||||
private server: Server | null = null;
|
||||
/** PEP-45: uploaded voice files by file_id (served at /file/bot<token>/<file_path>). */
|
||||
private files = new Map<string, { path: string; data: Buffer }>();
|
||||
/** PEP-60: channels by chat id; the bot's membership decides what getChat/sendMessage do. */
|
||||
readonly channels = new Map<number, { title: string; bot: "administrator" | "member" | "left"; canPost: boolean }>();
|
||||
url = "";
|
||||
|
||||
/** A channel; by default the bot is its admin with the right to post. */
|
||||
addChannel(chatId: number, title: string, o: { bot?: "administrator" | "member" | "left"; canPost?: boolean } = {}) {
|
||||
this.channels.set(chatId, { title, bot: o.bot ?? "administrator", canPost: o.canPost ?? true });
|
||||
}
|
||||
|
||||
async start(port = 0): Promise<this> {
|
||||
this.server = createServer((req, res) => {
|
||||
let body = "";
|
||||
@ -94,7 +101,24 @@ export class MockTelegram {
|
||||
}
|
||||
return { ok: true, result: pending() };
|
||||
}
|
||||
case "getChat": {
|
||||
const c = this.channels.get(Number(p.chat_id));
|
||||
if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
|
||||
return { ok: true, result: { id: Number(p.chat_id), type: "channel", title: c.title } };
|
||||
}
|
||||
case "getChatMember": {
|
||||
const c = this.channels.get(Number(p.chat_id));
|
||||
if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
|
||||
if (Number(p.user_id) !== this.bot.id) return { ok: false, error_code: 400, description: "Bad Request: user not found" };
|
||||
return { ok: true, result: { user: this.bot, status: c.bot, ...(c.bot === "administrator" ? { can_post_messages: c.canPost } : {}) } };
|
||||
}
|
||||
case "sendMessage": {
|
||||
// Channels (-100…): the bot must be an admin that may post.
|
||||
if (String(p.chat_id).startsWith("-100")) {
|
||||
const c = this.channels.get(Number(p.chat_id));
|
||||
if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
|
||||
if (c.bot !== "administrator" || !c.canPost) return { ok: false, error_code: 403, description: "Forbidden: bot is not a member of the channel chat" };
|
||||
}
|
||||
const m: MockTgMessage = {
|
||||
message_id: this.nextMessageId++,
|
||||
chat_id: Number(p.chat_id),
|
||||
|
||||
309
packages/testkit/test/platform-channel.test.ts
Normal file
309
packages/testkit/test/platform-channel.test.ts
Normal file
@ -0,0 +1,309 @@
|
||||
// PEP-60, spec platform-notifications: the platform channel (check through the Bot API),
|
||||
// platform events (new build, outage/recovery, restart) and the platform digest to the
|
||||
// channel and to users — mock-telegram as the Bot API, the real bot delivers the outbox,
|
||||
// a temp git repo as Peppa's checkout for builds.
|
||||
import assert from "node:assert/strict";
|
||||
import { execFile, execFileSync } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { after, before, beforeEach, describe, test } from "node:test";
|
||||
// helpers must load first: it sets the isolated test env that runner modules read on load.
|
||||
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
||||
import { MockTelegram } from "../src/mock-telegram.ts";
|
||||
import { questions, sessions, tasks, telegramOutbox, users } from "@peppa/db";
|
||||
import { eq, like, sql } from "drizzle-orm";
|
||||
|
||||
const { createBot } = await import("@peppa/bot");
|
||||
const { TelegramApi } = await import("@peppa/bot/telegram");
|
||||
|
||||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||||
const MIN = 60_000;
|
||||
const CHANNEL = -1004371018094;
|
||||
const tg = await new MockTelegram().start();
|
||||
const TG = { token: tg.token, apiUrl: tg.url };
|
||||
process.env.TELEGRAM_BOT_TOKEN = tg.token;
|
||||
process.env.TELEGRAM_API_URL = tg.url;
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
process.env.PEPPA_TZ = "UTC";
|
||||
|
||||
const ANNA = { login: "mock-anna", chatId: 9301 };
|
||||
const BEK = { login: "mock-bek", chatId: 9302 };
|
||||
let pep: Awaited<ReturnType<typeof project>>;
|
||||
let pepId = 0;
|
||||
|
||||
async function pair(login: string, chatId: number, giteaId: number) {
|
||||
const u = await core.upsertUserFromGitea(db, { id: giteaId, login }, { access_token: "x" });
|
||||
await db.update(users).set({ telegramChatId: chatId, telegramUserId: chatId }).where(eq(users.id, u.id));
|
||||
return u;
|
||||
}
|
||||
|
||||
/** Texts queued for a chat, oldest first. */
|
||||
async function queued(chatId: number, keyLike = "%"): Promise<string[]> {
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(telegramOutbox)
|
||||
.where(sql`${telegramOutbox.dedupeKey} like ${keyLike} and cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(chatId)}`)
|
||||
.orderBy(telegramOutbox.id);
|
||||
return rows.map((r) => String(r.params.text));
|
||||
}
|
||||
|
||||
async function connectChannel() {
|
||||
tg.addChannel(CHANNEL, "Peppa News");
|
||||
await core.setPlatformChannel(db, { chatId: CHANNEL });
|
||||
return core.checkPlatformChannel(db, TG);
|
||||
}
|
||||
|
||||
before(async () => {
|
||||
pep = await project({ steps: [] });
|
||||
process.env.PEPPA_PLATFORM_KEY = pep.key;
|
||||
pepId = (await core.getProject(db, pep.key)).id;
|
||||
await pair(ANNA.login, ANNA.chatId, 9401);
|
||||
await pair(BEK.login, BEK.chatId, 9402);
|
||||
});
|
||||
beforeEach(async () => {
|
||||
db.run(sql`delete from settings where key like 'platform.%' or key like 'heartbeat:%' or key like 'monitor.%' or key like 'notify.prefs:%'`);
|
||||
await db.delete(telegramOutbox);
|
||||
await db.delete(sessions);
|
||||
tg.channels.clear();
|
||||
});
|
||||
after(async () => {
|
||||
await tg.stop();
|
||||
await teardown();
|
||||
});
|
||||
|
||||
describe("Канал платформы", () => {
|
||||
test("Бот — админ канала", async () => {
|
||||
const c = await connectChannel();
|
||||
assert.equal(c.check?.ok, true);
|
||||
assert.equal(core.describeChannel(c), "канал подключён — Peppa News");
|
||||
assert.equal((await core.getPlatformChannel(db)).title, "Peppa News");
|
||||
});
|
||||
|
||||
test("Бот не добавлен в канал", async () => {
|
||||
await core.setPlatformChannel(db, { chatId: CHANNEL });
|
||||
const c = await core.checkPlatformChannel(db, TG);
|
||||
assert.equal(c.check?.ok, false);
|
||||
assert.equal(c.check?.error, "бот не видит канал — добавьте его администратором");
|
||||
// Not posting while the channel doesn't work.
|
||||
assert.equal(await core.postToChannel(db, "releases", "pch:test", "x"), false);
|
||||
});
|
||||
|
||||
test("Бот в канале без права публикации", async () => {
|
||||
tg.addChannel(CHANNEL, "Peppa News", { canPost: false });
|
||||
await core.setPlatformChannel(db, { chatId: CHANNEL });
|
||||
const c = await core.checkPlatformChannel(db, TG);
|
||||
assert.equal(c.check?.error, core.CHANNEL_NO_POST);
|
||||
});
|
||||
|
||||
test("Пеппа перепроверяет неработающий канал раз в час и включает его", async () => {
|
||||
await core.setPlatformChannel(db, { chatId: CHANNEL });
|
||||
const t0 = new Date("2026-03-01T10:00:00Z");
|
||||
assert.equal(await core.recheckPlatformChannel(db, { now: t0, tg: TG }), true);
|
||||
assert.equal((await core.getPlatformChannel(db)).check?.ok, false);
|
||||
tg.addChannel(CHANNEL, "Peppa News");
|
||||
assert.equal(await core.recheckPlatformChannel(db, { now: new Date(t0.getTime() + 30 * MIN), tg: TG }), false, "не раньше часа");
|
||||
assert.equal(await core.recheckPlatformChannel(db, { now: new Date(t0.getTime() + 61 * MIN), tg: TG }), true);
|
||||
assert.equal((await core.getPlatformChannel(db)).check?.ok, true);
|
||||
});
|
||||
|
||||
test("Неверный Chat ID и сброс проверки при смене канала", async () => {
|
||||
assert.throws(() => core.parseChatId("канал"), /Chat ID/);
|
||||
assert.equal(core.parseChatId("@peppa_news"), "@peppa_news");
|
||||
await connectChannel();
|
||||
const c = await core.setPlatformChannel(db, { chatId: -1009999999999 });
|
||||
assert.equal(c.check, null);
|
||||
});
|
||||
|
||||
test("Не суперадмин", async () => {
|
||||
await core.setPlatformAdmins(db, [ANNA.login]);
|
||||
await assert.rejects(core.requireSuperadmin(db, { login: BEK.login }));
|
||||
await core.requireSuperadmin(db, { login: ANNA.login });
|
||||
});
|
||||
|
||||
test("CLI: peppa platform channel", async () => {
|
||||
tg.addChannel(CHANNEL, "Peppa News");
|
||||
// Async: the mock Bot API lives in this process.
|
||||
const { stdout: out } = await promisify(execFile)(process.execPath, [join(ROOT, "packages/cli/src/index.ts"), "platform", "channel", `chat=${CHANNEL}`, "services=off", "time=08:30"], { encoding: "utf8", env: process.env });
|
||||
assert.match(out, /канал подключён — Peppa News/);
|
||||
assert.match(out, /services=off/);
|
||||
assert.match(out, /дайджест: 08:30/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("События платформы в канал", () => {
|
||||
test("Новый релиз", async () => {
|
||||
await connectChannel();
|
||||
await db.insert(tasks).values([
|
||||
{ projectId: pepId, number: 59, title: "Версия и коммит в футере веба" },
|
||||
{ projectId: pepId, number: 61, title: "Меню сверху" },
|
||||
]);
|
||||
const k = (n: number) => `${pep.key}-${n}`;
|
||||
assert.equal(await core.announcePlatformBuild(db, { version: "0.15.0", commit: "aa8796a".padEnd(40, "0"), tasks: [] }), false, "первая сборка только запоминается");
|
||||
assert.equal(await core.announcePlatformBuild(db, { version: "0.16.0", commit: "b1c2d3e".padEnd(40, "1"), tasks: [k(59), k(61)] }), true);
|
||||
const [msg] = await queued(CHANNEL);
|
||||
assert.match(msg!, /Peppa v0\.16\.0 · b1c2d3e/);
|
||||
assert.match(msg!, new RegExp(`Стори: ${k(59)}, ${k(61)}`));
|
||||
assert.match(msg!, /Версия и коммит в футере веба/);
|
||||
// The same commit again — nothing new.
|
||||
assert.equal(await core.announcePlatformBuild(db, { version: "0.16.0", commit: "b1c2d3e".padEnd(40, "1"), tasks: [] }), false);
|
||||
assert.equal((await queued(CHANNEL)).length, 1);
|
||||
});
|
||||
|
||||
test("Сборка из ветки стори не объявляется, из main — со стори из коммитов", async () => {
|
||||
await connectChannel();
|
||||
const repo = mkdtempSync(join(tmpdir(), "peppa-build-"));
|
||||
const git = (...a: string[]) => execFileSync("git", ["-C", repo, "-c", "user.name=t", "-c", "user.email=t@t", ...a], { encoding: "utf8" }).trim();
|
||||
git("init", "-q", "-b", "main");
|
||||
writeFileSync(join(repo, "package.json"), JSON.stringify({ version: "0.15.0" }));
|
||||
git("add", "-A");
|
||||
git("commit", "-qm", "base");
|
||||
const now = new Date("2026-03-02T10:00:00Z");
|
||||
await runner.platformBuildTick(db, { root: repo, force: true, now });
|
||||
assert.equal((await core.getPlatformBuild(db))?.version, "0.15.0");
|
||||
// A story branch checked out: not a release.
|
||||
git("checkout", "-qb", `task/${pep.key.toLowerCase()}-70`);
|
||||
mkdirSync(join(repo, "src"));
|
||||
writeFileSync(join(repo, "src/a.txt"), "a");
|
||||
git("add", "-A");
|
||||
git("commit", "-qm", `${pep.key}-70: work in progress`);
|
||||
assert.equal(await runner.platformBuildTick(db, { root: repo, force: true, now }), false);
|
||||
// Merged into main with a version bump: announced with the stories of the merged commits.
|
||||
git("checkout", "-q", "main");
|
||||
git("merge", "-q", "--no-ff", "-m", `Merge pull request '${pep.key}-70: канал' (#9) from task/${pep.key.toLowerCase()}-70 into main`, `task/${pep.key.toLowerCase()}-70`);
|
||||
writeFileSync(join(repo, "package.json"), JSON.stringify({ version: "0.16.0" }));
|
||||
git("commit", "-qam", `${pep.key}-72: bump`);
|
||||
assert.equal(await runner.platformBuildTick(db, { root: repo, force: true, now }), true);
|
||||
const [msg] = await queued(CHANNEL);
|
||||
assert.match(msg!, new RegExp(`Peppa v0\\.16\\.0 · ${git("rev-parse", "--short=7", "HEAD")}`));
|
||||
assert.match(msg!, new RegExp(`Стори: ${pep.key}-70, ${pep.key}-72`));
|
||||
});
|
||||
|
||||
test("Сервис упал и поднялся", async () => {
|
||||
await connectChannel();
|
||||
const T0 = Date.parse("2026-03-03T12:00:00Z");
|
||||
const at = (m: number) => new Date(T0 + m * MIN);
|
||||
const staleMs = 2 * MIN;
|
||||
await core.beat(db, "bot", { now: at(0) });
|
||||
for (const m of [1, 3, 4, 10]) {
|
||||
await core.checkServices(db, { self: "watchdog", now: at(m), staleMs });
|
||||
await core.checkServices(db, { self: "web", now: at(m), staleMs });
|
||||
}
|
||||
await core.beat(db, "bot", { now: at(12) });
|
||||
await core.checkServices(db, { self: "watchdog", now: at(12), staleMs });
|
||||
await core.checkServices(db, { self: "web", now: at(12.5), staleMs });
|
||||
const msgs = await queued(CHANNEL, "mon:ch:%");
|
||||
assert.equal(msgs.length, 2, msgs.join("\n"));
|
||||
assert.match(msgs[0]!, /бот не отвечает с/);
|
||||
assert.match(msgs[1]!, /бот снова работает — простой 12 мин/);
|
||||
});
|
||||
|
||||
test("Перезапуск сервиса без простоя", async () => {
|
||||
await connectChannel();
|
||||
const now = new Date();
|
||||
const hb = (pid: number) => ({ at: now.toISOString(), startedAt: new Date(now.getTime() - pid).toISOString(), pid, host: "mac", version: "0.15.0", commit: "abc1234".padEnd(40, "0") });
|
||||
await core.setSetting(db, "heartbeat:web", hb(100));
|
||||
await core.checkServices(db, { self: "watchdog", now });
|
||||
assert.equal((await queued(CHANNEL)).length, 0, "первый процесс только запоминается");
|
||||
await core.setSetting(db, "heartbeat:web", hb(200));
|
||||
await core.checkServices(db, { self: "watchdog", now });
|
||||
await core.checkServices(db, { self: "bot", now });
|
||||
const msgs = await queued(CHANNEL);
|
||||
assert.deepEqual(msgs, ["🔄 Пеппа: веб перезапущен (v0.15.0 · abc1234)."]);
|
||||
});
|
||||
|
||||
test("Выключенные события сервисов в канал не идут", async () => {
|
||||
await connectChannel();
|
||||
await core.setPlatformChannel(db, { events: { services: false } });
|
||||
const T0 = Date.parse("2026-03-04T12:00:00Z");
|
||||
await core.beat(db, "bot", { now: new Date(T0) });
|
||||
await core.checkServices(db, { self: "watchdog", now: new Date(T0 + 10 * MIN), staleMs: 2 * MIN });
|
||||
assert.equal((await queued(CHANNEL, "mon:ch:%")).length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Дайджест", () => {
|
||||
const day = (h: number, d = 5) => new Date(`2026-03-${String(d).padStart(2, "0")}T${String(h).padStart(2, "0")}:05:00Z`);
|
||||
|
||||
async function activity() {
|
||||
// Stories finished after the previous digest, two live runners and one open question.
|
||||
await db.insert(tasks).values([
|
||||
{ projectId: pepId, number: 159, title: "Футер с версией", status: "done", updatedAt: day(6) },
|
||||
{ projectId: pepId, number: 161, title: "Меню сверху", status: "done", updatedAt: day(7) },
|
||||
]);
|
||||
await db.insert(sessions).values([
|
||||
{ projectId: pepId, tmuxName: "mock-digest-1", status: "running" },
|
||||
{ projectId: pepId, tmuxName: "mock-digest-2", status: "idle" },
|
||||
]);
|
||||
await db.insert(questions).values({ projectId: pepId, kind: "question", text: "Какой цвет?" });
|
||||
}
|
||||
|
||||
async function cleanActivity() {
|
||||
await db.delete(questions);
|
||||
await db.delete(tasks).where(sql`${tasks.number} in (159, 161)`);
|
||||
}
|
||||
|
||||
test("Ежедневный дайджест", async () => {
|
||||
await connectChannel();
|
||||
await core.setSetting(db, "platform.digest.last", { date: "2026-03-04", at: day(9, 4).toISOString() });
|
||||
await activity();
|
||||
try {
|
||||
assert.equal(await core.platformDigestTick(db, { now: day(8) }), null, "до времени дайджеста — ничего");
|
||||
const r = await core.platformDigestTick(db, { now: day(9) });
|
||||
assert.deepEqual(r, { channel: true, users: 0 });
|
||||
const [msg] = await queued(CHANNEL, "pch:digest:%");
|
||||
assert.match(msg!, /<b>Что нового<\/b>/);
|
||||
assert.match(msg!, new RegExp(`Сделано: ${pep.key}-159, ${pep.key}-161`));
|
||||
assert.match(msg!, /<b>Сейчас<\/b>/);
|
||||
assert.match(msg!, /Раннеров: 2/);
|
||||
assert.match(msg!, /Вопросов: 1/);
|
||||
assert.equal(await core.platformDigestTick(db, { now: day(10) }), null, "раз в сутки");
|
||||
} finally {
|
||||
await cleanActivity();
|
||||
}
|
||||
});
|
||||
|
||||
test("Нечего сообщить", async () => {
|
||||
await connectChannel();
|
||||
await core.setSetting(db, "platform.digest.last", { date: "2026-03-04", at: day(9, 4).toISOString() });
|
||||
const r = await core.platformDigestTick(db, { now: day(9) });
|
||||
assert.deepEqual(r, { channel: false, users: 0 });
|
||||
assert.equal((await queued(CHANNEL)).length, 0);
|
||||
});
|
||||
|
||||
test("Отписка", async () => {
|
||||
await connectChannel();
|
||||
await core.setPlatformChannel(db, { digest: { users: true } });
|
||||
const anna = (await core.getUserByLogin(db, ANNA.login))!;
|
||||
const prefs = await core.getNotifyPrefs(db, anna.id);
|
||||
await core.setNotifyPrefs(db, anna.id, { ...prefs, events: { ...prefs.events, platform: { telegram: false, push: false } } });
|
||||
await core.setSetting(db, "platform.digest.last", { date: "2026-03-04", at: day(9, 4).toISOString() });
|
||||
await activity();
|
||||
try {
|
||||
const r = await core.platformDigestTick(db, { now: day(9) });
|
||||
assert.equal(r?.channel, true);
|
||||
assert.equal((await queued(ANNA.chatId, "pdigest:%")).length, 0, "отписавшийся не получает");
|
||||
assert.equal((await queued(BEK.chatId, "pdigest:%")).length, 1);
|
||||
assert.equal((await queued(CHANNEL, "pch:digest:%")).length, 1, "канал получает");
|
||||
} finally {
|
||||
await cleanActivity();
|
||||
}
|
||||
});
|
||||
|
||||
test("Бот доставляет сообщения канала из outbox", async () => {
|
||||
await connectChannel();
|
||||
await core.setPlatformChannel(db, { digest: { users: false } });
|
||||
await core.postToChannel(db, "releases", "pch:release:mock", "🚀 <b>Peppa v9.9.9 · mock000</b>");
|
||||
const bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 5000, heartbeatIntervalMs: 60_000 });
|
||||
await bot.start();
|
||||
try {
|
||||
await waitFor("channel message delivered", async () => tg.botMessages(CHANNEL).some((m) => /Peppa v9\.9\.9/.test(m.text)));
|
||||
const [row] = await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "pch:release:mock"));
|
||||
assert.equal(row?.status, "sent");
|
||||
} finally {
|
||||
await bot.stop();
|
||||
}
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user