Set up and configure a database's compute

A console for a database platform's compute, as one app document with no code of its own: every compute with what it may cost, a page that sets one up, and a page per compute that changes its settings, suspends, resumes and deletes it. It is drawn with this library's components. Every change is one of the platform's operations, and the platform's rules stay on its side: names are unique, the account has a credit limit, a new compute is approved before it starts (it costs money from then on), a save made over someone else's change is refused, and a running compute is suspended before it is deleted, which cannot be undone. The computes, sizes and credits are made up.

The backend. The pages read two tables (computes and sizes) and change them through five operations: create-compute, update-compute, suspend-compute, resume-compute and delete-compute. Each operation's arguments say what a form asks for: their labels, help, choices, limits and patterns. It is in memory here; on your own platform the tables are your API's reads and each operation is your handler, reached over HTTP as in own-operations:

compute.ts:

ts
import { type DataSource, OperationError, type OperationSpec, StaleOperationError, memoryDataSource, memoryOperations } from "@surfaces-ui/data";

/** One size of compute: what it has and what it costs. Made-up figures. */
export const SIZES = [
  { size: "XS", vcpus: 2, memory_gb: 16, credits_per_hour: 1 },
  { size: "S", vcpus: 4, memory_gb: 32, credits_per_hour: 2 },
  { size: "M", vcpus: 8, memory_gb: 64, credits_per_hour: 4 },
  { size: "L", vcpus: 16, memory_gb: 128, credits_per_hour: 8 },
  { size: "XL", vcpus: 32, memory_gb: 256, credits_per_hour: 16 },
] as const;
export const REGIONS = ["us-east", "us-west", "eu-central", "ap-southeast"] as const;
/** The account's limit: credits an hour across every running compute, counted at its most clusters. */
export const CREDIT_LIMIT = 48;

/** One compute: a named pool of clusters that runs queries. `version` goes up with every change to its settings. */
export type Compute = {
  name: string;
  workload: string;
  region: string;
  size: string;
  credits_per_hour: number;
  min_clusters: number;
  max_clusters: number;
  auto_suspend_minutes: number;
  auto_resume: boolean;
  status: "running" | "suspended";
  most_credits_per_hour: number;
  created_by: string;
  version: number;
};

const credits = (size: string) => SIZES.find((s) => s.size === size)!.credits_per_hour;
const compute = (c: Omit<Compute, "credits_per_hour" | "most_credits_per_hour">): Compute => ({ ...c, credits_per_hour: credits(c.size), most_credits_per_hour: credits(c.size) * c.max_clusters });

export const sampleComputes = (): Compute[] => [
  compute({ name: "reporting", workload: "Analytics", region: "us-east", size: "M", min_clusters: 1, max_clusters: 3, auto_suspend_minutes: 10, auto_resume: true, status: "running", created_by: "Ana Ruiz", version: 4 }),
  compute({ name: "etl-nightly", workload: "Loading", region: "us-east", size: "L", min_clusters: 1, max_clusters: 1, auto_suspend_minutes: 5, auto_resume: true, status: "suspended", created_by: "Ben Okafor", version: 2 }),
  compute({ name: "app-serving", workload: "Transactional", region: "eu-central", size: "S", min_clusters: 2, max_clusters: 4, auto_suspend_minutes: 0, auto_resume: false, status: "running", created_by: "Ana Ruiz", version: 7 }),
];

/**
 * The database's compute, in memory: a `DataSource` that reads the computes and the sizes as they are now, and the
 * operations that create, change, suspend, resume and delete one. The rules are the platform's and stay on its side:
 * a name is unique, the account has a credit limit, and a running compute is suspended before it is deleted.
 */
export function computeBackend(options: { actor?: { id: string; name: string } } = {}) {
  const actor = options.actor ?? { id: "u-ana", name: "Ana Ruiz" };
  let computes = sampleComputes();
  let source = memoryDataSource({ tables: { computes, sizes: [...SIZES] } });
  const changed = (rows: Compute[]) => {
    computes = rows;
    source = memoryDataSource({ tables: { computes: rows, sizes: [...SIZES] } });
  };
  const dataSource = new Proxy({} as DataSource, { get: (_target, key) => (...args: unknown[]) => (source as unknown as Record<PropertyKey, (...a: unknown[]) => unknown>)[key]!(...args) });
  const find = (name: unknown) => {
    const found = computes.find((c) => c.name === name);
    if (!found) throw new OperationError(`There is no compute called ${String(name)}.`);
    return found;
  };
  // What every running compute may use at most, leaving one out (the one being changed).
  const inUse = (except?: string) => computes.filter((c) => c.status === "running" && c.name !== except).reduce((sum, c) => sum + c.most_credits_per_hour, 0);
  const withinLimit = (name: string, size: string, max: number) => {
    const wanted = credits(size) * max;
    const others = inUse(name);
    if (others + wanted > CREDIT_LIMIT)
      throw new OperationError(`That needs up to ${wanted} credits an hour, and running compute already uses up to ${others} of the account's ${CREDIT_LIMIT}. Choose a smaller size or fewer clusters, or suspend another compute first.`);
  };
  const sizeArg = { name: "size", label: "Size", type: "choice", options: SIZES.map((s) => s.size), required: true, help: "Each step up doubles the CPUs, the memory and the credits an hour." } as const;
  const suspendArg = { name: "auto_suspend_minutes", label: "Suspend after idle (minutes)", type: "integer", required: true, min: 0, max: 1440, help: "0 never suspends: it costs credits all day." } as const;
  const maxArg = { name: "max_clusters", label: "Most clusters", type: "integer", required: true, min: 1, max: 10, help: "Clusters are added when queries queue, up to this many." } as const;
  const specs: OperationSpec[] = [
    {
      id: "create-compute",
      title: "Create compute",
      description: "Creates a compute and starts it. It uses credits from the moment it starts.",
      effect: "create",
      target: "platform.computes",
      risk: "high",
      args: [
        { name: "name", label: "Name", type: "text", required: true, pattern: "[a-z][a-z0-9-]{2,30}", help: "Lower-case letters, digits and dashes." },
        { name: "workload", label: "Workload", type: "choice", options: ["Analytics", "Transactional", "Loading"], required: true },
        { name: "region", label: "Region", type: "choice", options: [...REGIONS], required: true },
        sizeArg,
        { name: "min_clusters", label: "Fewest clusters", type: "integer", required: true, min: 1, max: 10 },
        maxArg,
        suspendArg,
        { name: "auto_resume", label: "Start again when a query arrives", type: "boolean" },
      ],
      refreshes: ["memory"],
      run: (args) => {
        const name = String(args.name);
        if (computes.some((c) => c.name === name)) throw new OperationError(`There is already a compute called ${name}. Choose another name.`);
        if (Number(args.min_clusters) > Number(args.max_clusters)) throw new OperationError("Fewest clusters is more than most clusters. Make most at least as many.");
        withinLimit(name, String(args.size), Number(args.max_clusters));
        changed([
          ...computes,
          compute({ name, workload: String(args.workload), region: String(args.region), size: String(args.size), min_clusters: Number(args.min_clusters), max_clusters: Number(args.max_clusters), auto_suspend_minutes: Number(args.auto_suspend_minutes), auto_resume: args.auto_resume === true, status: "running", created_by: actor.name, version: 1 }),
        ]);
        return { affected: 1, result: { name }, message: `Created ${name}. It is running.` };
      },
    },
    {
      id: "update-compute",
      title: "Save compute settings",
      description: "Changes one compute's size, most clusters and idle time. Refuses a save made over someone else's change.",
      effect: "update",
      target: "platform.computes",
      args: [{ name: "name", label: "Compute", type: "text", required: true }, sizeArg, maxArg, suspendArg, { name: "version", label: "Version", type: "integer", required: true }],
      refreshes: ["memory"],
      run: (args) => {
        const c = find(args.name);
        if (c.version !== args.version) throw new StaleOperationError("Someone else changed this compute since you read it. Read it again to see their change; what you typed is kept.");
        if (Number(args.max_clusters) < c.min_clusters) throw new OperationError(`Most clusters cannot be fewer than its fewest (${c.min_clusters}).`);
        if (c.status === "running") withinLimit(c.name, String(args.size), Number(args.max_clusters));
        changed(computes.map((x) => (x === c ? compute({ ...c, size: String(args.size), max_clusters: Number(args.max_clusters), auto_suspend_minutes: Number(args.auto_suspend_minutes), version: c.version + 1 }) : x)));
        return { affected: 1, message: `Saved ${c.name}.` };
      },
    },
    {
      id: "suspend-compute",
      title: "Suspend compute",
      description: "Stops a compute. Queries running on it are let finish; it uses no credits while suspended.",
      effect: "update",
      target: "platform.computes",
      args: [{ name: "name", label: "Compute", type: "text", required: true }],
      refreshes: ["memory"],
      run: (args) => {
        const c = find(args.name);
        if (c.status === "suspended") throw new OperationError(`${c.name} is already suspended.`);
        changed(computes.map((x) => (x === c ? { ...c, status: "suspended" } : x)));
        return { affected: 1, message: `Suspended ${c.name}.` };
      },
    },
    {
      id: "resume-compute",
      title: "Resume compute",
      description: "Starts a suspended compute. It uses credits from the moment it starts.",
      effect: "update",
      target: "platform.computes",
      args: [{ name: "name", label: "Compute", type: "text", required: true }],
      refreshes: ["memory"],
      run: (args) => {
        const c = find(args.name);
        if (c.status === "running") throw new OperationError(`${c.name} is already running.`);
        withinLimit(c.name, c.size, c.max_clusters);
        changed(computes.map((x) => (x === c ? { ...c, status: "running" } : x)));
        return { affected: 1, message: `Resumed ${c.name}.` };
      },
    },
    {
      id: "delete-compute",
      title: "Delete compute",
      description: "Deletes a suspended compute and its settings, for good. Data is not touched.",
      effect: "delete",
      target: "platform.computes",
      risk: "irreversible",
      reasonRequired: true,
      args: [{ name: "name", label: "Compute", type: "text", required: true }],
      refreshes: ["memory"],
      run: (args) => {
        const c = find(args.name);
        if (c.status === "running") throw new OperationError(`${c.name} is running. Suspend it first, so no query running on it is cut off.`);
        changed(computes.filter((x) => x !== c));
        return { affected: 1, message: `Deleted ${c.name}.` };
      },
    },
  ];
  const operations = memoryOperations({ operations: specs, actor: () => actor, dataSource });
  /** A change made by someone else, as another session would make it. */
  const touch = (name: string, change: Partial<Compute>) => changed(computes.map((c) => (c.name === name ? compute({ ...c, ...change, version: c.version + 1 }) : c)));
  return { dataSource, operations, computes: () => computes, touch };
}

The app. The list is a DataGrid whose rows open /compute/[name], with two Metrics over the running computes. Setting one up is a RecordForm with no record: a form for a new one, whose fields are create-compute's own arguments. The page's data fills it in first (/draft/setup), and then opens the compute the operation made (/@run/setup/result/name). A compute's page reads it once (record), shows Suspend or Resume by its status (visibleWhen), and changes its settings with a RecordForm for that record, whose version makes a save over someone else's change come back stale rather than overwrite it:

app.ts:

ts
import { A2UI_VERSION, type AppDocument, type SurfaceComponent } from "@surfaces-ui/document";
import { analyticsCatalog } from "@surfaces-ui/spec";

const CATALOG = analyticsCatalog.id;
const text = (id: string, value: unknown, variant?: string): SurfaceComponent => ({ id, component: "Text", text: value, ...(variant ? { variant } : {}) });
const button = (id: string, label: string, action: unknown, extra: Record<string, unknown> = {}): SurfaceComponent[] => [{ id, component: "Button", child: `${id}-label`, action, ...extra }, text(`${id}-label`, label)];
const run = (operation: string, args: Record<string, unknown>, then?: unknown) => ({ functionCall: { "@call": "run", args: { operation, args, ...(then ? { then } : {}) } } });
const page = (id: string, title: string, components: SurfaceComponent[], extra: Record<string, unknown> = {}) => ({ id, title, catalogId: CATALOG, a2ui: A2UI_VERSION, components, ...extra });
const running = [{ column: "status", op: "eq", values: ["running"] }];
const here = { "@path": "/@route/name" };

/**
 * Setting up and configuring a database's compute, as one app document with no code: every compute and what it may
 * cost, a page that sets one up (the platform's own fields, drawn by a record form for a new record), and a page per
 * compute that changes its settings, suspends, resumes and deletes it. Every change is an operation the platform
 * defines; creating one costs money, so it is approved first, and deleting one cannot be undone.
 */
export const computeApp: AppDocument = {
  id: "compute",
  title: "Compute",
  catalogId: CATALOG,
  a2ui: A2UI_VERSION,
  nav: [
    { label: "Compute", to: "/" },
    { label: "Set up compute", to: "/new" },
  ],
  operations: ["create-compute", "update-compute", "suspend-compute", "resume-compute", "delete-compute"],
  pages: [
    {
      route: "/",
      page: page("computes", "Compute", [
        { id: "root", component: "Column", gap: 4, children: ["heading", "intro", "figures", "list", "new"] },
        text("heading", "Compute", "h1"),
        text("intro", "Each compute is a pool of clusters that runs queries. It uses credits while it runs; a suspended one costs nothing. Open one to change it.", "caption"),
        { id: "figures", component: "Grid", columns: 3, children: ["running", "credits", "limit"] },
        { id: "running", component: "Metric", sourceId: "memory", sql: "SELECT * FROM computes", filters: running, column: "name", aggregate: "count", label: "Running", format: "number" },
        { id: "credits", component: "Metric", sourceId: "memory", sql: "SELECT * FROM computes", filters: running, column: "most_credits_per_hour", aggregate: "sum", label: "Credits an hour, at most", format: "number" },
        { id: "limit", component: "Stat", label: "Account limit", value: "48 credits an hour" },
        {
          id: "list",
          component: "DataGrid",
          sourceId: "memory",
          sql: "SELECT * FROM computes",
          label: "Compute",
          rowKey: "name",
          sorts: [{ column: "name" }],
          columns: {
            hidden: ["version", "credits_per_hour", "min_clusters", "auto_resume", "workload", "created_by"],
            labels: { name: "Name", region: "Region", size: "Size", max_clusters: "Most clusters", auto_suspend_minutes: "Suspend after (min)", status: "Status", most_credits_per_hour: "Credits/hour at most" },
            widths: { name: 160, region: 130, size: 80, max_clusters: 120, auto_suspend_minutes: 160, status: 110, most_credits_per_hour: 170 },
          },
          action: { functionCall: { "@call": "navigate", args: { to: "/compute/[name]", values: { name: { "@path": "/@event/key" } } } } },
        },
        ...button("new", "Set up compute", { functionCall: { "@call": "navigate", args: { to: "/new" } } }, { variant: "primary" }),
      ]),
    },
    {
      route: "/new",
      page: page(
        "new",
        "Set up compute",
        [
        { id: "root", component: "Column", gap: 4, children: ["heading", "intro", "layout"] },
        text("heading", "Set up compute", "h1"),
        text("intro", "Name it, choose where it runs and how big it is, and set how it scales and when it stops. You are asked to approve before it starts, since it uses credits from then on.", "caption"),
        { id: "layout", component: "Grid", columns: 2, widths: [3, 2], align: "start", children: ["form-card", "help-card"] },
        { id: "form-card", component: "Card", child: "setup" },
        // A record form with no record is a form for a new one: its fields are the operation's own arguments.
        {
          id: "setup",
          component: "RecordForm",
          label: "Compute",
          fields: ["name", "workload", "region", "size", "min_clusters", "max_clusters", "auto_suspend_minutes", "auto_resume"],
          save: { operation: "create-compute", label: "Create compute", then: { "@call": "navigate", args: { to: "/compute/[name]", values: { name: { "@path": "/@run/setup/result/name" } } } } },
        },
        { id: "help-card", component: "Card", child: "help" },
        { id: "help", component: "Column", gap: 3, children: ["sizes-title", "sizes", "budget-title", "budget", "budget-help"] },
        text("sizes-title", "Sizes", "h2"),
        { id: "sizes", component: "DataGrid", sourceId: "memory", sql: "SELECT * FROM sizes", label: "Sizes", rowKey: "size", columns: { labels: { size: "Size", vcpus: "vCPUs", memory_gb: "Memory (GB)", credits_per_hour: "Credits/hour" }, widths: { size: 64, vcpus: 72, memory_gb: 110, credits_per_hour: 110 } } },
        text("budget-title", "What is in use", "h2"),
        { id: "budget", component: "Metric", sourceId: "memory", sql: "SELECT * FROM computes", filters: running, column: "most_credits_per_hour", aggregate: "sum", label: "Credits an hour, at most, of 48", format: "number" },
        text("budget-help", "A compute counts at its size's credits times its most clusters. The platform refuses one that would take running compute past the account's limit.", "caption"),
        ],
        // Where the form starts: the record form keeps its draft at `/draft/<its id>`, so a page can fill it in first.
        { data: { draft: { setup: { workload: "Analytics", region: "us-east", size: "S", min_clusters: 1, max_clusters: 1, auto_suspend_minutes: 10, auto_resume: true } } } },
      ),
    },
    {
      route: "/compute/[name]",
      page: page(
        "compute",
        "Compute",
        [
          { id: "root", component: "Column", gap: 4, children: ["back", "title-row", "layout"] },
          { id: "back", component: "Link", text: "All compute", url: "/" },
          { id: "title-row", component: "Row", align: "center", sizes: ["hug", "hug"], children: ["heading", "status"] },
          text("heading", here, "h1"),
          { id: "status", component: "Badge", text: { "@path": "/@record/page/status" }, tone: "neutral" },
          { id: "layout", component: "Grid", columns: 2, align: "start", children: ["facts-card", "settings-card"] },
          { id: "facts-card", component: "Card", child: "facts-col" },
          { id: "facts-col", component: "Column", gap: 3, children: ["facts-title", "facts", "running-note", "suspend", "suspended-note", "resume", "delete-warn", "delete"] },
          text("facts-title", "About it", "h2"),
          {
            id: "facts",
            component: "KeyValue",
            items: [
              { label: "Workload", value: { "@path": "/@record/page/workload" } },
              { label: "Region", value: { "@path": "/@record/page/region" } },
              { label: "Credits an hour, per cluster", value: { "@path": "/@record/page/credits_per_hour" } },
              { label: "Credits an hour, at most", value: { "@path": "/@record/page/most_credits_per_hour" } },
              { label: "Fewest clusters", value: { "@path": "/@record/page/min_clusters" } },
              { label: "Created by", value: { "@path": "/@record/page/created_by" } },
            ],
          },
          { ...text("running-note", "It is running and using credits.", "caption"), visibleWhen: { path: "/@record/page/status", equals: "running" } },
          ...button("suspend", "Suspend", run("suspend-compute", { name: here }), { visibleWhen: { path: "/@record/page/status", equals: "running" } }),
          { ...text("suspended-note", "It is suspended and costs nothing until it starts again.", "caption"), visibleWhen: { path: "/@record/page/status", equals: "suspended" } },
          ...button("resume", "Resume", run("resume-compute", { name: here }), { variant: "primary", visibleWhen: { path: "/@record/page/status", equals: "suspended" } }),
          text("delete-warn", "Deleting removes the compute and its settings for good. Your data is not touched. Suspend it first.", "caption"),
          ...button("delete", "Delete compute", run("delete-compute", { name: here }, { "@call": "navigate", args: { to: "/" } })),
          { id: "settings-card", component: "Card", child: "settings-col" },
          { id: "settings-col", component: "Column", gap: 3, children: ["settings-title", "settings"] },
          text("settings-title", "Settings", "h2"),
          {
            id: "settings",
            component: "RecordForm",
            label: "Compute settings",
            sourceId: "memory",
            sql: "SELECT * FROM computes",
            recordKey: { column: "name", value: here },
            fields: ["size", "max_clusters", "auto_suspend_minutes"],
            version: "version",
            save: { operation: "update-compute", label: "Save settings" },
            back: "/",
          },
        ],
        { record: { sourceId: "memory", sql: "SELECT * FROM computes", key: { column: "name", value: here } } },
      ),
    },
  ],
};

The shell checks the document against the catalog and the platform's operations before anything is drawn:

App.tsx:

tsx
import { DataSourceProvider, ThemeProvider } from "@surfaces-ui/components";
import "@surfaces-ui/components/styles.css";
import type { DataSource, Operations } from "@surfaces-ui/data";
import { validateApp } from "@surfaces-ui/document";
import type { OperationDefinition } from "@surfaces-ui/proto";
import { analyticsCatalog, appOperationChecks } from "@surfaces-ui/spec";
import { AppView, analyticsRenderers, useHashLocation } from "@surfaces-ui/spec/react";
import { computeApp } from "./app.js";

export interface ComputeProps {
  dataSource: DataSource;
  operations: Operations;
  operationDefinitions: readonly OperationDefinition[];
  mode?: "light" | "dark";
}

/** The compute console: one document, this library's components, and the address kept in the hash. */
export function ComputeConsole({ dataSource, operations, operationDefinitions, mode = "light" }: ComputeProps) {
  const location = useHashLocation();
  const problems = validateApp(computeApp, analyticsCatalog, appOperationChecks(operationDefinitions));
  if (problems.length > 0) return <pre role="alert">{problems.map((p) => `${p.path}: ${p.message}`).join("\n")}</pre>;
  return (
    <ThemeProvider initialMode={mode} storage={null} scope="scoped">
      <DataSourceProvider dataSource={dataSource}>
        <AppView app={computeApp} catalog={analyticsCatalog} renderers={analyticsRenderers} operations={operations} operationDefinitions={operationDefinitions} storage={null} {...location} />
      </DataSourceProvider>
    </ThemeProvider>
  );
}

The test checks the document against the catalog, the operations and the data; holds the platform to its rules (approval first, a name in use, a name in the wrong form refused at its field, fewest clusters over most, the credit limit worked out by hand, a stale save, deleting a running compute); and in the page sets one up from the form, through the approval dialog, to the compute's own page:

compute-setup.test.tsx:

tsx
// @vitest-environment jsdom
import type { JsonObject } from "@bufbuild/protobuf";
import { validateApp, validateAppData } from "@surfaces-ui/document";
import { analyticsCatalog, appOperationChecks } from "@surfaces-ui/spec";
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { ComputeConsole } from "./App.js";
import { computeApp } from "./app.js";
import { computeBackend } from "./compute.js";

afterEach(() => {
  cleanup();
  window.location.hash = "";
});

/** Runs an operation as a person would: asked first where it needs approval, then allowed. */
async function approved(platform: ReturnType<typeof computeBackend>, operationId: string, args: JsonObject, reason?: string) {
  const idempotencyKey = `${operationId}-${Math.random()}`;
  const first = await platform.operations.run({ operationId, args, idempotencyKey });
  if (!first.approval) return first;
  return platform.operations.run({ operationId, args, idempotencyKey, approval: { id: first.approval.id, allow: true, digest: first.approval.digest, ...(reason ? { reason } : {}) } });
}
const setup = { workload: "Analytics", region: "us-east", size: "S", min_clusters: 1, max_clusters: 1, auto_suspend_minutes: 10, auto_resume: true };

describe("setting up and configuring a database's compute", () => {
  it("passes validateApp with the platform's operations, and every query names columns the data has", async () => {
    const platform = computeBackend();
    const { operations } = await platform.operations.listOperations({});
    expect(validateApp(computeApp, analyticsCatalog, appOperationChecks(operations))).toEqual([]);
    const report = await validateAppData(computeApp, analyticsCatalog, platform.dataSource);
    expect(report.problems).toEqual([]);
  });

  it("keeps the platform's rules on its side: approval, names, the credit limit, stale saves and deleting", async () => {
    const platform = computeBackend();
    // Creating costs money, so it is asked first; nothing exists until a person allows it.
    const asked = await platform.operations.run({ operationId: "create-compute", args: { name: "adhoc", ...setup } });
    expect(asked.message).toBe("A person must approve this first. Nothing ran.");
    expect(platform.computes().map((c) => c.name)).not.toContain("adhoc");

    expect((await approved(platform, "create-compute", { ...setup, name: "reporting" })).message).toBe("There is already a compute called reporting. Choose another name.");
    const badName = await platform.operations.run({ operationId: "create-compute", args: { ...setup, name: "Ad Hoc!" } });
    expect(badName.errors.map((e) => e.field)).toEqual(["name"]);
    expect((await approved(platform, "create-compute", { ...setup, name: "adhoc", min_clusters: 3, max_clusters: 2 })).message).toMatch(/Fewest clusters is more than most/);
    // Running now: reporting 4 × 3 = 12 and app-serving 2 × 4 = 8, so 20 of 48. XL × 2 is 32 more.
    expect((await approved(platform, "create-compute", { ...setup, name: "adhoc", size: "XL", max_clusters: 2 })).message).toBe(
      "That needs up to 32 credits an hour, and running compute already uses up to 20 of the account's 48. Choose a smaller size or fewer clusters, or suspend another compute first.",
    );
    expect((await approved(platform, "create-compute", { ...setup, name: "adhoc", size: "L", max_clusters: 2 })).message).toBe("Created adhoc. It is running.");
    expect(platform.computes().find((c) => c.name === "adhoc")).toMatchObject({ status: "running", most_credits_per_hour: 16, created_by: "Ana Ruiz", version: 1 });

    // A save made over someone else's change is refused, and says so.
    const before = platform.computes().find((c) => c.name === "etl-nightly")!;
    platform.touch("etl-nightly", { auto_suspend_minutes: 30 });
    const stale = await platform.operations.run({ operationId: "update-compute", args: { name: "etl-nightly", size: "M", max_clusters: 1, auto_suspend_minutes: 5, version: before.version } });
    expect(stale.message).toMatch(/Someone else changed this compute/);
    const fresh = platform.computes().find((c) => c.name === "etl-nightly")!;
    expect((await platform.operations.run({ operationId: "update-compute", args: { name: "etl-nightly", size: "M", max_clusters: 2, auto_suspend_minutes: 5, version: fresh.version } })).message).toBe("Saved etl-nightly.");

    // Deleting cannot be undone: it needs a reason, and a running compute is suspended first.
    expect((await approved(platform, "delete-compute", { name: "adhoc" }, "Done with it.")).message).toBe("adhoc is running. Suspend it first, so no query running on it is cut off.");
    expect((await platform.operations.run({ operationId: "suspend-compute", args: { name: "adhoc" } })).message).toBe("Suspended adhoc.");
    expect((await approved(platform, "delete-compute", { name: "adhoc" }, "Done with it.")).message).toBe("Deleted adhoc.");
    expect(platform.computes().map((c) => c.name)).toEqual(["reporting", "etl-nightly", "app-serving"]);
  });

  it("sets up a compute from the page: the form's fields are the operation's, approved in the dialog, then opened", async () => {
    const platform = computeBackend();
    const { operations } = await platform.operations.listOperations({});
    window.location.hash = "#/new";
    render(<ComputeConsole dataSource={platform.dataSource} operations={platform.operations} operationDefinitions={operations} />);
    await screen.findByRole("heading", { name: "Set up compute" });
    // The page filled the form in first; the person names it and picks a size.
    await waitFor(() => expect((screen.getByRole("combobox", { name: /^Size/ }) as HTMLSelectElement).value).toBe("S"));
    fireEvent.change(screen.getByRole("textbox", { name: /^Name/ }), { target: { value: "adhoc" } });
    fireEvent.change(screen.getByRole("combobox", { name: /^Size/ }), { target: { value: "M" } });
    fireEvent.click(screen.getByRole("button", { name: "Create compute" }));
    const dialog = await screen.findByRole("dialog");
    expect(within(dialog).getByText("adhoc")).toBeTruthy();
    fireEvent.click(within(dialog).getByRole("button", { name: "Create compute" }));
    // `then` opens the compute the operation made.
    await waitFor(() => expect(window.location.hash).toBe("#/compute/adhoc"), { timeout: 5000 });
    await screen.findByRole("heading", { name: "adhoc" });
    expect(platform.computes().find((c) => c.name === "adhoc")).toMatchObject({ size: "M", status: "running" });
  });
});

In a browser

See it with pnpm --filter @surfaces-ui/recipes exec vite src/compute-setup (?mode=dark for dark). apps/e2e/tests/compute-setup.spec.ts walks it in Chromium on every change, at desktop width in light and dark and at phone width: a name in the wrong form refused before anyone is asked, the approval, a compute over the credit limit refused with what is typed kept, one within it created and opened, another's settings changed, and a running compute's delete refused, then suspended and deleted. Axe's WCAG 2.2 AA checks pass and there are no console errors at each step. The pictures are taken by that test.

Every compute, and what the running ones may use:

The compute list: running count, credits an hour at most, the account limit, and a grid of three computes

The same list in dark mode

Setting one up: the platform's fields, and the approval before it starts:

The setup form behind a dialog: Create compute?, high risk, it uses credits from the moment it starts, and every value it will be created with

Over the account's limit: refused by the platform, with what was typed kept:

The setup form with the platform's refusal: that needs up to 32 credits an hour of the account's 48

A compute's page, its settings saved, at desktop and phone width:

The reporting compute: what it is, Suspend and Delete, and its settings form saved

The same page at phone width

Source and test: apps/recipes/src/compute-setup