109 lines
5.5 KiB
JavaScript
109 lines
5.5 KiB
JavaScript
import fs from "node:fs";
|
||
import path from "node:path";
|
||
|
||
// Очередь задач агента (BRM-54): срок, приоритет, зависимости, статус, повторы с растущей паузой.
|
||
export const BACKOFF_MS = [60e3, 5 * 60e3, 30 * 60e3, 2 * 3600e3]; // паузы между попытками
|
||
export const MAX_ATTEMPTS = BACKOFF_MS.length + 1;
|
||
export const STATUSES = ["pending", "running", "done", "failed"];
|
||
|
||
// Ошибка, которую повтором не исправить (нет доступа, остановка, правила): сразу в список ошибок.
|
||
export const permanent = (msg) => Object.assign(new Error(msg), { permanent: true });
|
||
// Ошибка «подождите до»: не считается попыткой (например, дневной лимит).
|
||
export const retryAt = (msg, at) => Object.assign(new Error(msg), { retryAt: at });
|
||
|
||
export function createJobs({ file, now = () => Date.now() }) {
|
||
let st;
|
||
try { st = JSON.parse(fs.readFileSync(file, "utf8")); } catch { st = {}; }
|
||
st.nextId ??= 1;
|
||
st.jobs ??= [];
|
||
st.effects ??= {}; // ключ → { at, ref }: внешнее действие уже сделано, повторять нельзя
|
||
// Перезапуск: задача, прерванная на середине, продолжается с той же попытки; сделанное не повторяется.
|
||
for (const j of st.jobs) if (j.status === "running") j.status = "pending";
|
||
const save = () => {
|
||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||
fs.writeFileSync(file + ".tmp", JSON.stringify(st, null, 2));
|
||
fs.renameSync(file + ".tmp", file);
|
||
};
|
||
save();
|
||
const iso = (t) => new Date(t).toISOString();
|
||
const byId = (id) => st.jobs.find((j) => j.id === id);
|
||
|
||
function add({ kind, key, payload = {}, dueAt, priority = 3, dependsOn = [] }) {
|
||
if (!kind) return { err: "Не указан вид задачи" };
|
||
if (key) {
|
||
const same = st.jobs.find((j) => j.key === key);
|
||
if (same) return { job: same, duplicate: true }; // та же задача второй раз не заводится
|
||
}
|
||
const job = {
|
||
id: st.nextId++, kind, key: key ?? null, payload, priority,
|
||
dueAt: dueAt ? iso(typeof dueAt === "string" ? Date.parse(dueAt) : dueAt) : iso(now()),
|
||
dependsOn, status: "pending", attempts: 0, nextAt: null, lastError: null, ref: null,
|
||
createdAt: iso(now()),
|
||
};
|
||
st.jobs.push(job);
|
||
save();
|
||
return { job };
|
||
}
|
||
|
||
const ready = (j, t) => j.status === "pending" && Date.parse(j.nextAt ?? j.dueAt) <= t
|
||
&& j.dependsOn.every((d) => byId(d)?.status === "done");
|
||
|
||
// Один проход: выполняет готовые задачи по приоритету (1 — самый важный), затем по сроку.
|
||
async function tick(handlers, { notify } = {}) {
|
||
const ran = [];
|
||
for (;;) {
|
||
const t = now();
|
||
const j = st.jobs.filter((x) => ready(x, t)).sort((a, b) => a.priority - b.priority || Date.parse(a.dueAt) - Date.parse(b.dueAt) || a.id - b.id)[0];
|
||
if (!j) break;
|
||
// зависимость провалилась — эта задача тоже не выполнится
|
||
const handler = handlers[j.kind];
|
||
if (j.key && st.effects[j.key]) { // действие уже сделано до перезапуска
|
||
j.status = "done"; j.ref = st.effects[j.key].ref; save(); ran.push(j); continue;
|
||
}
|
||
if (!handler) { fail(j, `нет обработчика «${j.kind}»`); save(); ran.push(j); continue; }
|
||
j.status = "running"; j.attempts++; save();
|
||
try {
|
||
const r = await handler(j);
|
||
j.status = "done"; j.lastError = null; j.ref = r?.ref ?? null; j.doneAt = iso(now());
|
||
if (j.key) st.effects[j.key] = { at: j.doneAt, ref: j.ref };
|
||
} catch (e) {
|
||
j.lastError = String(e.message ?? e);
|
||
if (e.retryAt) { j.attempts--; j.status = "pending"; j.nextAt = iso(Date.parse(e.retryAt)); }
|
||
else if (e.permanent || j.attempts >= MAX_ATTEMPTS) fail(j, j.lastError);
|
||
else { j.status = "pending"; j.nextAt = iso(now() + BACKOFF_MS[j.attempts - 1]); }
|
||
}
|
||
save();
|
||
ran.push(j);
|
||
if (j.status === "failed" && notify) {
|
||
try { await notify(j); j.notified = true; } catch { j.notified = false; }
|
||
save();
|
||
}
|
||
}
|
||
// задачи, ждущие провалившуюся зависимость, тоже в список ошибок
|
||
let more = true;
|
||
while (more) {
|
||
more = false;
|
||
for (const j of st.jobs) if (j.status === "pending" && j.dependsOn.some((d) => byId(d)?.status === "failed")) {
|
||
fail(j, "не выполнена задача, от которой она зависит"); more = true; save();
|
||
if (notify) { try { await notify(j); j.notified = true; } catch { j.notified = false; } save(); }
|
||
}
|
||
}
|
||
return ran;
|
||
}
|
||
function fail(j, why) { j.status = "failed"; j.lastError = why; j.failedAt = iso(now()); }
|
||
|
||
return {
|
||
add, tick, get: byId,
|
||
list: (status) => st.jobs.filter((j) => !status || j.status === status).map((j) => ({ ...j })),
|
||
failed: () => st.jobs.filter((j) => j.status === "failed").map((j) => ({ ...j })),
|
||
// ручной повтор задачи из списка ошибок
|
||
retry(id) {
|
||
const j = byId(id);
|
||
if (!j || j.status !== "failed") return null;
|
||
j.status = "pending"; j.attempts = 0; j.nextAt = null; j.notified = false; save();
|
||
return { ...j };
|
||
},
|
||
effects: () => ({ ...st.effects }),
|
||
};
|
||
}
|