import "server-only"; import { and, asc, desc, eq, gt, gte, inArray, isNull, or } from "drizzle-orm"; import { ulid } from "ulid"; import { db } from "@/lib/db/client"; import { hubMissingMessage } from "@/lib/hub/availability"; import { ACTIVE_JOB_STATES, type JobPurpose, type JobResult, jobFiles, jobLogs, jobs, modelFiles, models, } from "@/lib/db/schema"; export class JobError extends Error { constructor( public code: "not_found" | "busy" | "nothing_selected" | "not_cancellable" | "hub_missing", message: string, public status: number, ) { super(message); } } const OPEN_STATES = ["queued", ...ACTIVE_JOB_STATES] as const; const INSERT_CHUNK = 500; /** True if the model has a queued or running job (only one job per model at a time). */ export async function hasOpenJob(modelId: string): Promise { const open = await db().query.jobs.findFirst({ columns: { id: true }, where: and(eq(jobs.modelId, modelId), inArray(jobs.state, [...OPEN_STATES])), }); return !!open; } /** * Queue a download of all selected files of a model at its pinned SHA. hf skips files that are * already complete, so this also serves as resume and repair. `removePaths`: files of an older * revision to delete once the download succeeded (updates). */ export async function queueDownload( modelId: string, purpose: JobPurpose = "initial", options: { removePaths?: string[] } = {}, ): Promise<{ jobId: string }> { const d = db(); const model = await d.query.models.findFirst({ where: eq(models.id, modelId) }); if (!model) throw new JobError("not_found", "Model not found.", 404); const missing = hubMissingMessage(model); if (missing) throw new JobError("hub_missing", missing, 409); if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409); const files = await d .select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size }) .from(modelFiles) .where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true))) .orderBy(asc(modelFiles.path)); if (files.length === 0) throw new JobError("nothing_selected", "No files selected for this model.", 400); const jobId = ulid(); const rows = files.map((f) => ({ jobId, modelFileId: f.id, path: f.path, expectedBytes: f.size })); await d.batch([ d.insert(jobs).values({ id: jobId, modelId, kind: "download", purpose, targetSha: model.pinnedSha, totalBytes: files.reduce((s, f) => s + f.size, 0), result: options.removePaths?.length ? { removePaths: options.removePaths } : null, }), ...chunk(rows, INSERT_CHUNK).map((c) => d.insert(jobFiles).values(c)), d.update(models).set({ status: "downloading" }).where(eq(models.id, modelId)), ]); return { jobId }; } /** Queue a verify (size + hf metadata) or deep verify (hashes) of the selected files. Local only. */ export async function queueVerify(modelId: string, deep: boolean): Promise<{ jobId: string }> { const d = db(); const model = await d.query.models.findFirst({ where: eq(models.id, modelId) }); if (!model) throw new JobError("not_found", "Model not found.", 404); if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409); const files = await d .select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size }) .from(modelFiles) .where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true))) .orderBy(asc(modelFiles.path)); if (files.length === 0) throw new JobError("nothing_selected", "No files selected for this model.", 400); const jobId = ulid(); await d.batch([ d.insert(jobs).values({ id: jobId, modelId, kind: deep ? "deep_verify" : "verify", targetSha: model.pinnedSha, totalBytes: files.reduce((s, f) => s + f.size, 0), }), ...chunk( files.map((f) => ({ jobId, modelFileId: f.id, path: f.path, expectedBytes: f.size })), INSERT_CHUNK, ).map((c) => d.insert(jobFiles).values(c)), ]); return { jobId }; } /** Ask the worker to stop a job. Queued jobs are cancelled by the worker on its next tick. */ export async function requestCancel(jobId: string): Promise { const res = await db() .update(jobs) .set({ cancelRequestedAt: new Date() }) .where(and(eq(jobs.id, jobId), inArray(jobs.state, [...OPEN_STATES]), isNull(jobs.cancelRequestedAt))) .returning({ id: jobs.id }); if (res.length === 0) { const job = await db().query.jobs.findFirst({ columns: { id: true }, where: eq(jobs.id, jobId) }); if (!job) throw new JobError("not_found", "Job not found.", 404); throw new JobError("not_cancellable", "This job is not running anymore.", 409); } } // --------------------------------------------------------------------------- // Read models for the UI // --------------------------------------------------------------------------- export type JobSnapshot = { id: string; modelId: string; repoId: string; kind: string; purpose: string | null; state: string; attempt: number; totalBytes: number; doneBytes: number; speedBps: number | null; etaSeconds: number | null; exitCode: number | null; errorCode: string | null; errorMessage: string | null; result: JobResult | null; cancelRequested: boolean; createdAt: number; startedAt: number | null; finishedAt: number | null; }; export type JobFileSnapshot = { modelFileId: string; path: string; expectedBytes: number; doneBytes: number; state: string; }; export type LogLine = { id: number; ts: number; stream: string; line: string }; const jobColumns = { id: jobs.id, modelId: jobs.modelId, repoId: models.repoId, kind: jobs.kind, purpose: jobs.purpose, state: jobs.state, attempt: jobs.attempt, totalBytes: jobs.totalBytes, doneBytes: jobs.doneBytes, speedBps: jobs.speedBps, etaSeconds: jobs.etaSeconds, exitCode: jobs.exitCode, errorCode: jobs.errorCode, errorMessage: jobs.errorMessage, result: jobs.result, cancelRequestedAt: jobs.cancelRequestedAt, createdAt: jobs.createdAt, startedAt: jobs.startedAt, finishedAt: jobs.finishedAt, }; type JobRow = Omit & { repoId: string }; function toSnapshot(r: JobRow): JobSnapshot { const { cancelRequestedAt, createdAt, startedAt, finishedAt, ...rest } = r; return { ...rest, cancelRequested: cancelRequestedAt != null, createdAt: createdAt.getTime(), startedAt: startedAt?.getTime() ?? null, finishedAt: finishedAt?.getTime() ?? null, }; } /** Open jobs plus jobs that finished in the last few minutes (so the UI sees the final state). */ export async function listLiveJobs(): Promise { const recent = new Date(Date.now() - 5 * 60_000); const rows = await db() .select(jobColumns) .from(jobs) .innerJoin(models, eq(models.id, jobs.modelId)) .where(or(inArray(jobs.state, [...OPEN_STATES]), gte(jobs.finishedAt, recent))) .orderBy(desc(jobs.createdAt)); return rows.map(toSnapshot); } export async function listModelJobs(modelId: string, limit = 10): Promise { const rows = await db() .select(jobColumns) .from(jobs) .innerJoin(models, eq(models.id, jobs.modelId)) .where(eq(jobs.modelId, modelId)) .orderBy(desc(jobs.createdAt)) .limit(limit); return rows.map(toSnapshot); } export async function getJob(jobId: string): Promise { const [row] = await db() .select(jobColumns) .from(jobs) .innerJoin(models, eq(models.id, jobs.modelId)) .where(eq(jobs.id, jobId)); return row ? toSnapshot(row) : null; } export async function listJobFiles(jobId: string): Promise { return db() .select({ modelFileId: jobFiles.modelFileId, path: jobFiles.path, expectedBytes: jobFiles.expectedBytes, doneBytes: jobFiles.doneBytes, state: jobFiles.state, }) .from(jobFiles) .where(eq(jobFiles.jobId, jobId)) .orderBy(asc(jobFiles.path)); } /** Log lines after `afterId`; on first load (afterId 0) only the last `tail` lines. */ export async function listJobLogs(jobId: string, afterId: number, tail = 1000): Promise { const d = db(); const rows = afterId > 0 ? await d .select() .from(jobLogs) .where(and(eq(jobLogs.jobId, jobId), gt(jobLogs.id, afterId))) .orderBy(asc(jobLogs.id)) .limit(5000) : ( await d.select().from(jobLogs).where(eq(jobLogs.jobId, jobId)).orderBy(desc(jobLogs.id)).limit(tail) ).reverse(); return rows.map((r) => ({ id: r.id, ts: r.ts.getTime(), stream: r.stream, line: r.line })); } export async function fullJobLog(jobId: string): Promise { const rows = await db().select().from(jobLogs).where(eq(jobLogs.jobId, jobId)).orderBy(asc(jobLogs.id)); return rows.map((r) => `${r.ts.toISOString()} [${r.stream}] ${r.line}`).join("\n") + "\n"; } function chunk(items: T[], size: number): T[][] { const out: T[][] = []; for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size)); return out; }