Milestone (c): worker and downloads with live progress
- Worker queue with per-model exclusivity and MAX_CONCURRENT_DOWNLOADS, spawns `hf download --revision <sha> --local-dir ... --include <exact paths>` with HF_TOKEN via env only - Progress from bytes on disk (final + .incomplete files matched by etag), per job and per file, with speed and ETA; post-download size/etag check - Job logs (sanitized), cancel, graceful interrupt on shutdown, partial-file cleanup (hf 2.1.1 does not resume partials) - Single-worker DB lease, free-space check - SSE live updates for library, model and job pages - Dockerfile + compose.yaml (web, worker, data/models volumes) - HF_HUB_DISABLE_XET default on for measurable progress Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8f7ac60ccf
commit
49440154a2
42 files changed
+2974
-110
No files matched your search
@@ -0,0 +1,402 @@
|
||||
import { type ChildProcess, spawn } from "node:child_process";
|
||||
import { mkdir, statfs } from "node:fs/promises";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import {
|
||||
type JobErrorCode,
|
||||
type JobState,
|
||||
jobFiles,
|
||||
jobs,
|
||||
modelFiles,
|
||||
models,
|
||||
} from "@/lib/db/schema";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { escapeGlob } from "@/lib/selection";
|
||||
import {
|
||||
bytesOnDisk,
|
||||
type ExpectedFile,
|
||||
listIncomplete,
|
||||
modelDir,
|
||||
removeStaleIncomplete,
|
||||
} from "./hf-layout";
|
||||
import { JobLog } from "./job-log";
|
||||
import { log } from "./log";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
import { SpeedMeter } from "./speed";
|
||||
|
||||
const SAMPLE_MS = 1_000;
|
||||
const KILL_GRACE_MS = 10_000;
|
||||
|
||||
/** Environment variables passed through to hf (everything else, e.g. AUTH_SECRET, is withheld). */
|
||||
const PASSTHROUGH_ENV = [
|
||||
"PATH", "HOME", "USER", "LANG", "LC_ALL", "TZ", "TMPDIR",
|
||||
"SYSTEMROOT", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "TEMP", "TMP", "PATHEXT", "COMSPEC",
|
||||
"HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy",
|
||||
"SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "HF_ENDPOINT",
|
||||
];
|
||||
|
||||
type Job = typeof jobs.$inferSelect;
|
||||
type Model = typeof models.$inferSelect;
|
||||
type FileRow = {
|
||||
modelFileId: string;
|
||||
path: string;
|
||||
expectedBytes: number;
|
||||
doneBytes: number;
|
||||
lfsSha256: string | null;
|
||||
blobOid: string | null;
|
||||
};
|
||||
|
||||
type Outcome =
|
||||
| { state: "completed" }
|
||||
| { state: "cancelled" | "interrupted"; message: string }
|
||||
| { state: "failed"; code: JobErrorCode; message: string; exitCode?: number | null };
|
||||
|
||||
export class DownloadRunner {
|
||||
private child?: ChildProcess;
|
||||
private stopReason?: "cancelled" | "interrupted";
|
||||
private killTimer?: NodeJS.Timeout;
|
||||
private jobLog: JobLog;
|
||||
|
||||
constructor(
|
||||
private job: Job,
|
||||
private model: Model,
|
||||
private files: FileRow[],
|
||||
) {
|
||||
this.jobLog = new JobLog(job.id, [coreEnv().HF_TOKEN ?? ""]);
|
||||
}
|
||||
|
||||
get jobId() {
|
||||
return this.job.id;
|
||||
}
|
||||
|
||||
get modelId() {
|
||||
return this.model.id;
|
||||
}
|
||||
|
||||
/** User cancel: stop hf, keep completed files. */
|
||||
cancel() {
|
||||
this.stop("cancelled");
|
||||
}
|
||||
|
||||
/** Worker shutdown: stop hf, job can be resumed later. */
|
||||
interrupt() {
|
||||
this.stop("interrupted");
|
||||
}
|
||||
|
||||
private stop(reason: "cancelled" | "interrupted") {
|
||||
if (this.stopReason) return;
|
||||
this.stopReason = reason;
|
||||
this.jobLog.system(reason === "cancelled" ? "Cancel requested, stopping hf…" : "Worker shutting down, stopping hf…");
|
||||
if (!this.child || this.child.exitCode !== null) return;
|
||||
killTree(this.child, "SIGTERM");
|
||||
this.killTimer = setTimeout(() => {
|
||||
if (this.child && this.child.exitCode === null) killTree(this.child, "SIGKILL");
|
||||
}, KILL_GRACE_MS);
|
||||
}
|
||||
|
||||
async run(): Promise<void> {
|
||||
const outcome = await this.execute().catch(
|
||||
(err): Outcome => ({
|
||||
state: "failed",
|
||||
code: "unknown",
|
||||
message: `Internal worker error: ${err instanceof Error ? err.message : String(err)}`,
|
||||
}),
|
||||
);
|
||||
clearTimeout(this.killTimer);
|
||||
if (outcome.state !== "completed") await this.removePartials();
|
||||
await this.finish(outcome);
|
||||
}
|
||||
|
||||
/** hf can't resume partial files, so free their space as soon as hf has exited. */
|
||||
private async removePartials() {
|
||||
if (this.child && this.child.exitCode === null && this.child.signalCode === null) return; // still running
|
||||
try {
|
||||
const dir = modelDir(coreEnv().MODELS_DIR, this.model.localPath);
|
||||
const removed = await removeStaleIncomplete(dir);
|
||||
if (removed.count > 0) {
|
||||
this.jobLog.system(
|
||||
`Removed ${removed.count} partial file(s) (${formatBytes(removed.bytes)}); hf restarts unfinished files from the beginning.`,
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
log.error(`could not remove partial files for job ${this.job.id}`, err);
|
||||
}
|
||||
}
|
||||
|
||||
private async execute(): Promise<Outcome> {
|
||||
const env = coreEnv();
|
||||
const dir = modelDir(env.MODELS_DIR, this.model.localPath);
|
||||
const expected: ExpectedFile[] = this.files.map((f) => ({
|
||||
path: f.path,
|
||||
size: f.expectedBytes,
|
||||
etags: [f.lfsSha256, f.blobOid].filter((x): x is string => !!x),
|
||||
}));
|
||||
|
||||
await mkdir(dir, { recursive: true });
|
||||
this.jobLog.system(
|
||||
`Attempt ${this.job.attempt}: ${this.model.repoId} @ ${this.job.targetSha}, ${this.files.length} file(s), ${formatBytes(this.job.totalBytes)}`,
|
||||
);
|
||||
|
||||
// hf never resumes a partial file; leftovers from earlier runs only waste space.
|
||||
const stale = await removeStaleIncomplete(dir);
|
||||
if (stale.count > 0) {
|
||||
this.jobLog.system(`Removed ${stale.count} partial file(s) from an earlier run (${formatBytes(stale.bytes)}).`);
|
||||
}
|
||||
|
||||
const initial = await this.sample(dir, expected);
|
||||
const remaining = expected.reduce((s, f, i) => s + (initial[i].complete ? 0 : f.size), 0);
|
||||
const doneCount = initial.filter((p) => p.complete).length;
|
||||
if (doneCount > 0) this.jobLog.system(`${doneCount} file(s) already complete, hf will skip them.`);
|
||||
|
||||
const free = await freeBytes(dir);
|
||||
if (free != null && remaining > free) {
|
||||
return {
|
||||
state: "failed",
|
||||
code: "disk_full",
|
||||
message: `Not enough disk space: ${formatBytes(remaining)} still needed, ${formatBytes(free)} free on the models volume.`,
|
||||
};
|
||||
}
|
||||
if (this.stopReason) return { state: this.stopReason, message: "Stopped before hf started." };
|
||||
|
||||
const exit = await this.spawnHf(dir, expected);
|
||||
if (this.stopReason) {
|
||||
return {
|
||||
state: this.stopReason,
|
||||
message: this.stopReason === "cancelled" ? "Cancelled by user." : "Interrupted by worker shutdown.",
|
||||
};
|
||||
}
|
||||
if (exit.error) {
|
||||
return { state: "failed", code: "unknown", message: exit.error, exitCode: exit.code };
|
||||
}
|
||||
if (exit.code !== 0) {
|
||||
const tail = this.jobLog.stderrTail.slice(-8).join("\n");
|
||||
return {
|
||||
state: "failed",
|
||||
code: "unknown",
|
||||
exitCode: exit.code,
|
||||
message: `hf exited with code ${exit.code}${exit.signal ? ` (${exit.signal})` : ""}.${tail ? `\n${tail}` : ""}`,
|
||||
};
|
||||
}
|
||||
|
||||
// hf exits 0 even if e.g. a pattern matched nothing, so check every expected file.
|
||||
await this.setState("verifying");
|
||||
const final = await this.sample(dir, expected);
|
||||
await this.markFiles(final.map((p, i) => ({ id: this.files[i].modelFileId, complete: p.complete })));
|
||||
const bad = expected.filter((_, i) => !final[i].complete);
|
||||
if (bad.length > 0) {
|
||||
return {
|
||||
state: "failed",
|
||||
code: "size_mismatch",
|
||||
exitCode: 0,
|
||||
message: `hf finished, but ${bad.length} file(s) are missing or have the wrong size: ${bad
|
||||
.slice(0, 5)
|
||||
.map((f) => f.path)
|
||||
.join(", ")}${bad.length > 5 ? ", …" : ""}`,
|
||||
};
|
||||
}
|
||||
return { state: "completed" };
|
||||
}
|
||||
|
||||
private spawnHf(
|
||||
dir: string,
|
||||
expected: ExpectedFile[],
|
||||
): Promise<{ code: number | null; signal: NodeJS.Signals | null; error?: string }> {
|
||||
const env = coreEnv();
|
||||
const args = [
|
||||
"download",
|
||||
this.model.repoId,
|
||||
"--revision",
|
||||
this.job.targetSha,
|
||||
"--local-dir",
|
||||
dir,
|
||||
...expected.flatMap((f) => ["--include", escapeGlob(f.path)]),
|
||||
];
|
||||
|
||||
const childEnv: Record<string, string> = {};
|
||||
for (const k of PASSTHROUGH_ENV) {
|
||||
const v = process.env[k];
|
||||
if (v !== undefined) childEnv[k] = v;
|
||||
}
|
||||
Object.assign(childEnv, {
|
||||
HF_HUB_DISABLE_XET: env.HF_HUB_DISABLE_XET ? "1" : "0",
|
||||
HF_HUB_DISABLE_PROGRESS_BARS: "1",
|
||||
HF_HUB_DISABLE_TELEMETRY: "1",
|
||||
NO_COLOR: "1",
|
||||
PYTHONUNBUFFERED: "1",
|
||||
});
|
||||
if (env.HF_HOME) childEnv.HF_HOME = env.HF_HOME;
|
||||
if (env.HF_TOKEN) childEnv.HF_TOKEN = env.HF_TOKEN; // via env, never argv
|
||||
|
||||
this.jobLog.system(
|
||||
`$ hf download ${this.model.repoId} --revision ${this.job.targetSha} --local-dir ${dir} ` +
|
||||
`(${expected.length} --include pattern(s); xet ${env.HF_HUB_DISABLE_XET ? "off" : "on"}; token ${env.HF_TOKEN ? "set" : "not set"})`,
|
||||
);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const done = (r: { code: number | null; signal: NodeJS.Signals | null; error?: string }) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearInterval(timer);
|
||||
this.jobLog.end();
|
||||
resolve(r);
|
||||
};
|
||||
|
||||
const child = spawn("hf", args, { env: childEnv as NodeJS.ProcessEnv, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
||||
this.child = child;
|
||||
child.stdout.on("data", (d) => this.jobLog.chunk("stdout", d));
|
||||
child.stderr.on("data", (d) => this.jobLog.chunk("stderr", d));
|
||||
child.on("error", (err: NodeJS.ErrnoException) =>
|
||||
done({
|
||||
code: null,
|
||||
signal: null,
|
||||
error:
|
||||
err.code === "ENOENT"
|
||||
? "The hf CLI was not found on PATH. Install huggingface_hub[hf_xet] in the worker environment."
|
||||
: `Could not start hf: ${err.message}`,
|
||||
}),
|
||||
);
|
||||
child.on("close", (code, signal) => done({ code, signal }));
|
||||
|
||||
// Progress from bytes on disk, written to the DB once per second.
|
||||
const speed = new SpeedMeter();
|
||||
let busy = false;
|
||||
const timer = setInterval(async () => {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
try {
|
||||
const progress = await this.sample(dir, expected);
|
||||
const doneBytes = progress.reduce((s, p) => s + p.done, 0);
|
||||
speed.add(Date.now(), doneBytes);
|
||||
await this.writeProgress(progress, doneBytes, speed);
|
||||
await this.jobLog.flush();
|
||||
} catch (err) {
|
||||
log.error(`progress sample failed for job ${this.job.id}`, err);
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}, SAMPLE_MS);
|
||||
});
|
||||
}
|
||||
|
||||
private async sample(dir: string, expected: ExpectedFile[]) {
|
||||
const incomplete = await listIncomplete(dir);
|
||||
return Promise.all(expected.map((f) => bytesOnDisk(dir, f, incomplete)));
|
||||
}
|
||||
|
||||
private async writeProgress(
|
||||
progress: { done: number; complete: boolean }[],
|
||||
doneBytes: number,
|
||||
speed: SpeedMeter,
|
||||
) {
|
||||
const d = db();
|
||||
const fileUpdates = [];
|
||||
for (let i = 0; i < this.files.length; i++) {
|
||||
const f = this.files[i];
|
||||
if (f.doneBytes === progress[i].done) continue;
|
||||
f.doneBytes = progress[i].done;
|
||||
fileUpdates.push(
|
||||
d
|
||||
.update(jobFiles)
|
||||
.set({ doneBytes: f.doneBytes, state: progress[i].complete ? "done" : "downloading" })
|
||||
.where(and(eq(jobFiles.jobId, this.job.id), eq(jobFiles.modelFileId, f.modelFileId))),
|
||||
);
|
||||
}
|
||||
const bps = speed.bytesPerSecond();
|
||||
await d.batch([
|
||||
d
|
||||
.update(jobs)
|
||||
.set({
|
||||
doneBytes,
|
||||
speedBps: bps == null ? null : Math.round(bps),
|
||||
etaSeconds: speed.eta(this.job.totalBytes - doneBytes),
|
||||
})
|
||||
.where(eq(jobs.id, this.job.id)),
|
||||
...fileUpdates,
|
||||
]);
|
||||
}
|
||||
|
||||
private async markFiles(results: { id: string; complete: boolean }[]) {
|
||||
const d = db();
|
||||
const now = new Date();
|
||||
const statements = [];
|
||||
for (const [ids, fileState, jobFileState] of [
|
||||
[results.filter((r) => r.complete).map((r) => r.id), "present", "done"],
|
||||
[results.filter((r) => !r.complete).map((r) => r.id), "missing", "failed"],
|
||||
] as const) {
|
||||
if (ids.length === 0) continue;
|
||||
statements.push(
|
||||
d.update(modelFiles).set({ state: fileState, checkedAt: now }).where(inArray(modelFiles.id, ids)),
|
||||
d
|
||||
.update(jobFiles)
|
||||
.set({ state: jobFileState })
|
||||
.where(and(eq(jobFiles.jobId, this.job.id), inArray(jobFiles.modelFileId, ids))),
|
||||
);
|
||||
}
|
||||
if (statements.length > 0) await d.batch(statements as [(typeof statements)[number], ...typeof statements]);
|
||||
}
|
||||
|
||||
private async setState(state: JobState) {
|
||||
await db().update(jobs).set({ state }).where(eq(jobs.id, this.job.id));
|
||||
}
|
||||
|
||||
private async finish(outcome: Outcome) {
|
||||
const now = new Date();
|
||||
const d = db();
|
||||
switch (outcome.state) {
|
||||
case "completed":
|
||||
this.jobLog.system("Download complete, all files verified (size).");
|
||||
await d.batch([
|
||||
d
|
||||
.update(jobs)
|
||||
.set({ state: "completed", finishedAt: now, speedBps: null, etaSeconds: 0, doneBytes: this.job.totalBytes })
|
||||
.where(eq(jobs.id, this.job.id)),
|
||||
d.update(models).set({ downloadedAt: now }).where(eq(models.id, this.model.id)),
|
||||
]);
|
||||
break;
|
||||
case "failed":
|
||||
this.jobLog.system(`Failed: ${outcome.message}`);
|
||||
await d
|
||||
.update(jobs)
|
||||
.set({
|
||||
state: "failed",
|
||||
finishedAt: now,
|
||||
speedBps: null,
|
||||
etaSeconds: null,
|
||||
errorCode: outcome.code,
|
||||
errorMessage: outcome.message,
|
||||
exitCode: outcome.exitCode ?? null,
|
||||
})
|
||||
.where(eq(jobs.id, this.job.id));
|
||||
break;
|
||||
default:
|
||||
this.jobLog.system(outcome.message);
|
||||
await d
|
||||
.update(jobs)
|
||||
.set({ state: outcome.state, finishedAt: now, speedBps: null, etaSeconds: null })
|
||||
.where(eq(jobs.id, this.job.id));
|
||||
}
|
||||
await this.jobLog.close();
|
||||
await settleModelStatus(this.model.id, outcome.state === "failed" ? "failed" : undefined);
|
||||
log.info(`job ${this.job.id} (${this.model.repoId}) ${outcome.state}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function freeBytes(dir: string): Promise<number | null> {
|
||||
try {
|
||||
const s = await statfs(dir);
|
||||
return s.bavail * s.bsize;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function killTree(child: ChildProcess, signal: NodeJS.Signals) {
|
||||
if (process.platform === "win32" && child.pid) {
|
||||
// hf.exe is a launcher for python; kill the whole tree.
|
||||
spawn("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
||||
return;
|
||||
}
|
||||
child.kill(signal);
|
||||
}
|
||||
Reference in new issue
Block a user