Files
Kaname/src/lib/jobs.ts
T
Pascal LinxweilerandClaude Opus 5.5 3603742637 Flag models deleted from the Hub; tag picker, tags in settings, account menu
- Worker checks each model's repo and pinned commit on the Hub every
  UPDATE_CHECK_INTERVAL_HOURS and after failed downloads; missing repos or
  commits are flagged (badge, banner, Status filter) and block new
  downloads. Local files are never touched. "Check now" on the model page.
- Tag picker dropdown ("Create new tag…" first, then existing tags) on the
  model page and in Add model.
- Settings: separate File labels and Tags pages; create tags there. Unused
  tags are no longer deleted automatically.
- Header: app icon, nav with active state, account menu with the OIDC
  profile picture, theme switch and sign out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 22:53:57 +02:00

223 lines
7.2 KiB
TypeScript

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 { hubMissingMessage } from "@/lib/hub/availability";
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" | "hub_missing",
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 missing = hubMissingMessage(model);
if (missing) throw new JobError("hub_missing", missing, 409);
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;
}