Run operations from your own backend

An operation is how a page changes something: a ticket closed, a record deleted. The page sends an operation's id and arguments; your server decides what that does, who may do it and whether a person must approve it. Production needs no Surfaces server for this. Operations is an interface, as DataSource is: you serve it from the backend you already have, and the dev server (pnpm serve) is one implementation, for development.

Two pieces, both small:

  • On your server, createOperationHandler from @surfaces-ui/data/server. It is one function with every rule in it and no server: it imports no Connect, no engine and nothing of the dev server, and runs in any Node, edge or worker handler.
  • In the page, an Operations written over fetch to your own route.

What the handler does for you

In this order, for every call:

  1. Checks each argument against its field, as a form's values are checked. An argument the operation does not declare is an error.
  2. Asks your allow(ctx, args). ctx.actor is who you say is signed in. Nothing in the request is asked.
  3. For a run over "everyone who matches", reads the rows again itself through your DataSource, refuses the whole run past its limit, and asks allow for each row.
  4. For an operation whose risk is high or irreversible, answers NEEDS_APPROVAL with exactly what would run and a digest of it. The second call runs only with an answer carrying that digest, from the same person, under the same idempotency key, before it expires, and once.
  5. Runs your code, once per idempotency key, and writes a line to the run log. The log never holds an argument value.

The operations

Everything about a change is declared on the server, with your own code for the change itself:

operations.ts:

ts
import { OperationError, type OperationSpec, StaleOperationError, createOperationHandler, memoryOperationStore } from "@surfaces-ui/data/server";

/** A ticket in your own database. Here a map stands in for it. */
export interface Ticket {
  id: string;
  title: string;
  status: "open" | "closed";
  owner: string;
  version: number;
  resolution?: string;
}

export function ticketDesk(): Map<string, Ticket> {
  return new Map(
    [
      { id: "T-1", title: "Invoice shows the wrong tax", status: "open" as const, owner: "u-ana", version: 1 },
      { id: "T-2", title: "Cannot reset a password", status: "open" as const, owner: "u-ben", version: 1 },
      { id: "T-3", title: "Export stops at 1,000 rows", status: "open" as const, owner: "u-ana", version: 3 },
    ].map((t) => [t.id, t]),
  );
}

/**
 * The operations this backend offers. Everything about a change is here, on the server: its arguments, who may
 * make it, whether a person must approve it, and the code. A page only ever sends an id and arguments.
 */
export function ticketOperations(tickets: Map<string, Ticket>): OperationSpec[] {
  return [
    {
      id: "close-ticket",
      title: "Close ticket",
      description: "Marks a ticket closed with its resolution.",
      effect: "update",
      target: "support.tickets",
      args: [
        { name: "id", label: "Ticket", type: "text", required: true, pattern: "T-\\d+" },
        { name: "resolution", label: "Resolution", type: "longtext", required: true, maxLength: 500 },
        { name: "version", label: "Version read", type: "integer", required: true },
      ],
      refreshes: ["support"],
      // Whoever is signed in may close a ticket. `ctx.actor` is who your session says is calling.
      allow: (ctx) => ctx.actor !== undefined,
      run(args, ctx) {
        const ticket = tickets.get(args.id as string);
        if (!ticket) throw new OperationError("There is no such ticket.");
        // Someone else saved it first: say so, and write nothing.
        if (ticket.version !== args.version) throw new StaleOperationError();
        Object.assign(ticket, { status: "closed", resolution: args.resolution, owner: ctx.actor!.id, version: ticket.version + 1 });
        return { affected: 1, result: { id: ticket.id, version: ticket.version }, message: "Ticket closed." };
      },
    },
    {
      id: "delete-ticket",
      title: "Delete ticket",
      description: "Removes a ticket for good.",
      // A delete that cannot be undone: a person approves it each time, with a reason.
      effect: "delete",
      risk: "irreversible",
      reasonRequired: true,
      target: "support.tickets",
      args: [{ name: "id", label: "Ticket", type: "text", required: true, pattern: "T-\\d+" }],
      refreshes: ["support"],
      // Only the ticket's owner may delete it.
      allow: (ctx, args) => ctx.actor !== undefined && tickets.get(args.id as string)?.owner === ctx.actor.id,
      run(args) {
        return { affected: tickets.delete(args.id as string) ? 1 : 0, message: "Ticket deleted." };
      },
    },
  ];
}

/**
 * The handler: every rule a server must keep, in one function with no Surfaces server in it. Give it a store over
 * your own database in production (`OperationStore`: answers by idempotency key, waiting approvals, the run log);
 * the one in memory is for one process in development.
 */
export function ticketHandler(tickets: Map<string, Ticket> = ticketDesk()) {
  return createOperationHandler({ operations: ticketOperations(tickets), store: memoryOperationStore() });
}

memoryOperationStore() keeps answers, waiting approvals and the run log in the process. In production give store your own OperationStore: seven small methods over your database or key-value store (getAnswer, putAnswer, getApproval, putApproval, takeApproval, appendRun, listRuns). takeApproval must be true for one caller only, such as a delete that reports its count, so an approval is used once even when two servers get it together.

The route

A handler from Request to Response. In Next.js it is app/api/operations/route.ts:

ts
import { operationsRoute } from "./route";
import { ticketHandler } from "./operations";
import { currentUser } from "@/auth"; // your own sign-in

export const POST = operationsRoute(ticketHandler(), async (request) => currentUser(request));

The same function is what a worker's fetch, Bun.serve or Deno.serve takes as it is.

route.ts:

ts
import { type DescMessage, type JsonValue, type MessageShape, fromJson, toJson } from "@bufbuild/protobuf";
import type { OperationActor, ServerOperations } from "@surfaces-ui/data/server";
import {
  GetOperationRequestSchema,
  GetOperationResponseSchema,
  ListOperationRunsRequestSchema,
  ListOperationRunsResponseSchema,
  ListOperationsRequestSchema,
  ListOperationsResponseSchema,
  RunOperationRequestSchema,
  RunOperationResponseSchema,
} from "@surfaces-ui/proto";

/** Who is calling, by your own sign-in. This one reads a session cookie; yours is whatever your app already has. */
export type Session = (request: Request) => OperationActor | undefined | Promise<OperationActor | undefined>;

const json = (status: number, body: JsonValue) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store" } });
const read = <S extends DescMessage>(schema: S, value: JsonValue | undefined): MessageShape<S> => fromJson(schema, value ?? {}, { ignoreUnknownFields: true });
const MAX_BODY = 64 * 1024;

/**
 * A route handler for operations: `(Request) => Response`, which is what a Next.js `route.ts` exports as `POST`,
 * and what a worker or `Bun.serve` takes as it is. The body is `{ call, request }` with the request as protobuf
 * JSON; the reply is the response as protobuf JSON.
 */
export function operationsRoute(operations: ServerOperations, session: Session): (request: Request) => Promise<Response> {
  return async (request) => {
    if (request.method !== "POST") return json(405, { message: "Use POST." });
    // A page on another site cannot send JSON without asking first, and a form cannot send it at all.
    if (!request.headers.get("content-type")?.startsWith("application/json")) return json(415, { message: "Send JSON." });
    const text = await request.text();
    if (text.length > MAX_BODY) return json(413, { message: "The request is too large." });
    let body: { call?: string; request?: JsonValue };
    try {
      body = JSON.parse(text) as typeof body;
    } catch {
      return json(400, { message: "The request is not JSON." });
    }
    try {
      switch (body.call) {
        case "listOperations":
          return json(200, toJson(ListOperationsResponseSchema, await operations.listOperations(read(ListOperationsRequestSchema, body.request))));
        case "getOperation":
          return json(200, toJson(GetOperationResponseSchema, await operations.getOperation(read(GetOperationRequestSchema, body.request))));
        case "run":
          // The actor comes from the session, here on the server. Nothing in the body says who is calling.
          return json(200, toJson(RunOperationResponseSchema, await operations.runAs(await session(request), read(RunOperationRequestSchema, body.request), { signal: request.signal })));
        case "listRuns":
          return json(200, toJson(ListOperationRunsResponseSchema, await operations.listRuns(read(ListOperationRunsRequestSchema, body.request))));
        default:
          return json(400, { message: "No such call." });
      }
    } catch (error) {
      // A request that does not fit the contract, or an operation asked for by `getOperation` that is not there.
      return json(400, { message: error instanceof Error && /^No operation/.test(error.message) ? error.message : "The request could not be read." });
    }
  };
}

The wire format is a choice, not a rule: here one POST with { call, request }, the request and the reply as protobuf JSON (toJson and fromJson from @bufbuild/protobuf), so a server in another language can read it without the generated code. What is a rule: the actor comes from your session, on the server.

The page's side

httpOperations.ts:

ts
import { type DescMessage, type JsonValue, type MessageInitShape, type MessageShape, create, fromJson, toJson } from "@bufbuild/protobuf";
import type { Operations } from "@surfaces-ui/data";
import {
  GetOperationRequestSchema,
  GetOperationResponseSchema,
  ListOperationRunsRequestSchema,
  ListOperationRunsResponseSchema,
  ListOperationsRequestSchema,
  ListOperationsResponseSchema,
  RunOperationRequestSchema,
  RunOperationResponseSchema,
} from "@surfaces-ui/proto";

export interface HttpOperationsOptions {
  /** Where your route is, such as `/api/operations`. */
  url: string;
  /** Extra headers for each call, such as a CSRF token. The session cookie goes by itself on the same site. */
  headers?: () => Record<string, string> | Promise<Record<string, string>>;
  fetch?: typeof fetch;
}

/** `Operations` over your own route: what a page is given, with no Surfaces server and no Connect client. */
export function httpOperations(options: HttpOperationsOptions): Operations {
  const send = options.fetch ?? fetch;
  async function call<Req extends DescMessage, Res extends DescMessage>(name: string, requestSchema: Req, responseSchema: Res, request: MessageInitShape<Req>, signal?: AbortSignal): Promise<MessageShape<Res>> {
    const response = await send(options.url, {
      method: "POST",
      headers: { "content-type": "application/json", ...(await options.headers?.()) },
      body: JSON.stringify({ call: name, request: toJson(requestSchema, create(requestSchema, request)) }),
      credentials: "same-origin",
      ...(signal ? { signal } : {}),
    });
    const body = (await response.json().catch(() => ({}))) as JsonValue;
    // Everything a person can cause comes back as a status in a 200. Anything else is the call itself failing.
    if (!response.ok) throw new Error((body as { message?: string } | null)?.message ?? `The server answered ${response.status}.`);
    return fromJson(responseSchema, body, { ignoreUnknownFields: true });
  }
  return {
    listOperations: (request, o) => call("listOperations", ListOperationsRequestSchema, ListOperationsResponseSchema, request, o?.signal),
    getOperation: (request, o) => call("getOperation", GetOperationRequestSchema, GetOperationResponseSchema, request, o?.signal),
    run: (request, o) => call("run", RunOperationRequestSchema, RunOperationResponseSchema, request, o?.signal),
    listRuns: (request, o) => call("listRuns", ListOperationRunsRequestSchema, ListOperationRunsResponseSchema, request, o?.signal),
  };
}

Everything a person can cause comes back as a status in the reply: DONE, PARTIAL (rows left alone, named), INVALID (an error per field), REFUSED, NEEDS_APPROVAL, STALE (the record changed since it was read), FAILED. A thrown error means the call itself could not be made.

ts
const operations = httpOperations({ url: "/api/operations" });
const key = crypto.randomUUID(); // one per press, sent again on a retry
const reply = await operations.run({ operationId: "close-ticket", args: { id: "T-1", resolution, version }, idempotencyKey: key });
if (reply.status === OperationStatus.NEEDS_APPROVAL) {
  // Show reply.approval to the person. Work its digest out again from what you show (approvalDigest) and only then offer the button.
  await operations.run({ operationId, args, idempotencyKey: key, approval: { id: reply.approval.id, allow: true, digest: reply.approval.digest, reason } });
}

What is yours to do

  • Each operation must be safe for any caller its allow admits, with any arguments that pass their fields. The handler checks shape and order; it cannot know that this person may close that ticket unless allow or run says so.
  • Requests forged from another site. The route above takes only application/json, which a form on another site cannot send; your session cookie's SameSite setting and your own CSRF rules still apply, as for your other routes.
  • A store that outlives the process, for more than one server or a restart between a press and its retry.
  • Do not log an error's message from onError. It may hold a value. Log its kind and the run's id.

Not built yet: the run action that lets a page document call an operation from a button, and the approval dialog. Until then a page calls operations.run from its own code, as above.

Prove your route

The handler keeps the rules, but your route, your session and your store sit between it and the page, and each can lose something: an idempotency key dropped on the way, an actor taken from the request, an approval a second server cannot see. checkOperations from @surfaces-ui/data/conformance runs the handler's own cases through the page's client. Mount conformanceOperations() in your handler, give it the client for a signed-in person, for nobody and for a second person, and read the report.

conformance.test.ts:

ts
import fs from "node:fs";
import type { Operations } from "@surfaces-ui/data";
import { checkOperations, conformanceOperations, operationsChecks, vitestConformance } from "@surfaces-ui/data/conformance";
import { createOperationHandler } from "@surfaces-ui/data/server";
import { beforeAll, describe, it } from "vitest";
import { httpOperations } from "./httpOperations.js";
import { type Session, operationsRoute } from "./route.js";

// The route and the client of this recipe, with the suite's own operations behind them: what is checked is the
// part a team writes, the route, the session and the client, and that nothing is lost between them.
const sessions: Record<string, { id: string; name: string }> = { "s-ana": { id: "u-ana", name: "Ana" }, "s-ben": { id: "u-ben", name: "Ben" } };
const session: Session = (request) => sessions[/(?:^|;\s*)session=([^;]+)/.exec(request.headers.get("cookie") ?? "")?.[1] ?? ""];

vitestConformance({ beforeAll, describe, it }, "operations through your own route keep every rule", operationsChecks, async () => {
  const POST = operationsRoute(createOperationHandler({ operations: conformanceOperations() }), session);
  const as = (cookie?: string): Operations =>
    httpOperations({ url: "https://app.example/api/operations", fetch: (url, init) => POST(new Request(url as string, { ...init, headers: { ...(init?.headers as Record<string, string>), ...(cookie ? { cookie: `session=${cookie}` } : {}) } })) });
  const report = await checkOperations(as("s-ana"), { subject: "own-operations recipe (route and httpOperations)", anonymous: as(), other: as("s-ben") });
  if (process.env.SURFACES_CONFORMANCE_OUT) fs.appendFileSync(process.env.SURFACES_CONFORMANCE_OUT, `${JSON.stringify(report)}\n`);
  return report;
});

Source and test: apps/recipes/src/own-operations