Deal DSL
查看 Markdown把每笔交易描述成数据,再由同一个 Flow 运行任意交易、处理任意可销售的商品。
SDK: Python · Go · TypeScript · Java · Rust
展示:工作流 DSL。
上图和本页描述覆盖 Python、Java、TypeScript 和 Rust 示例。Go 示例扩展了这个模型,见 Go 示例。
产品需求
每个 Flow 是一位买家针对一件商品的一笔交易,商品可以是数据集、实体商品、订阅或服务。卖家的定义列出交易的各个状态、每个状态运行的动作、要等待的条件,以及状态转换。
- 所有被引用的状态和动作都必须存在。Go 示例在交易开始前校验整份定义,包括每个条件名称只属于一个等待。其他示例在开始时只检查初始状态,其余状态和动作在 Flow 运行时才解析。运行到缺失项的 Step 会失败,它的重试用完后 Flow 失败。
- 运行中的交易保留启动时的定义。修改只影响之后开始的交易。
- 一个状态可以在动作之前等待一条条件消息,在状态转换之前再等待一条。等待没有恰好收到一条消息时,Step 失败,不合并有歧义的输入。
- 状态转换拿状态数据中的一个值依次与各分支比较,第一个相等的分支决定下一个状态。没有相等的分支或缺少这个值时,进入兜底状态。
- 进入一个不带状态转换的状态时,交易结束。Flow 用累计的状态数据完成。
- 定义里可能有无出口的循环,Dex 会一直运行这样的 Flow。用校验或 Flow 超时来阻止非预期的循环。
Flow 设计
这个 Flow 是一个小型解释器。定义决定业务路径,图中的四种 Step 一直运行它,直到交易结束。
- 有限状态机:当前状态和每一次转换都是显式的。当前状态是一个可以读取的 Attribute。
- 每次 Step execution 只运行一个动作:一个状态的动作按声明顺序运行,每个动作单独提交。失败的付款单独重试,之前已完成的动作不会再运行。
- 键控 Channel:每个条件名称是同一个
ChannelMap的一个 key,所以定义增加条件不需要改代码。 - 共享状态 map:条件消息和动作结果把键值更新合并进同一个
DealStateDataAttribute,状态转换读取它。
被中断的 Step 可能再次运行,所以每个动作都拿到一个幂等键,供服务方去重。幂等键是 <Flow ID>/<StepExecutionID>。同一个动作重试时它不变;循环再次运行同一个动作时它会变化。示例的动作是本地函数。它们更新状态数据并把键写进日志,不调用服务方。真实集成在每次重试时都把同一个键传给服务方。
核心实现
每个标签页展示可运行示例中的 Flow 及其四个 Step。
# 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,
)
@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
type DealDSLFlow struct {
dex.FlowDefaults
actions *actionRegistry
}
type ConditionMessage struct {
ConditionName string `json:"conditionName"`
Data map[string]string `json:"data"`
}
func NewDealDSLFlow(logger dex.Logger) *DealDSLFlow {
return &DealDSLFlow{
actions: newActionRegistry(logger),
}
}
func (flow *DealDSLFlow) GetSteps() []dex.StepDef {
return []dex.StepDef{
dex.DefineStartStep(initializeStep{flow: flow}),
dex.DefineStep(preConditionStep{flow: flow}),
dex.DefineStep(executeAction{flow: flow}),
dex.DefineStep(postConditionStep{flow: flow}),
}
}
func (flow *DealDSLFlow) GetRPCs() []dex.RPCDef {
return []dex.RPCDef{
dex.DefineRPC(flow.GetSnapshot, nil),
dex.DefineRPC(flow.SendConditionMessage, nil),
}
}
func (*DealDSLFlow) GetPersistenceSchema() dex.PersistenceSchema {
return dex.PersistenceSchema{
Attributes: []dex.AttributeDef{
StateData,
ProcessDefinition,
ProcessID,
ItemID,
BuyerID,
CurrentState,
CurrentActionIndexToExecute,
PendingPreConditionState,
PendingPreConditionName,
},
Channels: []dex.ChannelDef{ConditionMessages},
}
}
func (*DealDSLFlow) SendConditionMessage(
ctx dex.Context,
message ConditionMessage,
) (*dex.RPCResult[dex.None], error) {
process, err := ProcessDefinition.Get(ctx)
if err != nil {
return nil, err
}
if !process.HasCondition(message.ConditionName) {
return nil, fmt.Errorf("condition %q is not defined by this deal process", message.ConditionName)
}
if err := ConditionMessages.Publish(ctx, message.ConditionName, message.Data); err != nil {
return nil, err
}
return &dex.RPCResult[dex.None]{}, nil
}
type initializeStep struct {
dex.StepDefaultsNoWaitFor[DealStart]
flow *DealDSLFlow
}
func (step initializeStep) Execute(
ctx dex.Context,
input DealStart,
) (*dex.StepDecision, error) {
if err := ValidateProcess(input.Process); err != nil {
return nil, fmt.Errorf("deal process is invalid: %w", err)
}
if err := BuyerID.Set(ctx, input.BuyerID); err != nil {
return nil, err
}
if err := ProcessID.Set(ctx, input.Process.ProcessID); err != nil {
return nil, err
}
if err := ItemID.Set(ctx, input.Process.ItemID); err != nil {
return nil, err
}
if err := ProcessDefinition.Set(ctx, input.Process); err != nil {
return nil, err
}
if err := StateData.Set(ctx, input.Process.InitialStateData); err != nil {
return nil, err
}
if err := CurrentActionIndexToExecute.Set(ctx, 0); err != nil {
return nil, err
}
return dex.GoTo(
preConditionStep{flow: step.flow},
stateStepInput{StateName: input.Process.InitialState},
), nil
}
type preConditionStep struct {
dex.StepDefaults
flow *DealDSLFlow
}
func (step preConditionStep) WaitFor(
ctx dex.Context,
input stateStepInput,
) (*dex.Wait, error) {
process, err := ProcessDefinition.Get(ctx)
if err != nil {
return nil, err
}
state, err := process.State(input.StateName)
if err != nil {
return nil, err
}
if state.PreCondition == nil {
return dex.SkipWaitImmediately(), nil
}
if err := PendingPreConditionState.Set(ctx, state.Name); err != nil {
return nil, err
}
if err := PendingPreConditionName.Set(ctx, state.PreCondition.Name); err != nil {
return nil, err
}
return dex.Until(ConditionMessages.ForOne(state.PreCondition.Name)), nil
}
func (step preConditionStep) Execute(
ctx dex.Context,
input stateStepInput,
) (*dex.StepDecision, error) {
process, err := ProcessDefinition.Get(ctx)
if err != nil {
return nil, err
}
state, err := process.State(input.StateName)
if err != nil {
return nil, err
}
if state.PreCondition != nil {
updates, resultErr := conditionUpdates(ctx, state.PreCondition.Name)
if resultErr != nil {
return nil, resultErr
}
if err := mergeStateData(ctx, updates); err != nil {
return nil, err
}
if err := PendingPreConditionState.Delete(ctx); err != nil {
return nil, err
}
if err := PendingPreConditionName.Delete(ctx); err != nil {
return nil, err
}
}
if err := CurrentActionIndexToExecute.Set(ctx, 0); err != nil {
return nil, err
}
if len(state.PreActions) > 0 {
return dex.GoTo(
executeAction{flow: step.flow},
actionStepInput{StateName: state.Name, Phase: preActionPhase},
), nil
}
return step.flow.gotoState(ctx, state)
}
type executeAction struct {
dex.StepDefaultsNoWaitFor[actionStepInput]
flow *DealDSLFlow
}
func (step executeAction) Execute(
ctx dex.Context,
input actionStepInput,
) (*dex.StepDecision, error) {
process, err := ProcessDefinition.Get(ctx)
if err != nil {
return nil, err
}
state, err := process.State(input.StateName)
if err != nil {
return nil, err
}
actions, err := actionsForPhase(state, input.Phase)
if err != nil {
return nil, err
}
actionIndex, err := CurrentActionIndexToExecute.Get(ctx)
if err != nil {
return nil, err
}
if actionIndex < 0 || actionIndex >= len(actions) {
return nil, fmt.Errorf(
"action index %d is invalid for %s actions in state %q",
actionIndex,
input.Phase,
state.Name,
)
}
// StepExecutionID stays stable on retries and changes when the same action runs again.
idempotencyKey := ctx.FlowID() + "/" + ctx.StepExecutionID()
actionInput := ActionInput{
FlowID: ctx.FlowID(),
IdempotencyKey: idempotencyKey,
ItemID: process.ItemID,
ItemName: process.ItemName,
TargetState: state.Name,
}
actionInput.ProcessID, err = ProcessID.Get(ctx)
if err != nil {
return nil, err
}
actionInput.BuyerID, err = BuyerID.Get(ctx)
if err != nil {
return nil, err
}
actionInput.StateData, err = StateData.Get(ctx)
if err != nil {
return nil, err
}
updates, err := step.flow.actions.execute(actions[actionIndex], actionInput)
if err != nil {
return nil, err
}
if err := mergeStateData(ctx, updates); err != nil {
return nil, err
}
nextActionIndex := actionIndex + 1
if err := CurrentActionIndexToExecute.Set(ctx, nextActionIndex); err != nil {
return nil, err
}
if nextActionIndex < len(actions) {
return dex.GoTo(executeAction{flow: step.flow}, input), nil
}
if err := CurrentActionIndexToExecute.Set(ctx, 0); err != nil {
return nil, err
}
if input.Phase == preActionPhase {
return step.flow.gotoState(ctx, state)
}
return dex.GoTo(
postConditionStep{flow: step.flow},
stateStepInput{StateName: state.Name},
), nil
}
type postConditionStep struct {
dex.StepDefaults
flow *DealDSLFlow
}
func (step postConditionStep) WaitFor(
ctx dex.Context,
input stateStepInput,
) (*dex.Wait, error) {
process, err := ProcessDefinition.Get(ctx)
if err != nil {
return nil, err
}
state, err := process.State(input.StateName)
if err != nil {
return nil, err
}
if state.PostCondition == nil || state.PostCondition.WaitFor == nil {
return dex.SkipWaitImmediately(), nil
}
return dex.Until(ConditionMessages.ForOne(state.PostCondition.WaitFor.Name)), nil
}
func (step postConditionStep) Execute(
ctx dex.Context,
input stateStepInput,
) (*dex.StepDecision, error) {
process, err := ProcessDefinition.Get(ctx)
if err != nil {
return nil, err
}
state, err := process.State(input.StateName)
if err != nil {
return nil, err
}
if state.PostCondition == nil {
snapshot, err := readDealStateSnapshot(ctx)
if err != nil {
return nil, err
}
return dex.GracefulComplete(snapshot), nil
}
if state.PostCondition.WaitFor != nil {
updates, resultErr := conditionUpdates(ctx, state.PostCondition.WaitFor.Name)
if resultErr != nil {
return nil, resultErr
}
if err := mergeStateData(ctx, updates); err != nil {
return nil, err
}
}
stateData, err := StateData.Get(ctx)
if err != nil {
return nil, err
}
nextState := evaluateDecision(state.PostCondition.Decision, stateData)
return dex.GoTo(
preConditionStep{flow: step.flow},
stateStepInput{StateName: nextState},
), nil
}
func (flow *DealDSLFlow) gotoState(
ctx dex.Context,
state StateDefinition,
) (*dex.StepDecision, error) {
if err := CurrentState.Set(ctx, state.Name); err != nil {
return nil, err
}
if err := CurrentActionIndexToExecute.Set(ctx, 0); err != nil {
return nil, err
}
if len(state.PostActions) > 0 {
return dex.GoTo(
executeAction{flow: flow},
actionStepInput{StateName: state.Name, Phase: postActionPhase},
), nil
}
return dex.GoTo(
postConditionStep{flow: flow},
stateStepInput{StateName: state.Name},
), nil
}
@Component
public class DealDSLFlow implements Flow<DealStart> {
public final Attribute<DealDefinition> definition =
Attribute.define("DealDefinition", DealDefinition.class);
public final Attribute<Map> stateData = Attribute.define("DealStateData", Map.class);
public final Attribute<String> processId = Attribute.define("DealProcessID", String.class);
public final Attribute<String> itemId = Attribute.define("DealItemID", String.class);
public final Attribute<String> buyerId = Attribute.define("DealBuyerID", String.class);
public final Attribute<String> currentState =
Attribute.define("DealCurrentState", String.class);
public final Attribute<String> pendingCondition =
Attribute.define("DealPendingCondition", String.class);
public final ChannelMap<Map> conditionMessages =
ChannelMap.define("DealConditionMessages", Map.class);
private final InitializeDeal initialize = new InitializeDeal();
private final WaitForDealCondition waitForCondition = new WaitForDealCondition();
private final ExecuteDealAction executeAction = new ExecuteDealAction();
private final EvaluateDealTransition evaluateTransition = new EvaluateDealTransition();
@Override
public StepList<DealStart> getSteps() {
return StepList.startStep(initialize)
.otherSteps(waitForCondition, executeAction, evaluateTransition);
}
@RPC
public void sendConditionMessage(
final Context context,
final ConditionMessage message) {
conditionMessages.publish(context, message.conditionName, message.data);
}
@SuppressWarnings("unchecked")
private Map<String, String> readStateData(final Context context) {
return new LinkedHashMap<>((Map<String, String>) stateData.get(context));
}
@SuppressWarnings("unchecked")
private void mergeCondition(final Context context, final String conditionName) {
final List<Map> messages = conditionMessages.getConditionResults(context, conditionName);
if (messages.size() != 1) {
throw new IllegalStateException("condition " + conditionName + " requires one message");
}
final Map<String, String> merged = readStateData(context);
merged.putAll((Map<String, String>) messages.get(0));
stateData.set(context, merged);
}
private void runAction(final Context context, final String actionName, final String idempotencyKey) {
final Map<String, String> updated = readStateData(context);
if ("deliverItemToBuyer".equals(actionName)) {
updated.put("itemDeliveryStatus", "delivered");
} else if (!"chargeBuyer".equals(actionName)) {
throw new IllegalArgumentException("deal action " + actionName + " is not registered");
}
updated.put("lastAction", actionName);
stateData.set(context, updated);
System.getLogger(DealDSLFlow.class.getName()).log(
System.Logger.Level.INFO,
"Deal action {0} completed with idempotency key {1}", actionName, idempotencyKey);
}
final class InitializeDeal implements Step<DealStart> {
@Override
public StepDecision execute(final Context context, final DealStart input) {
input.definition.state(input.definition.initialState);
definition.set(context, input.definition);
processId.set(context, input.definition.processId);
itemId.set(context, input.definition.itemId);
buyerId.set(context, input.buyerId);
stateData.set(context, new LinkedHashMap<>(input.definition.initialStateData));
return StepDecision.goTo(
WaitForDealCondition.class,
new StateStepInput(input.definition.initialState));
}
}
final class WaitForDealCondition implements Step<StateStepInput> {
@Override
public Wait waitFor(final Context context, final StateStepInput input) {
final DealDefinition.DealState state = definition.get(context).state(input.stateName);
if (state.preCondition == null) {
return Wait.skipImmediately();
}
pendingCondition.set(context, state.preCondition.name);
return Wait.until(conditionMessages.forOne(state.preCondition.name));
}
@Override
public StepDecision execute(final Context context, final StateStepInput input) {
final DealDefinition.DealState state = definition.get(context).state(input.stateName);
if (state.preCondition != null) {
mergeCondition(context, state.preCondition.name);
pendingCondition.delete(context);
}
currentState.set(context, state.name);
if (!state.actions.isEmpty()) {
return StepDecision.goTo(
ExecuteDealAction.class,
new ActionStepInput(state.name, 0));
}
return StepDecision.goTo(EvaluateDealTransition.class, input);
}
}
final class ExecuteDealAction implements Step<ActionStepInput> {
@Override
public StepDecision execute(final Context context, final ActionStepInput input) {
final DealDefinition.DealState state = definition.get(context).state(input.stateName);
if (input.actionIndex < 0 || input.actionIndex >= state.actions.size()) {
throw new IllegalArgumentException("invalid action index " + input.actionIndex);
}
// The execution ID stays stable on retries and changes when the same action runs again.
final String idempotencyKey = context.getFlowId() + "/" + context.getStepExecutionId();
runAction(context, state.actions.get(input.actionIndex), idempotencyKey);
final int nextIndex = input.actionIndex + 1;
if (nextIndex < state.actions.size()) {
return StepDecision.goTo(
ExecuteDealAction.class,
new ActionStepInput(state.name, nextIndex));
}
return StepDecision.goTo(
EvaluateDealTransition.class,
new StateStepInput(state.name));
}
}
final class EvaluateDealTransition implements Step<StateStepInput> {
@Override
public Wait waitFor(final Context context, final StateStepInput input) {
final DealDefinition.DealTransition transition =
definition.get(context).state(input.stateName).transition;
if (transition == null || transition.waitFor == null) {
return Wait.skipImmediately();
}
pendingCondition.set(context, transition.waitFor.name);
return Wait.until(conditionMessages.forOne(transition.waitFor.name));
}
@Override
public StepDecision execute(final Context context, final StateStepInput input) {
final DealDefinition.DealTransition transition =
definition.get(context).state(input.stateName).transition;
if (transition == null) {
return StepDecision.gracefulComplete(readStateData(context));
}
if (transition.waitFor != null) {
mergeCondition(context, transition.waitFor.name);
pendingCondition.delete(context);
}
final String value = readStateData(context).get(transition.key);
final String nextState = transition.cases.stream()
.filter(dealCase -> dealCase.equals.equals(value))
.map(dealCase -> dealCase.goToState)
.findFirst()
.orElse(transition.elseState);
return StepDecision.goTo(
WaitForDealCondition.class,
new StateStepInput(nextState));
}
}
}
例子: examples/java/src/main/java/io/superdurable/dex/products/dealdsl/DealDSLFlow.java
export class DealDSLFlow implements Flow<DealStart> {
public readonly definition = new Attribute("DealDefinition", dealDefinitionCodec);
public readonly stateData = new Attribute("DealStateData", stateDataCodec);
public readonly processId = new Attribute("DealProcessID", stringCodec);
public readonly itemId = new Attribute("DealItemID", stringCodec);
public readonly buyerId = new Attribute("DealBuyerID", stringCodec);
public readonly currentState = new Attribute("DealCurrentState", stringCodec);
public readonly pendingCondition = new Attribute("DealPendingCondition", stringCodec);
public readonly conditionMessages = new ChannelMap("DealConditionMessages", stateDataCodec);
public readonly initialize = new InitializeDeal(this);
public readonly waitForCondition = new WaitForDealCondition(this);
public readonly executeActionStep = new ExecuteDealAction(this);
public readonly evaluateTransition = new EvaluateDealTransition(this);
public getSteps() {
return StepList.startStep(this.initialize).otherSteps(
this.waitForCondition,
this.executeActionStep,
this.evaluateTransition,
);
}
@rpc({ inputCodec: conditionMessageCodec })
public sendConditionMessage(context: Context, message: ConditionMessage): void {
this.conditionMessages.publish(context, message.conditionName, message.values);
}
public state(context: Context, stateName: string): DealState {
const state = this.definition.get(context).states.find(({ name }) => name === stateName);
if (state === undefined) throw new Error(`deal state ${stateName} is not defined`);
return state;
}
public mergeCondition(context: Context, conditionName: string): void {
const messages = this.conditionMessages.results(context, conditionName);
if (messages.length !== 1) {
throw new Error(`condition ${conditionName} requires one message`);
}
this.stateData.set(context, {
...this.stateData.get(context),
...messages[0],
});
}
public executeAction(context: Context, actionName: string, idempotencyKey: string): void {
const stateData = { ...this.stateData.get(context) };
if (actionName === "deliverItemToBuyer") {
stateData.itemDeliveryStatus = "delivered";
} else if (actionName !== "chargeBuyer") {
throw new Error(`deal action ${actionName} is not registered`);
}
stateData.lastAction = actionName;
this.stateData.set(context, stateData);
console.info("Deal action completed", { actionName, idempotencyKey });
}
}
class InitializeDeal implements Step<DealStart> {
public readonly inputCodec = dealStartCodec;
public constructor(private readonly flow: DealDSLFlow) {}
public execute(context: Context, input: DealStart): StepDecision {
this.flow.definition.set(context, input.definition);
this.flow.processId.set(context, input.definition.processId);
this.flow.itemId.set(context, input.definition.itemId);
this.flow.buyerId.set(context, input.buyerId);
this.flow.stateData.set(context, { ...input.definition.initialStateData });
this.flow.state(context, input.definition.initialState);
return goTo(WaitForDealCondition, { stateName: input.definition.initialState });
}
}
class WaitForDealCondition implements Step<StateStepInput> {
public readonly inputCodec = stateStepInputCodec;
public constructor(private readonly flow: DealDSLFlow) {}
public waitFor(context: Context, input: StateStepInput): Wait {
const condition = this.flow.state(context, input.stateName).preCondition;
if (condition === undefined) return Wait.skipImmediately();
this.flow.pendingCondition.set(context, condition.name);
return Wait.until(this.flow.conditionMessages.forOne(condition.name));
}
public execute(context: Context, input: StateStepInput): StepDecision {
const state = this.flow.state(context, input.stateName);
if (state.preCondition !== undefined) {
this.flow.mergeCondition(context, state.preCondition.name);
this.flow.pendingCondition.delete(context);
}
this.flow.currentState.set(context, state.name);
if ((state.actions?.length ?? 0) > 0) {
return goTo(ExecuteDealAction, { stateName: state.name, actionIndex: 0 });
}
return goTo(EvaluateDealTransition, input);
}
}
class ExecuteDealAction implements Step<ActionStepInput> {
public readonly inputCodec = actionStepInputCodec;
public constructor(private readonly flow: DealDSLFlow) {}
public execute(context: Context, input: ActionStepInput): StepDecision {
const state = this.flow.state(context, input.stateName);
const action = state.actions?.[input.actionIndex];
if (action === undefined) throw new Error(`invalid action index ${input.actionIndex}`);
// The execution ID stays stable on retries and changes when the same action runs again.
const idempotencyKey = `${context.flowId}/${context.stepExecutionId}`;
this.flow.executeAction(context, action, idempotencyKey);
const nextIndex = input.actionIndex + 1;
if (nextIndex < (state.actions?.length ?? 0)) {
return goTo(ExecuteDealAction, { stateName: state.name, actionIndex: nextIndex });
}
return goTo(EvaluateDealTransition, { stateName: state.name });
}
}
class EvaluateDealTransition implements Step<StateStepInput> {
public readonly inputCodec = stateStepInputCodec;
public constructor(private readonly flow: DealDSLFlow) {}
public waitFor(context: Context, input: StateStepInput): Wait {
const condition = this.flow.state(context, input.stateName).transition?.waitFor;
if (condition === undefined) return Wait.skipImmediately();
this.flow.pendingCondition.set(context, condition.name);
return Wait.until(this.flow.conditionMessages.forOne(condition.name));
}
public execute(context: Context, input: StateStepInput): StepDecision {
const transition = this.flow.state(context, input.stateName).transition;
if (transition === undefined) return gracefulComplete(this.flow.stateData.get(context));
if (transition.waitFor !== undefined) {
this.flow.mergeCondition(context, transition.waitFor.name);
this.flow.pendingCondition.delete(context);
}
const stateData = this.flow.stateData.get(context);
const matched = transition.cases?.find(
(dealCase) => stateData[transition.key ?? ""] === dealCase.equals,
);
return goTo(WaitForDealCondition, {
stateName: matched?.goToState ?? transition.elseState,
});
}
}
例子: examples/typescript/src/products/deal-dsl/deal-dsl-flow.ts
#[derive(Default)]
pub struct DealDSLFlow {
initialize: InitializeDeal,
wait_for_condition: WaitForDealCondition,
execute_action: ExecuteDealAction,
evaluate_transition: EvaluateDealTransition,
}
impl DealDSLFlow {
fn send_condition_message(
&self,
context: &mut Context,
message: ConditionMessage,
) -> HandlerResult<()> {
DEAL_CONDITION_MESSAGES.publish(context, &message.condition_name, message.values)
}
}
impl Flow for DealDSLFlow {
type StartInput = DealStart;
fn steps(&self) -> StepList<'_, Self::StartInput> {
StepList::start(&self.initialize)
.and(&self.wait_for_condition)
.and(&self.execute_action)
.and(&self.evaluate_transition)
}
fn rpcs(&self) -> RpcList<Self> {
RpcList::new().procedure(SEND_DEAL_CONDITION_MESSAGE, Self::send_condition_message)
}
}
#[derive(Default)]
pub(super) struct InitializeDeal;
impl Step for InitializeDeal {
type Input = DealStart;
fn execute(&self, context: &mut Context, input: Self::Input) -> HandlerResult<StepDecision> {
deal_state(&input.definition, &input.definition.initial_state)?;
DEAL_DEFINITION.set(context, input.definition.clone())?;
DEAL_PROCESS_ID.set(context, input.definition.process_id.clone())?;
DEAL_ITEM_ID.set(context, input.definition.item_id.clone())?;
DEAL_BUYER_ID.set(context, input.buyer_id)?;
DEAL_STATE_DATA.set(context, input.definition.initial_state_data)?;
Ok(StepDecision::go_to(
&WaitForDealCondition,
StateStepInput {
state_name: input.definition.initial_state,
},
))
}
}
#[derive(Default)]
pub(super) struct WaitForDealCondition;
impl Step for WaitForDealCondition {
type Input = StateStepInput;
fn wait_for(&self, context: &mut Context, input: Self::Input) -> HandlerResult<Wait> {
let definition = DEAL_DEFINITION.get_required(context)?;
let state = deal_state(&definition, &input.state_name)?;
let Some(condition) = state.pre_condition else {
return Ok(Wait::skip_immediately());
};
DEAL_PENDING_CONDITION.set(context, condition.name.clone())?;
Ok(Wait::until(
DEAL_CONDITION_MESSAGES.for_one(&condition.name),
))
}
fn execute(&self, context: &mut Context, input: Self::Input) -> HandlerResult<StepDecision> {
let definition = DEAL_DEFINITION.get_required(context)?;
let state = deal_state(&definition, &input.state_name)?;
if let Some(condition) = state.pre_condition {
merge_condition(context, &condition.name)?;
DEAL_PENDING_CONDITION.delete(context)?;
}
DEAL_CURRENT_STATE.set(context, state.name.clone())?;
if state.actions.is_empty() {
return Ok(StepDecision::go_to(&EvaluateDealTransition, input));
}
Ok(StepDecision::go_to(
&ExecuteDealAction,
ActionStepInput {
state_name: state.name,
action_index: 0,
},
))
}
}
#[derive(Default)]
pub(super) struct ExecuteDealAction;
impl Step for ExecuteDealAction {
type Input = ActionStepInput;
fn execute(&self, context: &mut Context, input: Self::Input) -> HandlerResult<StepDecision> {
let definition = DEAL_DEFINITION.get_required(context)?;
let state = deal_state(&definition, &input.state_name)?;
let action = state.actions.get(input.action_index).ok_or_else(|| {
HandlerError::new(
"InvalidDealDSL",
format!("invalid action index {}", input.action_index),
)
})?;
// The execution ID stays stable on retries and changes when the same action runs again.
let idempotency_key = format!("{}/{}", context.flow_id(), context.step_execution_id());
run_action(context, action, &idempotency_key)?;
let next_index = input.action_index + 1;
if next_index < state.actions.len() {
return Ok(StepDecision::go_to(
&ExecuteDealAction,
ActionStepInput {
state_name: state.name,
action_index: next_index,
},
));
}
Ok(StepDecision::go_to(
&EvaluateDealTransition,
StateStepInput {
state_name: state.name,
},
))
}
}
#[derive(Default)]
pub(super) struct EvaluateDealTransition;
impl Step for EvaluateDealTransition {
type Input = StateStepInput;
fn wait_for(&self, context: &mut Context, input: Self::Input) -> HandlerResult<Wait> {
let definition = DEAL_DEFINITION.get_required(context)?;
let state = deal_state(&definition, &input.state_name)?;
let Some(condition) = state.transition.and_then(|transition| transition.wait_for) else {
return Ok(Wait::skip_immediately());
};
DEAL_PENDING_CONDITION.set(context, condition.name.clone())?;
Ok(Wait::until(
DEAL_CONDITION_MESSAGES.for_one(&condition.name),
))
}
fn execute(&self, context: &mut Context, input: Self::Input) -> HandlerResult<StepDecision> {
let definition = DEAL_DEFINITION.get_required(context)?;
let state = deal_state(&definition, &input.state_name)?;
let Some(transition) = state.transition else {
return Ok(StepDecision::graceful_complete(
DEAL_STATE_DATA.get_required(context)?,
));
};
if let Some(condition) = transition.wait_for {
merge_condition(context, &condition.name)?;
DEAL_PENDING_CONDITION.delete(context)?;
}
let state_data = DEAL_STATE_DATA.get_required(context)?;
let value = state_data.get(&transition.key);
let next_state = transition
.cases
.iter()
.find(|deal_case| value == Some(&deal_case.equals))
.map_or(transition.else_state, |deal_case| {
deal_case.go_to_state.clone()
});
Ok(StepDecision::go_to(
&WaitForDealCondition,
StateStepInput {
state_name: next_state,
},
))
}
}
Go 示例
Go 示例用同样的四种 Step 运行一个更大的模型。每个状态可以在成为当前状态之前运行前置动作,之后运行后置动作,每次 Step execution 按声明顺序运行一个;它的状态转换是带决策的后置条件。它的 Attribute 名为 stateData、processDefinition、currentState 等,键控 Channel 是 conditionMessages。它还加入了保存可编辑定义的 PostgreSQL 目录和浏览器 UI。它的条件 RPC 会拒绝定义中没有的条件名称。它给每笔交易的流程、商品、买家、当前状态和等待中的条件建了索引,所以可以按这些字段搜索交易。
运行
只有 Go 示例提供可运行的演示。它有自己的服务、UI 和 PostgreSQL 目录,所以不属于在 playground 里运行一个示例一节启动的 playground。请从仓库副本启动它。在 examples/go 目录下,这个脚本启动 PostgreSQL、Dex 和 Deal DSL 服务,再让三位买家按同一份定义完成交易:
KEEP_DEAL_DSL_DEMO=1 make dealDSLDemo
在脚本打印的地址打开 Dex Web。这次完成的运行协商了交易、向买家收款并交付了商品。Timeline 按顺序列出它的事件。
Graph 折叠了重复的轮次。最后一轮包含交付动作。

