109 lines
7.0 KiB
TypeScript
109 lines
7.0 KiB
TypeScript
// PEP-208: the platform's night silence — from 23:00 to 08:00 nobody (the superadmin included)
|
||
// gets a new Telegram message or push; night messages wait and go out in the morning.
|
||
import assert from "node:assert/strict";
|
||
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, teardown, waitFor } from "./helpers.ts";
|
||
import { MockTelegram } from "../src/mock-telegram.ts";
|
||
import { pushOutbox, pushSubscriptions, telegramOutbox, users } from "@peppa/db";
|
||
import { eq } from "drizzle-orm";
|
||
import type { Bot } from "@peppa/bot";
|
||
|
||
const { createBot } = await import("@peppa/bot");
|
||
const { TelegramApi } = await import("@peppa/bot/telegram");
|
||
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
process.env.PEPPA_TZ = "Asia/Almaty"; // UTC+5, no DST
|
||
const at = (hhmm: string) => new Date(`2026-11-18T${hhmm}:00+05:00`);
|
||
const tg = await new MockTelegram().start();
|
||
const ADMIN = { id: 801, chatId: 801 };
|
||
const OWNER = { id: 802, chatId: 802 };
|
||
let bot: Bot;
|
||
|
||
/** A window around the real clock (the bot reads `new Date()`): "now" is night. */
|
||
function nightNow() {
|
||
const fmt = (d: Date) => d.toLocaleTimeString("en-GB", { timeZone: "Asia/Almaty", hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
|
||
process.env.PEPPA_NIGHT_QUIET = `${fmt(new Date(Date.now() - 10 * 60_000))}-${fmt(new Date(Date.now() + 60 * 60_000))}`;
|
||
}
|
||
const sentTo = (chatId: number, needle: string) => tg.calls.filter((c) => c.method === "sendMessage" && c.params.chat_id === chatId && String(c.params.text).includes(needle));
|
||
|
||
before(async () => {
|
||
const admin = await core.upsertUserFromGitea(db, { id: 91, login: "mock-admin" }, { access_token: "x" });
|
||
const owner = await core.upsertUserFromGitea(db, { id: 92, login: "mock-owner" }, { access_token: "y" });
|
||
await db.update(users).set({ telegramChatId: ADMIN.chatId, telegramUserId: ADMIN.id }).where(eq(users.id, admin.id));
|
||
await db.update(users).set({ telegramChatId: OWNER.chatId, telegramUserId: OWNER.id }).where(eq(users.id, owner.id));
|
||
await core.setSetting(db, "platform.admins", ["mock-admin"]);
|
||
bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 300, log: (m) => process.env.MOCK_DEBUG && console.log(m) });
|
||
await bot.start();
|
||
});
|
||
after(async () => {
|
||
await bot.stop();
|
||
await tg.stop();
|
||
await teardown();
|
||
});
|
||
beforeEach(() => {
|
||
process.env.PEPPA_NIGHT_QUIET = "23:00-08:00";
|
||
process.env.PEPPA_TZ = "Asia/Almaty";
|
||
});
|
||
|
||
describe("PEP-208: ночная тишина", () => {
|
||
test("Окно через полночь: 23:00–08:00 по времени платформы", () => {
|
||
assert.equal(core.inNightQuiet(at("22:59")), false);
|
||
assert.equal(core.inNightQuiet(at("23:00")), true);
|
||
assert.equal(core.inNightQuiet(at("02:00")), true);
|
||
assert.equal(core.inNightQuiet(at("07:59")), true);
|
||
assert.equal(core.inNightQuiet(at("08:00")), false);
|
||
assert.equal(core.inNightQuiet(at("10:00")), false);
|
||
process.env.PEPPA_NIGHT_QUIET = "off";
|
||
assert.equal(core.inNightQuiet(at("02:00")), false);
|
||
process.env.PEPPA_NIGHT_QUIET = "01:00-05:00";
|
||
assert.equal(core.inNightQuiet(at("02:00")), true);
|
||
assert.equal(core.inNightQuiet(at("23:30")), false);
|
||
});
|
||
|
||
test("Пометка «отвечено» ночью: правки проходят, новые сообщения ждут утра", async () => {
|
||
await core.enqueueTelegram(db, { dedupeKey: "nq:send", method: "sendMessage", params: { chat_id: 999001, text: "новое" } });
|
||
await core.enqueueTelegram(db, { dedupeKey: "nq:photo", method: "sendPhoto", params: { chat_id: 999001, photo_path: "/none" } });
|
||
await core.enqueueTelegram(db, { dedupeKey: "nq:edit", method: "editMessageText", params: { chat_id: 999001, message_id: 1, text: "отвечено" } });
|
||
await core.enqueueTelegram(db, { dedupeKey: "mon:nq:alert", method: "sendMessage", params: { chat_id: 999001, text: "сбой" } });
|
||
const keys = (rows: { dedupeKey: string }[]) => rows.map((r) => r.dedupeKey).filter((k) => k.includes("nq:")).sort();
|
||
const later = new Date(Date.now() + 60_000); // rows are due: nextAttemptAt ≤ later
|
||
process.env.PEPPA_NIGHT_QUIET = "00:00-23:59"; // night for any clock but 23:59
|
||
const night = core.inNightQuiet(later) ? later : new Date(later.getTime() + 3600_000);
|
||
assert.deepEqual(keys(await core.dueOutbox(db, 100, night)), ["nq:edit"]);
|
||
assert.deepEqual(keys(await core.pendingMonitorMessages(db, night)), []);
|
||
process.env.PEPPA_NIGHT_QUIET = "off"; // the window is over
|
||
assert.deepEqual(keys(await core.dueOutbox(db, 100, night)), ["mon:nq:alert", "nq:edit", "nq:photo", "nq:send"]);
|
||
assert.deepEqual(keys(await core.pendingMonitorMessages(db, night)), ["mon:nq:alert"]);
|
||
for (const k of ["nq:send", "nq:photo", "nq:edit", "mon:nq:alert"]) await db.delete(telegramOutbox).where(eq(telegramOutbox.dedupeKey, k));
|
||
});
|
||
|
||
test("Push ночью не уходит, лежит в очереди", async () => {
|
||
const [sub] = await db.insert(pushSubscriptions).values({ userId: (await core.getUserByLogin(db, "mock-owner"))!.id, endpoint: "http://127.0.0.1:9/mock-push", p256dh: "x", auth: "y" }).returning();
|
||
await db.insert(pushOutbox).values({ dedupeKey: "nq:push", subscriptionId: sub.id, payload: { title: "вопрос" } });
|
||
assert.equal(await core.flushPushOutbox(db, { now: at("02:00") }), 0);
|
||
const [row] = await db.select().from(pushOutbox).where(eq(pushOutbox.dedupeKey, "nq:push"));
|
||
assert.equal(row.status, "pending");
|
||
assert.equal(row.attempts, 0);
|
||
await db.delete(pushOutbox);
|
||
await db.delete(pushSubscriptions);
|
||
});
|
||
|
||
test("Вопрос агента ночью: ни владельцу, ни суперадмину; в 08:00 оба приходят", async () => {
|
||
nightNow();
|
||
await core.alertAdmins(db, "nq:admin-alert", "Ночной сбой агента", () => {});
|
||
await core.enqueueTelegram(db, { dedupeKey: "nq:owner-q", method: "sendMessage", params: { chat_id: OWNER.chatId, text: "Ночной вопрос владельцу" } });
|
||
await new Promise((r) => setTimeout(r, 800)); // several outbox passes of the bot
|
||
assert.equal(sentTo(ADMIN.chatId, "Ночной сбой агента").length, 0);
|
||
assert.equal(sentTo(OWNER.chatId, "Ночной вопрос владельцу").length, 0);
|
||
|
||
// A person writes the bot at night — the reply is not a mailing, it comes at once.
|
||
tg.userSends(OWNER, "/непонятная");
|
||
await waitFor("ответ бота ночью", async () => sentTo(OWNER.chatId, "реплаем").length > 0);
|
||
|
||
// Morning: the window is over.
|
||
process.env.PEPPA_NIGHT_QUIET = "off";
|
||
await waitFor("утренняя отправка", async () => sentTo(ADMIN.chatId, "Ночной сбой агента").length === 1 && sentTo(OWNER.chatId, "Ночной вопрос владельцу").length === 1);
|
||
});
|
||
});
|