Milestone (b): repo lookup and file selection
- Hub API client: resolve revision to SHA, paginated recursive file tree, gated-access probe, readable error mapping - Add-model page with quant quick-select, fnmatch-compatible include/exclude globs, selection summary and free-space hint - Models stored pinned to the reviewed SHA with full file list and selection rule - Library list, model detail page, remove (never-downloaded models only) - Worker reports MODELS_DIR free space; unit tests for selection logic Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
891e496157
commit
8f7ac60ccf
35 files changed
+2567
-19
No files matched your search
@@ -0,0 +1,202 @@
|
||||
// Minimal Hugging Face Hub API client (metadata only; downloads go through the `hf` CLI).
|
||||
// Server-side only: it reads HF_TOKEN from the environment. Never import from client components.
|
||||
|
||||
import { coreEnv } from "@/lib/env";
|
||||
|
||||
const HUB = "https://huggingface.co";
|
||||
const TIMEOUT_MS = 20_000;
|
||||
const USER_AGENT = "kaname-model-manager";
|
||||
|
||||
export const REPO_ID_RE = /^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/;
|
||||
export const SHA_RE = /^[0-9a-f]{40}$/;
|
||||
|
||||
export type HubErrorCode =
|
||||
| "invalid_repo_id"
|
||||
| "invalid_token"
|
||||
| "repo_not_found" // or private without access
|
||||
| "revision_not_found"
|
||||
| "gated_no_token"
|
||||
| "gated_no_access"
|
||||
| "rate_limited"
|
||||
| "network"
|
||||
| "unknown";
|
||||
|
||||
export class HubError extends Error {
|
||||
constructor(
|
||||
public code: HubErrorCode,
|
||||
message: string,
|
||||
public status?: number,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "HubError";
|
||||
}
|
||||
}
|
||||
|
||||
export type HubFile = {
|
||||
path: string;
|
||||
size: number;
|
||||
/** Git blob SHA-1. */
|
||||
blobOid: string;
|
||||
/** SHA-256 of the content, for LFS/Xet files. */
|
||||
lfsSha256: string | null;
|
||||
xetHash: string | null;
|
||||
};
|
||||
|
||||
export type RepoInfo = {
|
||||
repoId: string;
|
||||
sha: string;
|
||||
gated: false | "auto" | "manual";
|
||||
private: boolean;
|
||||
lastModified: string | null;
|
||||
};
|
||||
|
||||
function headers(): HeadersInit {
|
||||
const h: Record<string, string> = { "User-Agent": USER_AGENT };
|
||||
const token = coreEnv().HF_TOKEN;
|
||||
if (token) h.Authorization = `Bearer ${token}`;
|
||||
return h;
|
||||
}
|
||||
|
||||
async function hubFetch(url: string, init: RequestInit = {}): Promise<Response> {
|
||||
try {
|
||||
return await fetch(url, {
|
||||
...init,
|
||||
headers: { ...headers(), ...init.headers },
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||
});
|
||||
} catch (err) {
|
||||
const reason = err instanceof Error ? err.message : String(err);
|
||||
throw new HubError("network", `Could not reach huggingface.co (${reason}).`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Is the configured token valid? Only called after a 401, to tell a bad token from a missing repo. */
|
||||
async function tokenIsValid(): Promise<boolean> {
|
||||
const res = await hubFetch(`${HUB}/api/whoami-v2`);
|
||||
return res.ok;
|
||||
}
|
||||
|
||||
async function toHubError(res: Response, repoId: string, revision?: string): Promise<HubError> {
|
||||
const code = res.headers.get("x-error-code");
|
||||
const hasToken = Boolean(coreEnv().HF_TOKEN);
|
||||
|
||||
if (code === "RevisionNotFound") {
|
||||
return new HubError("revision_not_found", `Revision "${revision}" not found in ${repoId}.`, res.status);
|
||||
}
|
||||
if (code === "GatedRepo") {
|
||||
return hasToken
|
||||
? new HubError(
|
||||
"gated_no_access",
|
||||
`${repoId} is gated and this token's account has not been granted access. Request access at ${HUB}/${repoId}.`,
|
||||
res.status,
|
||||
)
|
||||
: new HubError(
|
||||
"gated_no_token",
|
||||
`${repoId} is gated. Set HF_TOKEN for an account that has accepted the terms at ${HUB}/${repoId}.`,
|
||||
res.status,
|
||||
);
|
||||
}
|
||||
if (res.status === 429) {
|
||||
return new HubError("rate_limited", "Hugging Face rate limit hit. Try again in a minute.", res.status);
|
||||
}
|
||||
// The Hub answers 401 (without an error code) for missing repos when unauthenticated,
|
||||
// and 401 for any request when the token is invalid.
|
||||
if (res.status === 401 || res.status === 404 || code === "RepoNotFound") {
|
||||
if (res.status === 401 && hasToken && !(await tokenIsValid())) {
|
||||
return new HubError("invalid_token", "HF_TOKEN is invalid or expired.", res.status);
|
||||
}
|
||||
return new HubError(
|
||||
"repo_not_found",
|
||||
hasToken
|
||||
? `Repository ${repoId} not found, or this token has no access to it.`
|
||||
: `Repository ${repoId} not found. If it is private, set HF_TOKEN.`,
|
||||
res.status,
|
||||
);
|
||||
}
|
||||
const msg = res.headers.get("x-error-message") ?? res.statusText;
|
||||
return new HubError("unknown", `Hugging Face API error ${res.status}: ${msg}`, res.status);
|
||||
}
|
||||
|
||||
function assertRepoId(repoId: string) {
|
||||
if (!REPO_ID_RE.test(repoId) || repoId.split("/").some((p) => p === "." || p === "..")) {
|
||||
throw new HubError("invalid_repo_id", `"${repoId}" is not a valid repo ID (expected "org/name").`);
|
||||
}
|
||||
}
|
||||
|
||||
const enc = (s: string) => encodeURIComponent(s);
|
||||
const repoPath = (repoId: string) => repoId.split("/").map(enc).join("/");
|
||||
|
||||
/** Resolve a branch, tag or commit to its full commit SHA, plus basic repo info. */
|
||||
export async function getRepoInfo(repoId: string, revision: string): Promise<RepoInfo> {
|
||||
assertRepoId(repoId);
|
||||
const res = await hubFetch(`${HUB}/api/models/${repoPath(repoId)}/revision/${enc(revision)}`);
|
||||
if (!res.ok) throw await toHubError(res, repoId, revision);
|
||||
const j = (await res.json()) as {
|
||||
id: string;
|
||||
sha: string;
|
||||
gated?: false | "auto" | "manual";
|
||||
private?: boolean;
|
||||
lastModified?: string;
|
||||
};
|
||||
return {
|
||||
repoId: j.id ?? repoId,
|
||||
sha: j.sha,
|
||||
gated: j.gated ?? false,
|
||||
private: j.private ?? false,
|
||||
lastModified: j.lastModified ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
type TreeEntry = {
|
||||
type: "file" | "directory";
|
||||
path: string;
|
||||
size: number;
|
||||
oid: string;
|
||||
lfs?: { oid: string; size: number };
|
||||
xetHash?: string;
|
||||
};
|
||||
|
||||
/** All files (recursive) at a commit. Follows the Link header for pagination. */
|
||||
export async function listFiles(repoId: string, sha: string): Promise<HubFile[]> {
|
||||
assertRepoId(repoId);
|
||||
const files: HubFile[] = [];
|
||||
let url: string | null =
|
||||
`${HUB}/api/models/${repoPath(repoId)}/tree/${enc(sha)}?recursive=true&expand=false&limit=1000`;
|
||||
while (url) {
|
||||
const res = await hubFetch(url);
|
||||
if (!res.ok) throw await toHubError(res, repoId, sha);
|
||||
for (const e of (await res.json()) as TreeEntry[]) {
|
||||
if (e.type !== "file") continue;
|
||||
files.push({
|
||||
path: e.path,
|
||||
size: e.size,
|
||||
blobOid: e.oid,
|
||||
lfsSha256: e.lfs?.oid ?? null,
|
||||
xetHash: e.xetHash ?? null,
|
||||
});
|
||||
}
|
||||
url = nextLink(res.headers.get("link"));
|
||||
}
|
||||
return files.sort((a, b) => a.path.localeCompare(b.path));
|
||||
}
|
||||
|
||||
function nextLink(link: string | null): string | null {
|
||||
if (!link) return null;
|
||||
for (const part of link.split(",")) {
|
||||
const m = part.match(/<([^>]+)>\s*;\s*rel="?next"?/);
|
||||
if (m) return m[1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* For gated repos the file list is public, but downloads need accepted terms.
|
||||
* Probe one file with a HEAD request (no body is downloaded) to find out early.
|
||||
*/
|
||||
export async function checkFileAccess(repoId: string, sha: string, path: string): Promise<void> {
|
||||
const url = `${HUB}/${repoPath(repoId)}/resolve/${enc(sha)}/${path.split("/").map(enc).join("/")}`;
|
||||
const res = await hubFetch(url, { method: "HEAD", redirect: "manual" });
|
||||
if (res.ok || (res.status >= 300 && res.status < 400)) return;
|
||||
throw await toHubError(res, repoId, sha);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import "server-only";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { models } from "@/lib/db/schema";
|
||||
import { checkFileAccess, getRepoInfo, type HubFile, listFiles, type RepoInfo } from "./client";
|
||||
|
||||
export type LookupResult = {
|
||||
repoId: string;
|
||||
revision: string;
|
||||
sha: string;
|
||||
gated: RepoInfo["gated"];
|
||||
lastModified: string | null;
|
||||
files: HubFile[];
|
||||
/** Set when this repo is already in the library. */
|
||||
existingModelId: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Accept "org/name", or a pasted Hub URL like https://huggingface.co/org/name/tree/main.
|
||||
* Returns the repo id and, if the URL contained one, the revision.
|
||||
*/
|
||||
export function normalizeRepoInput(input: string): { repoId: string; revision?: string } {
|
||||
let s = input.trim();
|
||||
const url = s.match(/^https?:\/\/(?:www\.)?huggingface\.co\/(.+)$/i);
|
||||
if (url) s = url[1];
|
||||
s = s.replace(/[?#].*$/, "").replace(/\/+$/, "");
|
||||
const parts = s.split("/");
|
||||
const repoId = parts.slice(0, 2).join("/");
|
||||
const revision = parts[2] === "tree" || parts[2] === "blob" ? parts[3] : undefined;
|
||||
return { repoId, revision };
|
||||
}
|
||||
|
||||
/** Repo metadata + file list at the resolved commit, with an early access check for gated repos. */
|
||||
export async function lookupRepo(repoId: string, revision: string): Promise<LookupResult> {
|
||||
const info = await getRepoInfo(repoId, revision);
|
||||
const files = await listFiles(info.repoId, info.sha);
|
||||
|
||||
if (info.gated && files.length > 0) {
|
||||
const smallest = files.reduce((a, b) => (b.size < a.size ? b : a));
|
||||
await checkFileAccess(info.repoId, info.sha, smallest.path);
|
||||
}
|
||||
|
||||
const existing = await db().query.models.findFirst({
|
||||
columns: { id: true },
|
||||
where: and(eq(models.repoType, "model"), eq(models.repoId, info.repoId)),
|
||||
});
|
||||
|
||||
return {
|
||||
repoId: info.repoId,
|
||||
revision,
|
||||
sha: info.sha,
|
||||
gated: info.gated,
|
||||
lastModified: info.lastModified,
|
||||
files,
|
||||
existingModelId: existing?.id ?? null,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user