Files
khb_microservices/packages/scheduler/src/http-api.ts

55 lines
2.1 KiB
TypeScript

import Fastify, { type FastifyInstance } from "fastify";
import type { Pool } from "khb_common";
import { lastDue } from "./due-calculator.js";
import type { JobSettings } from "./settings.js";
export interface SchedulerApiDeps {
pool: Pool;
token: string;
jobs: JobSettings[];
tz: string;
nonWorkdays: () => Promise<ReadonlySet<string>>;
/** Ручной запуск: фиксирует запись и вызывает сервис; возвращает id записи sched_run или null (уже было в эту минуту). */
manualRun: (job: JobSettings) => Promise<string | null>;
}
export function buildApi(deps: SchedulerApiDeps): 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() };
});
app.get("/status", async () => {
const nonWork = await deps.nonWorkdays();
const now = new Date();
const jobs = [];
for (const j of deps.jobs) {
const last = (
await deps.pool.query("select scheduled_minute, status, noticed_at, message from sched_run where job_name = $1 order by scheduled_minute desc limit 1", [j.name])
).rows[0] ?? null;
jobs.push({ name: j.name, at: j.at ?? null, everyMinutes: j.everyMinutes ?? null, days: j.days, lastDue: lastDue(j, now, deps.tz, nonWork)?.toISOString() ?? null, lastRun: last });
}
return { jobs };
});
app.post<{ Params: { name: string } }>("/jobs/:name/run", async (req, reply) => {
const job = deps.jobs.find((j) => j.name === req.params.name);
if (!job) return reply.code(404).send({ error: "unknown job" });
const id = await deps.manualRun(job);
return id ? reply.code(202).send({ runId: id }) : reply.code(409).send({ error: "уже запускалось в эту минуту" });
});
return app;
}