Liking cljdoc? Tell your friends :D

taia.state-machines

A small hierarchical state machine for Clojure: the machine is a data literal and one pure function, transition, interprets it. It started as the state machine inside taia.ds and is now a library of its own.

;; deps.edn
io.github.danbunea/taia.state-machines {:mvn/version "0.2.7"}
(require '[taia.state-machines.core :as sm])

(sm/transition machine {:_state :a :memory {}} [:GO {}])
;; => the new ctx: state under :_state, :memory, whatever the actions added

Shape

(def machine
  {:id      :wizard
   :initial [:editing :details]                 ; keyword, or vector for a nested start
   :on      {:RESET {:target [:editing :details] :actions reset}}   ; machine-wide events
   :states  {:editing {:states {:details {:on {:NEXT [{:target :address :cond name-ok? :actions clear-error}
                                                      {:actions (set-error "Name is required")}]}}
                                :address {:on {:BACK :details :NEXT :review}}
                                :review  {:on {:SUBMIT {:target [:saving]}}}}}
             :saving  {:invoke {:id :save :src save!
                                :on-done  {:target [:done] :actions keep-receipt}
                                :on-error {:target [:editing :review] :actions keep-error}}}
             :done    {}}})

Transitions

A coffee machine driven from the REPL: COIN, COIN, CANCEL

(sm/transition machine ctx [:EVENT event-params])
(sm/transition machine ctx [:EVENT event-params] {:state-key :state})

ctx is a map holding the current state under the state key (:_state unless :state-key says otherwise), plus :memory and anything else your actions put there. The result is the new ctx.

A value under :on {:EVENT …} is one of:

FormMeaning
:target-statego there
{:target :x :actions f}go there after running f
{:actions f}stay in the current state, run f
{}stay, do nothing — the idiom for "this event is fine here"
[{:cond c1 …} {:cond c2 …} {…}]the first option whose :cond passes (or has none)
  • :actions is (fn [ctx event-params] -> ctx). It is the only place state changes; return the whole ctx.
  • :cond is (fn [ctx event-params] -> boolean) and sees :memory, so validation is a guard.
  • Lookup order: the machine's :on first, then the current state's :on (for nested states, the leaf's).

An unhandled event is dropped, not thrown

An event handled nowhere logs Event X not found! … don't exist in machine: <id> and transition returns the ctx unchanged. No exception: the caller just sees nothing happen. If an event can legitimately arrive in a state and should do nothing there, give it an {} entry. When something silently fails to move, grep the log for don't exist in machine first.

Nested states

State is a path: [:editing :address]. Inside a nested state, :target :review is relative (it replaces the last segment). To leave the parent give the full path: :target [:saving], and a single-element vector collapses to the keyword :saving. If the state is stored somewhere that loses keywords (JSON, for instance), coerce it back to keywords before calling transition.

Invokes

One transition, two steps: BREW enters :brewing, its invoke's outcome is the next event

A state with :invoke runs its :src synchronously, inside the same transition, as soon as a transition takes a target into it. Its outcome is one more event for that state — [:on-done result] or [:on-error ex-data] — handled like any event, from the invoke's :on-done / :on-error:

  • :src is (fn [ctx] -> result). It gets the ctx only — not the event params. Capture any param you need in the transition's :actions first, then read it from ctx.
  • Return value → :on-done, whose :actions is (fn [ctx result] -> ctx); the result is not merged automatically.
  • (throw (ex-info msg data)) → :on-error, whose :actions is (fn [ctx ex-data] -> ctx).
  • :on-done and :on-error are reserved event names: they are always answered from the current state's :invoke, never from an :on, so don't use them for your own events.
  • :on-done / :on-error accept the same forms as transitions, including conditional vectors (:cond there is (fn [ctx result])). If the target state has an invoke too, it runs next.
  • The :invoke key is always stripped from the result.
  • An invoke runs on entry, not whenever the machine is in its state: an event handled in the invoking state without a target, or one it does not handle, does not run it again. A handler that targets its own state does re-enter it, so the invoke runs again — a retry: :on-done [{:target :fetching :cond (fn [_ n] (< n 3))} {:target :done}].

Because the invoke is synchronous, a caller never sees the invoking state unless an error path lands there: a one-shot request goes review → saving → done in one call.

Async: a core.async flow

The same BREW through machine-flow with {:async? true}: :brewing comes out while brew! runs, then :served, :done? true

taia.state-machines.flow runs the same steps and invokes as transition, as a core.async flow instead of a loop: a :machine proc runs each step (pure), an :invoke proc runs each :src, and the two pass events back and forth, so a slow :src blocks no caller. Events go in at [:machine :events]; one channel, the flow's out, gets {:id :ctx :event :entered :done?} per microstep. With :async? true in the opts every microstep comes out as it happens, the last with :done? true; without it, only that last one — the ctx transition returns.

It is JVM-only and needs core.async with flow, an optional dependency you add yourself (flow ships only in the core.async alphas):

;; deps.edn
org.clojure/core.async {:mvn/version "1.10.874-alpha3"}
(require '[clojure.core.async :as async]
         '[clojure.core.async.flow :as flow]
         '[taia.state-machines.flow :refer [machine-flow]])

(def out (async/chan 100))
(def f (flow/create-flow (machine-flow machine {:out-ch out
                                                :opts {:async? true}})))   ; transition's opts + :async?
(flow/start f)
(flow/resume f)

;; the wizard above, submitting from :review
(flow/inject f [:machine :events] [{:id "form-1" :ctx {:_state [:editing :review]} :event [:SUBMIT {}]}])
(async/<!! out) ;=> {:id "form-1" :ctx {:_state :saving …} :event [:SUBMIT {}] :entered :saving :done? false}
(async/<!! out) ;=> {:id "form-1" :ctx {:_state :done …} :event [:on-done …] :entered :done :done? true}
  • The ctx travels in the messages and the procs keep none, so one flow runs any number of machine instances. Any other key you put on the message (an :id, a reply promise, a trace context) rides along, through the invoke and back, onto every message out.
  • Send the next event for an :id only after its :done? message: an event sent earlier steps from the ctx you gave it, not from the one the invoke is still producing.
  • Keep the out channel drained: the machine waits on a full one.
  • Invokes run one at a time, in arrival order, across all ids.
  • An action or guard that throws, or a :src that throws something other than an ex-info (an ex-info is its :on-error), ends the run: the last message, :done? true, carries the :error, and the ctx it stepped from.
  • :around-invoke, (fn [msg run] … (run) …) given to machine-flow, runs each :src: bind a trace or logging context from the message, say.

Testing a machine

transition is pure: (transition machine {:state :a :memory {}} [:GO {}] {:state-key :state}).

taia.state-machines.test-helpers/test-machine asserts, per state and event, where the machine lands and the ordered trace of the actions and invokes it went through. It runs neither: an action is recorded by its fn's name, an invoke by its id, answered from :invoke-returns. The actions have tests of their own.

(require '[taia.state-machines.test-helpers :refer [test-machine]])

(tests
 (test-machine
  {:displayed {:INCREMENT {:target :displayed :trace [:increment]}
               :SAVE      {:target :saved     :trace [:store-form :save :save-on-done]}}}
  machine
  {:invoke-returns {:save {:id 1}}})
 := :ok)

It returns :ok, or the failing [from event] pairs with expected and actual target and trace. Options: :state-key (default :_state), :ctx merged into the transition context, and :invoke-returns {invoke-id value | ex-info} (unlisted ids get {}).

For a machine that calls the world from somewhere test-machine cannot reach, sm/make-machine-testable swaps named functions for their vars so with-redefs can intercept them. transition also takes :trace-fn (in place of each invoke's :src) and :action-trace-fn (in place of each action) in its opts; test-machine is built on them.

If you know XState

The machine is an XState-style statechart as a Clojure map.

XStatetaia.state-machines
states, nested states:states, nested :states
initial: 'a':initial :a, or [:a :b] to start inside a nested state
on: { EVENT: 'target' }:on {:EVENT :target}; targets are relative to the parent, a vector leaves it
on: { EVENT: { target, guard, actions } }{:target … :cond … :actions …}; several options as a vector, the first passing :cond wins
root-level onmachine-wide :on
actions / assign:actions, a pure (fn [ctx event] -> ctx) returning the new ctx
invoke: { src, onDone, onError }:invoke {:src f :on-done {…} :on-error {…}}; src is (fn [ctx] -> result) and runs synchronously inside the transition
machine.transition(state, event)(transition machine ctx [:EVENT params] {:state-key :state})
type: 'parallel', history states, after, entry / exit, actorsnot supported

The wizard machine above, as a state diagram (a NEXT whose guard fails stays put and sets :error; the machine-wide RESET returns to details):

stateDiagram-v2
  direction LR
  [*] --> editing
  state editing {
    direction LR
    [*] --> details
    details --> address : NEXT [name ok]
    address --> review : NEXT [address ok]
    address --> details : BACK
    review --> address : BACK
  }
  review --> saving : SUBMIT
  saving --> done : save! ok / keep receipt
  saving --> review : save! failed / keep error

Namespaces

NamespaceWhat
taia.state-machines.coretransition (Malli-instrumented), the schemas MachineDefinition, Event, TransitionOpts, Context, and make-machine-testable
taia.state-machines.test-helperstest-machine
taia.state-machines.transitionthe interpreter: transition loops over steps, running the invoke of each state a step enters
taia.state-machines.stepone transition, pure, a -> pipeline: current state → handler → action → target
taia.state-machines.invokean invoke's :src as an event: [:on-done result] / [:on-error ex-data]
taia.state-machines.statehelpers the steps use: state key, paths, nodes, options, actions, the invoke a step entered
taia.state-machines.flowmachine-flow: the same steps and invokes as a core.async flow (JVM, optional core.async)

Development

bb dev           # nREPL with RCF enabled: (tests …) blocks run as you evaluate them
bb test          # Kaocha + the RCF (tests …) blocks: unit tests in src, integration tests in test
bb coverage      # under Cloverage → target/coverage/index.html
bb format        # cljfmt fix   (bb format:check to verify)
bb flow-gif      # regenerate docs/img/coffee-*.svg from scripts/coffee_flow_svg.clj, render the GIFs (npm ci in scripts/ first)
bb jar           # target/taia.state-machines-<version>.jar (the version is `version` in build.clj)
bb install       # jar + install into ~/.m2
bb deploy        # jar + deploy to Clojars (CLOJARS_USERNAME / CLOJARS_PASSWORD); refuses unless README, CHANGELOG and tag v<version> agree

License

Eclipse Public License 2.0.

Can you improve this documentation?Edit on GitHub

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close