- tsconfig: erasableSyntaxOnly + verbatimModuleSyntax; parameter properties rewritten (BugsinkError, GiteaError, GiteaClient, OAuthError, TelegramError, TelegramApi, MockGitea) - bin wrappers (peppa, peppa-mcp, peppa-hook, peppa-bot, testkit mocks, peppa-dev): `node --import scripts/lib/require-node.mjs` (clear error on Node < 26, PEPPA_NODE overrides the binary); package scripts and tests on `node` / `node --test`; tsx removed - install-launchd.sh pins PEPPA_NODE (checked absolute path) in the plists - fix a race the faster hooks exposed: the prompt hook answered every pending question, including a PM question raised after Peppa itself pasted text into the terminal; sendToSession now logs `input_sent` and the hook only answers questions older than that input - change pep-36-lightweight-stack: stage 1 done, hook start numbers Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
271 lines
11 KiB
TypeScript
271 lines
11 KiB
TypeScript
// PEP-20: service monitoring — heartbeats, /api/health report, alerts to platform admins
|
||
// (controlled clock, mock-telegram, the real bot), `peppa status`.
|
||
import assert from "node:assert/strict";
|
||
import { execFileSync } from "node:child_process";
|
||
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, runner, teardown, waitFor } from "./helpers.ts";
|
||
import { MockTelegram } from "../src/mock-telegram.ts";
|
||
import { telegramOutbox, users } from "@peppa/db";
|
||
import { eq, like, or, sql } from "drizzle-orm";
|
||
|
||
const { createBot } = await import("@peppa/bot");
|
||
const { TelegramApi } = await import("@peppa/bot/telegram");
|
||
const { createDb } = await import("@peppa/db");
|
||
|
||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||
const MIN = 60_000;
|
||
const T0 = Date.parse("2026-01-10T12:00:00Z");
|
||
const at = (m: number) => new Date(T0 + m * MIN);
|
||
|
||
const tg = await new MockTelegram().start();
|
||
const ADMIN = { login: "mock-admin", chatId: 9101 };
|
||
const OTHER = { login: "mock-other", chatId: 9102 };
|
||
const USER = { login: "mock-user", chatId: 9103 };
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
const logs: string[] = [];
|
||
const log = (m: string) => void logs.push(m);
|
||
|
||
async function pair(login: string, chatId: number | null, 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));
|
||
}
|
||
|
||
/** Monitor messages queued for a chat, oldest first. */
|
||
async function queued(chatId: number): Promise<string[]> {
|
||
const rows = await db
|
||
.select()
|
||
.from(telegramOutbox)
|
||
.where(sql`${telegramOutbox.dedupeKey} like 'mon:%' and ${telegramOutbox.params}->>'chat_id' = ${String(chatId)}`)
|
||
.orderBy(telegramOutbox.id);
|
||
return rows.map((r) => String(r.params.text));
|
||
}
|
||
|
||
const check = (self: "watchdog" | "bot", m: number) => core.checkServices(db, { self, now: at(m), log });
|
||
const beatAt = (service: "web" | "bot" | "watchdog", m: number) => core.beat(db, service, { now: at(m) });
|
||
|
||
before(async () => {
|
||
await pair(ADMIN.login, ADMIN.chatId, 9001);
|
||
await pair(OTHER.login, OTHER.chatId, 9002);
|
||
await pair(USER.login, USER.chatId, 9003);
|
||
await core.setAllowedLogins(db, [ADMIN.login, OTHER.login]);
|
||
});
|
||
beforeEach(async () => {
|
||
await db.execute(sql`delete from settings where key like 'heartbeat:%' or key like 'monitor.alert:%' or key = 'platform.admins'`);
|
||
await db.delete(telegramOutbox);
|
||
await core.setPlatformAdmins(db, [ADMIN.login]);
|
||
await pair(ADMIN.login, ADMIN.chatId, 9001);
|
||
logs.length = 0;
|
||
});
|
||
after(async () => {
|
||
await tg.stop();
|
||
await teardown();
|
||
});
|
||
|
||
describe("Heartbeat сервисов", () => {
|
||
test("Свежая отметка", async () => {
|
||
await beatAt("watchdog", 0);
|
||
const s = (await core.serviceStatus(db, { now: at(2) })).find((x) => x.service === "watchdog")!;
|
||
assert.equal(s.ok, true);
|
||
assert.equal(core.describeState(s), "ok");
|
||
assert.equal(core.minutes(s.ageMs!), 2);
|
||
assert.equal(s.heartbeat?.pid, process.pid);
|
||
assert.equal(s.heartbeat?.version, core.peppaVersion());
|
||
});
|
||
|
||
test("Старая отметка", async () => {
|
||
await beatAt("bot", 0);
|
||
const s = (await core.serviceStatus(db, { now: at(7) })).find((x) => x.service === "bot")!;
|
||
assert.equal(s.ok, false);
|
||
assert.equal(core.describeState(s), "молчит 7 мин");
|
||
});
|
||
|
||
test("Сервис ни разу не отмечался", async () => {
|
||
const s = (await core.serviceStatus(db, { now: at(0) })).find((x) => x.service === "web")!;
|
||
assert.equal(core.describeState(s), "нет данных");
|
||
assert.equal(await check("watchdog", 60), 0);
|
||
assert.deepEqual(await queued(ADMIN.chatId), []);
|
||
});
|
||
});
|
||
|
||
describe("Health-эндпоинт", () => {
|
||
test("Всё работает", async () => {
|
||
await beatAt("watchdog", 0);
|
||
const r = await core.healthReport(db, { now: at(1), version: "0.15.0", commit: "abc1234" });
|
||
assert.equal(r.ok, true);
|
||
assert.equal(r.db.ok, true);
|
||
assert.equal(r.version, "0.15.0");
|
||
assert.deepEqual(r.services.map((s) => s.service), ["web", "bot", "watchdog"]);
|
||
assert.equal(r.services.find((s) => s.service === "watchdog")?.ok, true);
|
||
assert.doesNotMatch(JSON.stringify(r), /mock-admin|9101/);
|
||
});
|
||
|
||
test("БД недоступна", async () => {
|
||
const dead = createDb("postgres://peppa:peppa@127.0.0.1:9/nothing");
|
||
const t0 = Date.now();
|
||
const r = await core.healthReport(dead, { version: "0.15.0" });
|
||
assert.ok(Date.now() - t0 < 3500);
|
||
assert.equal(r.ok, false);
|
||
assert.equal(r.db.ok, false);
|
||
assert.ok(r.db.error);
|
||
await dead.$client.end({ timeout: 0 }).catch(() => {});
|
||
});
|
||
});
|
||
|
||
describe("Алерт админу о молчащем сервисе", () => {
|
||
test("Бот молчит", async () => {
|
||
await beatAt("bot", 0);
|
||
await check("watchdog", 6);
|
||
const msgs = await queued(ADMIN.chatId);
|
||
assert.equal(msgs.length, 1);
|
||
assert.match(msgs[0]!, /бот молчит 6 мин/);
|
||
assert.deepEqual(await queued(USER.chatId), []);
|
||
assert.deepEqual(await queued(OTHER.chatId), []);
|
||
});
|
||
|
||
test("Сервис восстановился", async () => {
|
||
await beatAt("watchdog", 0);
|
||
await check("bot", 6);
|
||
assert.match((await queued(ADMIN.chatId))[0]!, /вачдог молчит/);
|
||
await beatAt("watchdog", 20);
|
||
await check("bot", 20);
|
||
const msgs = await queued(ADMIN.chatId);
|
||
assert.equal(msgs.length, 2);
|
||
assert.match(msgs[1]!, /вачдог снова на связи \(молчал 20 мин\)/);
|
||
// Recovered and quiet: nothing more.
|
||
await check("bot", 21);
|
||
assert.equal((await queued(ADMIN.chatId)).length, 2);
|
||
});
|
||
|
||
test("Упал сам бот", async () => {
|
||
await beatAt("bot", 0);
|
||
await runner.monitorTick(db, { now: at(6), log, telegram: { token: tg.token, apiUrl: tg.url } });
|
||
await waitFor("alert in admin's chat", async () => tg.botMessages(ADMIN.chatId).some((m) => /бот молчит 6 мин/.test(m.text)));
|
||
const [row] = await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "mon:bot:down:%"));
|
||
assert.equal(row?.status, "sent");
|
||
assert.ok(row?.telegramMessageId);
|
||
// Nothing left for the bot to send after its restart.
|
||
assert.equal((await core.dueOutbox(db)).length, 0);
|
||
// The watchdog's own heartbeat was written too.
|
||
assert.equal((await core.serviceStatus(db, { now: at(6) })).find((s) => s.service === "watchdog")?.ok, true);
|
||
});
|
||
|
||
test("Нет админа с привязкой", async () => {
|
||
await pair(ADMIN.login, null, 9001);
|
||
await beatAt("web", 0);
|
||
assert.equal(await check("watchdog", 10), 0);
|
||
assert.equal((await db.select().from(telegramOutbox)).length, 0);
|
||
assert.ok(logs.some((l) => /веб молчит 10 мин.*нет админа с Telegram/.test(l)));
|
||
});
|
||
|
||
for (const ex of [
|
||
{ admins: null, to: [ADMIN, OTHER] },
|
||
{ admins: [OTHER.login], to: [OTHER] },
|
||
]) {
|
||
test(`Кто админ: ${ex.admins ? `[${ex.admins.join(", ")}]` : "не задано"}`, async () => {
|
||
await core.setPlatformAdmins(db, ex.admins);
|
||
await beatAt("web", 0);
|
||
await check("watchdog", 6);
|
||
for (const u of [ADMIN, OTHER, USER]) {
|
||
assert.equal((await queued(u.chatId)).length, ex.to.includes(u) ? 1 : 0, `${u.login}`);
|
||
}
|
||
});
|
||
}
|
||
});
|
||
|
||
describe("Без спама", () => {
|
||
test("Повторные проверки", async () => {
|
||
await beatAt("bot", 0);
|
||
for (let m = 6; m <= 40; m += 0.5) await check("watchdog", m);
|
||
assert.equal((await queued(ADMIN.chatId)).length, 1);
|
||
});
|
||
|
||
test("Напоминание", async () => {
|
||
await beatAt("bot", 0);
|
||
for (let m = 6; m < 66; m += 5) await check("watchdog", m);
|
||
assert.equal((await queued(ADMIN.chatId)).length, 1);
|
||
await check("watchdog", 66);
|
||
await check("watchdog", 66.5);
|
||
const msgs = await queued(ADMIN.chatId);
|
||
assert.equal(msgs.length, 2);
|
||
assert.match(msgs[1]!, /бот молчит 66 мин/);
|
||
});
|
||
|
||
test("Дребезг", async () => {
|
||
await beatAt("bot", 0);
|
||
await check("watchdog", 6);
|
||
await beatAt("bot", 8);
|
||
await check("watchdog", 8);
|
||
assert.equal((await queued(ADMIN.chatId)).length, 2); // down + back up
|
||
// Quiet again since 8:00 → down at 13:00+; checks before 12:21 stay silent.
|
||
await check("watchdog", 15);
|
||
await check("watchdog", 20.5);
|
||
assert.equal((await queued(ADMIN.chatId)).length, 2);
|
||
await check("watchdog", 21.5);
|
||
await check("watchdog", 22);
|
||
const msgs = await queued(ADMIN.chatId);
|
||
assert.equal(msgs.length, 3);
|
||
assert.match(msgs[2]!, /бот молчит 14 мин/);
|
||
});
|
||
|
||
test("Две проверки одновременно", async () => {
|
||
await beatAt("web", 0);
|
||
await Promise.all([check("watchdog", 6), check("bot", 6.2)]);
|
||
assert.equal((await queued(ADMIN.chatId)).length, 1);
|
||
});
|
||
});
|
||
|
||
describe("Сводка в CLI", () => {
|
||
const cli = (...args: string[]) =>
|
||
execFileSync(process.execPath, [join(ROOT, "packages/cli/src/index.ts"), ...args], { encoding: "utf8", env: process.env });
|
||
|
||
test("Сводка", async () => {
|
||
const now = Date.now();
|
||
await core.beat(db, "watchdog", { now: new Date(now - MIN) });
|
||
await core.beat(db, "bot", { now: new Date(now - 10 * MIN) });
|
||
for (const i of [1, 2]) await core.enqueueTelegram(db, { dedupeKey: `mock-cli-${i}`, method: "sendMessage", params: { chat_id: 1, text: "x" } });
|
||
const out = cli("status");
|
||
assert.match(out, /вачдог\s+ok/);
|
||
assert.match(out, /бот\s+молчит 10 мин/);
|
||
assert.match(out, /веб\s+нет данных/);
|
||
assert.match(out, /outbox: 2 ожидают/);
|
||
});
|
||
|
||
test("Задать админов", async () => {
|
||
assert.match(cli("platform", "admins", OTHER.login), /^mock-other$/m);
|
||
assert.deepEqual(await core.platformAdmins(db), [OTHER.login]);
|
||
assert.match(cli("status"), /админы: mock-other \(Telegram\)/);
|
||
});
|
||
});
|
||
|
||
describe("бот: heartbeat и проверка вачдога", () => {
|
||
test("бот пишет heartbeat и доставляет алерт о молчащем вачдоге", async () => {
|
||
await core.beat(db, "watchdog", { now: new Date(Date.now() - 10 * MIN) });
|
||
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: 200,
|
||
});
|
||
await bot.start();
|
||
try {
|
||
await waitFor("bot heartbeat", async () => (await core.serviceStatus(db)).find((s) => s.service === "bot")?.ok);
|
||
await waitFor("watchdog alert delivered", async () => tg.botMessages(ADMIN.chatId).some((m) => /вачдог молчит 10 мин/.test(m.text)));
|
||
// Watchdog is back: the bot reports the recovery once.
|
||
await core.beat(db, "watchdog");
|
||
await waitFor("recovery delivered", async () => tg.botMessages(ADMIN.chatId).some((m) => /вачдог снова на связи/.test(m.text)));
|
||
const rows = await db.select().from(telegramOutbox).where(or(like(telegramOutbox.dedupeKey, "mon:watchdog:%")));
|
||
assert.equal(rows.length, 2);
|
||
assert.ok(rows.every((r) => r.status === "sent"));
|
||
} finally {
|
||
await bot.stop();
|
||
}
|
||
});
|
||
});
|