The worker reads README.md when it scans the models folder (the web app can't see it) and stores it on the folder and, after import, on the model; every scan refreshes it for local models. Relative images and links are dropped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
332 lines
16 KiB
TypeScript
332 lines
16 KiB
TypeScript
import "server-only";
|
|
import { and, eq, inArray, isNull, sql } from "drizzle-orm";
|
|
import { ulid } from "ulid";
|
|
import { db } from "@/lib/db/client";
|
|
import { jobFiles, jobs, localFolders, modelFiles, modelRevisions, models } from "@/lib/db/schema";
|
|
import { hubMissingMessage } from "@/lib/hub/availability";
|
|
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
|
|
import { metadataColumns } from "@/lib/hub/refresh";
|
|
import { hasOpenJob, queueDownload } from "@/lib/jobs";
|
|
import { getLocalFolder, localFolderExists, requestFolderScan } from "@/lib/local-folders";
|
|
import { purgeModelRows } from "@/lib/model-purge";
|
|
import { contentId } from "@/lib/update-diff";
|
|
import { escapeGlob, isSelected, matchesAny, type SelectionRule } from "@/lib/selection";
|
|
|
|
export class ModelError extends Error {
|
|
constructor(
|
|
public code: "already_exists" | "empty_selection" | "not_found" | "busy" | "hub_missing" | "no_update" | "local_model",
|
|
message: string,
|
|
public status: number,
|
|
) {
|
|
super(message);
|
|
}
|
|
}
|
|
|
|
const INSERT_CHUNK = 500;
|
|
|
|
/**
|
|
* Add a model pinned to `sha`. The file list is re-fetched from the Hub at that commit
|
|
* (the client's copy isn't trusted) and the selection rule is applied server-side.
|
|
*/
|
|
export async function addModel(input: {
|
|
repoId: string;
|
|
revision: string;
|
|
sha: string;
|
|
rule: SelectionRule;
|
|
/** Import: use this existing folder in MODELS_DIR (must be one the worker's scan found). */
|
|
localPath?: string;
|
|
}): Promise<{ id: string }> {
|
|
const info = await getRepoInfo(input.repoId, input.sha);
|
|
const repoId = info.repoId;
|
|
const localPath = input.localPath ?? repoId;
|
|
if (input.localPath && !(await localFolderExists(input.localPath))) {
|
|
throw new ModelError("not_found", `Folder ${input.localPath} was not found in the models folder. Rescan and try again.`, 404);
|
|
}
|
|
const usedBy = await db().query.models.findFirst({ columns: { repoId: true }, where: eq(models.localPath, localPath) });
|
|
if (usedBy) throw new ModelError("already_exists", `The folder ${localPath} already belongs to ${usedBy.repoId}.`, 409);
|
|
|
|
const existing = await db().query.models.findFirst({
|
|
columns: { id: true },
|
|
where: and(eq(models.repoType, "model"), eq(models.repoId, repoId)),
|
|
});
|
|
if (existing) throw new ModelError("already_exists", `${repoId} is already in the library.`, 409);
|
|
|
|
// Independent: the author's avatar loads while the file list does (usually cached from the lookup).
|
|
const [files, avatar] = await Promise.all([listFiles(repoId, info.sha), getAuthorAvatar(repoId.split("/")[0])]);
|
|
const selectedFiles = files.filter((f) => isSelected(f.path, input.rule));
|
|
if (selectedFiles.length === 0) {
|
|
throw new ModelError("empty_selection", "No files selected.", 400);
|
|
}
|
|
if (info.gated) {
|
|
const smallest = selectedFiles.reduce((a, b) => (b.size < a.size ? b : a));
|
|
await checkFileAccess(repoId, info.sha, smallest.path);
|
|
}
|
|
|
|
const d = db();
|
|
const modelId = ulid();
|
|
const fileRows = files.map((f) => ({
|
|
modelId,
|
|
path: f.path,
|
|
size: f.size,
|
|
blobOid: f.blobOid,
|
|
lfsSha256: f.lfsSha256,
|
|
selected: isSelected(f.path, input.rule),
|
|
}));
|
|
// One atomic batch: model, its first pinned revision and the full file list.
|
|
await d.batch([
|
|
d.insert(models).values({
|
|
id: modelId,
|
|
repoId,
|
|
trackedRevision: input.revision,
|
|
pinnedSha: info.sha,
|
|
localPath,
|
|
includePatterns: input.rule.include,
|
|
excludePatterns: input.rule.exclude,
|
|
...metadataColumns(info.metadata, avatar),
|
|
}),
|
|
d.insert(modelRevisions).values({ modelId, sha: info.sha }),
|
|
...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)),
|
|
d.delete(localFolders).where(eq(localFolders.path, localPath)), // no longer an import candidate
|
|
]);
|
|
return { id: modelId };
|
|
}
|
|
|
|
/**
|
|
* Add a folder from the models folder that has no Hub repo as a local model: every file the scan
|
|
* found, kept as it is. No pinned commit, so no Hub checks, updates, downloads or deep verify; its
|
|
* name is the folder's path.
|
|
*/
|
|
export async function addLocalModel(input: { localPath: string }): Promise<{ id: string }> {
|
|
const folder = await getLocalFolder(input.localPath);
|
|
if (!folder) throw new ModelError("not_found", `Folder ${input.localPath} was not found in the models folder. Rescan and try again.`, 404);
|
|
if (folder.files.length === 0) throw new ModelError("empty_selection", "This folder has no files.", 400);
|
|
if (folder.files.length < folder.fileCount) {
|
|
throw new ModelError("empty_selection", `This folder has ${folder.fileCount} files, more than a local model can list (${folder.files.length}).`, 400);
|
|
}
|
|
const usedBy = await db().query.models.findFirst({ columns: { repoId: true }, where: eq(models.localPath, folder.path) });
|
|
if (usedBy) throw new ModelError("already_exists", `The folder ${folder.path} already belongs to ${usedBy.repoId}.`, 409);
|
|
const existing = await db().query.models.findFirst({
|
|
columns: { id: true },
|
|
where: and(eq(models.repoType, "model"), eq(sql`lower(${models.repoId})`, folder.path.toLowerCase())),
|
|
});
|
|
if (existing) throw new ModelError("already_exists", `${folder.path} is already in the library.`, 409);
|
|
|
|
const d = db();
|
|
const modelId = ulid();
|
|
const now = new Date();
|
|
const fileRows = folder.files.map((f) => ({ modelId, path: f.path, size: f.size, selected: true, state: "present" as const, checkedAt: folder.scannedAt }));
|
|
await d.batch([
|
|
d.insert(models).values({
|
|
id: modelId,
|
|
repoId: folder.path,
|
|
source: "local",
|
|
trackedRevision: "",
|
|
pinnedSha: "",
|
|
localPath: folder.path,
|
|
status: "ready",
|
|
localReadme: folder.readme,
|
|
// Nothing to fetch from the Hub.
|
|
metadataFetchedAt: now,
|
|
}),
|
|
...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)),
|
|
d.delete(localFolders).where(eq(localFolders.path, folder.path)), // no longer an import candidate
|
|
]);
|
|
return { id: modelId };
|
|
}
|
|
|
|
/** Refuse Hub actions (download, update, adding files) for a local model. */
|
|
export function assertHubModel(model: { source: string }): void {
|
|
if (model.source === "local") throw new ModelError("local_model", "This is a local model without a Hugging Face repo.", 409);
|
|
}
|
|
|
|
/**
|
|
* Delete a model. With `deleteFiles` the worker removes its files from disk first (a "delete" job;
|
|
* files that aren't part of the repo are kept); without, only the library entry goes and the
|
|
* folder shows up under "Found in the models folder" again.
|
|
*/
|
|
export async function deleteModel(id: string, options: { deleteFiles: boolean }): Promise<{ queued: boolean }> {
|
|
const d = db();
|
|
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
|
|
if (!model) throw new ModelError("not_found", "Model not found.", 404);
|
|
if (await hasOpenJob(id)) {
|
|
throw new ModelError("busy", "A job for this model is still queued or running. Cancel it first.", 409);
|
|
}
|
|
const [{ n }] = await d.select({ n: sql<number>`count(*)` }).from(jobs).where(eq(jobs.modelId, id));
|
|
const neverDownloaded = model.status === "pending" && n === 0;
|
|
if (!options.deleteFiles || neverDownloaded) {
|
|
await purgeModelRows(id);
|
|
if (!neverDownloaded) await requestFolderScan();
|
|
return { queued: false };
|
|
}
|
|
await d.batch([
|
|
d.insert(jobs).values({ id: ulid(), modelId: id, kind: "delete", targetSha: model.pinnedSha }),
|
|
d.update(models).set({ status: "deleting" }).where(eq(models.id, id)),
|
|
]);
|
|
return { queued: true };
|
|
}
|
|
|
|
/**
|
|
* Update a model to the newer commit found by the last Hub check: pin it (the old commit stays in
|
|
* the revision history), refresh the file list, re-apply the selection rule and queue a download.
|
|
* Unchanged files are kept; changed ones are downloaded again; files that are no longer selected are
|
|
* deleted after the download succeeded.
|
|
*/
|
|
export async function applyUpdate(id: string): Promise<{ jobId: string; sha: string }> {
|
|
const d = db();
|
|
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
|
|
if (!model) throw new ModelError("not_found", "Model not found.", 404);
|
|
assertHubModel(model);
|
|
const missing = hubMissingMessage(model);
|
|
if (missing) throw new ModelError("hub_missing", missing, 409);
|
|
if (await hasOpenJob(id)) {
|
|
throw new ModelError("busy", "A job for this model is still queued or running. Try again when it has finished.", 409);
|
|
}
|
|
const target = model.updateDiff?.sha;
|
|
if (!target || target !== model.remoteSha || target === model.pinnedSha) {
|
|
throw new ModelError("no_update", "No update available. Check the Hub again.", 409);
|
|
}
|
|
|
|
const info = await getRepoInfo(model.repoId, target);
|
|
const files = await listFiles(model.repoId, info.sha);
|
|
const rule: SelectionRule = { include: model.includePatterns, exclude: model.excludePatterns };
|
|
const existing = await d.select().from(modelFiles).where(eq(modelFiles.modelId, id));
|
|
const byPath = new Map(existing.map((f) => [f.path, f]));
|
|
const next = new Set(files.map((f) => f.path));
|
|
|
|
const now = new Date();
|
|
const writes = [];
|
|
for (const f of files) {
|
|
const selected = isSelected(f.path, rule);
|
|
const old = byPath.get(f.path);
|
|
if (!old) {
|
|
writes.push(d.insert(modelFiles).values({ modelId: id, path: f.path, size: f.size, blobOid: f.blobOid, lfsSha256: f.lfsSha256, selected }));
|
|
continue;
|
|
}
|
|
const same = contentId(old) === contentId(f);
|
|
if (same && old.selected === selected) continue;
|
|
writes.push(
|
|
d
|
|
.update(modelFiles)
|
|
.set({ size: f.size, blobOid: f.blobOid, lfsSha256: f.lfsSha256, selected, state: same ? old.state : "pending" })
|
|
.where(eq(modelFiles.id, old.id)),
|
|
);
|
|
}
|
|
// Files gone at the new commit: drop them (and their rows in old jobs' file lists).
|
|
const gone = existing.filter((f) => !next.has(f.path));
|
|
if (gone.length > 0) {
|
|
const ids = gone.map((f) => f.id);
|
|
writes.push(d.delete(jobFiles).where(inArray(jobFiles.modelFileId, ids)), d.delete(modelFiles).where(inArray(modelFiles.id, ids)));
|
|
}
|
|
// Selected before, not anymore (removed from the repo or no longer matching): delete after the download.
|
|
const removePaths = existing.filter((f) => f.selected && (!next.has(f.path) || !isSelected(f.path, rule))).map((f) => f.path);
|
|
|
|
await d.batch([
|
|
d
|
|
.update(models)
|
|
.set({ pinnedSha: info.sha, updateDiff: null, ...metadataColumns(info.metadata, model.authorAvatarUrl) })
|
|
.where(eq(models.id, id)),
|
|
d
|
|
.update(modelRevisions)
|
|
.set({ supersededAt: now })
|
|
.where(and(eq(modelRevisions.modelId, id), isNull(modelRevisions.supersededAt))),
|
|
d.insert(modelRevisions).values({ modelId: id, sha: info.sha }),
|
|
...writes,
|
|
]);
|
|
const { jobId } = await queueDownload(id, "update", { removePaths });
|
|
return { jobId, sha: info.sha };
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
/**
|
|
* Add files to a model's selection and queue a download. The paths are added to the selection
|
|
* rule as exact includes; exclude patterns that would block one of them are dropped, then the
|
|
* rule is re-applied to the whole file list so `selected` always matches the stored rule.
|
|
*/
|
|
export async function addFilesToModel(modelId: string, paths: string[]): Promise<{ jobId: string; added: number }> {
|
|
const d = db();
|
|
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
|
if (!model) throw new ModelError("not_found", "Model not found.", 404);
|
|
assertHubModel(model);
|
|
const missing = hubMissingMessage(model);
|
|
if (missing) throw new ModelError("hub_missing", missing, 409);
|
|
|
|
const open = await d.query.jobs.findFirst({
|
|
columns: { id: true },
|
|
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, ["queued", "downloading", "verifying"])),
|
|
});
|
|
if (open) throw new ModelError("busy", "A download for this model is still queued or running. Add files when it has finished.", 409);
|
|
|
|
const files = await d.select().from(modelFiles).where(eq(modelFiles.modelId, modelId));
|
|
const known = new Map(files.map((f) => [f.path, f]));
|
|
const wanted = [...new Set(paths)].filter((p) => known.has(p) && !known.get(p)!.selected);
|
|
if (wanted.length === 0) throw new ModelError("empty_selection", "No new files selected.", 400);
|
|
|
|
const rule: SelectionRule = {
|
|
include: [...model.includePatterns, ...wanted.map(escapeGlob)],
|
|
exclude: model.excludePatterns.filter((p) => !wanted.some((path) => matchesAny(path, [p]))),
|
|
};
|
|
const changed = files.filter((f) => f.selected !== isSelected(f.path, rule));
|
|
|
|
await d.batch([
|
|
// The selection changed, so a stored update diff is stale; the next Hub check recomputes it.
|
|
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude, updateDiff: null }).where(eq(models.id, modelId)),
|
|
...changed.map((f) =>
|
|
d.update(modelFiles).set({ selected: !f.selected, state: "pending" }).where(eq(modelFiles.id, f.id)),
|
|
),
|
|
]);
|
|
const { jobId } = await queueDownload(modelId, "add");
|
|
return { jobId, added: changed.filter((f) => !f.selected).length };
|
|
}
|
|
|
|
/**
|
|
* Remove files from a model: take them out of the selection rule (exact-path excludes, and their
|
|
* exact includes dropped), mark them unselected, and queue a delete job that removes them from
|
|
* disk. The model and its other files stay. Removing every selected file is refused: delete the
|
|
* model instead.
|
|
*/
|
|
export async function removeFilesFromModel(modelId: string, paths: string[]): Promise<{ jobId: string; removed: number }> {
|
|
const d = db();
|
|
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
|
if (!model) throw new ModelError("not_found", "Model not found.", 404);
|
|
if (await hasOpenJob(modelId)) throw new ModelError("busy", "A job for this model is still queued or running. Remove files when it has finished.", 409);
|
|
|
|
const files = await d.select().from(modelFiles).where(eq(modelFiles.modelId, modelId));
|
|
const wanted = new Set(paths);
|
|
const remove = files.filter((f) => f.selected && wanted.has(f.path));
|
|
if (remove.length === 0) throw new ModelError("empty_selection", "None of these files is selected.", 400);
|
|
if (remove.length === files.filter((f) => f.selected).length) {
|
|
throw new ModelError("empty_selection", "That would remove every file of this model. Delete the model instead.", 400);
|
|
}
|
|
|
|
const exact = new Set(remove.map((f) => escapeGlob(f.path)));
|
|
// Drop the files' exact includes; files a broader pattern still selects get an exact exclude.
|
|
const include = model.includePatterns.filter((p) => !exact.has(p));
|
|
const stillSelected = remove.filter((f) => isSelected(f.path, { include, exclude: model.excludePatterns }));
|
|
const rule: SelectionRule = { include, exclude: [...model.excludePatterns, ...stillSelected.map((f) => escapeGlob(f.path))] };
|
|
// The rule must now select exactly the old selection minus these files.
|
|
const changed = files.filter((f) => f.selected !== isSelected(f.path, rule));
|
|
if (changed.some((f) => !wanted.has(f.path))) throw new ModelError("busy", "The selection rule couldn't be narrowed to just these files.", 409);
|
|
|
|
const jobId = ulid();
|
|
await d.batch([
|
|
// The selection changed, so a stored update diff is stale; the next Hub check recomputes it.
|
|
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude, updateDiff: null }).where(eq(models.id, modelId)),
|
|
...remove.map((f) => d.update(modelFiles).set({ selected: false }).where(eq(modelFiles.id, f.id))),
|
|
d.insert(jobs).values({
|
|
id: jobId,
|
|
modelId,
|
|
kind: "delete",
|
|
purpose: "remove",
|
|
targetSha: model.pinnedSha,
|
|
totalBytes: remove.reduce((s, f) => s + f.size, 0),
|
|
result: { removePaths: remove.map((f) => f.path) },
|
|
}),
|
|
]);
|
|
return { jobId, removed: remove.length };
|
|
}
|