Files
khb_microservices/packages/accounting_automation/src/http-api.ts
2026-11-18 09:28:12 +03:00

87 lines
4.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Fastify, { type FastifyInstance } from "fastify";
import type { Pool } from "khb_common";
import { registerMcp } from "./mcp.js";
import type { AccountingSettings } from "./settings.js";
/** Задания, которые вызывает scheduler (POST /jobs/<имя>); каждое возвращает произвольный JSON-итог. */
export interface JobHandlers {
"invoices-mail": () => Promise<unknown>;
finalize: () => Promise<unknown>;
categorize: () => Promise<unknown>;
summary: () => Promise<unknown>;
}
export const JOB_NAMES = ["invoices-mail", "finalize", "categorize", "summary"] as const;
export interface ApiDeps {
pool: Pool;
settings: Pick<AccountingSettings, "http" | "reviewers" | "mcp">;
jobs: JobHandlers;
/** Текст instructions для MCP (из p-mcp-instructions.md); не задан - встроенный. */
mcpInstructions?: string;
}
/**
* Служебные ручки закрыты токеном сервиса (`accounting_automation.http.token`); /healthz открыт.
* /mcp - отдельная аутентификация (токены сотрудников и Keycloak), наружу публикуется через nginx только он.
*/
export function buildApi(deps: ApiDeps): FastifyInstance {
const app = Fastify();
const running = new Set<string>();
app.addHook("onRequest", async (req, reply) => {
const path = req.url.split("?")[0]!;
if (path === "/healthz" || path === "/mcp" || path.startsWith("/.well-known/")) return;
if (req.headers.authorization !== `Bearer ${deps.settings.http.token}`) return reply.code(401).send({ error: "unauthorized" });
});
app.get("/healthz", async () => ({ ok: true, time: new Date().toISOString() }));
/**
* Запуск задания. По умолчанию - в фоне: 202 сразу (scheduler ждёт ответ не дольше 30 с, а агенты работают минутами),
* итог пишется в журнал сервиса. `?wait=true` - дождаться итога: 200 - выполнено, 502 - ошибка.
* 409 - это же задание уже идёт, 404 - нет такого задания.
*/
app.post<{ Params: { name: string }; Querystring: { wait?: string } }>("/jobs/:name", async (req, reply) => {
const name = req.params.name as keyof JobHandlers;
const handler = Object.prototype.hasOwnProperty.call(deps.jobs, name) ? deps.jobs[name] : undefined;
if (!handler) return reply.code(404).send({ error: "unknown_job" });
if (running.has(name)) return reply.code(409).send({ error: "already_running" });
running.add(name);
const exec = async (): Promise<unknown> => {
try {
const result = await handler();
req.log.info({ job: name, result }, "задание выполнено");
return result;
} finally {
running.delete(name);
}
};
if (req.query.wait === "true") {
try {
return { job: name, result: await exec() };
} catch (e) {
req.log.error({ err: String(e), job: name }, "задание упало");
return reply.code(502).send({ error: "job_failed", message: e instanceof Error ? e.message : String(e) });
}
}
void exec().catch((e) => req.log.error({ err: String(e), job: name }, "задание упало"));
return reply.code(202).send({ job: name, started: true });
});
// --- MCP для Claude сотрудников (Streamable HTTP, без сессий)
if (deps.settings.mcp.enabled) {
const base = deps.settings.mcp.publicUrl?.replace(/\/$/, "");
app.get("/.well-known/oauth-protected-resource", async (_req, reply) => {
if (!base) return reply.code(404).send({ error: "not configured" });
return {
resource: `${base}/mcp`,
...(deps.settings.mcp.issuer ? { authorization_servers: [deps.settings.mcp.issuer] } : {}),
bearer_methods_supported: ["header"],
scopes_supported: ["openid", "email", "profile"],
};
});
registerMcp(app, { pool: deps.pool, settings: deps.settings, instructions: deps.mcpInstructions });
}
return app;
}