Deal DSL
View as MarkdownDescribe each deal as data. One Flow then runs any deal, for any sellable item.
SDKs: Python · Go · TypeScript · Java · Rust
Shows: Workflow DSL.
The graph and this description cover the Python, Java, TypeScript, and Rust examples. The Go example extends the model; see 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
DealStateDataAttribute, which transitions read.
A Step that was cut off can run again, so each action gets an idempotency key 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.
# 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
)
Example: 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));
}
}
}
Example: 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,
});
}
}
Example: 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 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
Only the Go example 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 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:
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.
The Graph folds repeated rounds. The final round holds the delivery actions.

