import "server-only"; import { eq } from "drizzle-orm"; import { db } from "@/lib/db/client"; 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; 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, hfVersion: null, modelsDirFreeBytes: null, modelsDirTotalBytes: null, }; const toMiB = (bytes: number | null) => (bytes == null ? null : Math.round(bytes / MIB) * MIB); export async function getWorkerStatus(): Promise { 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, hfVersion: row.hfVersion, modelsDirFreeBytes: toMiB(row.modelsDirFreeBytes), modelsDirTotalBytes: toMiB(row.modelsDirTotalBytes), }; } catch { // Table missing (worker never ran migrations yet) or DB unavailable. return OFFLINE; } }