---
title: "Deal DSL"
description: "Describe each deal as data. One Flow then runs any deal, for any sellable item."
canonical_url: "https://docs.superdurable.io/examples/deal-dsl/"
source: "docs/content/use-cases/deal-dsl.mdx"
locale: "en"
language: "python"
---

> Index of every page for AI agents: https://docs.superdurable.io/llms.txt

# Deal DSL

Code on this page is in Python. Other languages: [Go](https://docs.superdurable.io/examples/deal-dsl.go.md) · [Java](https://docs.superdurable.io/examples/deal-dsl.java.md) · [TypeScript](https://docs.superdurable.io/examples/deal-dsl.typescript.md) · [Rust](https://docs.superdurable.io/examples/deal-dsl.rust.md)

Describe each deal as data. One Flow then runs any deal, for any sellable item.

**SDKs:** Python · Go · TypeScript · Java · Rust

**Shows:** [Workflow DSL](https://docs.superdurable.io/design-patterns/workflow-dsl.md).

**Flow graph: DealDSLFlow**

**Steps**

1. `InitializeDeal` (start Step): Load the deal definition and enter its initial state. Next: `WaitForDealCondition`. Writes `DealBuyerID`, `DealDefinition`, `DealItemID`, `DealProcessID`, `DealStateData`.
2. `EvaluateDealTransition`: Wait for the transition condition, then enter the next state or complete. Next: the Flow completes, or `WaitForDealCondition`. Reads `DealDefinition`, `DealStateData`; writes `DealPendingCondition`.
3. `ExecuteDealAction`: Run one action of the current state, then the next action or the transition. Next: `ExecuteDealAction` again, or `EvaluateDealTransition`. Reads `DealDefinition`.
4. `WaitForDealCondition`: Wait for the state's precondition, then run its actions or evaluate its transition. Next: `ExecuteDealAction`, or `EvaluateDealTransition`. Reads `DealDefinition`; writes `DealCurrentState`, `DealPendingCondition`.

**RPCs**

- `send_condition_message`: Publishes to `DealConditionMessages`.

Example: [examples/python/dex_examples/products/deal_dsl/deal_dsl_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/deal_dsl/deal_dsl_flow.py)

The graph and this description cover the Python, Java, TypeScript, and Rust examples. The Go example extends the model; see [Go example](https://docs.superdurable.io/examples/deal-dsl.md#go-example).

## Product requirements

Each Flow is one buyer's deal for one item, such as a dataset, a physical product, a subscription, or a service. The seller's definition lists the deal's states, the actions each state runs, the conditions it waits for, and its transitions.

- Every referenced state and action must exist. The Go example validates the whole definition before a deal starts, including that each condition name belongs to exactly one wait. The other examples check the initial state at start and resolve the other states and actions as the Flow runs. A missing one fails the Step that reaches it, and the Flow fails when that Step's retries run out.
- A running deal keeps the definition it started with. Edits apply to deals that start later.
- A state can wait for one condition message before its actions, and another before its transition. The Step fails unless the wait gets exactly one message, instead of merging ambiguous input.
- A transition compares one state-data value with its cases, in order. The first equal case picks the next state. Otherwise, or when the value is missing, the fallback state is next.
- A state without a transition ends the deal. The Flow completes with the accumulated state data.
- A definition can loop with no exit, and Dex keeps such a Flow running. Stop unwanted loops with validation or a Flow timeout.

## Flow design

The Flow is a small interpreter. The definition picks the business path, and the four Step types in the graph run it until the deal ends.

- **Finite-state machine**: the current state and every transition are explicit. The current state is an Attribute you can read.
- **One action per Step execution**: a state's actions run in declared order, and each commits on its own. A failed payment retries alone, and earlier completed actions do not run again.
- **Keyed Channel**: each condition name is a key of one `ChannelMap`, so a definition adds conditions without code changes.
- **Shared state map**: condition messages and action results merge key-value updates into one `DealStateData` Attribute, which transitions read.

A Step that was cut off can run again, so each action gets an [idempotency key](https://docs.superdurable.io/concepts/step.md#idempotency-keys) for the provider to deduplicate. The key is `<Flow ID>/<StepExecutionID>`. It stays the same across retries of one action and changes when a loop runs the same action again. The example's actions are local functions. They update the state data and log the key, and make no provider call. A real integration passes the same key to the provider on each retry.

## Core implementation

Each tab shows the Flow and its four Steps from the runnable example.

**Python**

```python
# dex:group group-id:setup group-label:"Setup"
# dex:explanation text:"Load the deal definition and enter its initial state."
class InitializeDeal(Step[DealStart]):
    def __init__(self, flow: "DealDSLFlow") -> None:
        self.flow = flow

    def execute(self, context: Context, input: DealStart) -> StepDecision:
        definition = input.definition
        definition.state(definition.initial_state)
        self.flow.definition.set(context, definition)
        self.flow.process_id.set(context, definition.process_id)
        self.flow.item_id.set(context, definition.item_id)
        self.flow.buyer_id.set(context, input.buyer_id)
        self.flow.state_data.set(context, dict(definition.initial_state_data))
        return go_to(WaitForDealCondition, StateStepInput(definition.initial_state))


# dex:group group-id:deal-state group-label:"Deal state"
# dex:explanation text:"Wait for the state's precondition, then run its actions or evaluate its transition."
class WaitForDealCondition(Step[StateStepInput]):
    def __init__(self, flow: "DealDSLFlow") -> None:
        self.flow = flow

    def wait_for(self, context: Context, input: StateStepInput) -> Wait:
        state = self.flow.definition.get(context).state(input.state_name)
        if state.pre_condition is None:
            return Wait.skip_immediately()
        self.flow.pending_condition.set(context, state.pre_condition.name)
        return Wait.until(self.flow.condition_messages.for_one(state.pre_condition.name))

    def execute(self, context: Context, input: StateStepInput) -> StepDecision:
        state = self.flow.definition.get(context).state(input.state_name)
        if state.pre_condition is not None:
            self.flow.merge_condition(context, state.pre_condition.name)
            self.flow.pending_condition.delete(context)
        self.flow.current_state.set(context, state.name)
        if state.actions:
            return go_to(ExecuteDealAction, ActionStepInput(state.name, 0))
        return go_to(EvaluateDealTransition, input)


# dex:group group-id:actions group-label:"Actions"
# dex:explanation text:"Run one action of the current state, then the next action or the transition."
class ExecuteDealAction(Step[ActionStepInput]):
    def __init__(self, flow: "DealDSLFlow") -> None:
        self.flow = flow

    def execute(self, context: Context, input: ActionStepInput) -> StepDecision:
        state = self.flow.definition.get(context).state(input.state_name)
        if input.action_index < 0 or input.action_index >= len(state.actions):
            raise ValueError(f"invalid action index {input.action_index}")
        # The execution ID stays stable on retries and changes when the same action runs again.
        idempotency_key = f"{context.flow_id}/{context.step_execution_id}"
        self.flow.execute_action(
            context, state.actions[input.action_index], idempotency_key
        )
        next_index = input.action_index + 1
        if next_index < len(state.actions):
            return go_to(ExecuteDealAction, ActionStepInput(state.name, next_index))
        return go_to(EvaluateDealTransition, StateStepInput(state.name))


# dex:group group-id:transition group-label:"Transition"
# dex:explanation text:"Wait for the transition condition, then enter the next state or complete."
class EvaluateDealTransition(Step[StateStepInput]):
    def __init__(self, flow: "DealDSLFlow") -> None:
        self.flow = flow

    def wait_for(self, context: Context, input: StateStepInput) -> Wait:
        transition = self.flow.definition.get(context).state(input.state_name).transition
        if transition is None or transition.wait_for is None:
            return Wait.skip_immediately()
        self.flow.pending_condition.set(context, transition.wait_for.name)
        return Wait.until(self.flow.condition_messages.for_one(transition.wait_for.name))

    def execute(self, context: Context, input: StateStepInput) -> StepDecision:
        transition = self.flow.definition.get(context).state(input.state_name).transition
        if transition is None:
            return graceful_complete(self.flow.state_data.get(context))
        if transition.wait_for is not None:
            self.flow.merge_condition(context, transition.wait_for.name)
            self.flow.pending_condition.delete(context)
        state_data = self.flow.state_data.get(context)
        next_state = transition.else_state
        for deal_case in transition.cases:
            if state_data.get(transition.key) == deal_case.equals:
                next_state = deal_case.go_to_state
                break
        return go_to(WaitForDealCondition, StateStepInput(next_state))


class DealDSLFlow(Flow[DealStart]):
    definition = Attribute("DealDefinition", DealDefinition)
    state_data = Attribute("DealStateData", dict[str, str])
    process_id = Attribute("DealProcessID", str)
    item_id = Attribute("DealItemID", str)
    buyer_id = Attribute("DealBuyerID", str)
    current_state = Attribute("DealCurrentState", str)
    pending_condition = Attribute("DealPendingCondition", str)
    condition_messages = ChannelMap("DealConditionMessages", dict[str, str])

    def __init__(self) -> None:
        self.initialize = InitializeDeal(self)
        self.wait_for_condition = WaitForDealCondition(self)
        self.execute_action_step = ExecuteDealAction(self)
        self.evaluate_transition = EvaluateDealTransition(self)

    def get_steps(self) -> StepList[DealStart]:
        return StepList.start_step(self.initialize).other_steps(
            self.wait_for_condition,
            self.execute_action_step,
            self.evaluate_transition,
        )

    def get_persistence_schema(self) -> PersistenceSchema:
        return PersistenceSchema.of(
            self.definition,
            self.state_data,
            self.process_id,
            self.item_id,
            self.buyer_id,
            self.current_state,
            self.pending_condition,
            self.condition_messages,
        )

    @rpc
    def send_condition_message(
        self,
        context: Context,
        input: ConditionMessage,
    ) -> None:
        self.condition_messages.publish(context, input.condition_name, input.values)

    def merge_condition(self, context: Context, condition_name: str) -> None:
        messages = self.condition_messages.results(context, condition_name)
        if len(messages) != 1:
            raise ValueError(f"condition {condition_name!r} requires one message")
        state_data = dict(self.state_data.get(context))
        state_data.update(messages[0])
        self.state_data.set(context, state_data)

    def execute_action(
        self, context: Context, action_name: str, idempotency_key: str
    ) -> None:
        state_data = dict(self.state_data.get(context))
        if action_name == "deliverItemToBuyer":
            state_data["itemDeliveryStatus"] = "delivered"
        elif action_name != "chargeBuyer":
            raise ValueError(f"deal action {action_name!r} is not registered")
        state_data["lastAction"] = action_name
        self.state_data.set(context, state_data)
        logging.getLogger(__name__).info(
            "Deal action %s completed with idempotency key %s", action_name, idempotency_key
        )
```

Example: [examples/python/dex_examples/products/deal_dsl/deal_dsl_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/deal_dsl/deal_dsl_flow.py)

<a id="go-example"></a>

## Go example

The Go example runs the same four Step types on a larger model. Each state can run pre-actions before it becomes the current state and post-actions after, one per Step execution in declared order, and its transition is a post-condition with a decision. Its Attributes are named `stateData`, `processDefinition`, `currentState`, and so on, and its keyed Channel is `conditionMessages`. It adds a PostgreSQL catalog of editable definitions and a browser UI. Its condition RPC rejects a condition name the definition does not define. It indexes each deal's process, item, buyer, current state, and pending condition, so search finds deals by them.

## Run it

<a id="demo"></a>

Only the [Go example](https://github.com/superdurable/dex/tree/main/examples/go/products/deal-dsl) has a runnable demo. It has its own server, UI, and PostgreSQL catalog, so it is not part of the playground that [Run an example from the playground](https://docs.superdurable.io/install.md#run-an-example-from-the-playground) starts. Run it from a clone of the repository. From the `examples/go` folder, this script starts PostgreSQL, Dex, and the Deal DSL server, then drives three buyers through one definition:

```bash
KEEP_DEAL_DSL_DEMO=1 make dealDSLDemo
```

Open Dex Web at the URL the script prints. This completed run negotiated a deal, charged the buyer, and delivered the item. The **Timeline** lists its events in order.

[![Timeline of a completed Deal DSL run](https://docs.superdurable.io/img/use-cases/deal-dsl-timeline.png)](https://docs.superdurable.io/img/use-cases/deal-dsl-timeline.png)

The **Graph** folds repeated rounds. The final round holds the delivery actions.

[![Execution graph of a completed Deal DSL run](https://docs.superdurable.io/img/use-cases/deal-dsl-graph.png)](https://docs.superdurable.io/img/use-cases/deal-dsl-graph.png)

## Next

- [Microservice Orchestration](https://docs.superdurable.io/examples/microservice-orchestration.md)
- [Design Patterns](https://docs.superdurable.io/design-patterns.md)
- [Concepts](https://docs.superdurable.io/concepts.md)
