brendmanager/test/agent.test.js
Peppa fbb384c1b2
All checks were successful
peppa/lint lint: success за 1с
peppa/test test: success за 1с
ci / checks (pull_request) Successful in 6s
deploy / deploy (pull_request) Successful in 15s
BRM-54: очередь задач с повторами, защита от дублей, дневной и недельный отчёты
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 01:54:15 +05:00

146 lines
8.4 KiB
JavaScript
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.

import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createJobs, BACKOFF_MS, permanent } from "../src/jobs.js";
import { createPublisher } from "../src/publisher.js";
import { createHandlers, failureNotifier } from "../src/agent.js";
import { mockTelegram } from "../src/telegram.js";
import { buildDailyReport, buildWeeklyReport } from "../src/reports.js";
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "brm54-"));
const clock = (t = Date.parse("2026-11-16T05:00:00Z")) => ({ now: () => t, adv: (ms) => { t += ms; } });
test("Сценарий: сбой отправки — повторы с растущей паузой, затем список ошибок и уведомление", async () => {
const dir = tmp(), c = clock();
const jobs = createJobs({ file: path.join(dir, "j.json"), now: c.now });
let calls = 0; const notes = [];
const handlers = { x: async () => { calls++; throw new Error("сеть"); } };
const j = jobs.add({ kind: "x" }).job;
const gaps = [];
for (let i = 0; i < 6; i++) {
await jobs.tick(handlers, { notify: async (x) => notes.push(x.id) });
const cur = jobs.get(j.id);
if (cur.status === "failed") break;
gaps.push(Date.parse(cur.nextAt) - c.now());
c.adv(Date.parse(cur.nextAt) - c.now());
}
assert.deepEqual(gaps, BACKOFF_MS);
assert.equal(calls, 5);
assert.equal(jobs.failed().length, 1);
assert.deepEqual(notes, [j.id]);
assert.equal(jobs.failed()[0].notified, true);
});
test("Сценарий: после перезапуска незавершённое продолжается, сделанное не повторяется", async () => {
const dir = tmp(), c = clock(), file = path.join(dir, "j.json");
let jobs = createJobs({ file, now: c.now });
const id = jobs.add({ kind: "x", key: "k1" }).job.id;
let n = 0;
await jobs.tick({ x: async () => { n++; return { ref: "№1" }; } });
jobs.add({ kind: "x", key: "k2" });
// «падение» посреди задачи: статус running на диске
const raw = JSON.parse(fs.readFileSync(file, "utf8")); raw.jobs[1].status = "running"; fs.writeFileSync(file, JSON.stringify(raw));
jobs = createJobs({ file, now: c.now });
assert.equal(jobs.get(2).status, "pending");
await jobs.tick({ x: async () => { n++; return { ref: "№2" }; } });
assert.equal(n, 2);
assert.equal(jobs.get(id).ref, "№1");
assert.equal(jobs.add({ kind: "x", key: "k1" }).duplicate, true); // та же задача заново не заводится
assert.equal(jobs.list().length, 2);
});
test("Сценарий: порядок — приоритет, срок и зависимости", async () => {
const c = clock(), jobs = createJobs({ file: path.join(tmp(), "j.json"), now: c.now });
const order = [];
const a = jobs.add({ kind: "x", payload: "a", priority: 3 }).job;
jobs.add({ kind: "x", payload: "b", priority: 1, dependsOn: [a.id] });
jobs.add({ kind: "x", payload: "c", priority: 2 });
jobs.add({ kind: "x", payload: "late", dueAt: c.now() + 1e6 });
await jobs.tick({ x: async (j) => { order.push(j.payload); } });
assert.deepEqual(order, ["c", "a", "b"]);
assert.equal(jobs.list("pending").length, 1);
});
test("Сценарий: зависимая задача падает вместе с зависимостью", async () => {
const jobs = createJobs({ file: path.join(tmp(), "j.json") });
const a = jobs.add({ kind: "x" }).job;
const b = jobs.add({ kind: "x", dependsOn: [a.id] }).job;
await jobs.tick({ x: async () => { throw permanent("нет"); } });
assert.equal(jobs.get(b.id).status, "failed");
});
test("Сценарий: одна публикация не уходит дважды, даже если запись о задаче потеряна", async () => {
const dir = tmp(), tg = mockTelegram(), c = clock();
const pub = createPublisher({ file: path.join(dir, "p.json"), channels: { telegram: tg }, now: c.now });
const handlers = createHandlers({ pub });
const payload = { channel: "telegram", text: "Пост", approvedBy: "tatiana" };
const j1 = createJobs({ file: path.join(dir, "a.json"), now: c.now });
j1.add({ kind: "publish", key: "post:1", payload });
await j1.tick(handlers);
const j2 = createJobs({ file: path.join(dir, "b.json"), now: c.now }); // журнал задач потерян
j2.add({ kind: "publish", key: "post:1", payload });
c.adv(3 * 864e5);
await j2.tick(handlers);
assert.equal(tg.sent.length, 1);
assert.equal(j2.list()[0].status, "done");
assert.match(j2.list()[0].ref, /№1/);
});
test("Сценарий: лимит публикаций переносит задачу без траты попыток", async () => {
const dir = tmp(), tg = mockTelegram(), c = clock();
const pub = createPublisher({ file: path.join(dir, "p.json"), channels: { telegram: tg }, now: c.now });
const jobs = createJobs({ file: path.join(dir, "j.json"), now: c.now });
const handlers = createHandlers({ pub });
jobs.add({ kind: "publish", key: "a", payload: { channel: "telegram", text: "A", approvedBy: "pm" } });
jobs.add({ kind: "publish", key: "b", payload: { channel: "telegram", text: "B", approvedBy: "pm" } });
await jobs.tick(handlers);
assert.equal(tg.sent.length, 1);
const b = jobs.get(2);
assert.equal(b.status, "pending"); assert.equal(b.attempts, 0);
c.adv(25 * 3600e3);
await jobs.tick(handlers);
assert.equal(tg.sent.length, 2);
});
test("Сценарий: уведомление о сбое не проходит мимо — без Telegram задача остаётся в списке ошибок", async () => {
const jobs = createJobs({ file: path.join(tmp(), "j.json") });
jobs.add({ kind: "x" });
const off = { connected: () => false, send: async () => {} };
await jobs.tick({ x: async () => { throw permanent("нет"); } }, { notify: failureNotifier(off) });
assert.equal(jobs.failed()[0].notified, false);
});
test("Сценарий: в дневном отчёте «запланировано» не выдаётся за «опубликовано», у результата есть номер", () => {
const log = [
{ time: "2026-11-16T05:00:00.000Z", channel: "telegram", text: "Вышел пост", result: "published", ref: "сообщение №7" },
{ time: "2026-11-16T06:00:00.000Z", channel: "telegram", text: "Не вышел", result: "error", reason: "сеть" },
];
const jobs = [
{ id: 1, kind: "publish", status: "pending", dueAt: "2026-11-16T07:00:00.000Z", lastError: "сеть", nextAt: "2026-11-16T07:05:00.000Z" },
{ id: 2, kind: "publish", status: "failed", dueAt: "2026-11-16T04:00:00.000Z", lastError: "нет доступа" },
{ id: 3, kind: "publish", status: "pending", dueAt: "2026-11-17T08:00:00.000Z" },
];
const t = buildDailyReport({ date: "2026-11-16", log, jobs, queue: [] });
const sec = (h) => t.split(`${h}:`)[1].split("\n\n")[0];
assert.match(sec("Сделано и опубликовано"), /Вышел пост — сообщение №7/);
assert.doesNotMatch(sec("Сделано и опубликовано"), /Не вышел/);
assert.match(t, /запланировано, но ещё не опубликовано: 2/);
assert.match(sec("Блокировки"), /нет доступа/);
assert.match(sec("План на завтра"), /publish №3/);
assert.ok(t.length <= 1500);
assert.match(buildDailyReport({ date: "2026-11-16", log: [], jobs: [] }), /Сделано и опубликовано:\nнет/);
});
test("Сценарий: недельный отчёт — показатели против старта, лиды, решения, план", () => {
const t = buildWeeklyReport({
date: "2026-11-22", log: [], jobs: [{ id: 4, kind: "publish", status: "pending", dueAt: "2026-11-23T05:00:00.000Z" }],
metrics: [{ name: "Отклики", unit: "шт.", entries: [{ date: "2026-11-01", value: 2 }, { date: "2026-11-20", value: 5 }] }],
opportunities: [{ stage: "Согласовано" }, { stage: "Выступили" }, { stage: "Идея" }], decisions: ["Выбрали Telegram"],
});
assert.match(t, /Отклики: 5 \(старт 2 на 2026-11-01, \+3\)/);
assert.match(t, /возможностей в работе: 2, согласовано: 1, выступили: 1/);
assert.match(t, /Выбрали Telegram/); assert.match(t, /нет данных об откликах по темам/); assert.match(t, /publish №4/);
});