Каркас monorepo: scheduler, data_collector, khbuild_assistant_prep, khb_common; миграции; CI/CD
Some checks failed
ci / test (push) Failing after 20s
ci / deploy (push) Has been skipped

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-11 09:44:50 +03:00
commit ebb1cb7950
101 changed files with 4971 additions and 0 deletions

View File

@@ -0,0 +1,56 @@
import { randomUUID } from "node:crypto";
import Fastify, { type FastifyInstance } from "fastify";
import type { Pool } from "khb_common";
import type { PrepJob, PrepResult } from "./jobs.js";
export interface PrepApiDeps {
pool: Pool;
token: string;
run(job: PrepJob, opts: { projectId?: string; dryRun?: boolean }): Promise<PrepResult>;
}
interface RunState {
id: string;
job: PrepJob;
status: "running" | "ok" | "skipped" | "error";
startedAt: string;
finishedAt?: string;
result?: PrepResult;
error?: string;
}
export function buildApi(deps: PrepApiDeps): FastifyInstance {
const app = Fastify();
const runs = new Map<string, RunState>(); // состояние последних запусков в памяти; постоянный след - ap_*, sched_run
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() };
});
app.post<{ Body: { job: PrepJob; projectId?: string; dryRun?: boolean } }>("/runs", async (req, reply) => {
const { job, projectId, dryRun } = req.body ?? ({} as never);
if (job !== "collect_morning" && job !== "recheck_noon") return reply.code(400).send({ error: "job должен быть collect_morning или recheck_noon" });
const st: RunState = { id: randomUUID(), job, status: "running", startedAt: new Date().toISOString() };
runs.set(st.id, st);
if (runs.size > 50) runs.delete(runs.keys().next().value as string);
deps.run(job, { projectId, dryRun }).then(
(r) => Object.assign(st, { status: r.status, result: r, finishedAt: new Date().toISOString() }),
(e) => Object.assign(st, { status: "error", error: e instanceof Error ? e.message : String(e), finishedAt: new Date().toISOString() }),
);
return reply.code(202).send({ runId: st.id, status: "running" });
});
app.get<{ Params: { id: string } }>("/runs/:id", async (req, reply) => runs.get(req.params.id) ?? reply.code(404).send({ error: "not found" }));
return app;
}