Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Accounts: the owner's API for what accounts make, and deleting their runs

Adarsh505dfdb66041
diff --git a/src/app/api/admin/accounts/route.ts b/src/app/api/admin/accounts/route.ts
index 82c866ed..01752b32 100644
--- a/src/app/api/admin/accounts/route.ts
+++ b/src/app/api/admin/accounts/route.ts
@@ -1,16 +1,23 @@
import { connection } from "next/server";
+import { accountsWithStats } from "@/server/account-admin";
import { accountsCsv, isOwnerRequest, listAccounts, sessionCookieOf } from "@/server/auth";
-/** Settings → Accounts (owner only): everyone who signed up, newest first. `?format=csv` downloads them. */
+const NO_STORE = { "Cache-Control": "no-store" };
+
+/**
+ * Settings → Accounts (owner only): everyone who signed up, newest first, with their runs and space and the totals.
+ * `?format=csv` downloads the list.
+ */
export async function GET(request: Request) {
await connection();
- if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner sees accounts" }, { status: 403 });
+ if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner sees accounts" }, { status: 403, headers: NO_STORE });
const items = listAccounts();
if (new URL(request.url).searchParams.get("format") === "csv") {
const day = new Date().toISOString().slice(0, 10);
return new Response(accountsCsv(items), {
- headers: { "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": `attachment; filename="fuobe-accounts-${day}.csv"`, "Cache-Control": "no-store" },
+ headers: { "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": `attachment; filename="fuobe-accounts-${day}.csv"`, ...NO_STORE },
});
}
- return Response.json({ total: items.length, items }, { headers: { "Cache-Control": "no-store" } });
+ const { items: listed, totals } = accountsWithStats(items);
+ return Response.json({ total: items.length, items: listed, totals }, { headers: NO_STORE });
}
diff --git a/src/app/api/admin/generations/[id]/route.ts b/src/app/api/admin/generations/[id]/route.ts
new file mode 100644
index 00000000..275d354a
--- /dev/null
+++ b/src/app/api/admin/generations/[id]/route.ts
@@ -0,0 +1,20 @@
+import { generationAccount } from "@/server/account-library";
+import { isOwnerRequest, sessionCookieOf } from "@/server/auth";
+import { deleteForever } from "@/server/library";
+
+const NO_STORE = { "Cache-Control": "no-store" };
+
+/**
+ * Delete an account's run for good (owner only), as the account's own delete does: a run still going is canceled
+ * first, and its files go unless another run still uses them, so the account's space comes back at once. The
+ * owner's own runs aren't deleted here (the Library has its Trash).
+ */
+export async function DELETE(request: Request, ctx: RouteContext<"/api/admin/generations/[id]">) {
+ if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner manages accounts" }, { status: 403, headers: NO_STORE });
+ const { id } = await ctx.params;
+ const account = generationAccount(id);
+ if (account === undefined) return Response.json({ error: "No such run" }, { status: 404, headers: NO_STORE });
+ if (account === null) return Response.json({ error: "That run is yours, not an account's. Delete it in the Library." }, { status: 404, headers: NO_STORE });
+ await deleteForever([id]);
+ return new Response(null, { status: 204, headers: NO_STORE });
+}
diff --git a/src/app/api/admin/generations/route.ts b/src/app/api/admin/generations/route.ts
new file mode 100644
index 00000000..71756038
--- /dev/null
+++ b/src/app/api/admin/generations/route.ts
@@ -0,0 +1,18 @@
+import { connection } from "next/server";
+import { accountRunOptions, listAccountRuns } from "@/server/account-admin";
+import { isOwnerRequest, sessionCookieOf } from "@/server/auth";
+
+const NO_STORE = { "Cache-Control": "no-store" };
+
+/**
+ * Accounts' runs (owner only), newest first: `?account=<id>` (else every account's), `status` (finished, running,
+ * failed), `kind` (image, video, audio, model3d, text), `before=<createdAt>:<id>` (the `next` of the last page) and
+ * `limit` (≤ 100). Never the owner's own runs: those are in the Library.
+ */
+export async function GET(request: Request) {
+ await connection();
+ if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner sees accounts' runs" }, { status: 403, headers: NO_STORE });
+ const o = accountRunOptions(new URL(request.url).searchParams);
+ if ("error" in o) return Response.json({ error: o.error }, { status: 400, headers: NO_STORE });
+ return Response.json(listAccountRuns(o), { headers: NO_STORE });
+}
diff --git a/src/lib/format.ts b/src/lib/format.ts
index 5ef173bb..12ea046e 100644
--- a/src/lib/format.ts
+++ b/src/lib/format.ts
@@ -27,6 +27,14 @@ export function elapsed(from: number, to = Date.now()): string {
return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${s % 60}s`;
}
+/** File space in binary units, as the account limits are written (1 GB = 2^30 bytes): "0 MB", "512 KB", "340 MB", "1.3 GB", "3 GB". */
+export function storageSize(bytes: number): string {
+ if (bytes <= 0) return "0 MB";
+ if (bytes < 2 ** 20) return `${Math.max(1, Math.round(bytes / 1024))} KB`;
+ if (bytes < 2 ** 30) return `${Math.round(bytes / 2 ** 20)} MB`;
+ return `${Number((bytes / 2 ** 30).toFixed(1))} GB`;
+}
+
/** The first of "Untitled project", "Untitled project 2", "Untitled project 3"… that isn't taken (case-insensitive). */
export function untitledName(taken: readonly string[], base = "Untitled project"): string {
const used = new Set(taken.map((n) => n.trim().toLowerCase()));
diff --git a/src/server/account-admin.ts b/src/server/account-admin.ts
new file mode 100644
index 00000000..1025b05e
--- /dev/null
+++ b/src/server/account-admin.ts
@@ -0,0 +1,137 @@
+import "server-only";
+import type { Generation } from "@/lib/catalog/types";
+import { accountsMaxBytes, accountTotalBytes } from "./account-files";
+import { listAccounts, type AccountInfo } from "./auth";
+import { db } from "./db";
+import { listGenerations, type ListOptions } from "./generations";
+import { cursorFrom, HELPER_SQL, KINDS } from "./library";
+
+/**
+ * Settings → Accounts (the owner only): what accounts make. Their numbers (runs, space) and their runs, newest first,
+ * one account's or every account's. Never the owner's own runs, and nothing here reaches the owner's Library or live
+ * feed (they leave accounts out: L-13). Read from the indexes (generations_account, assets_account), two grouped
+ * queries for every account at once; an account's runs and files go after 30 days, so these stay small.
+ */
+
+const DAY = 86_400_000;
+
+export interface AccountStats {
+ /** Runs (helper steps left out, as the lists leave them out): all time, the last 24 hours, the last 7 days. */
+ runs: number;
+ runsDay: number;
+ runsWeek: number;
+ /** Queued or running now. */
+ running: number;
+ /** Failed in the last 7 days (a run the account canceled isn't counted). */
+ failedWeek: number;
+ lastRunAt: number | null;
+ /** Its files on this server (uploads and results), and what it may keep (accountTotalBytes). */
+ bytes: number;
+ capBytes: number;
+}
+
+export interface AccountTotals {
+ accounts: number;
+ runsDay: number;
+ runsWeek: number;
+ running: number;
+ /** Every account's files together, and the share of the disk they may take (null when the disk can't be read). */
+ bytes: number;
+ shareBytes: number | null;
+}
+
+export type AccountListing = AccountInfo & AccountStats;
+
+/** Every account's runs in one pass over generations_account (a range search: only accounts' entries). */
+export const STATS_SQL = `SELECT json_extract(g.request_json, '$.account') AS account, COUNT(*) AS runs,
+ SUM(g.created_at >= @day) AS runsDay, SUM(g.created_at >= @week) AS runsWeek,
+ SUM(g.status IN ('queued', 'running')) AS running, SUM(g.status = 'failed' AND g.created_at >= @week) AS failedWeek,
+ MAX(g.created_at) AS lastRunAt
+ FROM generations g WHERE json_extract(g.request_json, '$.account') > '' AND NOT ${HELPER_SQL}
+ GROUP BY json_extract(g.request_json, '$.account')`;
+
+/** What each account's files weigh (what accountUsage counts), over assets_account. */
+export const SPACE_SQL = "SELECT account_id AS account, SUM(size) AS bytes FROM assets WHERE account_id > '' GROUP BY account_id";
+
+type StatsRow = { account: string; runs: number; runsDay: number; runsWeek: number; running: number; failedWeek: number; lastRunAt: number };
+
+/** Each account with its numbers, and the totals over every account's runs and files on this server. */
+export function accountsWithStats(items: AccountInfo[] = listAccounts(), now = Date.now()): { items: AccountListing[]; totals: AccountTotals } {
+ const runs = db().prepare(STATS_SQL).all({ day: now - DAY, week: now - 7 * DAY }) as StatsRow[];
+ const space = db().prepare(SPACE_SQL).all() as { account: string; bytes: number }[];
+ const runsOf = new Map(runs.map((r) => [r.account, r]));
+ const bytesOf = new Map(space.map((r) => [r.account, Number(r.bytes)]));
+ const sum = (key: "runsDay" | "runsWeek" | "running") => runs.reduce((n, r) => n + Number(r[key]), 0);
+ const share = accountsMaxBytes();
+ return {
+ items: items.map((a) => {
+ const r = runsOf.get(a.id);
+ return {
+ ...a,
+ runs: Number(r?.runs ?? 0),
+ runsDay: Number(r?.runsDay ?? 0),
+ runsWeek: Number(r?.runsWeek ?? 0),
+ running: Number(r?.running ?? 0),
+ failedWeek: Number(r?.failedWeek ?? 0),
+ lastRunAt: r ? Number(r.lastRunAt) : null,
+ bytes: bytesOf.get(a.id) ?? 0,
+ capBytes: accountTotalBytes(a.id, a.createdAt),
+ };
+ }),
+ // Every account's runs and files the server holds (what diskHasRoom weighs against the share).
+ totals: {
+ accounts: items.length,
+ runsDay: sum("runsDay"),
+ runsWeek: sum("runsWeek"),
+ running: sum("running"),
+ bytes: space.reduce((n, r) => n + Number(r.bytes), 0),
+ shareBytes: Number.isFinite(share) ? share : null,
+ },
+ };
+}
+
+/** The status filter's choices: a canceled run shows under "any status" only. */
+const STATUSES = new Map<string, Generation["status"][]>([
+ ["finished", ["succeeded"]],
+ ["running", ["queued", "running"]],
+ ["failed", ["failed"]],
+]);
+
+export const RUNS_PAGE = 30;
+const MAX_RUNS_PAGE = 100;
+
+/**
+ * GET /api/admin/generations query → listGenerations options: `account` (one account, else every account's), `status`
+ * (finished, running, failed), `kind`, `before=<createdAt>:<id>` and `limit` (≤ 100). Unknown statuses and kinds are
+ * ignored, as the Library's list ignores them.
+ */
+export function accountRunOptions(sp: URLSearchParams): ListOptions | { error: string } {
+ const account = sp.get("account")?.trim();
+ if (account && !/^[\w-]{1,40}$/.test(account)) return { error: "Pick an account" };
+ const kind = sp.get("kind") ?? "";
+ const asked = Math.trunc(Number(sp.get("limit")));
+ return {
+ ...(account ? { account } : { accounts: true }),
+ statuses: STATUSES.get(sp.get("status") ?? ""),
+ kind: KINDS.has(kind) ? kind : undefined,
+ ...cursorFrom(sp.get("before")),
+ limit: sp.get("limit") && Number.isFinite(asked) ? Math.max(1, Math.min(asked, MAX_RUNS_PAGE)) : RUNS_PAGE,
+ };
+}
+
+/** An account's run as the owner sees it: whose it is (null email: the account was deleted). */
+export type AccountRun = Generation & { account: { id: string; email: string | null } };
+
+/** One page of accounts' runs, newest first, and the cursor of the next (null on the last page). Never the owner's. */
+export function listAccountRuns(o: ListOptions): { items: AccountRun[]; next: string | null } {
+ const limit = o.limit ?? RUNS_PAGE;
+ const opts: ListOptions = o.account ? { ...o, accounts: undefined, limit } : { ...o, account: undefined, accounts: true, limit };
+ const emails = new Map(listAccounts().map((a) => [a.id, a.email]));
+ // The WHERE already leaves the owner's runs out; this keeps them out whatever a caller passes.
+ const found = listGenerations(opts).filter((g) => g.request.account);
+ const last = found.at(-1);
+ return {
+ items: found.map((g) => ({ ...g, account: { id: g.request.account!, email: emails.get(g.request.account!) ?? null } })),
+ next: last && found.length === limit ? `${last.createdAt}:${last.id}` : null,
+ };
+}
diff --git a/src/server/account-files.ts b/src/server/account-files.ts
index 26ccbf7d..6ebe7e9a 100644
--- a/src/server/account-files.ts
+++ b/src/server/account-files.ts
@@ -87,9 +87,8 @@ export const ACCOUNT_MESSAGES = {
lengthNeeded: "Send the file with its size (Content-Length).",
} as const;
-/** What an account may keep in all: 3 GB, or 1 GB in its first 7 days. */
-export function accountTotalBytes(id: string): number {
- const created = accountById(id)?.createdAt ?? 0;
+/** What an account may keep in all: 3 GB, or 1 GB in its first 7 days (`created`: when it signed up, when known). */
+export function accountTotalBytes(id: string, created = accountById(id)?.createdAt ?? 0): number {
return Date.now() - created < ACCOUNT_LIMITS.newAccountDays * DAY ? ACCOUNT_LIMITS.newAccountBytes : ACCOUNT_LIMITS.totalBytes;
}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 673f6ab0..b39a31c6 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -244,6 +244,8 @@ export interface ListOptions {
* own: they stay out of the owner's lists).
*/
account?: string;
+ /** Every account's runs, never the owner's: the owner's view of what accounts make (src/server/account-admin.ts). */
+ accounts?: boolean;
/** Date range on createdAt: since ≤ t < until. */
since?: number;
until?: number;
@@ -261,6 +263,8 @@ export function listGenerations(o: ListOptions = {}): Generation[] {
};
const oneOf = (col: string, values: unknown[]) => add(`${col} IN (${values.map(() => "?").join(", ")})`, ...values);
if (o.account) add("json_extract(g.request_json, '$.account') = ?", o.account);
+ // A range rather than IS NOT NULL: SQLite can search the generations_account index for a range (it scans it whole for IS NOT NULL).
+ else if (o.accounts) add("json_extract(g.request_json, '$.account') > ''");
else add("json_extract(g.request_json, '$.account') IS NULL");
if (o.batchId) add("g.batch_id = ?", o.batchId);
if (o.feature) add("g.feature = ?", o.feature);
diff --git a/src/server/library.ts b/src/server/library.ts
index dd848ed7..be5fcefc 100644
--- a/src/server/library.ts
+++ b/src/server/library.ts
@@ -36,7 +36,7 @@ const DAY = 86_400_000;
const MAX_IDS = 500;
const STATUSES = new Set(["queued", "running", "succeeded", "failed", "canceled"]);
-const KINDS = new Set(["image", "video", "audio", "text", "model3d"]);
+export const KINDS = new Set(["image", "video", "audio", "text", "model3d"]);
/** A library request that can't be done, with the HTTP status the routes answer with. */
export class LibraryError extends Error {
@@ -224,7 +224,7 @@ export function setReview(list: string[], review: ReviewStatus | null): number {
// Folders (nested: each has a parent, null at the library root; one folder per generation)
/** The SQL test for a helper step of `g` (isHelperFeature); the names are constants, not input. */
-const HELPER_SQL = `(g.feature LIKE '%${HELPER_SUFFIX}' OR g.feature IN (${HELPER_FEATURES.map((f) => `'${f}'`).join(", ")}))`;
+export const HELPER_SQL = `(g.feature LIKE '%${HELPER_SUFFIX}' OR g.feature IN (${HELPER_FEATURES.map((f) => `'${f}'`).join(", ")}))`;
interface FolderRow {
id: string;
diff --git a/tests/account-runs-admin.test.ts b/tests/account-runs-admin.test.ts
new file mode 100644
index 00000000..1a2d9488
--- /dev/null
+++ b/tests/account-runs-admin.test.ts
@@ -0,0 +1,351 @@
+import { createHmac } from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+import type { AccountListing, AccountRun, AccountTotals } from "@/server/account-admin";
+import { TINY_PNG } from "./helpers/fake-comfy-runner";
+
+// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-runs-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+delete process.env.FUOBE_PASSWORD;
+const auth = await import("@/server/auth");
+const { db } = await import("@/server/db");
+const gens = await import("@/server/generations");
+const { libraryFacets, listOptionsFrom } = await import("@/server/library");
+const live = await import("@/server/live");
+const admin = await import("@/server/account-admin");
+const { accountUsage } = await import("@/server/account-files");
+const { absolutePath, saveFile } = await import("@/server/storage");
+const { storageSize } = await import("@/lib/format");
+const { proxy } = await import("@/proxy");
+const accountsRoute = await import("@/app/api/admin/accounts/route");
+const runsRoute = await import("@/app/api/admin/generations/route");
+const runRoute = await import("@/app/api/admin/generations/[id]/route");
+const filesRoute = await import("@/app/api/files/[...path]/route");
+const generationsRoute = await import("@/app/api/generations/route");
+afterAll(() => {
+ delete process.env.FUOBE_PUBLIC_SIGNUP;
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const A = auth.createAccount("[email protected]", "long enough").id;
+const B = auth.createAccount("[email protected]", "long enough").id;
+const C = auth.createAccount("[email protected]", "long enough").id;
+const HOUR = 3_600_000;
+const DAY = 24 * HOUR;
+
+let seq = 0;
+/** A run as the runner stores it: `account`'s (or the owner's), made `ago` ms before now (or `at`). */
+function run(account?: string, o: { status?: string; kind?: string; feature?: string; ago?: number; at?: number; error?: string } = {}): string {
+ const id = `run-${String(++seq).padStart(4, "0")}`;
+ const at = o.at ?? Date.now() - (o.ago ?? 0);
+ const feature = o.feature ?? "image";
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, error, created_at, updated_at) VALUES (?, ?, 'm', 'open', 'comfyui', ?, ?, ?, ?, '[]', ?, ?, ?)",
+ )
+ .run(id, feature, o.kind === "video" ? "t2v" : "t2i", o.kind ?? "image", o.status ?? "succeeded", JSON.stringify({ feature, modelId: "m", prompt: "a fox", ...(account && { account }) }), o.error ?? null, at, at);
+ return id;
+}
+
+/** A stored result of run `id` (an account's file when the run is an account's), `bytes` over a tiny PNG. */
+function output(id: string, bytes = 0) {
+ const asset = saveFile({ data: Buffer.concat([TINY_PNG, Buffer.alloc(bytes)]), contentType: "image/png", source: "generation", generationId: id });
+ db().prepare("UPDATE generations SET outputs_json = ? WHERE id = ?").run(JSON.stringify([{ url: asset.url, kind: "image", assetId: asset.id }]), id);
+ return asset;
+}
+
+/** Session cookies: the owner's, account A's and C's, an owner-shaped one signed with auth.json's secret alone, and two at once. */
+const cookies = {} as Record<"owner" | "a" | "c" | "forged" | "doubled", string>;
+beforeAll(() => {
+ auth.setPassword("install password");
+ const owner = auth.createSession().value;
+ const a = auth.createSession(A).value;
+ const secret = (JSON.parse(fs.readFileSync(path.join(dir, "auth.json"), "utf8")) as { secret: string }).secret;
+ const exp = Date.now() + 60_000;
+ cookies.owner = `${auth.SESSION_COOKIE}=${owner}`;
+ cookies.a = `${auth.SESSION_COOKIE}=${a}`;
+ cookies.c = `${auth.SESSION_COOKIE}=${auth.createSession(C).value}`;
+ cookies.forged = `${auth.SESSION_COOKIE}=${exp}.${createHmac("sha256", secret).update(String(exp)).digest("base64url")}`;
+ cookies.doubled = `${auth.SESSION_COOKIE}=${owner}; ${auth.SESSION_COOKIE}=${a}`;
+});
+
+const viaProxy = (url: string, method = "GET", cookie?: string) =>
+ proxy(new NextRequest(`http://localhost:3000${url}`, { method, headers: cookie ? { cookie } : {}, ...(method !== "GET" && { body: "{}" }) }));
+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";
+const direct = (url: string, method = "GET", headers: Record<string, string> = {}) => new Request(`http://localhost:3000${url}`, { method, headers });
+const ctx = (id: string) => ({ params: Promise.resolve({ id }) }) as never;
+
+type Listed = { items: AccountRun[]; next: string | null };
+async function listed(qs = "", cookie = cookies.owner): Promise<Listed> {
+ const res = await runsRoute.GET(direct(`/api/admin/generations${qs ? `?${qs}` : ""}`, "GET", { cookie }));
+ expect(res.status).toBe(200);
+ return (await res.json()) as Listed;
+}
+const ids = (l: Listed) => l.items.map((g) => g.id);
+const remove = (id: string, headers: Record<string, string> = { cookie: cookies.owner }) => runRoute.DELETE(direct(`/api/admin/generations/${id}`, "DELETE", headers), ctx(id));
+
+/** The plan SQLite picks for the list query listGenerations builds inside `fn` (the real SQL, any values bound). */
+function listPlan(fn: () => unknown): string {
+ const d = db();
+ const spy = vi.spyOn(d, "prepare");
+ let calls: string[];
+ try {
+ fn();
+ } finally {
+ calls = spy.mock.calls.map((c) => c[0]);
+ spy.mockRestore();
+ }
+ const sql = calls.find((s) => s.startsWith("SELECT g.*") && s.includes("ORDER BY"));
+ expect(sql).toBeTruthy();
+ return plan(sql!, Array((sql!.match(/\?/g) ?? []).length).fill("x"));
+}
+const plan = (sql: string, args: unknown[] | Record<string, unknown> = []) =>
+ (db().prepare(`EXPLAIN QUERY PLAN ${sql}`).all(...(Array.isArray(args) ? args : [args])) as { detail: string }[]).map((r) => r.detail).join("\n");
+
+describe("Settings → Accounts: what accounts make", () => {
+ it("is the owner's only on every new route, and the stats route", async () => {
+ const routes: [string, string][] = [
+ ["GET", "/api/admin/generations"],
+ ["GET", `/api/admin/generations?account=${A}`],
+ ["DELETE", "/api/admin/generations/x"],
+ ["GET", "/api/admin/accounts"],
+ ];
+ for (const [m, p] of routes) {
+ expect(viaProxy(p, m, cookies.a).status, `account ${m} ${p}`).toBe(403);
+ expect(viaProxy(p, m).status, `guest ${m} ${p}`).toBe(401);
+ expect(viaProxy(p, m, cookies.forged).status, `forged ${m} ${p}`).toBe(401);
+ expect(viaProxy(p, m, cookies.doubled).status, `doubled ${m} ${p}`).toBe(401);
+ expect(passed(viaProxy(p, m, cookies.owner)), `owner ${m} ${p}`).toBe(true);
+ }
+ // The routes check again themselves.
+ for (const cookie of [cookies.a, cookies.forged, cookies.doubled, undefined]) {
+ const headers: Record<string, string> = cookie ? { cookie } : {};
+ expect((await runsRoute.GET(direct("/api/admin/generations", "GET", headers))).status).toBe(403);
+ expect((await runsRoute.GET(direct(`/api/admin/generations?account=${A}`, "GET", headers))).status).toBe(403);
+ expect((await accountsRoute.GET(direct("/api/admin/accounts", "GET", headers))).status).toBe(403);
+ const del = await remove("x", headers);
+ expect(del.status).toBe(403);
+ expect(del.headers.get("Cache-Control")).toBe("no-store");
+ }
+ const ok = await runsRoute.GET(direct("/api/admin/generations", "GET", { cookie: cookies.owner }));
+ expect(ok.status).toBe(200);
+ expect(ok.headers.get("Cache-Control")).toBe("no-store");
+ const missing = await remove("x");
+ expect(missing.status).toBe(404);
+ expect(missing.headers.get("Cache-Control")).toBe("no-store");
+ // An API token is the owner's.
+ const { token } = auth.createToken("t");
+ expect((await runsRoute.GET(direct("/api/admin/generations", "GET", { authorization: `Bearer ${token}` }))).status).toBe(200);
+ expect((await accountsRoute.GET(direct("/api/admin/accounts", "GET", { authorization: `Bearer ${token}` }))).status).toBe(200);
+ });
+
+ it("counts each account's runs, space and GPU", async () => {
+ const shown = run(A);
+ const kept = output(shown, 2000);
+ run(A, { status: "running" });
+ run(A, { status: "failed", ago: 2 * DAY, error: "Out of memory" });
+ run(A, { status: "failed", ago: 10 * DAY });
+ run(A, { status: "canceled", ago: HOUR });
+ run(A, { feature: "x-step" });
+ const upload = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", accountId: A });
+ run(B, { ago: 30 * HOUR });
+ auth.setAccountGpu(B, { url: "https://gpu.example.com" });
+ auth.setAccountDisabled(B, true);
+ for (let i = 0; i < 3; i++) output(run(), 1000);
+
+ const { items, totals } = admin.accountsWithStats();
+ const of = (id: string) => items.find((a) => a.id === id)!;
+ const newest = (db().prepare("SELECT MAX(created_at) AS t FROM generations WHERE json_extract(request_json, '$.account') = ? AND feature = 'image'").get(A) as { t: number }).t;
+ expect(accountUsage(A).total).toBe(kept.size + upload.size);
+ expect(of(A)).toMatchObject({ runs: 5, runsDay: 3, runsWeek: 4, running: 1, failedWeek: 1, bytes: accountUsage(A).total, capBytes: 2 ** 30 });
+ expect(of(A).lastRunAt).toBe(newest);
+ expect(of(B)).toMatchObject({ runs: 1, runsDay: 0, runsWeek: 1, running: 0, failedWeek: 0, bytes: 0, gpu: true, disabled: true });
+ expect(of(C)).toMatchObject({ runs: 0, runsDay: 0, runsWeek: 0, running: 0, failedWeek: 0, lastRunAt: null, bytes: 0 });
+ // The owner's runs and files are in none of it.
+ expect(totals).toMatchObject({ accounts: 3, runsDay: 3, runsWeek: 5, running: 1, bytes: accountUsage(A).total });
+
+ const res = await accountsRoute.GET(direct("/api/admin/accounts", "GET", { cookie: cookies.owner }));
+ expect(res.headers.get("Cache-Control")).toBe("no-store");
+ const body = (await res.json()) as { total: number; items: AccountListing[]; totals: AccountTotals };
+ expect(body.total).toBe(3);
+ expect(body.items.find((a) => a.id === A)).toMatchObject({ email: "[email protected]", runs: 5, failedWeek: 1, bytes: accountUsage(A).total });
+ expect(body.totals).toMatchObject({ accounts: 3, runsDay: 3, runsWeek: 5, running: 1 });
+ const csv = await (await accountsRoute.GET(direct("/api/admin/accounts?format=csv", "GET", { cookie: cookies.owner }))).text();
+ expect(csv.split("\r\n")[0]).toBe("email,created,last_login,gpu_connected,disabled");
+ });
+
+ it("reads its numbers and lists through the indexes", () => {
+ expect(plan(admin.STATS_SQL, { day: 0, week: 0 })).toMatch(/SEARCH g USING INDEX generations_account/);
+ expect(plan(admin.SPACE_SQL)).toMatch(/USING INDEX assets_account/);
+ // One account's: a search of its entries. Every account's: newest first along generations_created until the page is
+ // full (the limit is bound, so SQLite plans for any size), or a search of the accounts' entries when it reckons that cheaper.
+ expect(listPlan(() => admin.listAccountRuns({ account: A, before: Date.now(), beforeId: "x" }))).toMatch(/SEARCH g USING INDEX generations_account/);
+ expect(listPlan(() => admin.listAccountRuns({ accounts: true }))).toMatch(/^(SEARCH|SCAN) g USING INDEX generations_(account|created)\b/);
+ expect(listPlan(() => admin.listAccountRuns({ accounts: true, statuses: ["failed"] }))).toMatch(/^SEARCH g USING INDEX generations_(status|account)\b/);
+ });
+
+ it("pages newest first, and no run is skipped or repeated", async () => {
+ const pager = auth.createAccount("[email protected]", "long enough").id;
+ const at = Date.now() - HOUR;
+ const made = [run(pager, { at: at - 3 }), run(pager, { at }), run(pager, { at }), run(pager, { at }), run(pager, { at: at - 1 }), run(pager, { at: at + 1 }), run(pager, { at: at - 2 })];
+ const want = db()
+ .prepare(`SELECT id FROM generations WHERE id IN (${made.map(() => "?").join(", ")}) ORDER BY created_at DESC, id DESC`)
+ .all(...made)
+ .map((r) => (r as { id: string }).id);
+ const seen: string[] = [];
+ const sizes: number[] = [];
+ let before = "";
+ for (;;) {
+ const page = await listed(`account=${pager}&limit=3${before ? `&before=${before}` : ""}`);
+ seen.push(...ids(page));
+ sizes.push(page.items.length);
+ if (!page.next) break;
+ before = page.next;
+ }
+ expect(sizes).toEqual([3, 3, 1]);
+ expect(seen).toEqual(want);
+ expect(new Set(seen).size).toBe(7);
+ expect((admin.accountRunOptions(new URLSearchParams("limit=500")) as { limit: number }).limit).toBe(100);
+ expect((admin.accountRunOptions(new URLSearchParams("limit=0")) as { limit: number }).limit).toBe(1);
+ expect((admin.accountRunOptions(new URLSearchParams()) as { limit: number }).limit).toBe(30);
+ });
+
+ it("filters by account, status and kind", async () => {
+ const clip = run(B, { kind: "video" });
+ const waiting = run(B, { status: "queued" });
+ const ofA = await listed(`account=${A}`);
+ expect(ofA.items.length).toBe(5);
+ expect(ofA.items.every((g) => g.account.id === A && g.account.email === "[email protected]")).toBe(true);
+ const ofB = await listed(`account=${B}`);
+ expect(ofB.items.every((g) => g.account.id === B)).toBe(true);
+ expect(ids(ofB)).toEqual(expect.arrayContaining([clip, waiting]));
+
+ const statuses = async (qs: string) => new Set((await listed(qs)).items.map((g) => g.status));
+ expect(await statuses("status=failed")).toEqual(new Set(["failed"]));
+ expect(await statuses("status=running")).toEqual(new Set(["queued", "running"]));
+ expect(await statuses("status=finished")).toEqual(new Set(["succeeded"]));
+ const videos = await listed("kind=video");
+ expect(ids(videos)).toEqual([clip]);
+
+ const all = ids(await listed("limit=100"));
+ expect(all).toEqual(expect.arrayContaining([clip, waiting, ...ids(ofA)]));
+ expect(ids(await listed("limit=100&status=sideways&kind=hologram"))).toEqual(all);
+ const bad = await runsRoute.GET(direct("/api/admin/generations?account=../x", "GET", { cookie: cookies.owner }));
+ expect(bad.status).toBe(400);
+ expect(((await bad.json()) as { error: string }).error).toBe("Pick an account");
+ });
+
+ it("never lists the owner's runs, and never deletes them", async () => {
+ const mine = run(undefined, { status: "failed" });
+ const owners = new Set((db().prepare("SELECT id FROM generations WHERE json_extract(request_json, '$.account') IS NULL").all() as { id: string }[]).map((r) => r.id));
+ expect(owners.size).toBeGreaterThan(1);
+ for (const qs of ["limit=100", "account=&limit=100", "status=finished&limit=100", "status=running&limit=100", "status=failed&limit=100"]) {
+ const page = await listed(qs);
+ expect(page.items.length, qs).toBeGreaterThan(0);
+ expect(page.items.some((g) => owners.has(g.id)), qs).toBe(false);
+ expect(page.items.every((g) => g.account.id && g.request.account === g.account.id), qs).toBe(true);
+ }
+ const res = await remove(mine);
+ expect(res.status).toBe(404);
+ expect(gens.getGeneration(mine)).not.toBeNull();
+ });
+
+ it("L-13 still holds: the owner's Library, counts and live feed leave accounts' runs out", async () => {
+ const accounts = new Set((db().prepare("SELECT id FROM generations WHERE json_extract(request_json, '$.account') IS NOT NULL").all() as { id: string }[]).map((r) => r.id));
+ expect(accounts.size).toBeGreaterThan(10);
+ expect(gens.listGenerations({ limit: 200 }).some((g) => accounts.has(g.id))).toBe(false);
+ expect(gens.listGenerations({ steps: true, limit: 200 }).some((g) => accounts.has(g.id))).toBe(false);
+ const before = libraryFacets().total;
+ run(A);
+ expect(libraryFacets().total).toBe(before);
+
+ for (const qs of ["accounts=1", `account=${A}`]) {
+ const res = await generationsRoute.GET(direct(`/api/generations?${qs}&limit=200`, "GET", { cookie: cookies.owner }));
+ const items = ((await res.json()) as { items: { id: string; request: { account?: string } }[] }).items;
+ expect(items.length, qs).toBeGreaterThan(0);
+ expect(items.every((g) => !g.request.account && !accounts.has(g.id)), qs).toBe(true);
+ }
+ expect("accounts" in listOptionsFrom(new URLSearchParams("accounts=1"))).toBe(false);
+
+ gens.ensureRunner();
+ const mine = run();
+ const theirs = run(A);
+ const seen: string[] = [];
+ const off = live.subscribe((e) => seen.push(e.id));
+ try {
+ db().prepare("UPDATE generations SET message = 'tick' WHERE id IN (?, ?)").run(mine, theirs);
+ await new Promise((r) => setTimeout(r, 50));
+ } finally {
+ off();
+ }
+ expect(seen).toContain(mine);
+ expect(seen).not.toContain(theirs);
+
+ // Only the owner's view of accounts' runs asks for every account's.
+ const src = path.join(__dirname, "..", "src");
+ const users = (fs.readdirSync(src, { recursive: true }) as string[])
+ .filter((f) => /\.tsx?$/.test(f) && fs.readFileSync(path.join(src, f), "utf8").includes("accounts: true"))
+ .map((f) => f.split(path.sep).join("/"));
+ expect(users).toEqual(["server/account-admin.ts"]);
+ });
+
+ it("the owner opens an account's files, and accounts open only their own", async () => {
+ const id = run(A);
+ output(id, 10);
+ const item = (await listed(`account=${A}`)).items.find((g) => g.id === id)!;
+ const url = item.outputs[0].url;
+ expect(url).toMatch(/^\/api\/files\/outputs\//);
+ expect(passed(viaProxy(url, "GET", cookies.owner))).toBe(true);
+ expect(passed(viaProxy(url, "GET", cookies.a))).toBe(true);
+ expect(viaProxy(url, "GET", cookies.c).status).toBe(403);
+ expect(viaProxy(url, "GET").status).toBe(401);
+ const rel = url.slice("/api/files/".length);
+ const res = await filesRoute.GET(direct(url, "GET", { cookie: cookies.owner }), { params: Promise.resolve({ path: rel.split("/") }) } as never);
+ expect(res.status).toBe(200);
+ expect(res.headers.get("Content-Type")).toBe("image/png");
+ });
+
+ it("deletes an account's run with its files, and gives the account its space back", async () => {
+ const id = run(A);
+ const asset = output(id, 5000);
+ const file = absolutePath(asset.relPath);
+ expect(fs.existsSync(file)).toBe(true);
+ const usage = accountUsage(A).total;
+ const bytes = admin.accountsWithStats().items.find((a) => a.id === A)!.bytes;
+ expect(bytes).toBe(usage);
+
+ const res = await remove(id);
+ expect(res.status).toBe(204);
+ expect(db().prepare("SELECT id FROM generations WHERE id = ?").get(id)).toBeUndefined();
+ expect(db().prepare("SELECT id FROM assets WHERE id = ?").get(asset.id)).toBeUndefined();
+ expect(fs.existsSync(file)).toBe(false);
+ expect(accountUsage(A).total).toBe(usage - asset.size);
+ expect(admin.accountsWithStats().items.find((a) => a.id === A)!.bytes).toBe(bytes - asset.size);
+ expect(ids(await listed(`account=${A}&limit=100`))).not.toContain(id);
+ expect((await remove(id)).status).toBe(404);
+
+ // A run still going is stopped first, then deleted.
+ const going = run(A, { status: "running" });
+ expect((await remove(going)).status).toBe(204);
+ expect(db().prepare("SELECT id FROM generations WHERE id = ?").get(going)).toBeUndefined();
+ });
+
+ it("writes space as the account limits do", () => {
+ expect(storageSize(0)).toBe("0 MB");
+ expect(storageSize(512 * 1024)).toBe("512 KB");
+ expect(storageSize(340 * 2 ** 20)).toBe("340 MB");
+ expect(storageSize(2 ** 30)).toBe("1 GB");
+ expect(storageSize(1.25 * 2 ** 30)).toBe("1.3 GB");
+ expect(storageSize(3 * 2 ** 30)).toBe("3 GB");
+ });
+});