Workflow DSL
View as MarkdownDefine workflows at runtime as data, usually JSON, store them, and run every one with a single interpreter Flow. Use this pattern when every workflow is built from the same set of actions and external conditions.
Operators, customers, partners, or another system can define a workflow. The definition follows a serializable schema and lives in your application's versioned definition store. Users can edit, copy, import, and export these documents. Adding a workflow means adding a JSON document. It requires no code change or release.
For example, a seller can define one purchase workflow that charges a buyer after confirmation and another that sends a sample first. Both definitions use the same interpreter.
How it works
- Save and validate the definition. At the application boundary, check the definition on save and before starting a Flow. Check that every referenced state, action, and condition name exists and that each condition name belongs to one wait. Reject an invalid definition before it can start a Flow.
- Start the purchase. The start Step saves the whole definition in an Attribute and initializes a shared state data map. The run advances one position at a time. After startup, each Step input carries only the position, such as the state name and action index.
- Wait for the buyer. Before entering a state, wait for its condition if it has one. The RPC checks the condition name against the definition and publishes to one
ChannelMapkeyed by condition name. The persistence schema declares the map in code, and each definition supplies its keys at runtime. Each wait takes one message. The interpreter merges that message into the shared state data map. - Run one action. For a charge or a delivery, run the registered handler or script in one Step's
Execute. Treat a script like any external call and give it retries and an idempotency key. Give it a timeout too when it can block without observing cancellation. Merge the result into the shared map. Each action has its own checkpoint, so retrying it leaves earlier completed actions intact. - Choose what happens next. The transition Step can wait for another condition and merges its message into the same map. It reads the map to choose the next state. The interpreter uses
GoToto advance through these four Step types until the purchase reaches a state with no next transition. - Record progress. The definition decides what progress means, such as the current state, current step, or a custom stage. Write it to Attributes so the Client can read it. Use Attribute Sync when progress must be searchable. The Flow graph shows the interpreter Steps. The Attributes show where a particular purchase is in its workflow.
Example
The wait Step takes one message from the ChannelMap using the condition name as the key. It merges the message into the shared state data. The action Step runs one action, then routes to the next action or the transition. Each tab links to the full runnable example.
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))
Example: examples/python/dex_examples/products/deal_dsl/deal_dsl_flow.py
func (preConditionStep) GetStepType() string {
return "WaitForDealCondition"
}
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 (executeAction) GetStepType() string {
return "ExecuteDealAction"
}
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
}
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 Class<ActionStepInput> getInputType() {
return ActionStepInput.class;
}
@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));
}
}
Example: examples/java/src/main/java/io/superdurable/dex/products/dealdsl/DealDSLFlow.java
class WaitForDealCondition implements Step<StateStepInput> {
public getStepType(): string {
return "WaitForDealCondition";
}
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 getStepType(): string {
return "ExecuteDealAction";
}
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 });
}
}
Example: examples/typescript/src/products/deal-dsl/deal-dsl-flow.ts
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,
},
))
}
}
Definition versions
| Approach | What a run uses | What edits change |
|---|---|---|
| Snapshot at start | The start Step stores the full definition in an Attribute. Later Steps read that copy. This is what Deal DSL does. | New versions apply to newly started Flows. Running Flows keep their original definition. |
| Read the latest definition | Read from the store in Execute on each state entry or transition evaluation. Treat the read as an external call that can fail and retry. | Edits reach running Flows. A state can be renamed or removed, and an awaited condition can disappear. Define compatibility rules or migrate the saved position between versions. |
Parallel branches
If a state can open several branches, start them with GoToMany and keep each branch's position in its own Step input. Bring them together at a Join. Use an Attribute lock for concurrent writes to shared state, or let each branch write its own data and merge it after the Join. See Parallel Steps and Critical Section.