Workflows
A run registry for any workflow engine that members read through RLS, cron schedules, counting semaphores, admission control for starts, and useWorkflowRuns over Realtime.
The workflows block records the runs of your durable workflows in one
table, whatever engine runs them, so a run list, a run page and a cancel
button work the same way for every engine. It also adds schedules,
semaphores and admission control. Each of these hands a start to the engine
you choose rather than running the workflow itself. The
Workflow SDK adapter is the engine that ships
with it.
better-supabase add workflows # adds tenant and access as well| Table | Holds |
|---|---|
workflow_runs | One row per run: engine, external_id, definition, tenant_id, actor_id, status, attributes, error, the times, and the subject_type, subject_id, principal_kind, principal_id, mode and trigger_node below |
workflow_schedules | Recurring starts: name, workflow, input, cron, timezone, next_run_at, paused |
workflow_semaphores | The holders of each semaphore key, until they release it or their lease ends |
workflow_start_requests | Starts waiting for room under their key's concurrency, debounce or singleton rule |
| Permission | Lets | Default roles |
|---|---|---|
workflows.read | members read the tenant's runs and schedules | none by default |
workflows.run | members start runs, for helpers such as protectWebHandler | none by default |
workflows.manage | members cancel any run of the tenant and manage schedules | none by default |
Grant the keys to your roles in blocks.permissions.roles. A user always
reads the runs they started, without a permission.
A run's status is queued, running, waiting, completed, failed or
cancelled. Every status change sends a payload-free Realtime message on
workflow-run:<id> and, for a run with a tenant, on
workflow-runs:<tenant>. With the outbox installed,
a run that ends emits workflow_run.completed, workflow_run.failed or
workflow_run.cancelled.
Runs on a record
A run can belong to a record, such as a deal or a ticket: its subject,
stored as subject_type and subject_id. List a record's runs with
runs.list({ subject: { type: "deal", id: dealId } }), and the run's
outbox events carry subjectType and subjectId, so a record's activity
feed can show them. The Workflow SDK adapter records the subject from the
subject option of startFor (stored on the run as the bsb.subject
attribute), and queued starts take one in admission.request({ subject }).
A run also records who its steps act as: principal_kind is user,
service_principal, system or external, and principal_id names the
user or service principal. actor_id stays the user who triggered the run,
so a schedule's creator or an event's actor sees the run they caused, while
the steps run as the publisher. run.principal returns both. Over your own
runs table, principal_kind and principal_id are optional as a pair: map
both to null and the block keeps the principal in attributes
(bsb.principal_kind and bsb.principal), and run.principal reads it
from there.
mode is live or test. Test runs come from the
workflow builder's test button:
they emit no outbox events and fire no alerts, and runs.list leaves them
out unless you pass mode: "test" or mode: "all". trigger_node names
the trigger node a run of a graph with several started at.
Reading runs
Server code calls the workflows instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useWorkflows } = defineDataHooks(
"workflows",
(db: AppDb) => db.workflows,
);const rows = await db.workflows.list({ limit: 50 }).orThrow();"use client";
import { useWorkflows } from "@/lib/supabase/hooks";
const rows = useWorkflows({ limit: 50 });runs.get and requestCancel take the row's id or the engine's run id.
list returns the newest runs first; pass the last run's
createdAt as cursor for the next page. definitionId keeps the runs of one
or several builder definitions (definitionId: "d1" or ["d1", "d2"]): the
workflow editor stamps each run with its definition id in the bsb.definition
attribute, and the database filters on it, so the filter works on any page of
the history. requestCancel sets cancel_requested_at
for the run's actor, a workflows.manage of its tenant or the service role.
The engine does the cancelling. The Workflow SDK adapter calls
run.cancel() for you.
Engines write runs with runs.record (service role), and
runs.purge({ olderThan }) deletes finished runs older than 30 days by
default.
In Client Components
The React hooks are a registry item: npx shadcn add @better-supabase/use-workflows writes hooks/use-workflows.ts into the app.
"use client";
import { useWorkflowRuns } from "@/hooks/use-workflows";
export function RunList({ organizationId }: { organizationId: string }) {
const { runs, error } = useWorkflowRuns({ tenant: organizationId });
if (error) return <p role="alert">{error.message}</p>;
return (
<ul>
{runs?.map((run) => (
<li key={run.id}>
{run.definition}: {run.status}
</li>
))}
</ul>
);
}useWorkflowRuns loads the list and loads it again on every message on
workflow-runs:<tenant>. Without a tenant, it loads the user's own runs
once. The list holds live runs; pass mode: "test" or mode: "all" to include
the test runs an editor starts. useWorkflowRun(id) reads one run, follows workflow-run:<id> and
returns cancel(). In Server Components, call workflows.runs.list()
instead.
Vue
useBlockController from better-supabase/vue runs
createWorkflowRunsController for a list of runs and
createWorkflowRunController for one run, each with its options; auth and
ports come from app.use(betterSupabase(bsb)) unless you pass them.
state is a shallow ref of the snapshot and actions are the controller's
actions. The work starts on mount, and the controller is disposed with the
component.
<script setup lang="ts">
import { useBlockController, useSupabase } from "better-supabase/vue";
import {
createWorkflowRunsController,
createWorkflows,
rpcTransport,
} from "better-supabase/blocks/workflows";
const { organizationId } = defineProps<{ organizationId: string }>();
const supabase = useSupabase();
const { state } = useBlockController(createWorkflowRunsController, {
client: createWorkflows({ transport: rpcTransport(supabase) }),
tenant: organizationId,
});
</script>
<template>
<ul>
<li v-for="run in state.runs ?? []" :key="run.id">
{{ `${run.definition}: ${run.status}` }}
</li>
</ul>
</template>Svelte
useBlockController from better-supabase/svelte runs
createWorkflowRunsController or createWorkflowRunController with its
options; auth and ports come from setBetterSupabase(bsb) unless you pass
them. It returns a readable store of the snapshot, read with $, with the actions on
.actions. The work starts on mount, and the controller is disposed with
the component.
<script lang="ts">
import { betterSupabase, useBlockController } from "better-supabase/svelte";
import {
createWorkflowRunsController,
createWorkflows,
rpcTransport,
} from "better-supabase/blocks/workflows";
let { organizationId }: { organizationId: string } = $props();
const { supabase } = betterSupabase();
const runs = useBlockController(createWorkflowRunsController, {
client: createWorkflows({ transport: rpcTransport(supabase) }),
tenant: organizationId,
});
</script>
<ul>
{#each $runs.runs ?? [] as run (run.id)}
<li>{`${run.definition}: ${run.status}`}</li>
{/each}
</ul>Solid
useBlockController from better-supabase/solid runs
createWorkflowRunsController or createWorkflowRunController with its
options; auth and ports come from <BetterSupabaseProvider client={bsb}> unless you pass
them. state() reads the snapshot through from, and actions are the
controller's actions. The work starts on mount, and the controller is
disposed with the owner.
import { For } from "solid-js";
import { useBlockController, useSupabase } from "better-supabase/solid";
import {
createWorkflowRunsController,
createWorkflows,
rpcTransport,
} from "better-supabase/blocks/workflows";
export function Component(props: { organizationId: string }) {
const supabase = useSupabase();
const { state } = useBlockController(createWorkflowRunsController, {
client: createWorkflows({ transport: rpcTransport(supabase) }),
tenant: props.organizationId,
});
return (
<ul>
<For each={state().runs ?? []}>
{(run) => <li>{`${run.definition}: ${run.status}`}</li>}
</For>
</ul>
);
}Reading a run as a job
workflows.jobs is the workflow source of createJobs, so jobs.get("workflow:<run id>") returns the common JobResult. A queued run is pending, a waiting run is running, a completed run has the run as result, and a failed or cancelled run is failed with WORKFLOW_RUN_FAILED or WORKFLOW_RUN_CANCELLED. The engine starts runs, so there is no start call. A run the caller cannot see is not_found.
Schedules
Workflow schedules sit between job schedules and per-user AI tasks; see three scheduling layers.
import {
createWorkflows,
sqlTransport,
} from "better-supabase/blocks/workflows";
import { workflowStarter } from "better-supabase/workflow-sdk";
import { weeklyDigest } from "@/workflows/digest";
const workflows = createWorkflows({ transport: sqlTransport(postgres.admin) });
await workflows.schedules.create({
name: "weekly-digest",
workflow: "weeklyDigest",
cron: "0 9 * * 1",
timezone: "Europe/Amsterdam",
input: [organizationId],
tenant: organizationId,
});
export async function GET() {
const result = await workflows.schedules
.tick({
start: workflowStarter(
{ weeklyDigest },
{
runAs: { publisher: automationUserId, permissions: ["digest.send"] },
},
),
})
.orThrow();
return Response.json(result);
}cron takes five cron fields, a macro such as @daily or an interval such
as 30 seconds. tick claims the due schedules, starts each one with the
idempotency key schedule:<id>:<fire time> and moves it to its next time,
so a tick that runs twice for the same fire time starts one run. A start
that throws stays due and runs again once its lease ends. Call tick from
a cron route or a job every minute.
A schedule runs as the runAs publisher of workflowStarter, capped to
its permissions, never as the member who created it (see
Event and schedule starts run as a publisher).
The start call says which it is in call.source (schedule or
admission), and names the schedule's creator in call.actor for audit.
Members with workflows.manage create, pause and remove the schedules of
their tenant; the service role manages every schedule.
Semaphores and admission
const free = await workflows.semaphores
.acquire("stripe-sync", runId, { max: 3, ttl: 300 })
.orThrow();
await workflows.semaphores.release("stripe-sync", runId);
await workflows.admission.request({
key: `import:${organizationId}`,
workflow: "importContacts",
input: [fileId],
tenant: organizationId,
concurrency: 1,
debounce: 30,
});
await workflows.admission.tick({ start: workflowStarter({ importContacts }) });A semaphore lets at most max holders take a key at once, each until it
releases the key or its ttl runs out. Admission queues starts by key:
concurrency caps the runs of the key that are active, debounce waits
that many seconds and replaces a request that is still waiting, and
singleton drops the request while a run with the key is waiting or
active. admission.tick starts the requests whose key has room, with the
idempotency key admission:<id>. Both are service-role functions.
Run extra columns
Pass fields (a Standard Schema) to createWorkflows and map extra columns with alter table ... add column in your own schema files. runs.record validates fields, and runs.list, runs.get and the other run methods return them parsed on run.fields, typed by the schema. A run also carries idempotencyKey and dispatchUntil. runs.claimForDispatch leases a queued run (an external id that starts with pending:) and runs.setEngine records the engine's run id on it.
Map schedules, semaphores or startRequests to null in tables to install only the run registry.
Functions
| Function | Granted to | Does |
|---|---|---|
workflow_runs_list(tenant, definition, status, max, before, subject_type, subject_id, mode, definition_ids) | authenticated, service_role | The runs the caller may read, newest first; mode defaults to live, null lists both; definition_ids keeps the runs of those builder definitions |
workflow_run_get(run) | authenticated, service_role | One run by its id or its engine's id |
request_workflow_cancel(run) | authenticated, service_role | Marks a run for cancellation |
record_workflow_run(...) | service_role | Creates or updates a run by engine and external id |
purge_workflow_runs(older_than, batch) | service_role | Deletes finished runs |
create_workflow_schedule(...) | authenticated, service_role | Creates or replaces a schedule by tenant and name |
workflow_schedules_list(tenant) | authenticated, service_role | The schedules the caller may read |
pause_workflow_schedule(id, paused), delete_workflow_schedule | authenticated, service_role | Pauses, resumes or removes a schedule |
claim_due_workflow_schedules, advance_workflow_schedule | service_role | The schedule tick |
acquire_workflow_semaphore, release_workflow_semaphore | service_role | Semaphores |
request_workflow_start, claim_workflow_start_requests, mark_* | service_role | Admission control |
Hooks
createWorkflows takes hooks keyed by group, then method, such as
{ schedules: { create: { before } } } for a rule that returns a
DbError to refuse a schedule; see
extending blocks.
Without the client
db.workflows is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import {
createWorkflows,
rpcTransport,
} from "better-supabase/blocks/workflows";
const workflows = createWorkflows({ transport: rpcTransport(supabase) });
const runs = await workflows.runs
.list({ tenant: organizationId, status: "running", limit: 50 })
.orThrow();
const run = await workflows.runs.get(runId).orThrow();
await workflows.runs.requestCancel(runId);Last updated on