import { createHash } from "node:crypto"; import { withAuth } from "@/lib/api-auth"; import { getJob, listJobFiles, listJobLogs, listLiveJobs, listModelJobs } from "@/lib/jobs"; import { liveBody, type LiveSnapshot } from "@/lib/live-protocol"; import { getWorkerStatus } from "@/lib/worker-status"; export const dynamic = "force-dynamic"; /** * Live job state, polled by the browser about once per second while the tab is visible (one poller * per query and tab, see src/lib/live-store.ts). Short requests instead of a stream per component: * over HTTP/1.1 a browser allows 6 connections per host, and open streams used them up. * ?model= jobs of one model (+ files of its newest job) * ?job= one job with per-file progress; with &logAfter= also the log lines after * that id (0: the last 1000) * (none) open and recently finished jobs (library view) * &v= the snapshot version the client has; an unchanged snapshot is left out */ export const GET = withAuth(async (req) => { const sp = new URL(req.url).searchParams; const modelId = sp.get("model"); const jobId = sp.get("job"); const json = JSON.stringify(await buildSnapshot(modelId, jobId)); const version = createHash("sha1").update(json).digest("base64url").slice(0, 16); const logs = jobId && sp.has("logAfter") ? await listJobLogs(jobId, Number(sp.get("logAfter")) || 0) : undefined; return new Response(liveBody(json, version, sp.get("v"), logs), { headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" }, }); }); async function buildSnapshot(modelId: string | null, jobId: string | null): Promise { const worker = await getWorkerStatus(); if (jobId) { const job = await getJob(jobId); return { worker, jobs: job ? [job] : [], files: job ? await listJobFiles(jobId) : [] }; } if (modelId) { const jobs = await listModelJobs(modelId); const files = jobs[0] ? await listJobFiles(jobs[0].id) : []; return { worker, jobs, files }; } return { worker, jobs: await listLiveJobs(), files: [] }; }