Каркас monorepo: scheduler, data_collector, khbuild_assistant_prep, khb_common; миграции; CI/CD
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
58
packages/data_collector/src/http-api.ts
Normal file
58
packages/data_collector/src/http-api.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
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<unknown>;
|
||||
importHolidays(): Promise<unknown>;
|
||||
}
|
||||
|
||||
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() };
|
||||
});
|
||||
|
||||
// Ручной (on-demand) старт сбора. Возвращает ключ снапшота сразу после его создания; сбор идёт в фоне.
|
||||
app.post<{ Body: CollectRequest }>("/runs", async (req, reply) => {
|
||||
const body = req.body ?? {};
|
||||
const started = new Promise<Date>((resolve, reject) => {
|
||||
deps.runCollect(body, resolve).catch((e) => {
|
||||
reject(e);
|
||||
});
|
||||
});
|
||||
try {
|
||||
const ts = await started;
|
||||
return reply.code(202).send({ snapshotTs: ts.toISOString(), status: "running" });
|
||||
} catch (e) {
|
||||
return reply.code(409).send({ error: e instanceof Error ? e.message : String(e) });
|
||||
}
|
||||
});
|
||||
|
||||
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());
|
||||
return app;
|
||||
}
|
||||
Reference in New Issue
Block a user