import { asc, eq, isNull, lt, or } from "drizzle-orm"; import { db } from "@/lib/db/client"; import { models, type HubState } from "@/lib/db/schema"; import { getRepoInfo, HubError } from "./client"; type CheckedModel = Pick; /** 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 } | { state: null; error: string }; /** * Is the repo, and the pinned commit, still on the Hub? Stores the result on the model. Only a * definite answer changes `hubState`; network errors, rate limits or a bad token are kept as * `lastCheckError`. Never touches local files. */ export async function checkHubAvailability(model: CheckedModel): Promise { let result: HubCheckResult; try { await getRepoInfo(model.repoId, model.pinnedSha); result = { state: "available" }; } catch (err) { if (err instanceof HubError && err.code === "repo_not_found") result = { state: "repo_missing" }; else if (err instanceof HubError && err.code === "revision_not_found") result = { state: "commit_missing" }; // Gated repos exist; access is a download concern, not availability. else if (err instanceof HubError && (err.code === "gated_no_token" || err.code === "gated_no_access")) { result = { state: "available" }; } else result = { state: null, error: err instanceof Error ? err.message : String(err) }; } const now = new Date(); await db() .update(models) .set( result.state === null ? { lastCheckedAt: now, lastCheckError: result.error } : { lastCheckedAt: now, lastCheckError: null, hubState: result.state, hubMissingSince: result.state === "available" ? null : (model.hubMissingSince ?? now), }, ) .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({ id: models.id, repoId: models.repoId, pinnedSha: models.pinnedSha, hubMissingSince: models.hubMissingSince }) .from(models) .where(or(isNull(models.lastCheckedAt), lt(models.lastCheckedAt, cutoff))) .orderBy(asc(models.lastCheckedAt)) .limit(limit); } export async function getCheckedModel(id: string): Promise { return db().query.models.findFirst({ columns: { id: true, repoId: true, pinnedSha: true, hubMissingSince: true }, where: eq(models.id, id), }); }