import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify"; import { renderAris } from "./aris.js"; import { renderGantt, stageOrder } from "./gantt.js"; import { renderPage } from "./html.js"; import { PROCESS_SETS, type ProcessModel, type ProcessSet } from "./model.js"; import { computeSchedule } from "./schedule.js"; export interface ProcessVizApiDeps { token: string; defaultSet: ProcessSet; /** загрузка модели; в тестах подменяется */ load: (set: ProcessSet) => Promise; /** проверка доступности БД для /healthz */ dbOk: () => Promise; } type Query = Record; const COOKIE = "viz_token"; function tokenFrom(req: FastifyRequest): string | null { const auth = req.headers.authorization; if (auth?.startsWith("Bearer ")) return auth.slice(7); const q = (req.query as Query).token; if (q) return q; const m = (req.headers.cookie ?? "").split(/;\s*/).find((c) => c.startsWith(`${COOKIE}=`)); return m ? decodeURIComponent(m.slice(COOKIE.length + 1)) : null; } export function buildApi(deps: ProcessVizApiDeps): FastifyInstance { const app = Fastify(); app.addHook("onRequest", async (req, reply) => { if (req.url === "/healthz") return; const t = tokenFrom(req); if (t !== deps.token) return reply.code(401).type("text/plain; charset=utf-8").send("Нужен токен: ?token=... или заголовок Authorization: Bearer ..."); // Токен в адресе -> запоминаем в cookie, чтобы страница и SVG открывались без него if ((req.query as Query).token) reply.header("set-cookie", `${COOKIE}=${encodeURIComponent(t)}; Path=/; HttpOnly; SameSite=Strict`); }); const setOf = (q: Query): ProcessSet => { const s = q.set as ProcessSet | undefined; return s && PROCESS_SETS.includes(s) ? s : deps.defaultSet; }; const stagesOf = (q: Query): string[] | null => (q.stages ? q.stages.split("|").filter(Boolean) : null); const svgReply = (reply: FastifyReply, svg: string, name: string, q: Query) => reply .header("cache-control", "no-store") .header("content-disposition", `${q.download ? "attachment" : "inline"}; filename="${name}"`) .type("image/svg+xml; charset=utf-8") .send(svg); app.get("/healthz", async () => { const db = await deps.dbOk().catch(() => false); return { ok: true, db, time: new Date().toISOString() }; }); app.get("/", async (req, reply) => { const model = await deps.load(setOf(req.query as Query)); const sch = computeSchedule(model.rows); return reply.type("text/html; charset=utf-8").send( renderPage({ set: model.set, stages: stageOrder(model.rows, sch, model.stages), version: process.env.KHB_VERSION, warnings: sch.warnings, rows: model.rows.length, questions: model.rows.filter((r) => r.questions).length + model.data.filter((d) => d.comment).length + model.responsible.filter((r) => r.comment).length + model.stages.filter((r) => r.comment).length + model.systems.filter((s) => s.comment).length, }), ); }); app.get("/api/model", async (req) => { const model = await deps.load(setOf(req.query as Query)); const sch = computeSchedule(model.rows); return { ...model, schedule: { maxDay: sch.maxDay, timings: [...sch.timings.values()], warnings: sch.warnings } }; }); app.get("/gantt.svg", async (req, reply) => { const q = req.query as Query; const model = await deps.load(setOf(q)); const px = q.px !== undefined && q.px !== "" ? Number(q.px) : undefined; const collapsed = q.collapsed ? q.collapsed.split("|").filter(Boolean) : null; const svg = renderGantt(model, computeSchedule(model.rows), { kickoff: q.kickoff ?? null, deps: q.deps !== "0", stages: stagesOf(q), px, collapsed }); return svgReply(reply, svg, `process_gantt_${model.set}.svg`, q); }); app.get("/aris.svg", async (req, reply) => { const q = req.query as Query; const model = await deps.load(setOf(q)); const svg = renderAris(model, computeSchedule(model.rows), { data: q.data === "1", events: q.events !== "0", stages: stagesOf(q) }); return svgReply(reply, svg, `process_aris_${model.set}.svg`, q); }); return app; }