import "server-only"; import { asc, eq, inArray } from "drizzle-orm"; import { z } from "zod"; import { db } from "@/lib/db/client"; import { benchmarkRuns, ENDPOINT_ENGINES, type EndpointHardware, type EndpointProbe, endpoints } from "@/lib/db/schema"; import { EndpointUrlError, normalizeBaseUrl, probeEndpoint } from "@/lib/endpoint-probe"; export class EndpointError extends Error { constructor( public code: "invalid" | "not_found" | "already_exists" | "busy", message: string, public status: number, ) { super(message); } } /** An endpoint as the browser sees it: never the API key, only whether one is set. */ export type EndpointView = { id: string; name: string; baseUrl: string; hasApiKey: boolean; model: string | null; engine: (typeof ENDPOINT_ENGINES)[number] | null; hardware: EndpointHardware; probe: EndpointProbe | null; createdAt: number; updatedAt: number; }; export function toView(e: typeof endpoints.$inferSelect): EndpointView { return { id: e.id, name: e.name, baseUrl: e.baseUrl, hasApiKey: !!e.apiKey, model: e.model, engine: e.engine, hardware: e.hardware, probe: e.probe, createdAt: e.createdAt.getTime(), updatedAt: e.updatedAt.getTime(), }; } const line = (max: number) => z .string() .trim() .max(max, `at most ${max} characters`) .refine((v) => !/[\r\n\0]/.test(v), "one line only") .transform((v) => v || null) .nullish(); const num = (min: number, max: number, int = false) => z .union([z.number(), z.literal(""), z.null()]) .optional() .transform((v) => (v === "" || v == null ? null : v)) .refine((v) => v == null || (v >= min && v <= max && (!int || Number.isInteger(v))), `must be ${int ? "a whole number " : ""}between ${min} and ${max}`); export const hardwareSchema = z.object({ gpuName: line(80), gpuCount: num(1, 64, true), vramGb: num(0.5, 4096), pcie: line(20).refine((v) => !v || /^(?:gen\s*[1-6])?\s*(?:x\s*\d{1,2})?$/i.test(v), 'e.g. "Gen4 x16"'), p2p: z.enum(["on", "off", "partial"]).nullish(), rebar: z.boolean().nullish(), gpuDriver: line(80), cpu: line(80), memoryGb: num(0.5, 65_536), os: line(80), virtualization: line(80), engineName: line(60), engineVersion: line(60), image: line(200), quant: line(40), kvCache: line(40), contextSize: num(128, 100_000_000, true), concurrency: num(1, 4096, true), description: z.string().trim().max(2000, "at most 2000 characters").transform((v) => v || null).nullish(), }); const inputSchema = z.object({ name: z.string().trim().min(1, "required").max(60, "at most 60 characters"), baseUrl: z.string().trim().min(1, "required").max(500), /** undefined: keep the stored key (edit); "" or null: remove it. */ apiKey: z.string().trim().max(500).nullish(), model: line(300), engine: z.enum(ENDPOINT_ENGINES).nullish(), hardware: hardwareSchema.optional(), }); export type EndpointInput = z.input; function parse(input: unknown) { const r = inputSchema.safeParse(input); if (!r.success) { throw new EndpointError("invalid", r.error.issues.map((i) => `${i.path.join(".") || "input"}: ${i.message}`).join("; "), 400); } let baseUrl: string; try { baseUrl = normalizeBaseUrl(r.data.baseUrl); } catch (err) { if (err instanceof EndpointUrlError) throw new EndpointError("invalid", err.message, 400); throw err; } // Drop empty fields so the stored notes only hold what was entered. const hardware = Object.fromEntries(Object.entries(r.data.hardware ?? {}).filter(([, v]) => v != null)) as EndpointHardware; return { ...r.data, baseUrl, hardware }; } async function nameTaken(name: string, exceptId?: string) { const row = await db().query.endpoints.findFirst({ columns: { id: true }, where: eq(endpoints.name, name) }); return !!row && row.id !== exceptId; } export async function listEndpoints(): Promise { return (await db().select().from(endpoints).orderBy(asc(endpoints.name))).map(toView); } export async function getEndpoint(id: string): Promise { const e = await db().query.endpoints.findFirst({ where: eq(endpoints.id, id) }); return e ? toView(e) : null; } export async function createEndpoint(input: unknown): Promise { const v = parse(input); if (await nameTaken(v.name)) throw new EndpointError("already_exists", `An endpoint named "${v.name}" already exists.`, 409); const [row] = await db() .insert(endpoints) .values({ name: v.name, baseUrl: v.baseUrl, apiKey: v.apiKey || null, model: v.model ?? null, engine: v.engine ?? null, hardware: v.hardware }) .returning(); return toView(row); } export async function updateEndpoint(id: string, input: unknown): Promise { const existing = await db().query.endpoints.findFirst({ where: eq(endpoints.id, id) }); if (!existing) throw new EndpointError("not_found", "Endpoint not found.", 404); const v = parse(input); if (await nameTaken(v.name, id)) throw new EndpointError("already_exists", `An endpoint named "${v.name}" already exists.`, 409); const moved = v.baseUrl !== existing.baseUrl; const [row] = await db() .update(endpoints) .set({ name: v.name, baseUrl: v.baseUrl, // The key never reaches the browser, so the form leaves it out to keep it. apiKey: v.apiKey === undefined ? existing.apiKey : v.apiKey || null, model: v.model ?? null, engine: v.engine ?? null, hardware: v.hardware, // A probe of another server says nothing about this one. probe: moved ? null : existing.probe, }) .where(eq(endpoints.id, id)) .returning(); return toView(row); } /** Runs keep their snapshot; queued or running ones must finish or be cancelled first. */ export async function deleteEndpoint(id: string): Promise { const busy = await db().query.benchmarkRuns.findFirst({ columns: { id: true }, where: (r, { and, or }) => and(or(eq(r.endpointId, id), eq(r.endpointBId, id)), inArray(r.state, ["queued", "running"])), }); if (busy) throw new EndpointError("busy", "A benchmark of this endpoint is queued or running. Cancel it first.", 409); const res = await db().delete(endpoints).where(eq(endpoints.id, id)).returning({ id: endpoints.id }); if (!res.length) throw new EndpointError("not_found", "Endpoint not found.", 404); await db().update(benchmarkRuns).set({ endpointId: null }).where(eq(benchmarkRuns.endpointId, id)); await db().update(benchmarkRuns).set({ endpointBId: null }).where(eq(benchmarkRuns.endpointBId, id)); } /** "Test connection": ask the server, store what it said. Unsaved form values can be tested too. */ export async function testEndpoint(id: string | null, draft?: unknown): Promise { let target: { baseUrl: string; apiKey: string | null; engine: (typeof ENDPOINT_ENGINES)[number] | null }; const stored = id ? await db().query.endpoints.findFirst({ where: eq(endpoints.id, id) }) : null; if (id && !stored) throw new EndpointError("not_found", "Endpoint not found.", 404); if (draft) { const v = parse(draft); // The stored key only goes to the URL it was saved for. const keep = v.apiKey === undefined && stored?.baseUrl === v.baseUrl; target = { baseUrl: v.baseUrl, apiKey: keep ? stored!.apiKey : v.apiKey || null, engine: v.engine ?? null }; } else target = { baseUrl: stored!.baseUrl, apiKey: stored!.apiKey, engine: stored!.engine }; const probe = await probeEndpoint(target); if (stored && !draft) await db().update(endpoints).set({ probe }).where(eq(endpoints.id, stored.id)); return probe; }