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,38 @@
|
||||
// The /api/live protocol, shared by the route handler and the browser's live store. Types only and
|
||||
// pure helpers: safe to import from client components.
|
||||
|
||||
import type { JobFileSnapshot, JobSnapshot, LogLine } from "@/lib/jobs";
|
||||
import type { WorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
export type LiveSnapshot = { worker: WorkerStatus; jobs: JobSnapshot[]; files: JobFileSnapshot[] };
|
||||
|
||||
/** `model`: jobs of one model; `job`: one job; neither: open and recently finished jobs. */
|
||||
export type LiveQuery = { model?: string; job?: string };
|
||||
|
||||
/** `snapshot` is left out when it is the version the client already has (`v` in the request). */
|
||||
export type LiveResponse = { v: string; snapshot?: LiveSnapshot; logs?: LogLine[] };
|
||||
|
||||
/**
|
||||
* The poll URL. `logAfter` (job queries only): log lines after that id, 0 for the last ones; leave it
|
||||
* out for no logs. `v`: the snapshot version the client has.
|
||||
*/
|
||||
export function liveUrl(query: LiveQuery, opts: { logAfter?: number | null; v?: string | null } = {}): string {
|
||||
const p = new URLSearchParams();
|
||||
if (query.model) p.set("model", query.model);
|
||||
if (query.job) p.set("job", query.job);
|
||||
if (query.job && opts.logAfter != null) p.set("logAfter", String(opts.logAfter));
|
||||
if (opts.v) p.set("v", opts.v);
|
||||
const qs = p.toString();
|
||||
return qs ? `/api/live?${qs}` : "/api/live";
|
||||
}
|
||||
|
||||
/**
|
||||
* The response body, built around the already serialized snapshot so it isn't serialized twice.
|
||||
* `version` is a hash of `snapshotJson`.
|
||||
*/
|
||||
export function liveBody(snapshotJson: string, version: string, clientVersion: string | null, logs?: LogLine[]): string {
|
||||
let body = `{"v":${JSON.stringify(version)}`;
|
||||
if (clientVersion !== version) body += `,"snapshot":${snapshotJson}`;
|
||||
if (logs) body += `,"logs":${JSON.stringify(logs)}`;
|
||||
return `${body}}`;
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import type { JobSnapshot } from "./jobs";
|
||||
import type { LiveResponse } from "./live-protocol";
|
||||
import { createLiveStore, EMPTY_LIVE, KEEP_MS, type LiveEnv, POLL_MS, RETRY_MS, STATUS_POLL_MS } from "./live-store";
|
||||
|
||||
const worker = { online: true, hfVersion: null, modelsDirFreeBytes: 1, modelsDirTotalBytes: 2 };
|
||||
|
||||
function job(id: string, state: string): JobSnapshot {
|
||||
return {
|
||||
id,
|
||||
modelId: "m1",
|
||||
repoId: "org/repo",
|
||||
kind: "download",
|
||||
purpose: null,
|
||||
state,
|
||||
attempt: 1,
|
||||
totalBytes: 10,
|
||||
doneBytes: 0,
|
||||
speedBps: null,
|
||||
etaSeconds: null,
|
||||
exitCode: null,
|
||||
errorCode: null,
|
||||
errorMessage: null,
|
||||
result: null,
|
||||
cancelRequested: false,
|
||||
createdAt: 0,
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
const settle = () => new Promise((r) => setImmediate(r));
|
||||
|
||||
/** A fake browser: manual clock, scripted responses, visibility switch. */
|
||||
function fakeEnv() {
|
||||
let now = 0;
|
||||
let seq = 0;
|
||||
const timers = new Map<number, { at: number; fn: () => void }>();
|
||||
const calls: string[] = [];
|
||||
const onVisible: (() => void)[] = [];
|
||||
const state = {
|
||||
visible: true,
|
||||
fail: false,
|
||||
respond: (url: string): unknown => (url.startsWith("/api/status") ? { worker } : ({ v: "1", snapshot: { worker, jobs: [], files: [] } } satisfies LiveResponse)),
|
||||
};
|
||||
const env: LiveEnv = {
|
||||
fetch: async (url) => {
|
||||
calls.push(url);
|
||||
if (state.fail) throw new Error("offline");
|
||||
return { ok: true, json: async () => state.respond(url) };
|
||||
},
|
||||
setTimeout: (fn, ms) => {
|
||||
timers.set(++seq, { at: now + ms, fn });
|
||||
return seq;
|
||||
},
|
||||
clearTimeout: (t) => void timers.delete(t as number),
|
||||
visible: () => state.visible,
|
||||
onVisible: (fn) => void onVisible.push(fn),
|
||||
};
|
||||
return {
|
||||
env,
|
||||
calls,
|
||||
state,
|
||||
/** Runs timers that are due within `ms`, in order, letting each poll finish. */
|
||||
async advance(ms: number) {
|
||||
const end = now + ms;
|
||||
for (;;) {
|
||||
await settle(); // let running polls finish and schedule their next one
|
||||
const next = [...timers.entries()].filter(([, t]) => t.at <= end).sort((a, b) => a[1].at - b[1].at)[0];
|
||||
if (!next) break;
|
||||
timers.delete(next[0]);
|
||||
now = next[1].at;
|
||||
next[1].fn();
|
||||
}
|
||||
now = end;
|
||||
},
|
||||
async show() {
|
||||
state.visible = true;
|
||||
onVisible.forEach((fn) => fn());
|
||||
await settle();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const live = (calls: string[]) => calls.filter((c) => c.startsWith("/api/live"));
|
||||
|
||||
describe("live store", () => {
|
||||
it("components showing the same query share one poller", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
let a = 0;
|
||||
let b = 0;
|
||||
store.subscribe({ model: "m1" }, false, () => a++);
|
||||
store.subscribe({ model: "m1" }, false, () => b++);
|
||||
await settle();
|
||||
assert.deepEqual(f.calls, ["/api/live?model=m1"]);
|
||||
assert.equal(a, 1);
|
||||
assert.equal(b, 1);
|
||||
await f.advance(POLL_MS);
|
||||
assert.equal(f.calls.length, 2);
|
||||
});
|
||||
|
||||
it("an unchanged snapshot keeps the same state and wakes nobody", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
let renders = 0;
|
||||
store.subscribe({}, false, () => renders++);
|
||||
await settle();
|
||||
const first = store.get({});
|
||||
f.state.respond = () => ({ v: "1" });
|
||||
await f.advance(POLL_MS);
|
||||
assert.equal(f.calls[1], "/api/live?v=1");
|
||||
assert.equal(store.get({}), first);
|
||||
assert.equal(renders, 1);
|
||||
});
|
||||
|
||||
it("pauses while the tab is hidden and polls at once when it is shown", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
store.subscribe({}, false, () => {});
|
||||
await settle();
|
||||
f.state.visible = false;
|
||||
await f.advance(60_000);
|
||||
assert.equal(f.calls.length, 1);
|
||||
await f.show();
|
||||
assert.equal(f.calls.length, 2);
|
||||
await f.advance(POLL_MS);
|
||||
assert.equal(f.calls.length, 3);
|
||||
});
|
||||
|
||||
it("follows the log with a cursor", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
const line = (id: number) => ({ id, ts: id, stream: "stdout", line: `line ${id}` });
|
||||
f.state.respond = () => ({ v: "1", snapshot: { worker, jobs: [], files: [] }, logs: [line(1), line(2)] });
|
||||
store.subscribe({ job: "j1" }, true, () => {});
|
||||
await settle();
|
||||
assert.equal(f.calls[0], "/api/live?job=j1&logAfter=0");
|
||||
f.state.respond = () => ({ v: "1", logs: [line(3)] });
|
||||
await f.advance(POLL_MS);
|
||||
assert.equal(f.calls[1], "/api/live?job=j1&logAfter=2&v=1");
|
||||
assert.deepEqual(
|
||||
store.get({ job: "j1" }, true).logs.map((l) => l.id),
|
||||
[1, 2, 3],
|
||||
);
|
||||
});
|
||||
|
||||
it("refreshes once when a job finishes, however many components show it", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
let refreshes = 0;
|
||||
f.state.respond = () => ({ v: "a", snapshot: { worker, jobs: [job("j1", "downloading")], files: [] } });
|
||||
store.subscribe({}, false, () => {}, () => refreshes++);
|
||||
store.subscribe({}, false, () => {}, () => refreshes++);
|
||||
await settle();
|
||||
assert.equal(refreshes, 0);
|
||||
f.state.respond = () => ({ v: "b", snapshot: { worker, jobs: [job("j1", "completed")], files: [] } });
|
||||
await f.advance(POLL_MS);
|
||||
assert.equal(refreshes, 1);
|
||||
});
|
||||
|
||||
it("stops when nothing shows the query and keeps its data for a moment", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
const off = store.subscribe({}, false, () => {});
|
||||
await settle();
|
||||
off();
|
||||
await f.advance(POLL_MS * 3);
|
||||
assert.equal(f.calls.length, 1);
|
||||
assert.notEqual(store.get({}), EMPTY_LIVE);
|
||||
await f.advance(KEEP_MS);
|
||||
assert.equal(store.get({}), EMPTY_LIVE);
|
||||
});
|
||||
|
||||
it("backs off while requests fail", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
f.state.fail = true;
|
||||
store.subscribe({}, false, () => {});
|
||||
await settle();
|
||||
await f.advance(RETRY_MS[0] - 1);
|
||||
assert.equal(f.calls.length, 1);
|
||||
await f.advance(1);
|
||||
assert.equal(f.calls.length, 2);
|
||||
await f.advance(RETRY_MS[1]);
|
||||
assert.equal(f.calls.length, 3);
|
||||
f.state.fail = false;
|
||||
await f.advance(RETRY_MS[2]);
|
||||
await f.advance(POLL_MS);
|
||||
assert.equal(f.calls.length, 5);
|
||||
});
|
||||
|
||||
it("takes the worker status from the live poll, else from /api/status every 10 s", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
store.subscribeWorker(() => {});
|
||||
await f.advance(STATUS_POLL_MS);
|
||||
assert.deepEqual(f.calls, ["/api/status"]);
|
||||
assert.deepEqual(store.getWorker(), worker);
|
||||
const off = store.subscribe({}, false, () => {});
|
||||
await f.advance(STATUS_POLL_MS * 3);
|
||||
assert.equal(f.calls.filter((c) => c === "/api/status").length, 1);
|
||||
assert.ok(live(f.calls).length > 10);
|
||||
off();
|
||||
await f.advance(STATUS_POLL_MS);
|
||||
assert.equal(f.calls.filter((c) => c === "/api/status").length, 2);
|
||||
});
|
||||
|
||||
it("poke polls every shown query at once", async () => {
|
||||
const f = fakeEnv();
|
||||
const store = createLiveStore(f.env);
|
||||
store.subscribe({ model: "m1" }, false, () => {});
|
||||
store.subscribe({ job: "j1" }, false, () => {});
|
||||
await settle();
|
||||
assert.equal(f.calls.length, 2);
|
||||
store.poke();
|
||||
await settle();
|
||||
assert.equal(f.calls.length, 4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
// Live job state in the browser: one poller per query and tab, shared by every component that shows
|
||||
// it (the library header and table, a model's download card and job history, …). Short requests to
|
||||
// /api/live instead of a stream per component: over HTTP/1.1 a browser allows 6 connections per
|
||||
// host, and open streams used them up after a few tabs. Polling pauses while the tab is hidden.
|
||||
//
|
||||
// The worker status rides along: components that only need it (the menu's worker dot) read it from
|
||||
// whatever is polled; with nothing polled, /api/status is asked every 10 s.
|
||||
|
||||
import type { LogLine } from "@/lib/jobs";
|
||||
import { type LiveQuery, type LiveResponse, type LiveSnapshot, liveUrl } from "@/lib/live-protocol";
|
||||
import type { WorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
export type LiveState = { snapshot: LiveSnapshot | null; logs: LogLine[] };
|
||||
|
||||
export const TERMINAL_STATES = ["completed", "failed", "cancelled", "interrupted"];
|
||||
export const POLL_MS = 1_000;
|
||||
export const STATUS_POLL_MS = 10_000;
|
||||
/** After failed polls: wait this long before the next try (the last value repeats). */
|
||||
export const RETRY_MS = [3_000, 6_000, 12_000, 30_000];
|
||||
/** A query nobody shows any more keeps its data this long, so going back shows it at once. */
|
||||
export const KEEP_MS = 10_000;
|
||||
const MAX_LOG_LINES = 5000;
|
||||
|
||||
export const EMPTY_LIVE: LiveState = { snapshot: null, logs: [] };
|
||||
|
||||
/** What the store needs from the browser (injected so it can be tested without one). */
|
||||
export type LiveEnv = {
|
||||
fetch: (url: string) => Promise<{ ok: boolean; json(): Promise<unknown> }>;
|
||||
setTimeout: (fn: () => void, ms: number) => unknown;
|
||||
clearTimeout: (timer: unknown) => void;
|
||||
visible: () => boolean;
|
||||
/** Calls `fn` whenever the tab becomes visible again. */
|
||||
onVisible: (fn: () => void) => void;
|
||||
};
|
||||
|
||||
type Listener = () => void;
|
||||
|
||||
type Entry = {
|
||||
query: LiveQuery;
|
||||
withLogs: boolean;
|
||||
state: LiveState;
|
||||
/** Version of the snapshot in `state` (the server leaves an unchanged snapshot out). */
|
||||
version: string | null;
|
||||
/** Id of the newest log line received. */
|
||||
logCursor: number;
|
||||
listeners: Set<Listener>;
|
||||
/** Called (one of them) when a job of this query reaches a terminal state. */
|
||||
onFinish: Set<() => void>;
|
||||
jobStates: Map<string, string>;
|
||||
timer: unknown;
|
||||
inFlight: boolean;
|
||||
/** A poll was asked for while one was running: run another right after it. */
|
||||
again: boolean;
|
||||
failures: number;
|
||||
dropTimer: unknown;
|
||||
};
|
||||
|
||||
export function liveKey(query: LiveQuery, withLogs: boolean): string {
|
||||
return `${query.model ?? ""}|${query.job ?? ""}|${withLogs ? 1 : 0}`;
|
||||
}
|
||||
|
||||
const sameWorker = (a: WorkerStatus, b: WorkerStatus) =>
|
||||
a.online === b.online &&
|
||||
a.hfVersion === b.hfVersion &&
|
||||
a.modelsDirFreeBytes === b.modelsDirFreeBytes &&
|
||||
a.modelsDirTotalBytes === b.modelsDirTotalBytes;
|
||||
|
||||
export function createLiveStore(env: LiveEnv) {
|
||||
const entries = new Map<string, Entry>();
|
||||
let worker: WorkerStatus | null = null;
|
||||
const workerListeners = new Set<Listener>();
|
||||
let statusTimer: unknown = null;
|
||||
let statusInFlight = false;
|
||||
|
||||
const polling = () => [...entries.values()].some((e) => e.listeners.size > 0);
|
||||
|
||||
function setWorker(next: WorkerStatus) {
|
||||
if (worker && sameWorker(worker, next)) return;
|
||||
worker = next;
|
||||
for (const l of [...workerListeners]) l();
|
||||
}
|
||||
|
||||
function schedule(e: Entry, ms: number) {
|
||||
env.clearTimeout(e.timer);
|
||||
e.timer = null;
|
||||
// Hidden tab: nothing is scheduled; onVisible starts again.
|
||||
if (e.listeners.size === 0 || !env.visible()) return;
|
||||
e.timer = env.setTimeout(() => void poll(e), ms);
|
||||
}
|
||||
|
||||
async function poll(e: Entry): Promise<void> {
|
||||
env.clearTimeout(e.timer);
|
||||
e.timer = null;
|
||||
if (e.inFlight) {
|
||||
e.again = true;
|
||||
return;
|
||||
}
|
||||
if (e.listeners.size === 0 || !env.visible()) return;
|
||||
e.inFlight = true;
|
||||
let ok = false;
|
||||
try {
|
||||
const url = liveUrl(e.query, { v: e.version, logAfter: e.withLogs ? e.logCursor : null });
|
||||
const res = await env.fetch(url);
|
||||
if (res.ok) {
|
||||
apply(e, (await res.json()) as LiveResponse);
|
||||
ok = true;
|
||||
}
|
||||
} catch {
|
||||
// network error or a bad body: try again later
|
||||
}
|
||||
e.inFlight = false;
|
||||
e.failures = ok ? 0 : e.failures + 1;
|
||||
if (e.again) {
|
||||
e.again = false;
|
||||
return poll(e);
|
||||
}
|
||||
schedule(e, ok ? POLL_MS : RETRY_MS[Math.min(e.failures, RETRY_MS.length) - 1]);
|
||||
}
|
||||
|
||||
function apply(e: Entry, r: LiveResponse) {
|
||||
let state = e.state;
|
||||
let finished = false;
|
||||
if (r.snapshot) {
|
||||
e.version = r.v;
|
||||
state = { ...state, snapshot: r.snapshot };
|
||||
for (const j of r.snapshot.jobs) {
|
||||
const prev = e.jobStates.get(j.id);
|
||||
if (prev && prev !== j.state && TERMINAL_STATES.includes(j.state)) finished = true;
|
||||
e.jobStates.set(j.id, j.state);
|
||||
}
|
||||
setWorker(r.snapshot.worker);
|
||||
}
|
||||
if (r.logs && r.logs.length > 0) {
|
||||
const seen = state.logs.length ? state.logs[state.logs.length - 1].id : 0;
|
||||
const fresh = r.logs.filter((l) => l.id > seen);
|
||||
if (fresh.length > 0) {
|
||||
const merged = state.logs.concat(fresh);
|
||||
state = { ...state, logs: merged.length > MAX_LOG_LINES ? merged.slice(-MAX_LOG_LINES) : merged };
|
||||
}
|
||||
e.logCursor = Math.max(e.logCursor, r.logs[r.logs.length - 1].id);
|
||||
}
|
||||
if (state !== e.state) {
|
||||
e.state = state;
|
||||
for (const l of [...e.listeners]) l();
|
||||
}
|
||||
// Every handler refreshes the same page; one is enough.
|
||||
if (finished) [...e.onFinish][0]?.();
|
||||
}
|
||||
|
||||
function scheduleStatus() {
|
||||
if (statusTimer != null || statusInFlight || workerListeners.size === 0 || polling() || !env.visible()) return;
|
||||
statusTimer = env.setTimeout(() => void pollStatus(), STATUS_POLL_MS);
|
||||
}
|
||||
|
||||
function stopStatus() {
|
||||
env.clearTimeout(statusTimer);
|
||||
statusTimer = null;
|
||||
}
|
||||
|
||||
async function pollStatus() {
|
||||
statusTimer = null;
|
||||
if (statusInFlight || workerListeners.size === 0 || polling() || !env.visible()) return;
|
||||
statusInFlight = true;
|
||||
try {
|
||||
const res = await env.fetch("/api/status");
|
||||
if (res.ok) setWorker(((await res.json()) as { worker: WorkerStatus }).worker);
|
||||
} catch {
|
||||
// keep the last known status
|
||||
}
|
||||
statusInFlight = false;
|
||||
scheduleStatus();
|
||||
}
|
||||
|
||||
env.onVisible(() => {
|
||||
for (const e of entries.values()) if (e.listeners.size > 0 && e.timer == null) void poll(e);
|
||||
if (workerListeners.size > 0 && !polling() && statusTimer == null) void pollStatus();
|
||||
});
|
||||
|
||||
return {
|
||||
/** Current state of a query (the same object until something changes). */
|
||||
get(query: LiveQuery, withLogs = false): LiveState {
|
||||
return entries.get(liveKey(query, withLogs))?.state ?? EMPTY_LIVE;
|
||||
},
|
||||
|
||||
subscribe(query: LiveQuery, withLogs: boolean, listener: Listener, onFinish?: () => void): () => void {
|
||||
const key = liveKey(query, withLogs);
|
||||
let e = entries.get(key);
|
||||
if (!e) {
|
||||
e = {
|
||||
query: { model: query.model, job: query.job },
|
||||
withLogs,
|
||||
state: EMPTY_LIVE,
|
||||
version: null,
|
||||
logCursor: 0,
|
||||
listeners: new Set(),
|
||||
onFinish: new Set(),
|
||||
jobStates: new Map(),
|
||||
timer: null,
|
||||
inFlight: false,
|
||||
again: false,
|
||||
failures: 0,
|
||||
dropTimer: null,
|
||||
};
|
||||
entries.set(key, e);
|
||||
}
|
||||
const entry = e;
|
||||
env.clearTimeout(entry.dropTimer);
|
||||
entry.dropTimer = null;
|
||||
entry.listeners.add(listener);
|
||||
if (onFinish) entry.onFinish.add(onFinish);
|
||||
stopStatus(); // the live snapshot carries the worker status now
|
||||
if (entry.listeners.size === 1 && entry.timer == null && !entry.inFlight) void poll(entry);
|
||||
|
||||
return () => {
|
||||
entry.listeners.delete(listener);
|
||||
if (onFinish) entry.onFinish.delete(onFinish);
|
||||
if (entry.listeners.size > 0) return;
|
||||
env.clearTimeout(entry.timer);
|
||||
entry.timer = null;
|
||||
entry.dropTimer = env.setTimeout(() => {
|
||||
if (entry.listeners.size === 0 && entries.get(key) === entry) entries.delete(key);
|
||||
}, KEEP_MS);
|
||||
scheduleStatus();
|
||||
};
|
||||
},
|
||||
|
||||
/** Latest worker status seen (from a live snapshot or /api/status), null until there is one. */
|
||||
getWorker(): WorkerStatus | null {
|
||||
return worker;
|
||||
},
|
||||
|
||||
subscribeWorker(listener: Listener): () => void {
|
||||
workerListeners.add(listener);
|
||||
scheduleStatus();
|
||||
return () => {
|
||||
workerListeners.delete(listener);
|
||||
if (workerListeners.size === 0) stopStatus();
|
||||
};
|
||||
},
|
||||
|
||||
/** Poll every shown query now (after starting or cancelling a job, for instant feedback). */
|
||||
poke() {
|
||||
for (const e of entries.values()) if (e.listeners.size > 0) void poll(e);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type LiveStore = ReturnType<typeof createLiveStore>;
|
||||
|
||||
let store: LiveStore | null = null;
|
||||
|
||||
/** The tab's store, created on first use (never on the server). */
|
||||
export function liveStore(): LiveStore {
|
||||
return (store ??= createLiveStore({
|
||||
fetch: (url) => fetch(url, { cache: "no-store" }),
|
||||
setTimeout: (fn, ms) => window.setTimeout(fn, ms),
|
||||
clearTimeout: (t) => window.clearTimeout(t as number | undefined),
|
||||
visible: () => document.visibilityState === "visible",
|
||||
onVisible: (fn) =>
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.visibilityState === "visible") fn();
|
||||
}),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Poll now, if anything is shown (no-op on the server). */
|
||||
export function pokeLive() {
|
||||
if (typeof window !== "undefined" && store) store.poke();
|
||||
}
|
||||
@@ -5,33 +5,38 @@ import { workerState } from "@/lib/db/schema";
|
||||
|
||||
/** The worker writes a heartbeat every 5s; after this long without one we call it offline. */
|
||||
const OFFLINE_AFTER_MS = 20_000;
|
||||
const MIB = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* What the UI shows about the worker. No heartbeat time on purpose: it changes every 5 s, and the
|
||||
* live snapshot (see /api/live) would then change every 5 s even when nothing else did.
|
||||
*/
|
||||
export type WorkerStatus = {
|
||||
online: boolean;
|
||||
heartbeatAt: string | null;
|
||||
hfVersion: string | null;
|
||||
/** Free/total bytes of the models folder, rounded to whole MiB for the same reason. */
|
||||
modelsDirFreeBytes: number | null;
|
||||
modelsDirTotalBytes: number | null;
|
||||
};
|
||||
|
||||
const OFFLINE: WorkerStatus = {
|
||||
online: false,
|
||||
heartbeatAt: null,
|
||||
hfVersion: null,
|
||||
modelsDirFreeBytes: null,
|
||||
modelsDirTotalBytes: null,
|
||||
};
|
||||
|
||||
const toMiB = (bytes: number | null) => (bytes == null ? null : Math.round(bytes / MIB) * MIB);
|
||||
|
||||
export async function getWorkerStatus(): Promise<WorkerStatus> {
|
||||
try {
|
||||
const row = await db().query.workerState.findFirst({ where: eq(workerState.id, "worker") });
|
||||
if (!row) return OFFLINE;
|
||||
return {
|
||||
online: Date.now() - row.heartbeatAt.getTime() < OFFLINE_AFTER_MS,
|
||||
heartbeatAt: row.heartbeatAt.toISOString(),
|
||||
hfVersion: row.hfVersion,
|
||||
modelsDirFreeBytes: row.modelsDirFreeBytes,
|
||||
modelsDirTotalBytes: row.modelsDirTotalBytes,
|
||||
modelsDirFreeBytes: toMiB(row.modelsDirFreeBytes),
|
||||
modelsDirTotalBytes: toMiB(row.modelsDirTotalBytes),
|
||||
};
|
||||
} catch {
|
||||
// Table missing (worker never ran migrations yet) or DB unavailable.
|
||||
|
||||
Reference in new issue
Block a user