Live updates: one poller per tab instead of SSE streams
Every useLive() call opened its own EventSource, and the library page and a model's Jobs tab call it twice. Over plain HTTP a browser allows 6 connections per host, so with three library tabs open the third took ~10 s to load and its requests never got an answer; a fourth tab didn't load. - /api/live answers one short request with the job snapshot (left out when the client already has that version) and, for job pages, new log lines. - src/lib/live-store.ts runs one poller per query per tab, shared by every component showing it, paused while the tab is hidden, with backoff on errors. One router.refresh() per finished job instead of one per component. - The worker dot reads the status from that poll; it only asks /api/status (every 10 s) when nothing else is polled. - The worker status no longer carries the heartbeat time (it changed every 5 s, so every idle stream re-sent its snapshot) and rounds free space to MiB. - Removes /api/stream: its sleep() added an abort listener per second to the request signal and never removed it. - Job actions poll right away after starting or cancelling a job; drops approveJob/rejectJob, whose routes went away in 0.15. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
This commit is contained in:
11 files changed
+623
-185
No files matched your search
@@ -0,0 +1,43 @@
|
||||
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=<id> jobs of one model (+ files of its newest job)
|
||||
* ?job=<id> one job with per-file progress; with &logAfter=<id> also the log lines after
|
||||
* that id (0: the last 1000)
|
||||
* (none) open and recently finished jobs (library view)
|
||||
* &v=<version> 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<LiveSnapshot> {
|
||||
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: [] };
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
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=<id> jobs of one model (+ files of its newest job)
|
||||
* ?job=<id> 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<void>((resolve) => {
|
||||
const t = setTimeout(resolve, ms);
|
||||
signal.addEventListener("abort", () => {
|
||||
clearTimeout(t);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user