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,15 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { JobError, requestCancel } from "@/lib/jobs";
|
||||
|
||||
export const POST = withAuth<RouteContext<"/api/jobs/[id]/cancel">>(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
await requestCancel(id);
|
||||
return NextResponse.json({ ok: true }, { status: 202 });
|
||||
} catch (err) {
|
||||
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { fullJobLog, getJob } from "@/lib/jobs";
|
||||
|
||||
/** Full job log as a plain-text download. */
|
||||
export const GET = withAuth<RouteContext<"/api/jobs/[id]/log">>(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
const job = await getJob(id);
|
||||
if (!job) return apiError(404, "not_found", "Job not found.");
|
||||
return new Response(await fullJobLog(id), {
|
||||
headers: {
|
||||
"Content-Type": "text/plain; charset=utf-8",
|
||||
"Content-Disposition": `attachment; filename="job-${id}.log"`,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError } from "@/lib/api-errors";
|
||||
import { JobError, queueDownload } from "@/lib/jobs";
|
||||
|
||||
/** Queue a download of the model's selected files at its pinned SHA. */
|
||||
export const POST = withAuth<RouteContext<"/api/models/[id]/download">>(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
return NextResponse.json(await queueDownload(id), { status: 201 });
|
||||
} catch (err) {
|
||||
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { z } from "zod";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { REPO_ID_RE, SHA_RE } from "@/lib/hub/client";
|
||||
import { queueDownload } from "@/lib/jobs";
|
||||
import { addModel, ModelError } from "@/lib/models";
|
||||
|
||||
const Body = z.object({
|
||||
@@ -11,9 +12,10 @@ const Body = z.object({
|
||||
sha: z.string().regex(SHA_RE, "must be a full 40-character commit SHA"),
|
||||
include: z.array(z.string().min(1).max(1024)).max(10_000),
|
||||
exclude: z.array(z.string().min(1).max(1024)).max(1_000),
|
||||
download: z.boolean().default(true),
|
||||
});
|
||||
|
||||
/** Add a model to the library, pinned to the SHA the user reviewed. */
|
||||
/** Add a model to the library, pinned to the SHA the user reviewed, and queue its download. */
|
||||
export const POST = withAuth(async (req) => {
|
||||
try {
|
||||
const body = Body.parse(await req.json());
|
||||
@@ -23,7 +25,8 @@ export const POST = withAuth(async (req) => {
|
||||
sha: body.sha,
|
||||
rule: { include: body.include, exclude: body.exclude },
|
||||
});
|
||||
return NextResponse.json({ id }, { status: 201 });
|
||||
const job = body.download ? await queueDownload(id) : null;
|
||||
return NextResponse.json({ id, jobId: job?.jobId ?? null }, { status: 201 });
|
||||
} catch (err) {
|
||||
if (err instanceof ModelError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { getJob, listJobFiles, listJobLogs, listLiveJobs, listModelJobs } from "@/lib/jobs";
|
||||
import { getWorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const INTERVAL_MS = 1_000;
|
||||
const KEEPALIVE_MS = 15_000;
|
||||
|
||||
/**
|
||||
* Server-Sent Events with live job state, polled from the DB once per second.
|
||||
* ?model=<id> jobs of one model (+ files of its newest job)
|
||||
* ?job=<id> one job with per-file progress and incremental log lines
|
||||
* (none) open and recently finished jobs (library view)
|
||||
* Events: "snapshot" (only when something changed) and "logs" (new lines).
|
||||
*/
|
||||
export const GET = withAuth(async (req) => {
|
||||
const url = new URL(req.url);
|
||||
const modelId = url.searchParams.get("model");
|
||||
const jobId = url.searchParams.get("job");
|
||||
let logCursor = Number(url.searchParams.get("logAfter") ?? 0) || 0;
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const signal = req.signal;
|
||||
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
let last = "";
|
||||
let lastWrite = Date.now();
|
||||
const write = (chunk: string) => {
|
||||
controller.enqueue(encoder.encode(chunk));
|
||||
lastWrite = Date.now();
|
||||
};
|
||||
const send = (event: string, data: unknown) => write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
|
||||
|
||||
try {
|
||||
write("retry: 3000\n\n");
|
||||
while (!signal.aborted) {
|
||||
const snapshot = await buildSnapshot(modelId, jobId);
|
||||
const serialized = JSON.stringify(snapshot);
|
||||
if (serialized !== last) {
|
||||
send("snapshot", snapshot);
|
||||
last = serialized;
|
||||
}
|
||||
if (jobId) {
|
||||
const lines = await listJobLogs(jobId, logCursor);
|
||||
if (lines.length > 0) {
|
||||
logCursor = lines[lines.length - 1].id;
|
||||
send("logs", lines);
|
||||
}
|
||||
}
|
||||
if (Date.now() - lastWrite > KEEPALIVE_MS) write(": keepalive\n\n");
|
||||
await sleep(INTERVAL_MS, signal);
|
||||
}
|
||||
} catch {
|
||||
// client went away or the stream was closed
|
||||
} finally {
|
||||
try {
|
||||
controller.close();
|
||||
} catch {}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream; charset=utf-8",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
Connection: "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
async function buildSnapshot(modelId: string | null, jobId: string | null) {
|
||||
const worker = await getWorkerStatus();
|
||||
if (jobId) {
|
||||
const job = await getJob(jobId);
|
||||
return { worker, jobs: job ? [job] : [], files: job ? await listJobFiles(jobId) : [] };
|
||||
}
|
||||
if (modelId) {
|
||||
const jobs = await listModelJobs(modelId);
|
||||
const files = jobs[0] ? await listJobFiles(jobs[0].id) : [];
|
||||
return { worker, jobs, files };
|
||||
}
|
||||
return { worker, jobs: await listLiveJobs(), files: [] };
|
||||
}
|
||||
|
||||
function sleep(ms: number, signal: AbortSignal) {
|
||||
return new Promise<void>((resolve) => {
|
||||
const t = setTimeout(resolve, ms);
|
||||
signal.addEventListener("abort", () => {
|
||||
clearTimeout(t);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user