peppa/packages/testkit/test/monitor.test.ts
Асель 3a282b8054 PEP-36 stage 2: SQLite (node:sqlite, WAL) instead of Postgres
- packages/db: schema on sqlite-core (timestamps as epoch ms → Date, JSON as text,
  booleans 0/1), one baseline migration; node:sqlite client under drizzle's
  better-sqlite3 session (busy_timeout first, WAL, BEGIN IMMEDIATE, retries on
  SQLITE_BUSY, lazy open, async transaction callbacks refused); PEPPA_DB
  (default ~/.peppa/peppa.db)
- live updates: notify() pokes the bot over a unix socket; the bot also watches
  PRAGMA data_version every second (writes by other processes)
- Postgres specifics ported: createTask transaction is synchronous, no
  `for update skip locked`, `count(*)`, json_extract instead of ->>, json_each
  instead of @>
- `peppa db migrate` and `peppa db migrate-to-sqlite <file>` (read-only
  snapshot of Postgres, FK order from the schema, row count + foreign key
  checks, file appears only when they pass); old Postgres schema kept in
  packages/cli/legacy-pg-migrations for the migration and its test
- daily VACUUM INTO backup from the watchdog (7 copies, admin alert on failure)
- tests: a temp SQLite file per test file; storage.test.ts (20 processes,
  per-project numbering across processes, socket/data_version, migration from
  Postgres incl. a dangling foreign key, backups); two test races fixed
- CI: no per-run Postgres database; PEPPA_TEST_PG only for the migration test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 17:23:24 +05:00

274 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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 { mkdtempSync } 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, 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 cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${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 () => {
db.run(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 () => {
// A database file without Peppa's tables (deleted and recreated, or the wrong file).
const dead = createDb(join(mkdtempSync(join(tmpdir(), "peppa-dead-")), "peppa.db"));
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);
dead.$client.close();
});
});
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();
}
});
});