# Workflows

::: info What you'll learn
Write work that takes minutes or days (charge a card, wait for the payment, ship, or cancel after a
day) as one function you read top to bottom, kept in the database step by step, so restarts and
deploys lose nothing.

**Before this page:** [Jobs and tasks](./jobs).
:::

A **workflow** is a function whose steps Easy CMS records. When it waits (a sleep, an event), the
run stops and holds no process; when it goes on, Easy CMS runs the function again from the top,
and every step already done returns what it returned the first time, without running again.

```ts
import { defineWorkflow, type WorkflowArgs } from '@easy-cms/core'

export const orderCheckout = defineWorkflow({
  name: 'order-checkout',
  run: async ({ input, step, cms }: WorkflowArgs<{ orderId: number }>) => {
    const charge = await step.run('charge', () => stripe.charge(input.orderId))
    const paid = await step.waitForEvent('payment.confirmed', {
      match: { chargeId: charge.id },
      timeout: '24h',
    })
    if (!paid) {
      await step.run('cancel', () => cancelOrderAndRestock(cms, input.orderId))
      return { status: 'cancelled' }
    }
    await step.run('stock', () => cutStock(cms, input.orderId))
    await step.run('email', () => sendReceipt(cms, input.orderId))
    return { status: 'done' }
  },
})

export default defineConfig({
  // …
  workflows: [orderCheckout],
})
```

Start a run from a hook, an action or a [state machine](./state-machines)'s `effect`, and send it
events from your own endpoint (where you check the provider's signature):

```ts
await cms.workflows.start('order-checkout', { orderId: order.id }, { id: `order-${order.id}` })

// e.g. a Stripe webhook endpoint, after checking its signature
await cms.workflows.sendEvent('payment.confirmed', { chargeId: event.data.object.id })
```

`id` names the run and makes starting idempotent: the same id gives the run already there. Without
it, a run gets a random id. Inside `cms.transaction`, a run starts once the transaction commits.

## Steps

| | |
|---|---|
| `step.run(name, fn, { retries? })` | Runs `fn` once and keeps its result (JSON, up to 256 KB). A throw runs it again later (5 retries by default, after 1m, 5m, 30m, 2h, 12h); `NonRetryableError`, or the last retry, throws `StepFailedError` into the workflow. |
| `step.sleep(name, duration)` | Waits (`'10m'`, `'2h'`, `'3d'`, or milliseconds). |
| `step.waitForEvent(event, { match?, timeout? })` | Waits for `sendEvent(event, payload)` whose payload has `match`'s values, and returns the payload, or `null` once `timeout` passes. An event sent after the run started but before it got here counts (events are kept 7 days). An event goes to one wait of a run: a second wait for the same event takes another one, the oldest first. |
| `step.now()`, `step.random()` | The time and a random number, kept like steps. |

**Undo by hand.** Catch `StepFailedError` and undo what was done in steps of their own (a saga):

```ts
try {
  await step.run('ship', () => createShipment(order))
} catch (error) {
  if (!(error instanceof StepFailedError)) throw error
  await step.run('refund', () => refund(charge.id))
}
```

An error the workflow doesn't catch fails the run.

## Rules for replays

- **Do the work in steps.** Code outside `step.*` runs again on every replay; keep it to deciding
  what to do next. Use `step.now()` and `step.random()` instead of `new Date()` and `Math.random()`.
- **Make steps safe to repeat.** A process that stops after a step did its work but before it was
  recorded runs it again. Pass the provider's idempotency key (e.g. Stripe's) where there is one.
- **Steps are matched by order and name.** If a deploy changes the steps a running run already
  took, the run stops with **needs attention** instead of guessing: retry it to go on with the code
  as it is now (the steps from where it changed run again), or cancel it.
- **Versions.** Give a workflow `version: 2` when its steps change, and keep the old one in
  `workflows` while runs of it are still going: a run keeps the version it started with. New runs
  use the highest.

## Running

Runs advance as [tasks](./jobs#tasks): a run started, an event sent or a retry due runs right away
in the same process, and each step's next step runs straight after it. Sleeps, timeouts and retries
wake with the jobs (every minute on a long-running server, or a cron calling `<api>/jobs/run`). A
run is claimed while it advances, so it never advances twice at once, and one whose process stopped
goes on after a 5-minute lease.

Finished runs (completed, failed, cancelled) and their steps are removed after `taskRetentionDays`
(default 30).

| `cms.workflows` | |
|---|---|
| `start(name, input?, { id? })` | Starts a run (or returns the one with that id). |
| `sendEvent(event, payload?)` | Sends an event; returns how many waiting runs it woke (each checks its `match`). |
| `get(id)` | The run with its steps: status, what each returned, errors and attempts. |
| `list({ name?, status?, limit? })` | The latest runs. |
| `cancel(id)` | Stops a run that hasn't finished. |
| `retry(id)` | Runs a failed run, or one that needs attention, again from where it stopped. |

Statuses: `pending`, `running`, `sleeping`, `waiting`, `completed`, `failed`, `cancelled` and
`needs_attention`.

## Settings → Jobs

The **Workflows** tab lists the latest 50 runs with what they wait for and, opened, each step with
its status, attempts and error. Admins of the whole site **Retry** a failed run (or one that needs
attention) and **Cancel** one that hasn't finished.

## Testing

Call `cms.runJobs(new Date(Date.now() + …))` to wake sleeps and timeouts as if that time had come,
and `await cms.jobs.idle()` to let what a start or an event set off finish.
