import Fastify, { type FastifyInstance } from "fastify"; import type { Pool } from "khb_common"; import type { CollectRequest } from "./collect.js"; export interface CollectorApiDeps { pool: Pool; token: string; /** Запускает сбор; вызывает onStarted, когда снапшот создан; возвращает итог раундов. */ runCollect(req: CollectRequest, onStarted: (ts: Date) => void): Promise<{ status: "ok" | "error" }[]>; runRetention(): Promise; importHolidays(): Promise; /** Синхронизирует ленту событий JobTread (jt_event) для отчётов активности. */ syncEvents(opts?: { days?: number }): Promise; } export function buildApi(deps: CollectorApiDeps): FastifyInstance { const app = Fastify(); app.addHook("onRequest", async (req, reply) => { if (req.url === "/healthz") return; if (req.headers.authorization !== `Bearer ${deps.token}`) return reply.code(401).send({ error: "unauthorized" }); }); app.get("/healthz", async () => { let db = false; try { await deps.pool.query("select 1"); db = true; } catch { /* db=false */ } return { ok: db, db, time: new Date().toISOString() }; }); // Вид снапшота для ответа: статус, длительность, таблицы (одинаково для POST ?wait=true и ожидания идущего сбора). async function snapshotView(ts: string) { const snap = (await deps.pool.query("select started_at, finished_at, had_errors from sync_snapshot where started_at = $1", [ts])).rows[0]; if (!snap) return null; const tables = (await deps.pool.query("select table_name as name, status, row_count as \"rowCount\", error_message as error from sync_table_status where snapshot_ts = $1 order by table_name", [ts])).rows; const finished = snap.finished_at ? new Date(snap.finished_at).getTime() : null; return { snapshotTs: new Date(snap.started_at).toISOString(), status: finished === null ? "running" : snap.had_errors ? "error" : "ok", durationMs: (finished ?? Date.now()) - new Date(snap.started_at).getTime(), tables, }; } // Ручной (on-demand) старт сбора. Без wait: 202 с ключом снапшота сразу после его создания, сбор идёт в фоне. // С ?wait=true (необязательно &timeoutSec=1..300, по умолчанию 120): ответ приходит по завершении сбора - // 200 {snapshotTs, status: ok|error, durationMs, tables[]}; по истечении таймаута - 202 {status: running}. // Если сбор уже идёт, возвращается его снапшот (при wait - дожидаемся именно его), а не отказ. app.post<{ Body: CollectRequest; Querystring: { wait?: string; timeoutSec?: string } }>("/runs", async (req, reply) => { const body = req.body ?? {}; const wait = ["true", "1"].includes(String(req.query?.wait ?? "")); const timeoutSec = Math.min(Math.max(Number(req.query?.timeoutSec) || 120, 1), 300); const t0 = Date.now(); const deadline = t0 + timeoutSec * 1000; let done: Promise<{ snapshotTs: Date; status: "ok" | "error"; tables: unknown[] }[]> | undefined; const started = new Promise((resolve, reject) => { done = deps.runCollect(body, resolve) as typeof done; done!.catch(reject); }); let ts: Date; try { ts = await started; } catch (e) { const msg = e instanceof Error ? e.message : String(e); // сбор уже идёт: отдаём идущий снапшот и при wait ждём его завершения const running = msg.includes("уже выполняется") ? (await deps.pool.query("select started_at from sync_snapshot where finished_at is null order by started_at desc limit 1")).rows[0] : undefined; if (!running) return reply.code(409).send({ error: msg }); const runTs = new Date(running.started_at).toISOString(); if (wait) { for (;;) { const v = await snapshotView(runTs); if (v && v.status !== "running") return { ...v, alreadyRunning: true }; if (Date.now() >= deadline) return reply.code(202).send({ ...(v ?? { snapshotTs: runTs, status: "running" }), alreadyRunning: true }); await new Promise((r) => setTimeout(r, 1000)); } } return reply.code(202).send({ snapshotTs: runTs, status: "running", alreadyRunning: true }); } if (!wait) return reply.code(202).send({ snapshotTs: ts.toISOString(), status: "running" }); let timer: NodeJS.Timeout | undefined; const timeout = new Promise<"timeout">((r) => { timer = setTimeout(() => r("timeout"), Math.max(deadline - Date.now(), 0)); }); try { const res = await Promise.race([done!, timeout]); if (res === "timeout") return reply.code(202).send({ snapshotTs: ts.toISOString(), status: "running" }); return { snapshotTs: ts.toISOString(), status: res.some((r) => r.status === "error") ? "error" : "ok", durationMs: Date.now() - t0, tables: res.flatMap((r) => r.tables), }; } catch (e) { return { snapshotTs: ts.toISOString(), status: "error", durationMs: Date.now() - t0, tables: [], error: e instanceof Error ? e.message : String(e) }; } finally { clearTimeout(timer); } }); app.get<{ Params: { snapshotTs: string } }>("/runs/:snapshotTs", async (req, reply) => { const { rows } = await deps.pool.query("select * from sync_snapshot where started_at = $1", [req.params.snapshotTs]); if (!rows.length) return reply.code(404).send({ error: "not found" }); const tables = (await deps.pool.query("select table_name as name, status, row_count as \"rowCount\", error_message as error from sync_table_status where snapshot_ts = $1 order by table_name", [req.params.snapshotTs])).rows; return { snapshot: rows[0], tables }; }); app.post("/retention/run", async () => deps.runRetention()); app.post("/holidays/import", async () => deps.importHolidays()); app.post<{ Body: { days?: number } | undefined }>("/events/sync", async (req, reply) => { try { const days = Number(req.body?.days); return await deps.syncEvents(Number.isFinite(days) && days > 0 ? { days: Math.min(Math.floor(days), 400) } : undefined); } catch (e) { return reply.code(502).send({ error: e instanceof Error ? e.message : String(e) }); } }); return app; }