Durable.Context (Durable v2.0.2)

View Source

Context management for workflow execution.

The context is a key-value store that persists across steps within a workflow. It provides a way to share state between steps and is automatically persisted to the database after each step completes.

Usage

defmodule MyApp.OrderWorkflow do
  use Durable
  use Durable.Context

  workflow "process_order" do
    step :init, fn order ->
      put_context(:order_id, order["id"])
      {:ok, order}
    end

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

    step :finalize, fn order ->
      Orders.close(get_context(:order_id), get_context(:total))
      {:ok, order}
    end
  end
end

A step still returns {:ok, data}. What it put in the context is kept beside what it returns.

Keys

The context's keys are strings, as they are stored. A key may be named with an atom or a string: put_context(:total, 10) and put_context("total", 10) write the same key, get_context(:total) and get_context("total") read it, and context()["total"] is where it is. The same holds for input/0, and for the data a step is handed.

Context Storage

During execution, context is stored in the process dictionary for fast access. After each step completes, the context is persisted to the database. When a workflow resumes (e.g., after a sleep or wait), the context is restored from the database.

Summary

Functions

Injects context management functions into the calling module.

Appends a value to a list in the context.

Returns which attempt of the current step this is, starting at 1.

Wraps a function so it runs as part of the current step in another process.

Returns true once the run has been cancelled.

Returns the entire context map.

Returns the current step name.

Deletes a key from the context.

Gets a value from the context by key.

Gets a value from the context by key with a default.

Checks if a key exists in the context.

Increments a numeric value in the context.

Returns the input the run was started with, as it is stored: its keys are strings, whatever they were when it was passed to Durable.start/3.

Returns true on the current step's last attempt: if it returns an error, the step won't be tried again.

Returns how many attempts the current step gets: its retry: [max_attempts: n], or 1 if it has no retry:.

Deep merges a map into the context.

Merges a map into the context.

Puts a single key-value pair into the context.

Returns true once this node has started shutting down.

Updates a context value using a function.

Returns the current workflow ID.

Functions

__using__(opts)

(macro)

Injects context management functions into the calling module.

append_context(key, value)

@spec append_context(atom() | String.t(), any()) :: :ok

Appends a value to a list in the context.

If the key doesn't exist, creates a new list with the value.

Examples

append_context(:events, %{type: :clicked, timestamp: DateTime.utc_now()})

attempt()

@spec attempt() :: pos_integer()

Returns which attempt of the current step this is, starting at 1.

The count carries over when a run resumes after a crash, and starts again at 1 after Durable.retry/2.

Examples

step :charge, [retry: [max_attempts: 5]], fn ctx ->
  Logger.info("charging, attempt #{attempt()} of #{max_attempts()}")
  ...
end

bind(fun)

@spec bind((-> result)) :: (-> result) when result: term()
@spec bind((arg -> result)) :: (arg -> result) when arg: term(), result: term()

Wraps a function so it runs as part of the current step in another process.

A Task starts with none of the step's state. Wrapped, its function can read the context and has the step's Logger metadata and OpenTelemetry span, and its log lines are saved on the step's row. Lines from a plain Task still reach the console, but aren't saved.

Task.await(Task.async(bind(fn -> fetch(order_id) end)))
Task.async_stream(orders, bind(&fetch/1))

Changes it makes to the context stay in its own process. Lines it logs after the step has ended aren't saved.

cancelled?()

@spec cancelled?() :: boolean()

Returns true once the run has been cancelled.

A cancelled run's step is stopped at the worker's next heartbeat, killed like any process. A step that would rather stop cleanly, between two chunks of work, can check this first. It reads the database, so check it between chunks and not in a tight loop:

Examples

step :export, fn ctx ->
  for chunk <- chunks_left(ctx), not cancelled?(), do: export(chunk)
  {:ok, ctx}
end

context()

@spec context() :: map()

Returns the entire context map.

Examples

ctx = context()
# => %{"order_id" => 123, "items" => [...]}

current_step()

@spec current_step() :: atom() | nil

Returns the current step name.

Examples

step = current_step()

delete_context(key)

@spec delete_context(atom() | String.t()) :: :ok

Deletes a key from the context.

Examples

delete_context(:temporary_data)
delete_context("temporary_data")

get_context(key)

@spec get_context(atom() | String.t()) :: any()

Gets a value from the context by key.

Returns nil if the key doesn't exist.

Examples

order_id = get_context(:order_id)

get_context(key, default)

@spec get_context(atom() | String.t(), any()) :: any()

Gets a value from the context by key with a default.

Examples

count = get_context(:retry_count, 0)
count = get_context("retry_count", 0)

has_context?(key)

@spec has_context?(atom() | String.t()) :: boolean()

Checks if a key exists in the context.

Examples

if has_context?(:order_id) do
  # ...
end

increment_context(key, amount \\ 1)

@spec increment_context(atom() | String.t(), number()) :: :ok

Increments a numeric value in the context.

If the key doesn't exist, starts from 0.

Examples

increment_context(:retry_count, 1)
increment_context(:processed_items, 1)

input()

@spec input() :: map()

Returns the input the run was started with, as it is stored: its keys are strings, whatever they were when it was passed to Durable.start/3.

Examples

order_id = input()["order_id"]

last_attempt?()

@spec last_attempt?() :: boolean()

Returns true on the current step's last attempt: if it returns an error, the step won't be tried again.

Examples

step :charge, [retry: [max_attempts: 5]], fn ctx ->
  case Payments.charge(ctx["order"]) do
    {:ok, _} = ok -> ok
    {:error, reason} ->
      if last_attempt?(), do: Orders.mark_payment_failed(ctx["order"])
      {:error, reason}
  end
end

max_attempts()

@spec max_attempts() :: pos_integer()

Returns how many attempts the current step gets: its retry: [max_attempts: n], or 1 if it has no retry:.

merge_context(map)

@spec merge_context(map()) :: :ok

Deep merges a map into the context.

Examples

merge_context(%{settings: %{notifications: true}})

put_context(map)

@spec put_context(map()) :: :ok

Merges a map into the context.

Examples

put_context(%{order_id: 123, customer_id: 456})

put_context(key, value)

@spec put_context(atom() | String.t(), any()) :: :ok

Puts a single key-value pair into the context.

Examples

put_context(:order_id, 123)
put_context("order_id", 123)

shutting_down?()

@spec shutting_down?() :: boolean()

Returns true once this node has started shutting down.

The node finishes the step it's on, then hands the rest of the run to another node. A step that runs longer than the :shutdown_grace_period can check this and stop early. Snoozing doesn't use an attempt, and another node carries on straight away:

Examples

step :crawl, fn ctx ->
  for page <- pages_left(ctx), not shutting_down?(), do: crawl(page)

  if shutting_down?(),
    do: {:snooze, 0, "node stopping"},
    else: {:ok, ctx}
end

update_context(key, fun)

@spec update_context(atom() | String.t(), (any() -> any())) :: :ok

Updates a context value using a function.

Examples

update_context(:retry_count, &(&1 + 1))
update_context(:items, &[new_item | &1])

workflow_id()

@spec workflow_id() :: String.t() | nil

Returns the current workflow ID.

Examples

id = workflow_id()