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.1.0"}
(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

(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

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.

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

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 jar           # target/taia.state-machines-<version>.jar
bb install       # jar + install into ~/.m2
bb deploy        # jar + deploy to Clojars (CLOJARS_USERNAME / CLOJARS_PASSWORD)

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