The Chenile story · Data and workflows · 2 of 3

Workflows: the flow is data

A Chenile workflow keeps the flow in a states XML that a business analyst can read and keeps the code in small components the state machine finds by name. One polymorphic operation serves every event, automatic states chain decisions until a person is needed, post-save hooks carry the after-effects, second transition actions let other teams join a transition, enablement changes the flow per tenant without touching the XML, and stm-cli draws the flow and derives its tests.

The flow is data

A workflow entity, such as an issue, an order or a claim, changes only through events. Which events are allowed in which state, which state each one leads to, who may raise it and what metadata travels with it are written once, in a states XML read by Finito, Chenile’s state machine. The code is a set of small components, and the state machine finds them by name.

The How it works tab shows one event travelling through all of this. This page explains the decisions behind it, one at a time.

One operation for every event

Every event of every workflow goes through one operation:

PATCH /{entity}/{id}/{eventID}      →   processById(id, eventID, payload)

The obvious alternative is a method per event: resolve(id, ResolvePayload), close(id, ClosePayload) and so on. It reads well, and the framework would be simpler for it: each method declares its own payload type and its own security, and nothing has to work them out at run time.

Chenile chose the polymorphic operation on purpose, because a method per event puts the flow back into Java. A new event would need a new endpoint, a new controller method, new security annotations and a new client call, and the states XML would no longer be the whole truth about the workflow. With one operation:

  • A new event is a line in the states XML and, if it needs logic, one transition action. The controller, the service and the clients do not change.
  • The client learns what it may do next from the response. Every response carries allowedActionsAndMetadata: the events allowed from the new state, already filtered by security. A user interface builds its buttons from it instead of hard-coding the flow.
  • Everything else per event is derived from the flow. Authorities come from each event’s acls, MCP tools are published one per event, and test cases are generated from the transitions (see below).

The cost lands in the framework, which has to recover what a typed method would have declared. That is StmBodyTypeSelector. For each request it reads the eventID, finds the transition action that will handle it and takes the payload type from the second type argument of that action’s transitionTo(...). When an event has no such action, it falls back to a meta-bodyType in the states XML. The same component is the operation’s polymorph provider: it publishes one variant per event, typed by that event’s payload and guarded by that event’s acls. The complexity is written once, in the framework, so that no workflow pays for it.

A pure state machine: components found by name

The states XML names states, events and transitions. It does not name Spring beans or Java classes. The state machine asks STMTransitionActionResolver for the component it needs, and the resolver builds the bean name from the workflow’s prefix and the event or state:

Component When it runs Name for prefix issue (suffixes on)
Transition action during a transition, for an event issueResolveAction
Automatic state computation when the entity enters an automatic state issueAutoCloseCheckAutoState
Post-save hook after the entity is stored in a state issueRESOLVEDPostSaveHook

The wfcustom blueprint turns the suffixes on. Without them the names are issueResolve and so on, which is what the wfservice blueprint generates. If nothing matches, the resolver falls back: a transition action falls back to the configured default action, an automatic state to an empty event, and a post-save hook is skipped. The polymorphism concept explains how to make those silent fallbacks loud.

Finding components by name buys two things.

The XML stays readable by the people who own the process. A business analyst can read and review a states XML: states, events, the transitions between them, who may raise each event. A bean reference such as componentName="resolveIssueActionImpl" means nothing to them; it is a Java detail from the Spring bean factory. Leaving those names out keeps the definition about the business process and nothing else.

A tenant or a trajectory can override one component. The resolver can be given extra prefix keys, such as chenile-tenant-id or chenile-trajectory-id. For each key it reads the matching x- header and tries a prefixed name first. For tenant acme it tries acmeIssueResolveAction, then falls back to issueResolveAction. In a SaaS deployment, acme ships its own resolve action, or its own automatic-state computation or post-save hook, and every other tenant keeps the base component. The XML does not change, and neither does anyone else’s code. StmBodyTypeSelector uses the same resolver, so acme’s action also decides acme’s payload type.

Automatic states: decisions without waiting

A manual state waits for someone to raise an event. An automatic state does not wait: the moment the entity enters it, the state machine works out the next event itself and moves on. One request can therefore pass through several automatic states, and the state machine returns only when it reaches a manual state or a final one.

<manual-state id="ASSIGNED">
  <on eventId="resolve" newStateId="isCritical" meta-acls="issue.resolve"/>
</manual-state>
<if id="isCritical" condition="severity == 'CRITICAL'" then="yes" else="no">
  <on eventId="yes" newStateId="REVIEW_PENDING"/>
  <on eventId="no"  newStateId="autoCloseCheck"/>
</if>
<auto-state id="autoCloseCheck">
  <on eventId="keepOpen" newStateId="RESOLVED"/>
  <on eventId="close"    newStateId="CLOSED"/>
</auto-state>

Here resolve leads into isCritical. An <if> evaluates its condition against the entity and raises yes or no on its own, so a simple decision needs no Java at all; <switch> and <script> work the same way. When the decision needs code, an <auto-state> asks a component for the next event, found by the resolver as issueAutoCloseCheckAutoState with the same tenant and trajectory overrides as any transition action. autoCloseCheck returns keepOpen, the entity reaches RESOLVED, which is manual, and only then does the call return.

A few rules make chains safe to reason about:

  • Each state entered runs the full sequence: the exit action of the old state, the transition action, the new state, then the new state’s entry action. So the entity is stored at each step of the chain.
  • Automatic transitions skip the acl check. The person who raised resolve was checked once; the decisions after it belong to the workflow, not to the caller.
  • The process logic stays visible. The decisions are states in the XML, drawn on the diagram and covered by the generated tests, instead of if statements buried in a transition action.

Process management is built this way: isThisLeafNode, areAllSubProcessesDone and areThereErrors are <if> states in its flow.

Post-save hooks: after-effects in their place

Some work must happen only once the new state is safely stored: notifying the assignee, publishing an event, calling another system. Doing it in the transition action is wrong, because the transition action runs before the save. If the save then fails, the email has already gone out about a resolution that never happened.

So the entry action, GenericEntryAction, works in a fixed order. It stamps the state entry time and the SLA hours, calls EntityStore.store, and only then calls the post-save hook. The default hook looks up a hook for the state just entered (issueRESOLVEDPostSaveHook) and runs it if there is one. Hooks receive the old and new state, the entity and its transient map.

Where the transaction ends is a choice, and the right choice depends on the hook.

  • Outside the transaction, for after-effects. If nothing wraps the call in a transaction, the entity store’s own save has committed by the time the hook runs. The hook cannot undo the state change, and that is the point: a notification or an event should describe something that has happened. A failure in the hook leaves the state change in place, so make such effects retryable or idempotent at the receiver.
  • Inside the transaction, when the effect decides success. If the hook’s work must succeed for the state change to count, such as writing a related record that has to agree with the entity, wrap the call in one transaction. A failing hook then rolls back the save with it.

Process management shows the strongest form of the second option: every consequence of a state change is written to a durable outbox in the same transaction as the change, and a dispatcher carries it out afterwards.

Second transition actions: more than one team per transition

A transition has one transition action, owned by the team that owns the workflow. Often another group needs to act on the same event, in the same transaction, without editing that team’s code. An order management team owns OrderSubmitAction; an analytics group wants to update order metrics whenever an order is submitted, and the metrics must commit or roll back with the order.

That group writes a second transition action:

public class OrderMetricsAction extends SecondSTMTransitionAction<Order, SubmitOrderPayload> {
    public OrderMetricsAction(MultipleCommandsRegistry<Order, SubmitOrderPayload> registry) {
        super(registry, 1, "submit");      // index 1, for the submit event
    }
    @Override
    public void transitionTo(Order order, SubmitOrderPayload payload, State start, String eventId,
                             State end, STMInternalTransitionInvoker<?> stm, Transition transition) {
        // update the metrics
    }
}
  • It lives in its own jar. When the application starts, the action registers itself for its events in the workflow’s MultipleCommandsRegistry. Putting the jar on the class path and declaring the bean is all it takes; the order team’s code and the states XML do not change.
  • It runs in the same transition. The main action runs first. Then every second action registered for the event runs in index order: index 1, then 2, and so on (index 0 is reserved). They run inside the same transition call, so they share its transaction and its failure: an exception in any of them fails the event.
  • It is typed like the main action. It receives the same payload, already typed.

The only wiring the owning team provides is a shared MultipleCommandsRegistry bean, passed to its main actions.

Enablement: change the flow without changing the XML

The states XML is the base flow. An enablement strategy changes it for a deployment or a tenant from configuration, at run time. ConfigBasedEnablementStrategy reads properties through a ConfigProvider:

# add a manual state, and a path into and out of it
IssueFlow.state.add.EXTENSION=
IssueFlow.ASSIGNED.transition.add.escalate=EXTENSION
IssueFlow.EXTENSION.transition.add.close=CLOSED

# hide a transition or a state (only an explicit false disables)
IssueFlow.ASSIGNED.resolve.enabled=false
IssueFlow.REVIEW_PENDING.enabled=false

# send an existing transition somewhere else, and add metadata
IssueFlow.ASSIGNED.close.newStateId=CLOSED
IssueFlow.ASSIGNED.escalate.meta.label=Escalate to tier 2

Make the ConfigProvider tenant-aware and each tenant gets its own flow from one states XML. States and transitions added this way are marked with enablement metadata, so they can be told apart on a diagram. Properties can add manual states and plain transitions; for an automatic state, actions or custom tags, overlay the XML instead. The workflow extension guide has the details.

Seeing the flow: stm-cli

Because the flow is data, it can be drawn without running anything. stm-cli reads a states XML and prints a diagram:

stm-cli --mermaid issue-states.xml                     # Mermaid
stm-cli -s -o issue.puml issue-states.xml              # PlantUML
stm-cli -s -S styles.json -o issue.puml issue-states.xml
stm-cli -m -e tenant-acme.properties issue-states.xml  # the flow acme sees

The styling file picks out states and transitions by their metadata, so that the lines that matter stand out:

{ "rules": [ { "id": "mainPath", "expression": "mainPath==true",
               "style": { "color": "Fuchsia", "thickness": 3, "lineStyle": "bold" } } ] }

Mark the happy path with meta-mainPath="true" and it is drawn thick and coloured. With -e, the diagram shows the flow after an enablement file is applied. A running workflow service serves the same views at /{entity}/info/state-diagram, /info/allowed-actions and /info/json.

Tests from the flow

The flow also says which tests to write. stm-cli --generate-test-cases walks the transitions from the initial state and produces one test case per path. To keep the walk finite, it skips self-transitions and any transition back into a state already visited on that path. Every forward path is covered, and a cycle such as reopen is not followed forever. Automatic states are folded into the step that led into them, because a test can only raise manual events: the expected state after resolve is RESOLVED, not isCritical.

The wfcustom JGen blueprint uses this when it generates a workflow service. It runs the same generator on your states XML and writes one Cucumber feature per test case. Each feature creates an entity, raises each event of its path through PATCH /{entity}/{id}/{event}, and checks the state after every step. The generated service starts with a test suite that covers its own flow, and regenerating after the XML changes keeps the suite in step.

To see the cases, stm-cli -T draws them all, and stm-cli -r -o folder writes one diagram per test case, with that case’s path highlighted and its steps numbered on the transitions.

Where to go next