import { listContainers, getLlamaHealth, NODE_INSTANCE } from "@/lib/docker"; export const dynamic = "force-dynamic"; export const runtime = "nodejs"; export const maxDuration = 300; /** * Server-Sent Events stream for status updates. * * Replaces fetch-polling — client opens a single EventSource connection * and receives a `status` event every N seconds with the full status * payload. SSE was chosen over WebSocket because: * - one-way (server → client) is all we need for status pushes * - works through any HTTP proxy (Tailscale serve) without WS upgrade * - built into the browser (EventSource API), no extra deps * - keeps Next.js standalone output (smaller docker image) * * Client usage: * const es = new EventSource("/api/status/stream"); * es.addEventListener("status", (e) => { * const data = JSON.parse(e.data); * ... * }); */ export async function GET() { const encoder = new TextEncoder(); const stream = new ReadableStream({ async start(controller) { const send = (event: string, data: unknown) => { try { controller.enqueue( encoder.encode( `event: ${event}\ndata: ${JSON.stringify(data)}\n\n` ) ); } catch { /* stream closed */ } }; // Initial hello so the client knows the stream is alive send("hello", { instance: NODE_INSTANCE, ts: Date.now(), }); // Push status immediately (don't wait for the first interval) const pushStatus = async () => { try { const [containers, llamaHealth] = await Promise.all([ listContainers(), getLlamaHealth(), ]); send("status", { instance: NODE_INSTANCE, containers, llamaHealth, timestamp: new Date().toISOString(), }); } catch (err) { send("error", { message: (err as Error).message }); } }; await pushStatus(); const interval = setInterval(pushStatus, 4000); // Cleanup when client disconnects // The controller.close() is called when the consumer cancels the stream // ( AbortController / EventSource.close() on the client side). // We use the `cancel` method below. // Store interval on the controller via closure. (controller as unknown as { _interval?: NodeJS.Timeout })._interval = interval; }, cancel(controller) { const interval = ( controller as unknown as { _interval?: NodeJS.Timeout } )._interval; if (interval) clearInterval(interval); }, }); 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", }, }); }