State machine
Allowed status transitions as the caller, a history row, status events, and an optional lifecycle with pause, flags and a pinned version.
state-machine rejects a status change the machine does not allow (STATE_TRANSITION_INVALID), writes a history row and records status.changed. Audit, webhooks and notifications pick that event up when those modules are installed. A machine can also keep a stages timeline and a lifecycle row that pauses the record, holds flags and pins the machine version it started on.
better-supabase add state-machineServer code calls the state-machine instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useStateMachine } = defineDataHooks(
"stateMachine",
(db: AppDb) => db.stateMachine,
);const rows = await db.stateMachine.list({ limit: 50 }).orThrow();"use client";
import { useStateMachine } from "@/lib/supabase/hooks";
const rows = useStateMachine({ limit: 50 });options.machines names each subject table, its status column, the initial status and the allowed edges. A trigger on that table runs the check, writes the history row and records status.changed, so a direct update or a board move into another status emits the event too, and an update that keeps the status emits nothing. A client role (anon, authenticated) inserts a new record only in the initial status, a status the initial status moves to in one step, or one the machine's insertStatuses lists (["*"] turns the check off); anything else fails with STATE_TRANSITION_INVALID, so a client can't create a record that skipped the steps before it. The check runs as the invoker, so trusted SQL is not held to it: a migration, the service role, an import run, and a security definer function that a signed-in user calls. The machine name is the subjectType of the history row and the events, so name a machine after its subject (deal, task) when watchers or comments use the same subject type.
A machine without a table takes its table, id type and tenant column from config.recordTypes under the same name, so a subject declared once needs only its status column and edges here. idType (without it, ids compare as text) makes the lookups compare the id in its own type, which keeps the primary key index in use.
recordTypes: {
quote: { table: "public.quotes", idType: "uuid", tenant: "organization_id" },
},
blocks: {
"state-machine": {
options: {
machines: {
quote: {
column: "status",
initial: "draft",
transitions: { draft: ["sent", "void"], sent: ["accepted", "void"] },
order: ["draft", "sent", "accepted"],
},
},
},
},
},Who may transition
transition(subject_type, id, to, reason, actor) runs as the caller. It updates the status column with the caller's privileges, so the subject table's row level security decides whether they may change that record: a member of another tenant, or a member whose policies allow a read but not an update, gets STATE_SUBJECT_NOT_FOUND (Postgres P0002, a not_found error in TypeScript). The trigger then checks the edge, and the history, stages and lifecycle writes happen inside it. The service role passes every policy, as it does for a direct update.
The block's readers run as the caller too, and return STATE_SUBJECT_NOT_FOUND for a record the caller can't see:
| Method | Returns |
|---|---|
state(subject) | The status, the next statuses the caller may move it to, its step and progress through order, and with a lifecycle its version, flags and pause |
history(subject, page) | Status changes, newest first, 50 per page and at most 500; pass the last createdAt as cursor for the next page |
stages(subject) | The stages timeline in display order, empty for a machine without stages: true |
Every method takes the record as a RecordRef, { type, id }, whose type is the machine name; createStateMachine<"quote"> narrows it. state returns the record as subject next to its organizationId.
progress is 0 at the first status of order and 1 at the last; a status outside order (void above) has no step or progress. The status_history, status_stages and subject_lifecycles tables have select policies that show a row when the caller can see its record, so a query on them returns the same rows as the readers.
History goes to status_history, or to a table named on the machine (history.table and its columns; history() also reads its id and createdAt columns). Set stages: true on a machine to also write status_stages: a label snapshot, an optional outcome, a display order and cleared_at on the previous open stage.
Allowed next statuses
state(subject).next lists the statuses the caller may move the record to now: the machine's edges from its status, without the edges whose guard the caller fails, and none while the record is paused. Edges in requiresApproval stay in the list, since an approved request can make them. A workflow machine reads them from the version the record pinned.
better-supabase gen writes each machine's transitions to the block's generated options, so a board, a route or an MCP tool that needs the edges of many records reads them without keeping a copy:
import { blockConfig } from "@/lib/supabase/blocks.config";
const edges: Readonly<Record<string, readonly string[]>> =
blockConfig["state-machine"].options.transitions.quote;
const targets = edges[status] ?? [];Status timestamps
stamps names a column the trigger sets to now() when a record enters a status, in the same update as the transition. On insert it fills an empty column of the record's first status, except during an import, which brings its own values.
quote: {
column: "status",
initial: "draft",
transitions: { draft: ["sent"], sent: ["accepted", "rejected"] },
stamps: { sent: "sent_at", accepted: "accepted_at" },
},Guards
guards adds checks to an edge, keyed like transitions by the from status and then the to status. The trigger runs them after the edge check, so they hold for transition(), a direct update and a board move alike.
permissionis a permission key the caller must hold in the record's tenant. A caller without it getsSTATE_TRANSITION_FORBIDDEN(Postgres42501); the service role passes.checkis a function that takes the record's row and returns a boolean, such as "the quote has at least one line". When it returns false or null the transition fails withSTATE_GUARD_FAILED(23514). It runs inside the trigger, as the trigger's owner, and sees the row with the new status.
quote: {
column: "status",
initial: "draft",
transitions: { draft: ["sent"], sent: ["accepted"] },
guards: {
draft: { sent: { check: "public.quote_has_lines" } },
sent: { accepted: { permission: "quotes.accept" } },
},
},create function public.quote_has_lines(quote public.quotes)
returns boolean
language sql
stable
set search_path = ''
as $$
select exists (select 1 from public.quote_lines l where l.quote_id = quote.id)
$$;state().next runs the same guards as the caller, so a status the caller can't reach doesn't show up there.
Who made the change
The client's transition(subject, to, options) takes the reason and an actor in one object. The history row keeps the caller's user id, and the actor adds a name, an email, an IP address and a user agent, for a change a portal visitor made without an auth user or to record where a request came from:
await machine
.transition({ type: "quote", id }, "accepted", {
reason: "Signed in the portal",
actor: { name: "Ada Lovelace", email: "ada@example.com", ip, userAgent },
})
.orThrow();An ip that isn't an IPv4 or IPv6 address fails with STATE_ACTOR_INVALID. The service role, which has no user of its own, passes the user it acts for as actor.id; the history row keeps it as the actor's user id, and a signed-in caller's own id always wins.
Status changes the quotes and invoices blocks write themselves fill the same columns: send, publish, revise, withdraw and decide on quotes and issue, recordPayment, void, writeOff, reversePayment, charge and removeCharge on invoices take an actor, the void, write-off and reversal reasons, a payment's reason, a quote's withdraw reason and the note of decide become the history's reason, a customer's answer or view through a quote's link or portal passes their name, email, IP address and user agent, portalView takes the customer the app's portal acts for, and expire_quotes clears the actor so an expiry inherits none. A machine over those tables can then write its own history (no write: false needed). history(subject) returns the four fields as actorName, actorEmail, ip and userAgent. An app history table keeps them when it declares the columns actor_name, actor_email, ip and user_agent in your schema files, or when the machine names other columns (history.actorName, history.actorEmail, history.ip, history.userAgent); without either the table keeps the user id and reason only. The ip column may be inet or text.
history: "app" leaves the history to the app: the block writes no history row, and history() fails with STATE_HISTORY_APP. The trigger still checks the edge and records status.changed, and the reason and actor stay readable in the transaction as the settings better_supabase.transition_reason and better_supabase.transition_actor (JSON), so an app trigger on the subject table can write its own row. history: { table, write: false, ... } reads an app table the app writes itself.
Lifecycle: pause, flags and a pinned version
Set lifecycle: true on a machine to keep one subject_lifecycles row per record. The trigger creates it on insert with the machine's version (default 1), so a record keeps the version it started on after you change the machine and raise the version. flags lists the flags a record may carry.
quote: {
column: "status",
initial: "draft",
transitions: { draft: ["sent"], sent: ["accepted"] },
lifecycle: true,
version: 2,
flags: ["urgent", "needs-legal"],
},const quote = { type: "quote", id: quoteId } as const;
await machine
.pause(quote, {
until: Temporal.Now.instant().add({ hours: 48 }),
reason: "waiting for the client",
})
.orThrow();
await machine.setFlag(quote, "urgent", true).orThrow();
await machine.resume(quote).orThrow();While a pause holds, the trigger refuses every transition with STATE_PAUSED, including a direct update of the status column. A pause without until holds until resume(); a pause with one ends on its own, and the next transition clears it and records status.resumed. pause() refuses an until in the past (STATE_PAUSE_INVALID), and setFlag() refuses a flag the machine doesn't list (STATE_FLAG_UNKNOWN). Each returns false when nothing changed: resume() on a record that wasn't paused, or setFlag() with the value the flag already has.
pause, resume and setFlag run as the caller and are authorized like transition: the caller must be able to update the record. They write by updating the status column to its current value, so a before update trigger of your own on that column runs for them too. A machine without lifecycle: true refuses them with STATE_LIFECYCLE_DISABLED; version and flags need lifecycle: true.
Events
| Type | When | Payload beyond organizationId, subjectType, subjectId |
|---|---|---|
status.changed | The status moved along an allowed edge | from, to, reason |
status.paused | pause() started or replaced a pause | until, reason |
status.resumed | resume(), or a transition after a pause ended | none |
status.flagged | setFlag() changed a flag | flag, enabled |
The events need the outbox module; the subject of each is statuses/<machine>/<id>.
A lifecycle driven by a workflow
A workflow can own the part of a lifecycle that runs on a timer or waits on someone, while the machine keeps the rules. Start a workflow-editor definition from an event trigger with config.type set to status.changed, and have your outbox consumer hand it only the events of the subject type the workflow is for:
const isQuote = (payload: unknown) =>
typeof payload === "object" &&
payload !== null &&
"subjectType" in payload &&
payload.subjectType === "quote";
for (const event of batch) {
if (event.type === "status.changed" && isQuote(event.payload)) {
await serviceBuilder.triggers.onEvent(event).orThrow();
}
}The workflow's steps then call machine.pause() while it waits (a client reply, a signature), machine.setFlag() when a step escalates, and machine.transition() when it is done. The trigger still checks each edge, so a workflow can't move a record along an edge the machine doesn't allow, and a member who moves the record by hand while it is paused gets STATE_PAUSED.
A machine read from a workflow version
A machine can also take its statuses and edges from a published workflow-editor version, so the team that edits the process edits the machine. Set workflow to the definition's slug and leave out initial, transitions and order:
machines: {
change_request: { column: "status", workflow: "change-requests" },
},The graph's stages are the nodes with a string config.stage, in graph order. A path from one stage to the next, through nodes without a stage (a sleep, an approval, a condition), is an allowed edge, and a stage's config.returnsTo lists the earlier stages it may go back to. The initial status is the trigger's own stage, else the first stage after the trigger.
A new record pins the newest published version of the definition, the organization's own before a system one, in its lifecycle row (state() returns it as workflow and workflowVersionId), and keeps checking its edges against that version after a new one is published. A record created before the machine pins the published version on its first transition. The trigger refuses an insert while the definition has no published version (STATE_LIFECYCLE_UNPUBLISHED, Postgres 55000), and a status that isn't a stage or an edge the version doesn't draw (STATE_TRANSITION_INVALID, 22023). A workflow machine needs the workflow-editor module and keeps a lifecycle row, so it can't set lifecycle: false.
Transitions that need approval
requiresApproval lists edges, in the shape of transitions, that only an approved request of the approvals module may make. Any other caller gets STATE_APPROVAL_REQUIRED; the service role can still make them. Pair it with an approvals policy whose run is { transition: "<status>" } on a subject type named after the machine.
machines: {
invoice: {
table: "public.invoices",
column: "status",
initial: "draft",
transitions: { draft: ["sent", "void"] },
requiresApproval: { draft: ["sent"] },
},
},Over your own tables
Point history.table at public.quote_status_history or public.invoice_status_history. Portal-only columns such as actor_customer_id stay on the table and are not required by the module. history() reads the table's id and created_at columns; name others with history.id and history.createdAt.
A machine with lifecycle: true needs a lifecycles table with the columns of subject_lifecycles and a unique key on (subject_type, subject_id). Over a table of your own the block adds the columns it lacks and its own read policy, named bsb_<table>_select so it never replaces one of yours; doctor reports it when your policies for select are narrower.
The subject's status column and the history table's from_status and to_status can be a Postgres enum or a domain over text. The block casts the status it writes to the column's type, so a value the type rejects fails the transition as a direct write would.
Hooks
createStateMachine takes hooks around its methods, such as a rule before
transition that returns a DbError to refuse the call; see
extending blocks.
Without the client
db.stateMachine is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createStateMachine } from "better-supabase/blocks/state-machine";
const machine = createStateMachine<"quote">({ transport });
await machine
.transition({ type: "quote", id: quoteId }, "sent", {
reason: "ready for the client",
})
.orThrow();Last updated on