import type { Logger, Pool } from "khb_common"; import { decide, lastDue } from "./due-calculator.js"; import type { JobSettings } from "./settings.js"; export interface DispatchResult { httpStatus: number; responseRef?: string; message?: string; } export interface TickDeps { pool: Pool; jobs: JobSettings[]; tz: string; graceSeconds: number; now?: () => Date; nonWorkdays: () => Promise>; dispatch: (job: JobSettings) => Promise; log: Logger; } /** Фиксирует срабатывание в sched_run; false, если запись (job, minute) уже есть (повторный старт исключён). */ async function claim(pool: Pool, job: string, minute: Date, status: "started" | "missed", message?: string): Promise { const { rows } = await pool.query( "insert into sched_run (job_name, scheduled_minute, status, message) values ($1,$2,$3,$4) on conflict (job_name, scheduled_minute) do nothing returning id", [job, minute, status, message ?? null], ); return rows[0]?.id ?? null; } async function run(deps: TickDeps, job: JobSettings, id: string): Promise { try { const r = await deps.dispatch(job); const ok = r.httpStatus >= 200 && r.httpStatus < 300; await deps.pool.query( "update sched_run set status = $2, finished_at = now(), http_status = $3, response_ref = $4, message = $5 where id = $1", [id, ok ? "ok" : "error", r.httpStatus, r.responseRef ?? null, r.message ?? null], ); if (!ok) deps.log.error({ job: job.name, ...r }, "вызов задания вернул ошибку"); } catch (e) { const msg = e instanceof Error ? e.message : String(e); await deps.pool.query("update sched_run set status = 'error', finished_at = now(), message = $2 where id = $1", [id, msg]); deps.log.error({ job: job.name, err: msg }, "вызов задания упал"); } } /** Один тик: для каждого задания определяет, пора ли стартовать, пропущено ли оно, или уже обработано. Возвращает фоновые вызовы. */ export async function tick(deps: TickDeps): Promise[]> { const now = (deps.now ?? (() => new Date()))(); const nonWork = await deps.nonWorkdays(); const running: Promise[] = []; for (const job of deps.jobs) { const due = lastDue(job, now, deps.tz, nonWork); if (!due) continue; const recorded = ( await deps.pool.query("select 1 from sched_run where job_name = $1 and scheduled_minute = $2", [job.name, due]) ).rowCount! > 0; const action = decide(due, recorded, now, deps.graceSeconds); if (action === "start") { const id = await claim(deps.pool, job.name, due, "started"); if (id) running.push(run(deps, job, id)); } else if (action === "missed") { const lateSec = Math.round((now.getTime() - due.getTime()) / 1000); const id = await claim(deps.pool, job.name, due, "missed", `пропуск замечен ${now.toISOString()}, опоздание ${lateSec} с; задание не запускалось`); if (id) deps.log.warn({ job: job.name, due: due.toISOString(), lateSec }, "пропущенное задание не запускается"); } } return running; }