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
@@ -239,6 +239,8 @@ export const jobLogs = sqliteTable(
|
||||
|
||||
export const workerState = sqliteTable("worker_state", {
|
||||
id: text("id").primaryKey(), // "worker"
|
||||
/** Random per process; the row acts as a lease so only one worker runs at a time. */
|
||||
instanceId: text("instance_id"),
|
||||
pid: integer("pid"),
|
||||
hfVersion: text("hf_version"),
|
||||
/** Free/total bytes on the filesystem holding MODELS_DIR (the web app has no access to it). */
|
||||
|
||||
@@ -12,6 +12,16 @@ const coreSchema = z.object({
|
||||
DATABASE_URL: z.preprocess(emptyToUndefined, z.string().default("file:/data/app.db")),
|
||||
MAX_CONCURRENT_DOWNLOADS: z.preprocess(emptyToUndefined, z.coerce.number().int().min(1).default(1)),
|
||||
UPDATE_CHECK_INTERVAL_HOURS: z.preprocess(emptyToUndefined, z.coerce.number().min(0).default(12)),
|
||||
/**
|
||||
* Passed to the hf CLI. Default on: with Xet the partial file only grows in large bursts, so
|
||||
* progress from bytes on disk is useless; plain HTTP writes steadily. Set to 0 to use Xet.
|
||||
*/
|
||||
HF_HUB_DISABLE_XET: z.preprocess(
|
||||
(v) => (v === undefined || v === "" ? true : !["0", "false", "no", "off"].includes(String(v).toLowerCase())),
|
||||
z.boolean(),
|
||||
),
|
||||
/** hf CLI home (token cache, Xet logs/cache). Not the model storage. */
|
||||
HF_HOME: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
});
|
||||
|
||||
const authSchema = z.object({
|
||||
|
||||
@@ -13,6 +13,25 @@ export function formatBytes(bytes: number | null | undefined): string {
|
||||
return `${v >= 100 ? v.toFixed(0) : v >= 10 ? v.toFixed(1) : v.toFixed(2)} ${UNITS[i]}`;
|
||||
}
|
||||
|
||||
export function formatSpeed(bps: number | null | undefined): string {
|
||||
return bps == null ? "–" : `${formatBytes(Math.round(bps))}/s`;
|
||||
}
|
||||
|
||||
/** 3725 -> "1h 2m", 95 -> "1m 35s". */
|
||||
export function formatDuration(seconds: number | null | undefined): string {
|
||||
if (seconds == null || !Number.isFinite(seconds)) return "–";
|
||||
const s = Math.max(0, Math.round(seconds));
|
||||
const h = Math.floor(s / 3600);
|
||||
const m = Math.floor((s % 3600) / 60);
|
||||
if (h > 0) return `${h}h ${m}m`;
|
||||
if (m > 0) return `${m}m ${s % 60}s`;
|
||||
return `${s}s`;
|
||||
}
|
||||
|
||||
export function percent(done: number, total: number): number {
|
||||
return total > 0 ? Math.min(100, (done / total) * 100) : 0;
|
||||
}
|
||||
|
||||
export function shortSha(sha: string | null | undefined): string {
|
||||
return sha ? sha.slice(0, 7) : "–";
|
||||
}
|
||||
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
import "server-only";
|
||||
import { and, asc, desc, eq, gt, gte, inArray, isNull, or } from "drizzle-orm";
|
||||
import { ulid } from "ulid";
|
||||
import { db } from "@/lib/db/client";
|
||||
import {
|
||||
ACTIVE_JOB_STATES,
|
||||
type JobPurpose,
|
||||
jobFiles,
|
||||
jobLogs,
|
||||
jobs,
|
||||
modelFiles,
|
||||
models,
|
||||
} from "@/lib/db/schema";
|
||||
|
||||
export class JobError extends Error {
|
||||
constructor(
|
||||
public code: "not_found" | "busy" | "nothing_selected" | "not_cancellable",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
const OPEN_STATES = ["queued", ...ACTIVE_JOB_STATES] as const;
|
||||
const INSERT_CHUNK = 500;
|
||||
|
||||
/** Queue a download of all selected files of a model at its pinned SHA. */
|
||||
export async function queueDownload(modelId: string, purpose: JobPurpose = "initial"): Promise<{ jobId: string }> {
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
||||
if (!model) throw new JobError("not_found", "Model not found.", 404);
|
||||
|
||||
const open = await d.query.jobs.findFirst({
|
||||
columns: { id: true },
|
||||
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, [...OPEN_STATES])),
|
||||
});
|
||||
if (open) throw new JobError("busy", "This model already has a queued or running job.", 409);
|
||||
|
||||
const files = await d
|
||||
.select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size })
|
||||
.from(modelFiles)
|
||||
.where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true)))
|
||||
.orderBy(asc(modelFiles.path));
|
||||
if (files.length === 0) throw new JobError("nothing_selected", "No files selected for this model.", 400);
|
||||
|
||||
const jobId = ulid();
|
||||
const rows = files.map((f) => ({ jobId, modelFileId: f.id, path: f.path, expectedBytes: f.size }));
|
||||
await d.batch([
|
||||
d.insert(jobs).values({
|
||||
id: jobId,
|
||||
modelId,
|
||||
kind: "download",
|
||||
purpose,
|
||||
targetSha: model.pinnedSha,
|
||||
totalBytes: files.reduce((s, f) => s + f.size, 0),
|
||||
}),
|
||||
...chunk(rows, INSERT_CHUNK).map((c) => d.insert(jobFiles).values(c)),
|
||||
d.update(models).set({ status: "downloading" }).where(eq(models.id, modelId)),
|
||||
]);
|
||||
return { jobId };
|
||||
}
|
||||
|
||||
/** Ask the worker to stop a job. Queued jobs are cancelled by the worker on its next tick. */
|
||||
export async function requestCancel(jobId: string): Promise<void> {
|
||||
const res = await db()
|
||||
.update(jobs)
|
||||
.set({ cancelRequestedAt: new Date() })
|
||||
.where(and(eq(jobs.id, jobId), inArray(jobs.state, [...OPEN_STATES]), isNull(jobs.cancelRequestedAt)))
|
||||
.returning({ id: jobs.id });
|
||||
if (res.length === 0) {
|
||||
const job = await db().query.jobs.findFirst({ columns: { id: true }, where: eq(jobs.id, jobId) });
|
||||
if (!job) throw new JobError("not_found", "Job not found.", 404);
|
||||
throw new JobError("not_cancellable", "This job is not running anymore.", 409);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Read models for the UI
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type JobSnapshot = {
|
||||
id: string;
|
||||
modelId: string;
|
||||
repoId: string;
|
||||
kind: string;
|
||||
purpose: string | null;
|
||||
state: string;
|
||||
attempt: number;
|
||||
totalBytes: number;
|
||||
doneBytes: number;
|
||||
speedBps: number | null;
|
||||
etaSeconds: number | null;
|
||||
exitCode: number | null;
|
||||
errorCode: string | null;
|
||||
errorMessage: string | null;
|
||||
cancelRequested: boolean;
|
||||
createdAt: number;
|
||||
startedAt: number | null;
|
||||
finishedAt: number | null;
|
||||
};
|
||||
|
||||
export type JobFileSnapshot = {
|
||||
modelFileId: string;
|
||||
path: string;
|
||||
expectedBytes: number;
|
||||
doneBytes: number;
|
||||
state: string;
|
||||
};
|
||||
|
||||
export type LogLine = { id: number; ts: number; stream: string; line: string };
|
||||
|
||||
const jobColumns = {
|
||||
id: jobs.id,
|
||||
modelId: jobs.modelId,
|
||||
repoId: models.repoId,
|
||||
kind: jobs.kind,
|
||||
purpose: jobs.purpose,
|
||||
state: jobs.state,
|
||||
attempt: jobs.attempt,
|
||||
totalBytes: jobs.totalBytes,
|
||||
doneBytes: jobs.doneBytes,
|
||||
speedBps: jobs.speedBps,
|
||||
etaSeconds: jobs.etaSeconds,
|
||||
exitCode: jobs.exitCode,
|
||||
errorCode: jobs.errorCode,
|
||||
errorMessage: jobs.errorMessage,
|
||||
cancelRequestedAt: jobs.cancelRequestedAt,
|
||||
createdAt: jobs.createdAt,
|
||||
startedAt: jobs.startedAt,
|
||||
finishedAt: jobs.finishedAt,
|
||||
};
|
||||
|
||||
type JobRow = Omit<typeof jobs.$inferSelect, "targetSha" | "updatedAt"> & { repoId: string };
|
||||
|
||||
function toSnapshot(r: JobRow): JobSnapshot {
|
||||
const { cancelRequestedAt, createdAt, startedAt, finishedAt, ...rest } = r;
|
||||
return {
|
||||
...rest,
|
||||
cancelRequested: cancelRequestedAt != null,
|
||||
createdAt: createdAt.getTime(),
|
||||
startedAt: startedAt?.getTime() ?? null,
|
||||
finishedAt: finishedAt?.getTime() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Open jobs plus jobs that finished in the last few minutes (so the UI sees the final state). */
|
||||
export async function listLiveJobs(): Promise<JobSnapshot[]> {
|
||||
const recent = new Date(Date.now() - 5 * 60_000);
|
||||
const rows = await db()
|
||||
.select(jobColumns)
|
||||
.from(jobs)
|
||||
.innerJoin(models, eq(models.id, jobs.modelId))
|
||||
.where(or(inArray(jobs.state, [...OPEN_STATES]), gte(jobs.finishedAt, recent)))
|
||||
.orderBy(desc(jobs.createdAt));
|
||||
return rows.map(toSnapshot);
|
||||
}
|
||||
|
||||
export async function listModelJobs(modelId: string, limit = 10): Promise<JobSnapshot[]> {
|
||||
const rows = await db()
|
||||
.select(jobColumns)
|
||||
.from(jobs)
|
||||
.innerJoin(models, eq(models.id, jobs.modelId))
|
||||
.where(eq(jobs.modelId, modelId))
|
||||
.orderBy(desc(jobs.createdAt))
|
||||
.limit(limit);
|
||||
return rows.map(toSnapshot);
|
||||
}
|
||||
|
||||
export async function getJob(jobId: string): Promise<JobSnapshot | null> {
|
||||
const [row] = await db()
|
||||
.select(jobColumns)
|
||||
.from(jobs)
|
||||
.innerJoin(models, eq(models.id, jobs.modelId))
|
||||
.where(eq(jobs.id, jobId));
|
||||
return row ? toSnapshot(row) : null;
|
||||
}
|
||||
|
||||
export async function listJobFiles(jobId: string): Promise<JobFileSnapshot[]> {
|
||||
return db()
|
||||
.select({
|
||||
modelFileId: jobFiles.modelFileId,
|
||||
path: jobFiles.path,
|
||||
expectedBytes: jobFiles.expectedBytes,
|
||||
doneBytes: jobFiles.doneBytes,
|
||||
state: jobFiles.state,
|
||||
})
|
||||
.from(jobFiles)
|
||||
.where(eq(jobFiles.jobId, jobId))
|
||||
.orderBy(asc(jobFiles.path));
|
||||
}
|
||||
|
||||
/** Log lines after `afterId`; on first load (afterId 0) only the last `tail` lines. */
|
||||
export async function listJobLogs(jobId: string, afterId: number, tail = 1000): Promise<LogLine[]> {
|
||||
const d = db();
|
||||
const rows =
|
||||
afterId > 0
|
||||
? await d
|
||||
.select()
|
||||
.from(jobLogs)
|
||||
.where(and(eq(jobLogs.jobId, jobId), gt(jobLogs.id, afterId)))
|
||||
.orderBy(asc(jobLogs.id))
|
||||
.limit(5000)
|
||||
: (
|
||||
await d.select().from(jobLogs).where(eq(jobLogs.jobId, jobId)).orderBy(desc(jobLogs.id)).limit(tail)
|
||||
).reverse();
|
||||
return rows.map((r) => ({ id: r.id, ts: r.ts.getTime(), stream: r.stream, line: r.line }));
|
||||
}
|
||||
|
||||
export async function fullJobLog(jobId: string): Promise<string> {
|
||||
const rows = await db().select().from(jobLogs).where(eq(jobLogs.jobId, jobId)).orderBy(asc(jobLogs.id));
|
||||
return rows.map((r) => `${r.ts.toISOString()} [${r.stream}] ${r.line}`).join("\n") + "\n";
|
||||
}
|
||||
|
||||
function chunk<T>(items: T[], size: number): T[][] {
|
||||
const out: T[][] = [];
|
||||
for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
|
||||
return out;
|
||||
}
|
||||
Reference in new issue
Block a user