Durable.DSL.Step (Durable v2.0.2)

View Source

Provides macros for defining workflow steps using a pure pipeline model.

Pipeline Model

Data flows from step to step. Each step receives the previous step's output and returns {:ok, data} or {:error, reason}.

A step's data

A step is handed its data as it is stored: string keys at every depth. That is the same on every pass, whether the previous step just ran or the run was reloaded after a wait, a sleep, a retry, a crash or a move to another node. The same goes for a decision, a branch, an into: function and a compensate. Durable never makes atoms out of data.

step :check, fn data ->
  get(data, [:invoice, :total])   # Durable.Helpers: keys named by atoms
  data["invoice"]["total"]
  %{"invoice" => %{"total" => total}} = data
  {:ok, data}
end

Reading and writing through Durable.Helpers (get/2, assign/3 and the rest) is the recommended way: a step names its keys with atoms and the helpers use the string keys the data has.

What a step returns may be written with atom keys. It is stored with string keys, and the next step reads strings:

step :first, fn input ->
  {:ok, %{order_id: input["id"], status: :new}}
end

step :second, fn data ->
  data["order_id"]   # the id
  data["status"]     # "new"
  {:ok, data}
end

Values are stored as JSON too. From the next step on, an atom is its text (:new is "new"), a tuple is a list, a DateTime or Date is its ISO 8601 string and a struct is a map.

To change data a step was handed, use Durable.Helpers or string keys: assign(data, :total, 10) or Map.put(data, "total", 10). %{data | total: 10} raises, since the data has no :total key.

Future work — each/foreach isolation (L-5)

If/when this DSL gains an iteration primitive (e.g. each/3 to run a step once per item in a list), design with context isolation per iteration. Parallel-style shared context across concurrent iterations creates races on put_context/2 writes; isolated contexts avoid that class of bug.

Usage

workflow "process_order" do
  step :validate, fn order ->
    {:ok, %{order_id: order["id"], items: order["items"]}}
  end

  step :calculate, fn data ->
    total = data["items"] |> Enum.map(& &1["price"]) |> Enum.sum()
    {:ok, assign(data, :total, total)}
  end

  step :charge, [retry: [max_attempts: 3]], fn data ->
    {:ok, assign(data, :receipt, PaymentService.charge(data["total"]))}
  end
end

A step can run more than once

A step that finished is not run again. A step whose worker is lost part-way is: after a payment provider accepted a charge, say, and before the step was recorded as done. Make any step with an effect outside your database safe to repeat, by giving the provider an idempotency key that is the same on every attempt, such as "#{Durable.Context.workflow_id()}:charge_card". See "Make steps safe to run twice" in the Production guide.

Options

  • :retry - Retry configuration

    • :max_attempts - Maximum retry attempts (default: 1)
    • :backoff - Backoff strategy: :exponential, :linear, :constant
    • :base - Base delay in ms (default: 1000)
    • :max_backoff - Maximum backoff in ms (default: 3_600_000, 1 hour)

    Between attempts the run is parked: it goes back on its queue until the backoff has passed, so the wait holds no worker. Each attempt starts with the data the last one got, and what it wrote with put_context/2.

  • :timeout - How long one attempt may run, in milliseconds. A slower attempt is stopped and fails with a "timeout" error, which is retried like any error. A step with a timeout, or in a workflow with one, runs in a separate process: its body sees the same context and captured logs, but self() is not the worker.

  • :compensate - Name of compensation function for saga pattern

  • :queue - The queue this step runs on. The run moves there before the step and takes a slot from that queue's :concurrency, which is per node. The next step without a :queue goes back to the queue the run started on. Moving costs one more claim, so with no :pubsub configured it waits up to that queue's :poll_interval. A run on a queue no live node polls waits there until the workflow's :timeout, if it has one. In a parallel block each branch is its own run on this queue

The options are checked when the workflow compiles. One that would crash or hang a run is a compile error: a :retry that isn't a keyword list, a :max_attempts or :timeout that isn't a positive integer, a :backoff that doesn't exist, a :compensate naming no compensate of the workflow, a step name that isn't an atom. An option the step doesn't take, such as retries:, is ignored, so it compiles with a warning at the step's line.

Summary

Functions

Defines a conditional branch within a workflow.

A branch with a name: a step decides, and its arms hold what runs next.

Defines a compensation handler for saga pattern.

Defines a decision step for conditional branching.

A parallel block. It takes a name: see parallel/3.

A parallel block with a name: each lane is a sequence that runs on its own.

Defines a step within a workflow.

Functions

branch(opts, list)

(macro)

Defines a conditional branch within a workflow.

The :on option takes a function that extracts the value to match. Only ONE branch executes based on the condition value.

Examples

branch on: fn data -> data["type"] end do
  "physical" ->
    step :ship, fn data -> {:ok, assign(data, :shipped, true)} end
  "digital" ->
    step :download, fn data -> {:ok, assign(data, :download_url, "...")} end
  _ ->
    step :manual, fn data -> {:ok, assign(data, :needs_review, true)} end
end

branch(name, decider, list)

(macro)

A branch with a name: a step decides, and its arms hold what runs next.

The function is run like a step body, with the same :retry and :timeout options, its own row, logs and span. It returns {arm, data}, naming one of the arms in the block; data goes to that arm's first step, and the arm's last result goes to whatever follows the block. Naming an arm the block doesn't have fails the run, without retries. Any other step return ({:error, reason}, {:fail, reason}, {:rollback, reason}, {:snooze, ms}, {:cancel, reason}) means what it means in a step.

branch :risk, [retry: [max_attempts: 3]], fn order ->
  cond do
    order["risk"] < 40 -> {:clear, order}
    order["risk"] < 80 -> {:review, order}
    true -> {:blocked, order}
  end
end do
  :clear ->
    pass()

  :review ->
    step :ask_reviewer, fn order -> {:ok, order} end
    step :record_review, fn order -> {:ok, order} end

  :blocked ->
    step :cancel_order, fn _order -> {:cancel, "blocked by risk check"} end
end

An arm holds steps, named branches and named parallel blocks, or pass() for nothing. Steps inside are stored as <branch>__<arm>__<step>, so the same step name can be used in two arms, and renaming one step renames only that step.

branch(name, opts, decider, list)

(macro)

compensate(name, opts_or_fn, maybe_fn \\ nil)

(macro)

Defines a compensation handler for saga pattern.

Compensations receive the current data and return {:ok, data}. Returning {:error, reason} or raising marks the compensation failed once its retries run out, and {:fail, reason} marks it failed with no retries. The run then ends :compensation_failed.

Examples

compensate :cancel_flight, fn data ->
  FlightAPI.cancel(data["flight_booking_id"])
  {:ok, data}
end

decision(name, opts_or_fn, maybe_fn \\ nil)

(macro)

Defines a decision step for conditional branching.

Decision steps can return:

  • {:ok, data} - Continue to the next sequential step
  • {:goto, :step_name, data} - Jump to the named step

Examples

decision :check_amount, fn data ->
  if data["total"] > 1000 do
    {:goto, :manual_review, data}
  else
    {:ok, data}
  end
end

parallel(opts_or_name \\ [], do_block)

(macro)

A parallel block. It takes a name: see parallel/3.

parallel(name, opts, list)

(macro)

A parallel block with a name: each lane is a sequence that runs on its own.

parallel :fulfil do
  lane :shipment do
    step :pick_and_pack, fn order -> {:ok, order} end
    step :send_tracking, fn order -> {:ok, order} end
  end

  lane :loyalty do
    step :add_points, fn order -> {:ok, order} end
  end
end

step :close_order, fn %{"fulfil" => %{"shipment" => shipment, "loyalty" => loyalty}} = order ->
  {:ok, order}
end

Every lane starts from the data the block was given and sees none of what another lane does. A lane holds steps, named branches and named parallel blocks; a step written straight in the block is a lane of one step. The step after the block gets the data from before it, with what each lane produced under the block's name: the keys its steps added or changed, not the data it was started with. The block's name and each lane's name are string keys, like the rest of the data: order["fulfil"]["shipment"].

A lane that fails fails the block and stops the others. Pass on_error: :collect to run every lane and hand the next step each one as {:ok, data} or {:error, reason}, or :into to decide for yourself: the function gets the data and every lane's {:ok, data} or {:error, reason} by lane name, a string: fn order, %{"shipment" => {:ok, shipment}} -> ... end.

Lane options

On lane :name, opts do, or in the options of a step written straight in the block:

  • :optional - true for a lane the block can do without: if it fails, the next step gets nil for it and the run goes on
  • :default - what the next step gets for an optional lane that failed, in place of nil. Like a lane's own data it is handed over as stored, so a map's keys are strings
  • :timeout - on lane only: how long the whole lane may take, in milliseconds, its retries and waits included. Past it the lane fails with a "timeout" error, like any failed lane. A step's own :timeout limits one attempt

step(name, opts_or_fn, maybe_fn \\ nil)

(macro)

Defines a step within a workflow.

The step receives the previous step's output (or workflow input for the first step), with string keys at every depth, and returns one of:

  • {:ok, data} - Done; data goes to the next step
  • {:error, reason} - Failed; retried while attempts are left
  • {:fail, reason} - Failed, and not retried: the run fails now
  • {:rollback, reason} - Failed, not retried, and undone: the run fails now and the compensate: of every completed step runs, whatever the workflow's on_failure: is
  • {:snooze, ms} or {:snooze, ms, reason} - Run the step again in ms milliseconds, without using an attempt. The run is parked meanwhile, like between retries. Snoozes have no limit; the workflow's timeout: is what stops a step that snoozes forever
  • {:cancel, reason} - The run is cancelled now, like Durable.cancel/2: no retries, no compensations. A call_workflow child's parent gets it as an error. In a parallel step the whole workflow holding the block is cancelled
  • {:cancel, reason, scope: scope} - Choose what's cancelled: :run (only the run the step is in, so in a parallel step only that branch, which the block sees as an error), :workflow (the workflow the step is written in; the default) or :root (the top run of the tree, through call_workflow and start_workflow parents, and every run under it)

Examples

step :validate, fn order ->
  {:ok, assign(order, :order_id, order["id"])}
end

step :charge, [retry: [max_attempts: 3]], fn data ->
  {:ok, assign(data, :receipt, PaymentService.charge(data["total"]))}
end