---
title: "Deal DSL"
description: "把每笔交易描述成数据，再由同一个 Flow 运行任意交易、处理任意可销售的商品。"
canonical_url: "https://docs.superdurable.io/zh-Hans/examples/deal-dsl/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/use-cases/deal-dsl.mdx"
locale: "zh-Hans"
language: "python"
---

> 供 AI Agent 使用的全部页面索引：https://docs.superdurable.io/zh-Hans/llms.txt

# Deal DSL

本页代码为 Python。其他语言：[Go](https://docs.superdurable.io/zh-Hans/examples/deal-dsl.go.md) · [Java](https://docs.superdurable.io/zh-Hans/examples/deal-dsl.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/examples/deal-dsl.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/examples/deal-dsl.rust.md)

把每笔交易描述成数据，再由同一个 Flow 运行任意交易、处理任意可销售的商品。

**SDK：** Python · Go · TypeScript · Java · Rust

**展示：**[工作流 DSL](https://docs.superdurable.io/zh-Hans/design-patterns/workflow-dsl.md)。

**Flow 图：DealDSLFlow**

**Step 列表**

1. `InitializeDeal`（起始 Step）：Load the deal definition and enter its initial state. 下一步：`WaitForDealCondition`。 写入 `DealBuyerID`、`DealDefinition`、`DealItemID`、`DealProcessID`、`DealStateData`。
2. `EvaluateDealTransition`：Wait for the transition condition, then enter the next state or complete. 下一步：Flow 完成，或 `WaitForDealCondition`。 读取 `DealDefinition`、`DealStateData`；写入 `DealPendingCondition`。
3. `ExecuteDealAction`：Run one action of the current state, then the next action or the transition. 下一步：`ExecuteDealAction`（再次），或 `EvaluateDealTransition`。 读取 `DealDefinition`。
4. `WaitForDealCondition`：Wait for the state's precondition, then run its actions or evaluate its transition. 下一步：`ExecuteDealAction`，或 `EvaluateDealTransition`。 读取 `DealDefinition`；写入 `DealCurrentState`、`DealPendingCondition`。

**RPC 列表**

- `send_condition_message`：发布到 `DealConditionMessages`。

例子: [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)

上图和本页描述覆盖 Python、Java、TypeScript 和 Rust 示例。Go 示例扩展了这个模型，见 [Go 示例](https://docs.superdurable.io/zh-Hans/examples/deal-dsl.md#go-example)。

<a id="product-requirements"></a>

## 产品需求

<a id="产品需求"></a>

每个 Flow 是一位买家针对一件商品的一笔交易，商品可以是数据集、实体商品、订阅或服务。卖家的定义列出交易的各个状态、每个状态运行的动作、要等待的条件，以及状态转换。

- 所有被引用的状态和动作都必须存在。Go 示例在交易开始前校验整份定义，包括每个条件名称只属于一个等待。其他示例在开始时只检查初始状态，其余状态和动作在 Flow 运行时才解析。运行到缺失项的 Step 会失败，它的重试用完后 Flow 失败。
- 运行中的交易保留启动时的定义。修改只影响之后开始的交易。
- 一个状态可以在动作之前等待一条条件消息，在状态转换之前再等待一条。等待没有恰好收到一条消息时，Step 失败，不合并有歧义的输入。
- 状态转换拿状态数据中的一个值依次与各分支比较，第一个相等的分支决定下一个状态。没有相等的分支或缺少这个值时，进入兜底状态。
- 进入一个不带状态转换的状态时，交易结束。Flow 用累计的状态数据完成。
- 定义里可能有无出口的循环，Dex 会一直运行这样的 Flow。用校验或 Flow 超时来阻止非预期的循环。

<a id="flow-design"></a>

## Flow 设计

<a id="flow-设计"></a>

这个 Flow 是一个小型解释器。定义决定业务路径，图中的四种 Step 一直运行它，直到交易结束。

- **有限状态机**：当前状态和每一次转换都是显式的。当前状态是一个可以读取的 Attribute。
- **每次 Step execution 只运行一个动作**：一个状态的动作按声明顺序运行，每个动作单独提交。失败的付款单独重试，之前已完成的动作不会再运行。
- **键控 Channel**：每个条件名称是同一个 `ChannelMap` 的一个 key，所以定义增加条件不需要改代码。
- **共享状态 map**：条件消息和动作结果把键值更新合并进同一个 `DealStateData` Attribute，状态转换读取它。

被中断的 Step 可能再次运行，所以每个动作都拿到一个[幂等键](https://docs.superdurable.io/zh-Hans/concepts/step.md#idempotency-keys)，供服务方去重。幂等键是 `<Flow ID>/<StepExecutionID>`。同一个动作重试时它不变；循环再次运行同一个动作时它会变化。示例的动作是本地函数。它们更新状态数据并把键写进日志，不调用服务方。真实集成在每次重试时都把同一个键传给服务方。

<a id="core-implementation"></a>

## 核心实现

<a id="核心实现"></a>

每个标签页展示可运行示例中的 Flow 及其四个 Step。

**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
        )
```

例子: [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 示例

Go 示例用同样的四种 Step 运行一个更大的模型。每个状态可以在成为当前状态之前运行前置动作，之后运行后置动作，每次 Step execution 按声明顺序运行一个；它的状态转换是带决策的后置条件。它的 Attribute 名为 `stateData`、`processDefinition`、`currentState` 等，键控 Channel 是 `conditionMessages`。它还加入了保存可编辑定义的 PostgreSQL 目录和浏览器 UI。它的条件 RPC 会拒绝定义中没有的条件名称。它给每笔交易的流程、商品、买家、当前状态和等待中的条件建了索引，所以可以按这些字段搜索交易。

<a id="run-it"></a>

## 运行

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

只有 [Go 示例](https://github.com/superdurable/dex/tree/main/examples/go/products/deal-dsl)提供可运行的演示。它有自己的服务、UI 和 PostgreSQL 目录，所以不属于[在 playground 里运行一个示例](https://docs.superdurable.io/zh-Hans/install.md#run-an-example-from-the-playground)一节启动的 playground。请从仓库副本启动它。在 `examples/go` 目录下，这个脚本启动 PostgreSQL、Dex 和 Deal DSL 服务，再让三位买家按同一份定义完成交易：

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

在脚本打印的地址打开 Dex Web。这次完成的运行协商了交易、向买家收款并交付了商品。**Timeline** 按顺序列出它的事件。

[![已完成的 Deal DSL 运行的时间线](https://docs.superdurable.io/img/use-cases/deal-dsl-timeline.png)](https://docs.superdurable.io/zh-Hans/img/use-cases/deal-dsl-timeline.png)

**Graph** 折叠了重复的轮次。最后一轮包含交付动作。

[![已完成的 Deal DSL 运行的执行图](https://docs.superdurable.io/img/use-cases/deal-dsl-graph.png)](https://docs.superdurable.io/zh-Hans/img/use-cases/deal-dsl-graph.png)

<a id="next"></a>

## 下一步

<a id="下一步"></a>

- [微服务编排](https://docs.superdurable.io/zh-Hans/examples/microservice-orchestration.md)
- [设计模式](https://docs.superdurable.io/zh-Hans/design-patterns.md)
- [概念](https://docs.superdurable.io/zh-Hans/concepts.md)
