Milestone (a): project skeleton and OIDC login
- Next.js 16 + Tailwind + shadcn/ui skeleton - Auth.js v5 generic OIDC (Pocket ID, PKCE) with optional group gate - proxy.ts gates all pages and API routes - Drizzle schema (models, files, jobs, logs, worker state) on SQLite/libsql - Worker skeleton: migrations, interrupted-job recovery, heartbeat Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
891e496157
47 files changed
+14945
No files matched your search
@@ -0,0 +1,42 @@
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { createClient, type Client } from "@libsql/client";
|
||||
import { drizzle, type LibSQLDatabase } from "drizzle-orm/libsql";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import * as schema from "./schema";
|
||||
|
||||
export type Db = LibSQLDatabase<typeof schema>;
|
||||
|
||||
type Holder = { client?: Client; db?: Db };
|
||||
// Survive Next.js dev hot reloads without opening a new pool each time.
|
||||
const holder = ((globalThis as { __kanameDb?: Holder }).__kanameDb ??= {});
|
||||
|
||||
function ensureParentDir(url: string) {
|
||||
if (!url.startsWith("file:")) return;
|
||||
const path = url.slice("file:".length);
|
||||
if (path === ":memory:") return;
|
||||
mkdirSync(dirname(resolve(path)), { recursive: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared Drizzle instance. Web and worker each open their own pool on the same SQLite file;
|
||||
* WAL mode lets the web app read while the worker writes.
|
||||
*/
|
||||
export function db(): Db {
|
||||
if (!holder.db) {
|
||||
const url = coreEnv().DATABASE_URL;
|
||||
ensureParentDir(url);
|
||||
// `timeout` is SQLite's busy timeout (ms) and applies to every pooled connection.
|
||||
holder.client = createClient({ url, timeout: 5000 });
|
||||
holder.db = drizzle(holder.client, { schema });
|
||||
}
|
||||
return holder.db;
|
||||
}
|
||||
|
||||
/** Database-level settings. journal_mode=WAL is persistent, so running it once per process is enough. */
|
||||
export async function initDb(): Promise<void> {
|
||||
db();
|
||||
await holder.client!.execute("PRAGMA journal_mode=WAL");
|
||||
}
|
||||
|
||||
export { schema };
|
||||
@@ -0,0 +1,8 @@
|
||||
import { runMigrations } from "./migrate";
|
||||
|
||||
runMigrations()
|
||||
.then(() => console.log("migrations applied"))
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import { resolve } from "node:path";
|
||||
import { migrate } from "drizzle-orm/libsql/migrator";
|
||||
import { db, initDb } from "./client";
|
||||
|
||||
/** Applies pending migrations from ./drizzle. Run by the worker at startup (and `npm run db:migrate`). */
|
||||
export async function runMigrations(): Promise<void> {
|
||||
await initDb();
|
||||
await migrate(db(), { migrationsFolder: resolve(process.cwd(), "drizzle") });
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
import {
|
||||
index,
|
||||
integer,
|
||||
primaryKey,
|
||||
sqliteTable,
|
||||
text,
|
||||
uniqueIndex,
|
||||
} from "drizzle-orm/sqlite-core";
|
||||
import { ulid } from "ulid";
|
||||
|
||||
// Conventions (keep these when adding tables in later steps, they keep a Postgres port simple):
|
||||
// - Primary keys are ULID strings, generated in the app, never reused.
|
||||
// - Timestamps are integer milliseconds (mode "timestamp_ms").
|
||||
// - Byte counts are integers (safe up to 2^53).
|
||||
// - Enums are text columns with a TS-level enum, not DB enums.
|
||||
// - Foreign keys are declared, but deletes cascade in app code: SQLite only enforces
|
||||
// FKs per connection with PRAGMA foreign_keys=ON, which libsql's pool doesn't guarantee.
|
||||
|
||||
const id = () =>
|
||||
text("id")
|
||||
.primaryKey()
|
||||
.$defaultFn(() => ulid());
|
||||
const createdAt = () =>
|
||||
integer("created_at", { mode: "timestamp_ms" })
|
||||
.notNull()
|
||||
.$defaultFn(() => new Date());
|
||||
const updatedAt = () =>
|
||||
integer("updated_at", { mode: "timestamp_ms" })
|
||||
.notNull()
|
||||
.$defaultFn(() => new Date())
|
||||
.$onUpdateFn(() => new Date());
|
||||
const ts = (name: string) => integer(name, { mode: "timestamp_ms" });
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Models
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const MODEL_STATUSES = [
|
||||
"pending", // added, nothing downloaded yet
|
||||
"downloading",
|
||||
"ready", // all selected files present at pinned SHA
|
||||
"incomplete", // verify found missing/broken files, or an update/repair didn't finish
|
||||
"failed", // last download failed
|
||||
"deleting",
|
||||
] as const;
|
||||
export type ModelStatus = (typeof MODEL_STATUSES)[number];
|
||||
|
||||
export const models = sqliteTable(
|
||||
"models",
|
||||
{
|
||||
id: id(),
|
||||
repoType: text("repo_type", { enum: ["model"] }).notNull().default("model"),
|
||||
repoId: text("repo_id").notNull(), // "org/name"
|
||||
trackedRevision: text("tracked_revision").notNull().default("main"),
|
||||
pinnedSha: text("pinned_sha").notNull(),
|
||||
/** Relative to MODELS_DIR, e.g. "unsloth/Qwen3-27B-GGUF". */
|
||||
localPath: text("local_path").notNull(),
|
||||
/**
|
||||
* Selection rule, applied to the repo's file list. Checkbox picks are stored as escaped
|
||||
* exact-path globs, so the same rule can be re-applied to a newer revision.
|
||||
*/
|
||||
includePatterns: text("include_patterns", { mode: "json" })
|
||||
.$type<string[]>()
|
||||
.notNull()
|
||||
.default(sql`'[]'`),
|
||||
excludePatterns: text("exclude_patterns", { mode: "json" })
|
||||
.$type<string[]>()
|
||||
.notNull()
|
||||
.default(sql`'[]'`),
|
||||
status: text("status", { enum: MODEL_STATUSES }).notNull().default("pending"),
|
||||
/** Latest SHA of trackedRevision seen on the Hub (update check). */
|
||||
remoteSha: text("remote_sha"),
|
||||
lastCheckedAt: ts("last_checked_at"),
|
||||
lastCheckError: text("last_check_error"),
|
||||
lastVerifiedAt: ts("last_verified_at"),
|
||||
downloadedAt: ts("downloaded_at"),
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
},
|
||||
(t) => [uniqueIndex("models_repo_uq").on(t.repoType, t.repoId)],
|
||||
);
|
||||
|
||||
/** History of SHAs a model has been pinned to. */
|
||||
export const modelRevisions = sqliteTable(
|
||||
"model_revisions",
|
||||
{
|
||||
id: id(),
|
||||
modelId: text("model_id")
|
||||
.notNull()
|
||||
.references(() => models.id),
|
||||
sha: text("sha").notNull(),
|
||||
pinnedAt: ts("pinned_at")
|
||||
.notNull()
|
||||
.$defaultFn(() => new Date()),
|
||||
supersededAt: ts("superseded_at"),
|
||||
},
|
||||
(t) => [index("model_revisions_model_idx").on(t.modelId)],
|
||||
);
|
||||
|
||||
export const MODEL_FILE_STATES = [
|
||||
"pending", // not downloaded yet / not checked
|
||||
"present", // exists with the expected size
|
||||
"missing",
|
||||
"size_mismatch",
|
||||
"hash_mismatch",
|
||||
"verified", // deep verify: hash matches
|
||||
] as const;
|
||||
export type ModelFileState = (typeof MODEL_FILE_STATES)[number];
|
||||
|
||||
/** All files in the repo at the pinned SHA. `selected` marks what we keep locally. */
|
||||
export const modelFiles = sqliteTable(
|
||||
"model_files",
|
||||
{
|
||||
id: id(),
|
||||
modelId: text("model_id")
|
||||
.notNull()
|
||||
.references(() => models.id),
|
||||
path: text("path").notNull(),
|
||||
size: integer("size").notNull(),
|
||||
/** Git blob SHA-1 from the Hub tree API. */
|
||||
blobOid: text("blob_oid"),
|
||||
/** SHA-256 for LFS/Xet files (null for small git-stored files). */
|
||||
lfsSha256: text("lfs_sha256"),
|
||||
selected: integer("selected", { mode: "boolean" }).notNull().default(false),
|
||||
state: text("state", { enum: MODEL_FILE_STATES }).notNull().default("pending"),
|
||||
checkedAt: ts("checked_at"),
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
},
|
||||
(t) => [uniqueIndex("model_files_model_path_uq").on(t.modelId, t.path)],
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Jobs (executed by the worker)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const JOB_KINDS = ["download", "verify", "deep_verify"] as const;
|
||||
export type JobKind = (typeof JOB_KINDS)[number];
|
||||
|
||||
export const JOB_PURPOSES = ["initial", "repair", "update"] as const;
|
||||
export type JobPurpose = (typeof JOB_PURPOSES)[number];
|
||||
|
||||
export const JOB_STATES = [
|
||||
"queued",
|
||||
"downloading",
|
||||
"verifying",
|
||||
"completed",
|
||||
"failed",
|
||||
"cancelled",
|
||||
"interrupted",
|
||||
] as const;
|
||||
export type JobState = (typeof JOB_STATES)[number];
|
||||
export const ACTIVE_JOB_STATES = ["downloading", "verifying"] as const satisfies JobState[];
|
||||
|
||||
export const JOB_ERROR_CODES = [
|
||||
"auth", // invalid/missing token
|
||||
"gated", // gated repo, access not granted
|
||||
"repo_not_found",
|
||||
"revision_not_found",
|
||||
"disk_full",
|
||||
"network",
|
||||
"size_mismatch", // finished but files don't match expected sizes
|
||||
"unknown",
|
||||
] as const;
|
||||
export type JobErrorCode = (typeof JOB_ERROR_CODES)[number];
|
||||
|
||||
export const jobs = sqliteTable(
|
||||
"jobs",
|
||||
{
|
||||
id: id(),
|
||||
modelId: text("model_id")
|
||||
.notNull()
|
||||
.references(() => models.id),
|
||||
kind: text("kind", { enum: JOB_KINDS }).notNull(),
|
||||
purpose: text("purpose", { enum: JOB_PURPOSES }),
|
||||
targetSha: text("target_sha").notNull(),
|
||||
state: text("state", { enum: JOB_STATES }).notNull().default("queued"),
|
||||
attempt: integer("attempt").notNull().default(0),
|
||||
totalBytes: integer("total_bytes").notNull().default(0),
|
||||
doneBytes: integer("done_bytes").notNull().default(0),
|
||||
speedBps: integer("speed_bps"),
|
||||
etaSeconds: integer("eta_seconds"),
|
||||
exitCode: integer("exit_code"),
|
||||
errorCode: text("error_code", { enum: JOB_ERROR_CODES }),
|
||||
errorMessage: text("error_message"),
|
||||
/** Set by the web app; the worker picks it up and stops the job. */
|
||||
cancelRequestedAt: ts("cancel_requested_at"),
|
||||
startedAt: ts("started_at"),
|
||||
finishedAt: ts("finished_at"),
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
},
|
||||
(t) => [index("jobs_state_idx").on(t.state), index("jobs_model_idx").on(t.modelId)],
|
||||
);
|
||||
|
||||
export const JOB_FILE_STATES = ["pending", "downloading", "done", "failed"] as const;
|
||||
export type JobFileState = (typeof JOB_FILE_STATES)[number];
|
||||
|
||||
export const jobFiles = sqliteTable(
|
||||
"job_files",
|
||||
{
|
||||
jobId: text("job_id")
|
||||
.notNull()
|
||||
.references(() => jobs.id),
|
||||
modelFileId: text("model_file_id")
|
||||
.notNull()
|
||||
.references(() => modelFiles.id),
|
||||
path: text("path").notNull(),
|
||||
expectedBytes: integer("expected_bytes").notNull(),
|
||||
doneBytes: integer("done_bytes").notNull().default(0),
|
||||
state: text("state", { enum: JOB_FILE_STATES }).notNull().default("pending"),
|
||||
},
|
||||
(t) => [primaryKey({ columns: [t.jobId, t.modelFileId] })],
|
||||
);
|
||||
|
||||
export const LOG_STREAMS = ["stdout", "stderr", "system"] as const;
|
||||
export type LogStream = (typeof LOG_STREAMS)[number];
|
||||
|
||||
export const jobLogs = sqliteTable(
|
||||
"job_logs",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
jobId: text("job_id")
|
||||
.notNull()
|
||||
.references(() => jobs.id),
|
||||
ts: ts("ts")
|
||||
.notNull()
|
||||
.$defaultFn(() => new Date()),
|
||||
stream: text("stream", { enum: LOG_STREAMS }).notNull(),
|
||||
line: text("line").notNull(),
|
||||
},
|
||||
(t) => [index("job_logs_job_idx").on(t.jobId, t.id)],
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Worker liveness
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const workerState = sqliteTable("worker_state", {
|
||||
id: text("id").primaryKey(), // "worker"
|
||||
pid: integer("pid"),
|
||||
hfVersion: text("hf_version"),
|
||||
startedAt: ts("started_at").notNull(),
|
||||
heartbeatAt: ts("heartbeat_at").notNull(),
|
||||
});
|
||||
Reference in new issue
Block a user