@foliot/sdk
Client SDK for Foliot, a workflow orchestrator. The engine keeps the state, the clock and the history; your app keeps the business logic.
You define a workflow as a versioned list of steps. Foliot pushes each task to your app over signed HTTPS, records every attempt, retries with backoff, waits for timers and signals, and lets an operator redrive, rewind or skip runs.
npm install @foliot/sdk
Ships both ESM and CommonJS, so it works in a modern ESM service and in a CommonJS NestJS app without a dynamic import.
Define a workflow
import { defineWorkflow, task, wait, choice, when, END, FAIL } from "@foliot/sdk";
export const orderFulfilment = defineWorkflow<Order>()({
name: "order-fulfilment",
version: 1,
retry: { maxAttempts: 5, backoff: "exponential", initial: "10s", max: "1h" },
steps: [
task("reserve-stock", { timeout: "30s" }),
task("charge-card", { timeout: "60s", onFailure: "release-stock" }),
wait("shipped", { timeout: "5d" }),
task("send-receipt", { next: END }),
task("release-stock", { next: FAIL }),
],
});
Register it
The package ships a foliot CLI. Point it at a module that exports your
workflows and run it from CI or on deploy, with FOLIOT_URL
(https://api.foliot.app), FOLIOT_TOKEN and FOLIOT_APP set in the
environment:
npx foliot push dist/workflows.js
--url and --app can be passed as flags instead. Keep the API key in
FOLIOT_TOKEN rather than --token: a flag's value is visible in process
listings and in CI logs that echo commands. foliot whoami shows who a token
belongs to. Definitions are
versioned: a run stays on the version it started on, so pushing a new version
never disturbs work in flight.
Handle the steps
One handler per task step — a missing one is a compile error, so a workflow cannot reference a step nobody implements.
export const handlers = orderFulfilment.handlers({
"reserve-stock": async (ctx) =>
inventory.reserve(ctx.input.items, { attemptKey: ctx.attemptKey }),
"charge-card": async (ctx) =>
payments.charge(ctx.input.card, ctx.input.amount, { attemptKey: ctx.attemptKey }),
"send-receipt": async (ctx) => mail.send(ctx.input.email),
"release-stock": async (ctx) => inventory.release(ctx.output("reserve-stock")),
});
Throw NonRetryableError to go straight to onFailure; throw anything else
and the retry policy decides. Return defer() to answer 202 and finish later
with client.completeTask(token, output); return jumpTo("step", output) to
choose the next step yourself.
Mount it
import { createTaskHandler } from "@foliot/sdk";
import { foliotExpress } from "@foliot/sdk/express";
const taskHandler = createTaskHandler({
workflows: [handlers],
signingSecret: process.env.FOLIOT_SIGNING_SECRET!,
});
// Express — mount BEFORE express.json(): signatures are over the raw body.
app.use("/foliot", foliotExpress(taskHandler));
To rotate the signing secret without dropping tasks, pass both the new and the
old secret as an array (signingSecret: [next, previous]), deploy, then drop the
old one.
// NestJS — create the app with { rawBody: true } for the same reason.
import { FoliotModule } from "@foliot/sdk/nest";
FoliotModule.forRoot({ handler: taskHandler });
Start runs and send signals
import { FoliotClient } from "@foliot/sdk";
const foliot = new FoliotClient({
baseUrl: "https://api.foliot.app",
token: process.env.FOLIOT_TOKEN!,
app: "orders",
});
await foliot.start(orderFulfilment, {
input: order,
businessKey: order.id,
idempotencyKey: order.id,
});
await foliot.signalByBusinessKey(orderFulfilment, order.id, {
name: "shipped",
payload: { tracking },
idempotencyKey: eventId,
});
// Just the run, without its history:
const { run } = await foliot.getRunStatus(runId);
Step and attempt keys
A step can run more than once: when Foliot can't tell whether a try finished, it tries again. Each task has two keys, both opaque:
ctx.stepKeyis the same for every try of one entry into the step, and new when the run comes back to the step (a loop, a redrive or a rewind). Pass it to anything your handler does that must happen only once per step, such as a payment provider's idempotency key.ctx.attemptKeyis unique to one try, and Foliot never sends it twice. The handler records it before running the step and keeps the answer under it, so a request that reaches you twice (a proxy resending it) runs once: a copy of a request that has been answered gets the same answer, and a copy that arrives while the first is still running is answered503withRetry-After: Foliot tries again under a newattemptKeyand the samestepKey, without using up one of the step's attempts.
The default store is in memory, so it holds on one replica only. With more
than one, pass idempotency a store they share. Its claim(key) must be
atomic (Redis SET key value NX, or an insert into a unique column), and it
should keep a key for at least the signature tolerance plus the longest a step
runs.
A late answer from before a redrive is refused.
Documentation
Guides and the full HTTP API reference are at docs.foliot.app: start with the quickstart and defining workflows.
License
Apache-2.0