// Hub checks per model: is the repo (and the pinned commit) still there, and is there a newer // commit on the tracked revision? Run periodically by the worker and on "Check now". Results are // stored on the model; nothing local is ever changed by a check. import { and, asc, eq, isNull, lt, or } from "drizzle-orm"; import { db } from "@/lib/db/client"; import { type HubState, modelFiles, models, type UpdateDiff } from "@/lib/db/schema"; import { computeUpdateDiff } from "@/lib/update-diff"; import { HubError, listFiles, resolveRevision, SHA_RE } from "./client"; type CheckedModel = Pick< typeof models.$inferSelect, "id" | "repoId" | "source" | "pinnedSha" | "trackedRevision" | "hubMissingSince" | "updateDiff" | "includePatterns" | "excludePatterns" >; const CHECKED_COLUMNS = { id: models.id, repoId: models.repoId, source: models.source, pinnedSha: models.pinnedSha, trackedRevision: models.trackedRevision, hubMissingSince: models.hubMissingSince, updateDiff: models.updateDiff, includePatterns: models.includePatterns, excludePatterns: models.excludePatterns, }; /** Why new downloads are impossible, or null if the Hub still has the repo at the pinned commit. */ export function hubMissingMessage(model: { repoId: string; hubState: HubState | null }): string | null { if (model.hubState === "repo_missing") { return `${model.repoId} is no longer on Hugging Face (deleted, or made private), so nothing more can be downloaded. Your local files are kept.`; } if (model.hubState === "commit_missing") { return `The pinned commit of ${model.repoId} is no longer on Hugging Face (history rewritten), so nothing more can be downloaded from it. Your local files are kept.`; } return null; } export type HubCheckResult = | { state: HubState; remoteSha: string | null; update: UpdateDiff | null; warning: string | null } | { state: null; error: string }; const message = (err: unknown) => (err instanceof Error ? err.message : String(err)); const isGated = (err: unknown) => err instanceof HubError && (err.code === "gated_no_token" || err.code === "gated_no_access"); /** Resolve a revision to its commit; null if the Hub says the revision doesn't exist. */ async function resolve(repoId: string, revision: string): Promise { try { return await resolveRevision(repoId, revision); } catch (err) { if (err instanceof HubError && err.code === "revision_not_found") return null; throw err; } } async function run(model: CheckedModel): Promise { // 1. Head of the tracked revision (a full SHA as revision means "pinned for good"). let remoteSha: string | null; let warning: string | null = null; if (SHA_RE.test(model.trackedRevision)) { remoteSha = model.trackedRevision; } else { remoteSha = await resolve(model.repoId, model.trackedRevision); if (!remoteSha) warning = `Revision "${model.trackedRevision}" no longer exists on the Hub; can't check for updates.`; } // 2. Is the pinned commit still there? (Known if it's the head.) const pinnedExists = remoteSha === model.pinnedSha || (await resolve(model.repoId, model.pinnedSha)) !== null; const state: HubState = pinnedExists ? "available" : "commit_missing"; // 3. Newer commit: what would change in the selection? Only recomputed when the head moved. let update: UpdateDiff | null = null; if (remoteSha && remoteSha !== model.pinnedSha) { update = model.updateDiff?.sha === remoteSha ? model.updateDiff : null; if (!update) { const [next, current] = await Promise.all([ listFiles(model.repoId, remoteSha), db() .select({ path: modelFiles.path, size: modelFiles.size, blobOid: modelFiles.blobOid, lfsSha256: modelFiles.lfsSha256 }) .from(modelFiles) .where(and(eq(modelFiles.modelId, model.id), eq(modelFiles.selected, true))), ]); update = computeUpdateDiff(remoteSha, current, next, { include: model.includePatterns, exclude: model.excludePatterns }); } } return { state, remoteSha, update, warning }; } /** * Check one model against the Hub and store the result. Only a definite answer changes the stored * state; network errors, rate limits or a bad token are kept as `lastCheckError`. */ export async function checkHub(model: CheckedModel): Promise { let result: HubCheckResult; try { result = await run(model); } catch (err) { if (err instanceof HubError && err.code === "repo_not_found") { result = { state: "repo_missing", remoteSha: null, update: null, warning: null }; } else if (isGated(err)) { // Gated repos exist; access is a download concern. result = { state: "available", remoteSha: null, update: model.updateDiff ?? null, warning: message(err) }; } else { result = { state: null, error: message(err) }; } } const now = new Date(); await db() .update(models) .set( result.state === null ? { lastCheckedAt: now, lastCheckError: result.error } : { lastCheckedAt: now, lastCheckError: result.warning, hubState: result.state, hubMissingSince: result.state === "available" ? null : (model.hubMissingSince ?? now), ...(result.state === "repo_missing" ? {} : { remoteSha: result.remoteSha, updateDiff: result.update }), }, ) .where(eq(models.id, model.id)); return result; } /** Models whose last Hub check is older than `intervalMs` (or never ran), oldest first. */ export async function modelsDueForHubCheck(intervalMs: number, limit = 50): Promise { const cutoff = new Date(Date.now() - intervalMs); return db() .select(CHECKED_COLUMNS) .from(models) .where(and(eq(models.source, "hub"), or(isNull(models.lastCheckedAt), lt(models.lastCheckedAt, cutoff)))) .orderBy(asc(models.lastCheckedAt)) .limit(limit); } export async function getCheckedModel(id: string): Promise { const [row] = await db().select(CHECKED_COLUMNS).from(models).where(eq(models.id, id)); return row; }