Workflows, schedules and webhooks
A workflow is work your app does on its own, on the server: tell instructors about a new booking, email a confirmation and ask for feedback a day later, send a digest every morning, mark an invoice paid when the provider calls back. You write it as a TypeScript function in workflows/. Every step is recorded, so a retry or a week-long wait picks up where it stopped and an email goes out once.
Triggers
| Trigger | Fires | Example |
|---|---|---|
on.created(table, fn) | After a row is inserted | Notify instructors of a new booking |
on.updated(table, fn) | After any update; old holds the row before | Re-sync a changed customer |
on.transition(table, column, value, fn) | When the column moves into that value (not on later updates while it stays there) | Booking confirmed: email the booker |
on.deleted(table, fn) | After a delete, with the row as it was; on a soft-delete table, when the row moves to the trash | Tell the host a booking was removed |
cron(schedule, { tz }, fn) | "06:00", "daily 06:00", "every 15m", "weekly mon 09:00", "monthly 1 09:00" or a cron expression; UTC unless tz | A morning digest |
webhook(name, { verify? }, fn) | When something POSTs to /hooks/<project-id>/<name> | A payment provider's callback |
Data-change triggers come from the database's change log, so they fire for every write, whoever makes it. A workflow can't stop a write; that is a rule's job.
Code
// workflows/booking.ts
import { cron, on } from "@appbricx/workflows";
type Booking = { id: string; ref: string; email: string; team_size: number; status: string };
// Confirmed: email the booker, wait a day, then wait (up to a week) for their stars.
export const bookingConfirmed = on.transition<Booking>("booking", "status", "confirmed", async ({ row }, step) => {
await step.send.email("booking-confirmed", {
to: row.email,
vars: { ref: row.ref, team_size: row.team_size, link: step.url("/bookings") },
});
await step.sleep("1d");
const feedback = await step.waitFor<{ stars: number }>("feedback", { key: row.id, timeout: "7d" });
if (feedback) {
await step.run("keep the stars", () => step.ctx.db.update("booking", row.id, { notes: feedback.stars + " stars" }));
}
return { feedback };
});
// Every morning: tell ops how many bookings wait for them.
export const morningDigest = cron("06:00", { tz: "Asia/Kolkata" }, async (_event, step) => {
const rows = await step.sql("waiting", "select count(*)::int as n from booking where status = 'requested'");
const count = Number(rows[0]?.n ?? 0);
if (count > 0) await step.send.notify("bookings-waiting", { role: "ops", vars: { count } });
return { count };
});An action wakes the waiting run:
// server/bookings.ts
export const leaveFeedback = defineAction({
input: v.object({ booking: v.uuid(), stars: v.integer({ min: 1, max: 5 }) }),
roles: ["hr"],
handler: async (ctx, input) => ctx.signal("feedback", input.booking, { stars: input.stars }), // { woken }
});Steps
step.* | Does |
|---|---|
run(name, fn) | Runs fn once; its result is recorded and answered on every later pass |
now() | The time, recorded |
sleep("30s" | "15m" | "2h" | "1d"), sleepUntil(date, { minus }) | The run waits without holding anything and wakes at the time |
waitFor(name, { key, timeout }) | Waits for ctx.signal(name, key, payload); the payload, or null at the timeout. A signal sent before the run got there still counts |
send.email | sms(template, { to, vars, locale? }) | Renders a messages/ template (its vars are typed) and sends it once |
send.notify(template, { user | role, vars }) | An in-app notification, once |
prompt(name, vars) | Asks the app's AI with a prompts/ template; the answer is recorded |
pdf(name, html) | Prints a PDF kept as an app file: { fileId, url, bytes } |
sql(name, sql, params) | One SQL statement ($1, $2 for params), recorded |
url(path), ctx | An absolute link into the app; the raw server context (reads that needn't be recorded) |
Durable means re-run. After a sleep, a wait or a retry, the function runs again from the top and the steps it already took answer from the record. So code between steps must do the same thing every time: take the time from step.now(), and put anything random or anything that talks to the outside world inside step.run. The check refuses Date.now(), new Date() and Math.random() outside a step.
Webhooks
Signed by Stripe, Razorpay, GitHub or your own secret
// workflows/stripe.ts
import { webhook } from "@appbricx/workflows";
type StripeEvent = { type?: string; data?: { object?: { client_reference_id?: string; payment_status?: string } } };
export const stripeEvents = webhook(
"stripe-events",
{ verify: { provider: "stripe", secret: "STRIPE_WEBHOOK_SECRET", events: ["checkout.session.completed"] } },
async ({ body, row }, step) => {
const e = (body ?? row) as StripeEvent;
const s = e.data?.object;
if (e.type !== "checkout.session.completed" || s?.payment_status !== "paid" || !s.client_reference_id) return { ignored: e.type };
const paid = await step.sql("mark paid",
"update class_order set status = 'paid' where id = $1 and status = 'pending' returning id", [s.client_reference_id]);
return { paid: paid.length };
},
);provider:stripe(theStripe-Signatureheader),razorpay(X-Razorpay-Signature),github(X-Hub-Signature-256), orgeneric-hmacwith theheaderyou name (HMAC-SHA256 of the raw body;encodinghex or base64, an optionalprefixsuch assha256=).secretnames the project secret that holds the signing secret. The code never holds the value; one that looks like a value is refused.eventslists the event types that run the workflow; others are acknowledged and ignored.customer.subscription.*matches a family. A provider event id seen in the last seven days answers as a duplicate and runs nothing.- The handler gets the request's JSON as
body(and asrow, which is what a dry run passes), andheaders. get_contractlists every webhook's URL underwebhooks, with who signs it: the URL to paste into the provider.
Without verify
The caller signs the raw body with the signing secret the platform keeps for that webhook and sends the hex HMAC-SHA256 in x-appbricx-signature; anything else is refused with 401. Add x-appbricx-idempotency-key and a repeat within 24 hours answers without running again. When you control the sender, generic-hmac with a secret you set is simpler to share.
Check it
A workflow's id is its export name in lower case: bookingConfirmed is bookingconfirmed. workflows { "action": "list" } shows each one with its trigger, next run, webhook URL and recent runs.
// Run it once against the real dev data with nothing written or sent: every effect comes back listed.
workflows { "project_id": "…", "action": "dry_run", "id": "bookingconfirmed",
"row": { "id": "…", "ref": "BK-ACME1", "email": "offsite@acme.test", "team_size": 12, "status": "confirmed" } }
// effects: the email, the sleep and the waitFor (which answers null, as at its timeout), each listed
message_previews { "project_id": "…" } // every template rendered with its sample
run { "project_id": "…", "action": "workflow", "id": "morningdigest" } // for real, now, on dev
run { "project_id": "…", "action": "get_run", "runId": "…" } // each step's status, output, attempts and log lines
logs { "project_id": "…", "workflow": "bookingconfirmed", "status": "failed" }- A failing step is retried with backoff; a run that runs out of retries is
dead.run{ "action": "dead_letters" }lists them andreplayruns them again, or a finished run from a given step. workflows{ "action": "pause", "id": "…" }stops a schedule, webhook or data trigger (deploys keep the pause);resumestarts it again.
Gotchas
- Data-change, scheduled and webhook runs act as the app, past row-level security (your constraints and triggers still apply). Keep their writes narrow and check what a webhook sends.
step.ctxcalls aren't recorded. Reads are fine; a write, a message or an outside call goes instep.runor astep.send, or a retry repeats it.- A signal's name has no
:; put the rest in its key. - Schedules run in UTC unless you give
tz. On the day the clocks go back a fixed-hour schedule fires once; on the day they go forward it fires an hour later, not never. - Return small results from
step.run(an id, a count): every result is recorded.