import { withAuth } from "@/lib/api-auth"; import { getJob, listJobFiles, listJobLogs, listLiveJobs, listModelJobs } from "@/lib/jobs"; import { getWorkerStatus } from "@/lib/worker-status"; export const dynamic = "force-dynamic"; const INTERVAL_MS = 1_000; const KEEPALIVE_MS = 15_000; /** * Server-Sent Events with live job state, polled from the DB once per second. * ?model= jobs of one model (+ files of its newest job) * ?job= one job with per-file progress and incremental log lines * (none) open and recently finished jobs (library view) * Events: "snapshot" (only when something changed) and "logs" (new lines). */ export const GET = withAuth(async (req) => { const url = new URL(req.url); const modelId = url.searchParams.get("model"); const jobId = url.searchParams.get("job"); let logCursor = Number(url.searchParams.get("logAfter") ?? 0) || 0; const encoder = new TextEncoder(); const signal = req.signal; const stream = new ReadableStream({ async start(controller) { let last = ""; let lastWrite = Date.now(); const write = (chunk: string) => { controller.enqueue(encoder.encode(chunk)); lastWrite = Date.now(); }; const send = (event: string, data: unknown) => write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); try { write("retry: 3000\n\n"); while (!signal.aborted) { const snapshot = await buildSnapshot(modelId, jobId); const serialized = JSON.stringify(snapshot); if (serialized !== last) { send("snapshot", snapshot); last = serialized; } if (jobId) { const lines = await listJobLogs(jobId, logCursor); if (lines.length > 0) { logCursor = lines[lines.length - 1].id; send("logs", lines); } } if (Date.now() - lastWrite > KEEPALIVE_MS) write(": keepalive\n\n"); await sleep(INTERVAL_MS, signal); } } catch { // client went away or the stream was closed } finally { try { controller.close(); } catch {} } }, }); return new Response(stream, { headers: { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache, no-transform", Connection: "keep-alive", "X-Accel-Buffering": "no", }, }); }); async function buildSnapshot(modelId: string | null, jobId: string | null) { 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: [] }; } function sleep(ms: number, signal: AbortSignal) { return new Promise((resolve) => { const t = setTimeout(resolve, ms); signal.addEventListener("abort", () => { clearTimeout(t); resolve(); }); }); }