Hub: reuse commit trees, ask for SHAs only, stream the model card
- listFiles() keeps the last trees it fetched by repo@SHA (a commit's files never change; capped at 50,000 files): adding a model right after the lookup no longer downloads the whole tree again. Callers get copies. - addModel() fetches the author's avatar in parallel with the file list. - The Hub check resolves revisions with resolveRevision(): /revision/<rev> with expand=sha, as huggingface_hub's model_info(expand=...) does, instead of the full model info (file list, card data, the Spaces using the model). Falls back to the full request if an answer comes without a SHA. - The Model card tab renders inside <Suspense>: the page no longer waits for the README to arrive from the Hub (up to the 20 s timeout when it's slow). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
This commit is contained in:
7 files changed
+189
-34
No files matched your search
@@ -6,7 +6,7 @@ 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 { getRepoInfo, HubError, listFiles, SHA_RE } from "./client";
|
||||
import { HubError, listFiles, resolveRevision, SHA_RE } from "./client";
|
||||
|
||||
type CheckedModel = Pick<
|
||||
typeof models.$inferSelect,
|
||||
@@ -45,7 +45,7 @@ const isGated = (err: unknown) => err instanceof HubError && (err.code === "gate
|
||||
/** Resolve a revision to its commit; null if the Hub says the revision doesn't exist. */
|
||||
async function resolve(repoId: string, revision: string): Promise<string | null> {
|
||||
try {
|
||||
return (await getRepoInfo(repoId, revision)).sha;
|
||||
return await resolveRevision(repoId, revision);
|
||||
} catch (err) {
|
||||
if (err instanceof HubError && err.code === "revision_not_found") return null;
|
||||
throw err;
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// Hub client: the per-commit tree cache and the SHA-only revision lookup, against a stubbed fetch.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { after, beforeEach, describe, it } from "node:test";
|
||||
import { HubError, listFiles, resolveRevision } from "./client";
|
||||
|
||||
const realFetch = globalThis.fetch;
|
||||
let requests: string[] = [];
|
||||
let respond: (url: string) => Response;
|
||||
|
||||
const json = (body: unknown, status = 200, headers: Record<string, string> = {}) =>
|
||||
new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json", ...headers } });
|
||||
|
||||
beforeEach(() => {
|
||||
requests = [];
|
||||
globalThis.fetch = (async (input: string | URL | Request) => {
|
||||
const url = String(input instanceof Request ? input.url : input);
|
||||
requests.push(url);
|
||||
return respond(url);
|
||||
}) as typeof fetch;
|
||||
});
|
||||
|
||||
after(() => {
|
||||
globalThis.fetch = realFetch;
|
||||
});
|
||||
|
||||
const SHA = "a".repeat(40);
|
||||
const tree = [
|
||||
{ type: "file", path: "b.gguf", size: 2, oid: "o2" },
|
||||
{ type: "directory", path: "sub", size: 0, oid: "d" },
|
||||
{ type: "file", path: "a.gguf", size: 1, oid: "o1", lfs: { oid: "f".repeat(64), size: 1 } },
|
||||
];
|
||||
|
||||
describe("listFiles", () => {
|
||||
it("downloads a commit's tree once and hands out copies", async () => {
|
||||
respond = () => json(tree);
|
||||
const first = await listFiles("org/cached", SHA);
|
||||
assert.deepEqual(first.map((f) => f.path), ["a.gguf", "b.gguf"]);
|
||||
first.pop();
|
||||
const second = await listFiles("org/cached", SHA);
|
||||
assert.equal(second.length, 2, "the cached list isn't changed by callers");
|
||||
assert.equal(requests.length, 1);
|
||||
});
|
||||
|
||||
it("doesn't cache a branch name (it can move)", async () => {
|
||||
respond = () => json(tree);
|
||||
await listFiles("org/branch", "main");
|
||||
await listFiles("org/branch", "main");
|
||||
assert.equal(requests.length, 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveRevision", () => {
|
||||
it("asks only for the SHA", async () => {
|
||||
respond = () => json({ _id: "x", id: "org/repo", sha: SHA });
|
||||
assert.equal(await resolveRevision("org/repo", "main"), SHA);
|
||||
assert.deepEqual(requests, ["https://huggingface.co/api/models/org/repo/revision/main?expand=sha"]);
|
||||
});
|
||||
|
||||
it("falls back to the full model info when the answer has no SHA", async () => {
|
||||
respond = (url) => (url.endsWith("?expand=sha") ? json({ id: "org/repo" }) : json({ id: "org/repo", sha: SHA }));
|
||||
assert.equal(await resolveRevision("org/repo", "main"), SHA);
|
||||
assert.deepEqual(requests, [
|
||||
"https://huggingface.co/api/models/org/repo/revision/main?expand=sha",
|
||||
"https://huggingface.co/api/models/org/repo/revision/main",
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports a missing repo or revision like the full lookup", async () => {
|
||||
respond = () => json({ error: "nope" }, 404, { "x-error-code": "RevisionNotFound" });
|
||||
await assert.rejects(resolveRevision("org/repo", "gone"), (err) => err instanceof HubError && err.code === "revision_not_found");
|
||||
assert.equal(requests.length, 1);
|
||||
});
|
||||
});
|
||||
+45
-2
@@ -160,9 +160,50 @@ type TreeEntry = {
|
||||
xetHash?: string;
|
||||
};
|
||||
|
||||
/** All files (recursive) at a commit. Follows the Link header for pagination. */
|
||||
/**
|
||||
* The commit a revision points to. Asks the Hub for just the SHA (`expand=sha`, as huggingface_hub's
|
||||
* model_info does): the full model info can be large (file list, card data, the Spaces using it).
|
||||
* Falls back to the full info if an answer comes without a SHA.
|
||||
*/
|
||||
export async function resolveRevision(repoId: string, revision: string): Promise<string> {
|
||||
assertRepoId(repoId);
|
||||
const res = await hubFetch(`${HUB}/api/models/${repoPath(repoId)}/revision/${enc(revision)}?expand=sha`);
|
||||
if (res.ok) {
|
||||
const j = (await res.json().catch(() => null)) as { sha?: unknown } | null;
|
||||
if (typeof j?.sha === "string" && SHA_RE.test(j.sha)) return j.sha;
|
||||
} else if (res.status !== 400) {
|
||||
throw await toHubError(res, repoId, revision);
|
||||
}
|
||||
return (await getRepoInfo(repoId, revision)).sha;
|
||||
}
|
||||
|
||||
// A commit's file list never changes, so the last few are kept: adding a model right after looking
|
||||
// it up doesn't download its tree again. Capped by the number of files held.
|
||||
const treeCache = new Map<string, HubFile[]>();
|
||||
const TREE_CACHE_MAX_FILES = 50_000;
|
||||
let treeCacheFiles = 0;
|
||||
|
||||
function rememberTree(key: string, files: HubFile[]) {
|
||||
if (files.length > TREE_CACHE_MAX_FILES) return;
|
||||
treeCache.set(key, files);
|
||||
treeCacheFiles += files.length;
|
||||
for (const [k, v] of treeCache) {
|
||||
if (treeCacheFiles <= TREE_CACHE_MAX_FILES) break;
|
||||
treeCache.delete(k);
|
||||
treeCacheFiles -= v.length;
|
||||
}
|
||||
}
|
||||
|
||||
/** All files (recursive) at a commit, sorted by path. Follows the Link header for pagination. */
|
||||
export async function listFiles(repoId: string, sha: string): Promise<HubFile[]> {
|
||||
assertRepoId(repoId);
|
||||
const key = `${repoId}@${sha}`;
|
||||
const cached = treeCache.get(key);
|
||||
if (cached) {
|
||||
treeCache.delete(key); // most recently used last
|
||||
treeCache.set(key, cached);
|
||||
return [...cached];
|
||||
}
|
||||
const files: HubFile[] = [];
|
||||
let url: string | null =
|
||||
`${HUB}/api/models/${repoPath(repoId)}/tree/${enc(sha)}?recursive=true&expand=false&limit=1000`;
|
||||
@@ -181,7 +222,9 @@ export async function listFiles(repoId: string, sha: string): Promise<HubFile[]>
|
||||
}
|
||||
url = nextLink(res.headers.get("link"));
|
||||
}
|
||||
return files.sort((a, b) => a.path.localeCompare(b.path));
|
||||
files.sort((a, b) => a.path.localeCompare(b.path));
|
||||
if (SHA_RE.test(sha)) rememberTree(key, files);
|
||||
return [...files];
|
||||
}
|
||||
|
||||
function nextLink(link: string | null): string | null {
|
||||
|
||||
+3
-2
@@ -51,7 +51,8 @@ export async function addModel(input: {
|
||||
});
|
||||
if (existing) throw new ModelError("already_exists", `${repoId} is already in the library.`, 409);
|
||||
|
||||
const files = await listFiles(repoId, info.sha);
|
||||
// Independent: the author's avatar loads while the file list does (usually cached from the lookup).
|
||||
const [files, avatar] = await Promise.all([listFiles(repoId, info.sha), getAuthorAvatar(repoId.split("/")[0])]);
|
||||
const selectedFiles = files.filter((f) => isSelected(f.path, input.rule));
|
||||
if (selectedFiles.length === 0) {
|
||||
throw new ModelError("empty_selection", "No files selected.", 400);
|
||||
@@ -81,7 +82,7 @@ export async function addModel(input: {
|
||||
localPath,
|
||||
includePatterns: input.rule.include,
|
||||
excludePatterns: input.rule.exclude,
|
||||
...metadataColumns(info.metadata, await getAuthorAvatar(repoId.split("/")[0])),
|
||||
...metadataColumns(info.metadata, avatar),
|
||||
}),
|
||||
d.insert(modelRevisions).values({ modelId, sha: info.sha }),
|
||||
...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)),
|
||||
|
||||
Reference in new issue
Block a user