Defining workflows
A workflow is a versioned list of steps and transitions. Foliot never runs your code. Instead, it calls your provided handler for each step (or have your pull workers query the task) and tracks progress. While the examples on this page use the official Node.js SDK (@foliot/sdk), you can also use the Foliot API with your preferred programming language (refer to Without the SDK below).
import { defineWorkflow, task, sleep, wait, choice, when, END, FAIL } from "@foliot/sdk";
export const orderFulfilment = defineWorkflow<Order>()({
name: "order-fulfilment",
version: 3,
runTimeout: "14d",
retry: { maxAttempts: 5, backoff: "exponential", initial: "10s", max: "1h" },
steps: [
task("reserve-stock", { timeout: "30s" }),
task("charge-card", { timeout: "60s", retry: { maxAttempts: 3 }, onFailure: "release-stock" }),
task("create-shipment"),
wait("shipped", { timeout: "5d", onTimeout: "escalate-warehouse" }),
sleep("settle", { for: "3d" }),
choice("needs-review?", {
when: when.gt("state.charge-card.amount", 500),
then: "send-review-email",
else: END,
}),
task("send-review-email", { next: END }),
task("release-stock", { next: FAIL }),
task("escalate-warehouse", { next: "shipped" }),
],
});
Create handlers
You define one unique handler for each task defined in your workflow. If you are using the SDK, leaving one out will result in a compile error.
export const handlers = orderFulfilment.handlers({
"reserve-stock": async (ctx) =>
inventory.reserve(ctx.input.items, { idempotencyKey: ctx.stepKey }),
"charge-card": async (ctx) =>
payments.charge(ctx.input.card, ctx.input.amount, { idempotencyKey: ctx.stepKey }),
"create-shipment": async (ctx) => shipping.create(ctx.output("reserve-stock")),
"send-review-email": async (ctx) => mail.send(ctx.input.customerEmail),
"release-stock": async (ctx) => inventory.release(ctx.output("reserve-stock")),
"escalate-warehouse": async (ctx) => warehouse.escalate(ctx.input.orderId),
});
Please note a step can run more than once. When Foliot can’t tell whether a step was completed - for example your charge-card handler processed a transaction but the its reply arrived after Foliot’s respondBy window - it will retry the step. Foliot passes a stepKey to your handler, which will be the same value for every retry of a step, and a new value when the run comes back to the step: a loop in your workflow, a redrive or a rewind. Use this stepKey if you need to ensure something must happen only once per step: give it to your payment provider as their idempotency key like the charge-card example does above, or save it with your work and skip taking action if you receive a key you’ve already handled. Each try also has its own attemptKey, which Foliot never sends twice. A proxy between you can still deliver one request twice; see Managing runs.
Each task step calls one of your handlers and your handler response tells Foliot what to do next:
| When the handler… | Foliot… |
|---|---|
| returns a value | marks the step done, keeps the value for later steps (ctx.output("step-name")) and runs the next step. |
| throws an error | tries the step again later, as many times as its retry setting allows. If the retry budget is used, the step fails. |
throws NonRetryableError |
does not try again and the step fails straight away. Use it when retries cannot help, such as a declined card. |
returns defer() |
waits. Your service finishes the step itself later with client.completeTask(ctx.taskToken, output). Use it for work that takes longer than a single request cycle. |
returns jumpTo("step-name", output) |
marks the step done and runs the step you named instead of the next one. |
When an individual step fails, the run will proceed to the step configured inside its onFailure setting (if configured). Otherwise the run fails.
Mount the handler routes
// Express
const taskHandler = createTaskHandler({
workflows: [handlers],
signingSecret: process.env.FOLIOT_SIGNING_SECRET!,
});
app.use("/foliot", foliotExpress(taskHandler)); // before express.json()
// NestJS (create the app with { rawBody: true })
FoliotModule.forRoot({ handler: taskHandler });
Foliot signs each task over the raw request body, so the handler must see the bytes before any
JSON parser does. That is why the Express mount goes before express.json() and Nest needs
rawBody: true.
Register the workflow definition
You can register your workflow definition from CI during each deployment by passing FOLIOT_URL, FOLIOT_TOKEN and FOLIOT_APP using the environment secrets:
foliot push dist/workflows.js
If you are not using the SDK, you can register the definition by sending it in JSON format to the PUT /apps/{appId}/workflows API endpoint.
Definitions are versioned. A run keeps the version it started on, so a new version deployment does not impact runs already in progress. See Concepts.
You can find more details in the Workflow definition reference.
Without the SDK
Foliot sends each task as a signed JSON POST to <handler base URL>/foliot/<workflow>/<step>, unless the step sets its own handler path. Your service should check the foliot-signature header on every task before acting on it. Here is the check in Node.js, without the SDK:
import { createHmac, timingSafeEqual } from "node:crypto";
// header: "t=1730800000,v1=5f2b…" (two v1= values while the secret is being rotated)
function isFromFoliot(rawBody: Buffer, header: string, signingSecret: string): boolean {
let t = NaN;
const signatures: string[] = [];
for (const part of header.split(",")) {
const [key, value] = part.split("=", 2);
if (key === "t") t = Number(value);
if (key === "v1" && signatures.length < 2) signatures.push(value);
}
// Refuse a delivery more than 300 seconds old (or ahead).
if (!Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > 300) return false;
// Sign "<t>.<raw body>" with the app's signing secret, exactly as received.
const expected = createHmac("sha256", signingSecret).update(`${t}.`).update(rawBody).digest();
// Accept if any v1= matches, compared in constant time.
return signatures.some((sig) => {
const given = Buffer.from(sig, "hex");
return given.length === expected.length && timingSafeEqual(given, expected);
});
}
// In your route, mounted with express.raw({ type: "application/json" }) so that
// req.body is the raw bytes: answer 401 when the check fails, before doing anything else.
const header = req.get("foliot-signature") ?? "";
if (!isFromFoliot(req.body, header, process.env.FOLIOT_SIGNING_SECRET!)) {
return res.status(401).end();
}
Use the raw body bytes as they arrive, before any JSON parser touches them, or the signature won’t match. Your handler should respond with one of the documented status codes. The payload, the header and the response codes are documented under Webhooks and in the receiveTask reference.
A service that cannot take inbound calls can pull its tasks instead. In this case, give the task step a queue, then poll tasks with POST /apps/{appId}/tasks/poll and answer each one with POST /apps/{appId}/tasks/complete or /fail, with the token in the body.