- Delete any model (incl. failed ones); the worker removes the repo's files (keeps foreign files and empty-folder cleanup), then the rows. - Verify (existence, size, hf metadata) and deep verify (SHA-256 / git blob SHA-1 against the Hub) with missing/mismatch/extra report. - Repair = download of the selection; broken files are deleted first because hf skips files whose metadata matches without checking them. - Hub check resolves the tracked revision and stores which selected files a newer commit changes/adds/removes; Update pins it (old commit kept in model_revisions), downloads, then removes dropped files. - Worker runs verify/delete jobs next to downloads (2 local slots). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
140 lines
5.5 KiB
TypeScript
140 lines
5.5 KiB
TypeScript
// What `hf download --local-dir <dir>` writes to disk (verified against huggingface_hub 2.1.1):
|
|
//
|
|
// <dir>/<path> final file (moved in place when complete)
|
|
// <dir>/.cache/huggingface/download/<path>.metadata "<commit sha>\n<etag>\n<timestamp>\n"
|
|
// <dir>/.cache/huggingface/download/<path>.lock lock file, left behind
|
|
// <dir>/.cache/huggingface/download/**/<b64>.<etag>.<random>.incomplete partial download
|
|
// <dir>/.cache/huggingface/trees/<sha>.json cached file tree
|
|
//
|
|
// The etag is the LFS sha256 for LFS/Xet files and the git blob SHA-1 for small files.
|
|
// Partial files are NOT resumed: every run writes a new <random> name, and a killed run leaves
|
|
// its .incomplete file behind. We delete those before each run.
|
|
|
|
import { readdir, readFile, rm, stat } from "node:fs/promises";
|
|
import { join, resolve, sep } from "node:path";
|
|
|
|
export const HF_CACHE_DIR = join(".cache", "huggingface");
|
|
const DOWNLOAD_DIR = join(HF_CACHE_DIR, "download");
|
|
|
|
/** Absolute local dir for a model; refuses paths that would escape MODELS_DIR. */
|
|
export function modelDir(modelsDir: string, localPath: string): string {
|
|
const root = resolve(modelsDir);
|
|
const dir = resolve(root, localPath);
|
|
if (dir === root || !dir.startsWith(root + sep)) {
|
|
throw new Error(`Refusing model path outside MODELS_DIR: ${localPath}`);
|
|
}
|
|
return dir;
|
|
}
|
|
|
|
export type FileMetadata = { commit: string; etag: string };
|
|
|
|
export async function readMetadata(dir: string, path: string): Promise<FileMetadata | null> {
|
|
try {
|
|
const text = await readFile(join(dir, DOWNLOAD_DIR, `${path}.metadata`), "utf8");
|
|
const [commit, etag] = text.split("\n");
|
|
return commit && etag ? { commit: commit.trim(), etag: etag.trim() } : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** Size of a file, or null if it doesn't exist. */
|
|
export async function fileSize(path: string): Promise<number | null> {
|
|
try {
|
|
const s = await stat(path);
|
|
return s.isFile() ? s.size : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** Extract the etag (40 or 64 hex chars) from an .incomplete file name. */
|
|
export function etagFromIncompleteName(name: string): string | null {
|
|
if (!name.endsWith(".incomplete")) return null;
|
|
for (const part of name.split(".")) {
|
|
if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(part)) return part;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export type IncompleteFile = { path: string; etag: string | null; size: number };
|
|
|
|
/** All partial files under the local dir's download cache. */
|
|
export async function listIncomplete(dir: string): Promise<IncompleteFile[]> {
|
|
const root = join(dir, DOWNLOAD_DIR);
|
|
let entries;
|
|
try {
|
|
entries = await readdir(root, { recursive: true, withFileTypes: true });
|
|
} catch {
|
|
return [];
|
|
}
|
|
const out: IncompleteFile[] = [];
|
|
for (const e of entries) {
|
|
if (!e.isFile() || !e.name.endsWith(".incomplete")) continue;
|
|
const full = join(e.parentPath, e.name);
|
|
const size = await fileSize(full);
|
|
if (size == null) continue; // finished and moved between readdir and stat
|
|
out.push({ path: full, etag: etagFromIncompleteName(e.name), size });
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** Delete leftover partial files from earlier runs. Only call while no hf process uses the dir. */
|
|
export async function removeStaleIncomplete(dir: string): Promise<{ count: number; bytes: number }> {
|
|
const files = await listIncomplete(dir);
|
|
for (const f of files) await rm(f.path, { force: true });
|
|
return { count: files.length, bytes: files.reduce((s, f) => s + f.size, 0) };
|
|
}
|
|
|
|
export type ExpectedFile = { path: string; size: number; etags: string[] };
|
|
|
|
/**
|
|
* Bytes present for one expected file:
|
|
* - final file with the expected size and matching (or missing) metadata etag → complete
|
|
* - otherwise the size of its in-progress .incomplete file (matched by etag), else 0
|
|
*/
|
|
export async function bytesOnDisk(
|
|
dir: string,
|
|
file: ExpectedFile,
|
|
incomplete: IncompleteFile[],
|
|
): Promise<{ done: number; complete: boolean }> {
|
|
const size = await fileSize(join(dir, file.path));
|
|
if (size === file.size) {
|
|
const meta = await readMetadata(dir, file.path);
|
|
if (!meta || file.etags.includes(meta.etag)) return { done: file.size, complete: true };
|
|
}
|
|
let partial = 0;
|
|
for (const inc of incomplete) {
|
|
if (inc.etag && file.etags.includes(inc.etag)) partial = Math.max(partial, inc.size);
|
|
}
|
|
return { done: Math.min(partial, file.size), complete: false };
|
|
}
|
|
|
|
/** Delete a downloaded file and hf's metadata/lock for it, so the next `hf download` fetches it again. */
|
|
export async function removeLocalFile(dir: string, path: string): Promise<boolean> {
|
|
const full = join(dir, path);
|
|
const existed = (await fileSize(full)) != null;
|
|
await rm(full, { force: true });
|
|
await rm(join(dir, DOWNLOAD_DIR, `${path}.metadata`), { force: true });
|
|
await rm(join(dir, DOWNLOAD_DIR, `${path}.lock`), { force: true });
|
|
return existed;
|
|
}
|
|
|
|
/** All files under `dir` (relative, "/"-separated), skipping hf's .cache and .git folders. */
|
|
export async function listLocalFiles(dir: string): Promise<{ path: string; size: number }[]> {
|
|
let entries;
|
|
try {
|
|
entries = await readdir(dir, { recursive: true, withFileTypes: true });
|
|
} catch {
|
|
return [];
|
|
}
|
|
const out: { path: string; size: number }[] = [];
|
|
for (const e of entries) {
|
|
if (!e.isFile()) continue;
|
|
const rel = join(e.parentPath, e.name).slice(dir.length + 1).split(sep).join("/");
|
|
if (rel.startsWith(".cache/") || rel.startsWith(".git/")) continue;
|
|
out.push({ path: rel, size: (await fileSize(join(dir, rel))) ?? 0 });
|
|
}
|
|
return out.sort((a, b) => a.path.localeCompare(b.path));
|
|
}
|