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
+233
-46
@@ -1,44 +1,45 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, statfs } from "node:fs/promises";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, statfs, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { inArray } from "drizzle-orm";
|
||||
import { and, asc, eq, inArray, isNotNull, isNull, lt, or, sql } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { runMigrations } from "@/lib/db/migrate";
|
||||
import { ACTIVE_JOB_STATES, jobLogs, jobs, workerState } from "@/lib/db/schema";
|
||||
import { ACTIVE_JOB_STATES, jobFiles, jobLogs, jobs, modelFiles, models, workerState } from "@/lib/db/schema";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { DownloadRunner } from "./download";
|
||||
import { log } from "./log";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
|
||||
const HEARTBEAT_MS = 5_000;
|
||||
const TICK_MS = 1_000;
|
||||
/** A lease older than this is considered abandoned (worker crashed without releasing it). */
|
||||
const LEASE_STALE_MS = 20_000;
|
||||
const SHUTDOWN_GRACE_MS = 8_000;
|
||||
/** Touched on every heartbeat; the Docker healthcheck checks its age. */
|
||||
const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive");
|
||||
|
||||
const instanceId = randomUUID();
|
||||
const startedAt = new Date();
|
||||
const runners = new Map<string, DownloadRunner>();
|
||||
let hfVersion: string | null = null;
|
||||
let stopping = false;
|
||||
|
||||
async function detectHfVersion(): Promise<string | null> {
|
||||
try {
|
||||
const { stdout } = await promisify(execFile)("hf", ["version"], { timeout: 30_000 });
|
||||
return stdout.trim() || null;
|
||||
const { stdout } = await promisify(execFile)("hf", ["version"], {
|
||||
timeout: 30_000,
|
||||
env: { ...process.env, NO_COLOR: "1" },
|
||||
});
|
||||
const m = stdout.match(/version:\s*(\S+)/);
|
||||
return m ? `huggingface_hub ${m[1]}` : stdout.trim() || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Jobs that were running when the worker last stopped can't still be running: mark them interrupted. */
|
||||
async function recoverInterruptedJobs() {
|
||||
const stale = await db()
|
||||
.update(jobs)
|
||||
.set({ state: "interrupted", finishedAt: new Date(), speedBps: null, etaSeconds: null })
|
||||
.where(inArray(jobs.state, [...ACTIVE_JOB_STATES]))
|
||||
.returning({ id: jobs.id });
|
||||
if (stale.length === 0) return;
|
||||
await db()
|
||||
.insert(jobLogs)
|
||||
.values(
|
||||
stale.map((j) => ({
|
||||
jobId: j.id,
|
||||
stream: "system" as const,
|
||||
line: "Worker restarted while this job was running. Marked as interrupted; resume to continue.",
|
||||
})),
|
||||
);
|
||||
log.warn(`marked ${stale.length} job(s) as interrupted`);
|
||||
}
|
||||
|
||||
async function diskSpace(dir: string) {
|
||||
try {
|
||||
const s = await statfs(dir);
|
||||
@@ -48,48 +49,234 @@ async function diskSpace(dir: string) {
|
||||
}
|
||||
}
|
||||
|
||||
async function heartbeat(startedAt: Date, hfVersion: string | null) {
|
||||
// ---------------------------------------------------------------------------
|
||||
// Lease: only one worker may run, otherwise two processes would run the same jobs.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function tryAcquireLease(): Promise<boolean> {
|
||||
const now = new Date();
|
||||
await db()
|
||||
.insert(workerState)
|
||||
.values({ id: "worker", startedAt: now, heartbeatAt: new Date(0) })
|
||||
.onConflictDoNothing();
|
||||
const won = await db()
|
||||
.update(workerState)
|
||||
.set({ instanceId, pid: process.pid, startedAt, heartbeatAt: now })
|
||||
.where(
|
||||
and(
|
||||
eq(workerState.id, "worker"),
|
||||
or(
|
||||
isNull(workerState.instanceId),
|
||||
eq(workerState.instanceId, instanceId),
|
||||
lt(workerState.heartbeatAt, new Date(now.getTime() - LEASE_STALE_MS)),
|
||||
),
|
||||
),
|
||||
)
|
||||
.returning({ id: workerState.id });
|
||||
return won.length > 0;
|
||||
}
|
||||
|
||||
async function acquireLease() {
|
||||
let warned = false;
|
||||
while (!(await tryAcquireLease())) {
|
||||
if (!warned) {
|
||||
const other = await db().query.workerState.findFirst({ where: eq(workerState.id, "worker") });
|
||||
log.warn(`another worker (pid ${other?.pid ?? "?"}) holds the lease; waiting until it stops or goes stale`);
|
||||
warned = true;
|
||||
}
|
||||
await sleep(5_000);
|
||||
}
|
||||
}
|
||||
|
||||
async function heartbeat() {
|
||||
const values = {
|
||||
pid: process.pid,
|
||||
hfVersion,
|
||||
startedAt,
|
||||
heartbeatAt: now,
|
||||
heartbeatAt: new Date(),
|
||||
...(await diskSpace(coreEnv().MODELS_DIR)),
|
||||
};
|
||||
const kept = await db()
|
||||
.update(workerState)
|
||||
.set(values)
|
||||
.where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId)))
|
||||
.returning({ id: workerState.id });
|
||||
if (kept.length === 0) {
|
||||
log.error("lost the worker lease to another process; exiting");
|
||||
await shutdown("lease lost", 1);
|
||||
return;
|
||||
}
|
||||
await writeFile(HEALTH_FILE, String(Date.now())).catch(() => {});
|
||||
}
|
||||
|
||||
async function releaseLease() {
|
||||
await db()
|
||||
.insert(workerState)
|
||||
.values({ id: "worker", ...values })
|
||||
.onConflictDoUpdate({ target: workerState.id, set: values });
|
||||
.update(workerState)
|
||||
.set({ heartbeatAt: new Date(0) })
|
||||
.where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId)));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Jobs
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Jobs that were running when the previous worker stopped can't still be running. */
|
||||
async function recoverInterruptedJobs() {
|
||||
const stale = await db()
|
||||
.update(jobs)
|
||||
.set({ state: "interrupted", finishedAt: new Date(), speedBps: null, etaSeconds: null })
|
||||
.where(inArray(jobs.state, [...ACTIVE_JOB_STATES]))
|
||||
.returning({ id: jobs.id, modelId: jobs.modelId });
|
||||
if (stale.length === 0) return;
|
||||
await db()
|
||||
.insert(jobLogs)
|
||||
.values(
|
||||
stale.map((j) => ({
|
||||
jobId: j.id,
|
||||
stream: "system" as const,
|
||||
line: "Worker restarted while this job was running. Marked as interrupted; resume to continue.",
|
||||
})),
|
||||
);
|
||||
for (const j of stale) await settleModelStatus(j.modelId);
|
||||
log.warn(`marked ${stale.length} job(s) as interrupted`);
|
||||
}
|
||||
|
||||
async function handleCancelRequests() {
|
||||
const requested = await db()
|
||||
.select({ id: jobs.id, state: jobs.state, modelId: jobs.modelId })
|
||||
.from(jobs)
|
||||
.where(and(isNotNull(jobs.cancelRequestedAt), inArray(jobs.state, ["queued", ...ACTIVE_JOB_STATES])));
|
||||
for (const j of requested) {
|
||||
const runner = runners.get(j.id);
|
||||
if (runner) {
|
||||
runner.cancel();
|
||||
} else if (j.state === "queued") {
|
||||
await db()
|
||||
.update(jobs)
|
||||
.set({ state: "cancelled", finishedAt: new Date() })
|
||||
.where(and(eq(jobs.id, j.id), eq(jobs.state, "queued")));
|
||||
await settleModelStatus(j.modelId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Claim the oldest queued download whose model has no running job. */
|
||||
async function claimNextJob() {
|
||||
const busyModels = [...runners.values()].map((r) => r.modelId);
|
||||
const candidates = await db()
|
||||
.select({ id: jobs.id, modelId: jobs.modelId })
|
||||
.from(jobs)
|
||||
.where(and(eq(jobs.state, "queued"), eq(jobs.kind, "download"), isNull(jobs.cancelRequestedAt)))
|
||||
.orderBy(asc(jobs.createdAt))
|
||||
.limit(20);
|
||||
const next = candidates.find((c) => !busyModels.includes(c.modelId));
|
||||
if (!next) return null;
|
||||
|
||||
const [job] = await db()
|
||||
.update(jobs)
|
||||
.set({ state: "downloading", startedAt: new Date(), finishedAt: null, attempt: sql`${jobs.attempt} + 1` })
|
||||
.where(and(eq(jobs.id, next.id), eq(jobs.state, "queued")))
|
||||
.returning();
|
||||
return job ?? null;
|
||||
}
|
||||
|
||||
async function startJob(job: typeof jobs.$inferSelect) {
|
||||
const model = await db().query.models.findFirst({ where: eq(models.id, job.modelId) });
|
||||
if (!model) {
|
||||
await db()
|
||||
.update(jobs)
|
||||
.set({ state: "failed", errorCode: "unknown", errorMessage: "Model no longer exists.", finishedAt: new Date() })
|
||||
.where(eq(jobs.id, job.id));
|
||||
return;
|
||||
}
|
||||
const files = await db()
|
||||
.select({
|
||||
modelFileId: jobFiles.modelFileId,
|
||||
path: jobFiles.path,
|
||||
expectedBytes: jobFiles.expectedBytes,
|
||||
doneBytes: jobFiles.doneBytes,
|
||||
lfsSha256: modelFiles.lfsSha256,
|
||||
blobOid: modelFiles.blobOid,
|
||||
})
|
||||
.from(jobFiles)
|
||||
.innerJoin(modelFiles, eq(modelFiles.id, jobFiles.modelFileId))
|
||||
.where(eq(jobFiles.jobId, job.id));
|
||||
|
||||
await db().update(models).set({ status: "downloading" }).where(eq(models.id, model.id));
|
||||
const runner = new DownloadRunner(job, model, files);
|
||||
runners.set(job.id, runner);
|
||||
log.info(`job ${job.id}: downloading ${model.repoId} (${files.length} files, attempt ${job.attempt})`);
|
||||
runner
|
||||
.run()
|
||||
.catch((err) => log.error(`job ${job.id} crashed`, err))
|
||||
.finally(() => runners.delete(job.id));
|
||||
}
|
||||
|
||||
let ticking = false;
|
||||
async function tick() {
|
||||
if (ticking || stopping) return;
|
||||
ticking = true;
|
||||
try {
|
||||
await handleCancelRequests();
|
||||
const max = coreEnv().MAX_CONCURRENT_DOWNLOADS;
|
||||
while (runners.size < max && !stopping) {
|
||||
const job = await claimNextJob();
|
||||
if (!job) break;
|
||||
await startJob(job);
|
||||
}
|
||||
} catch (err) {
|
||||
log.error("tick failed", err);
|
||||
} finally {
|
||||
ticking = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Lifecycle
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const timers: NodeJS.Timeout[] = [];
|
||||
|
||||
async function shutdown(reason: string, code = 0) {
|
||||
if (stopping) return;
|
||||
stopping = true;
|
||||
log.info(`shutting down (${reason})`);
|
||||
timers.forEach(clearInterval);
|
||||
if (runners.size > 0) {
|
||||
for (const r of runners.values()) r.interrupt();
|
||||
const deadline = Date.now() + SHUTDOWN_GRACE_MS;
|
||||
while (runners.size > 0 && Date.now() < deadline) await sleep(200);
|
||||
}
|
||||
await releaseLease().catch(() => {});
|
||||
process.exit(code);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const env = coreEnv();
|
||||
log.info(`starting (pid ${process.pid}), models dir: ${env.MODELS_DIR}`);
|
||||
log.info(`starting (pid ${process.pid}), models dir: ${env.MODELS_DIR}, max concurrent: ${env.MAX_CONCURRENT_DOWNLOADS}`);
|
||||
await mkdir(env.MODELS_DIR, { recursive: true });
|
||||
|
||||
await runMigrations();
|
||||
log.info("database migrated");
|
||||
|
||||
process.on("SIGINT", () => void shutdown("SIGINT"));
|
||||
process.on("SIGTERM", () => void shutdown("SIGTERM"));
|
||||
|
||||
await acquireLease();
|
||||
log.info("acquired worker lease");
|
||||
await recoverInterruptedJobs();
|
||||
|
||||
const hfVersion = await detectHfVersion();
|
||||
if (hfVersion) log.info(`hf CLI: ${hfVersion}`);
|
||||
hfVersion = await detectHfVersion();
|
||||
if (hfVersion) log.info(`hf CLI: ${hfVersion}, xet ${env.HF_HUB_DISABLE_XET ? "disabled" : "enabled"}`);
|
||||
else log.warn("hf CLI not found on PATH; downloads will fail until it is installed");
|
||||
|
||||
const startedAt = new Date();
|
||||
await heartbeat(startedAt, hfVersion);
|
||||
const timer = setInterval(() => {
|
||||
heartbeat(startedAt, hfVersion).catch((err) => log.error("heartbeat failed", err));
|
||||
}, HEARTBEAT_MS);
|
||||
await heartbeat();
|
||||
timers.push(setInterval(() => heartbeat().catch((err) => log.error("heartbeat failed", err)), HEARTBEAT_MS));
|
||||
timers.push(setInterval(() => void tick(), TICK_MS));
|
||||
void tick();
|
||||
}
|
||||
|
||||
const shutdown = (signal: string) => {
|
||||
log.info(`received ${signal}, shutting down`);
|
||||
clearInterval(timer);
|
||||
process.exit(0);
|
||||
};
|
||||
process.on("SIGINT", () => shutdown("SIGINT"));
|
||||
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
||||
function sleep(ms: number) {
|
||||
return new Promise((r) => setTimeout(r, ms));
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
|
||||
Reference in new issue
Block a user