Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork59
Go library for creating finite state machines
License
qmuntal/stateless
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Createstate machines and lightweightstate machine-based workflows directly in Go code:
phoneCall:=stateless.NewStateMachine(stateOffHook)phoneCall.Configure(stateOffHook).Permit(triggerCallDialed,stateRinging)phoneCall.Configure(stateRinging).OnEntryFrom(triggerCallDialed,func(_ context.Context,args...any)error {onDialed(args[0].(string))returnnil }).Permit(triggerCallConnected,stateConnected)phoneCall.Configure(stateConnected).OnEntry(func(_ context.Context,_...any)error {startCallTimer()returnnil }).OnExit(func(_ context.Context,_...any)error {stopCallTimer()returnnil }).Permit(triggerLeftMessage,stateOffHook).Permit(triggerPlacedOnHold,stateOnHold)// ...phoneCall.Fire(triggerCallDialed,"qmuntal")
This project, as well as the example above, is almost a direct, yet idiomatic, port ofdotnet-state-machine/stateless, which is written in C#.
The state machine implemented in this library is based on the theory ofUML statechart. The concepts behind it are about organizing the way a device, computer program, or other (often technical) process works such that an entity or each of its sub-entities is always in exactly one of a number of possible states and where there are well-defined conditional transitions between these states.
Most standard state machine constructs are supported:
- Support for states and triggers of any comparable type (int, strings, boolean, structs, etc.)
- Hierarchical states
- Entry/exit events for states
- Guard clauses to support conditional transitions
- Introspection
Some useful extensions are also provided:
- Ability to store state externally (for example, in a property tracked by an ORM)
- Parameterised triggers
- Reentrant states
- Thread-safe
- Export to DOT graph
In the example below, theOnHold state is a substate of theConnected state. This means that anOnHold call is still connected.
phoneCall.Configure(stateOnHold).SubstateOf(stateConnected).Permit(triggerTakenOffHold,stateConnected).Permit(triggerPhoneHurledAgainstWall,statePhoneDestroyed)
In addition to theStateMachine.State property, which will report the precise current state, anIsInState(State) method is provided.IsInState(State) will take substates into account, so that if the example above was in theOnHold state,IsInState(State.Connected) would also evaluate totrue.
In the example, theStartCallTimer() method will be executed when a call is connected. TheStopCallTimer() will be executed when call completes (by either hanging up or hurling the phone against the wall.)
The call can move between theConnected andOnHold states without theStartCallTimer() andStopCallTimer() methods being called repeatedly because theOnHold state is a substate of theConnected state.
Entry/Exit event handlers can be supplied with a parameter of typeTransition that describes the trigger, source and destination states.
A substate can be marked as initial state. When the state machine enters the super state it will also automatically enter the substate. This can be configured like this:
sm.Configure(State.B) .InitialTransition(State.C);sm.Configure(State.C) .SubstateOf(State.B);
Stateless is designed to be embedded in various application models. For example, some ORMs place requirements upon where mapped data may be stored, and UI frameworks often require state to be stored in special "bindable" properties. To this end, theStateMachine constructor can accept function arguments that will be used to read and write the state values:
machine:=stateless.NewStateMachineWithExternalStorage(func(_ context.Context) (stateless.State,error) {returnmyState.Value,nil},func(_ context.Context,state stateless.State)error {myState.Value=statereturnnil},stateless.FiringQueued)
In this example the state machine will use themyState object for state storage.
This can further be extended to support more complex scenarios, such as when not only the current state is required but also the arguments which were supplied to that state. This can be useful when using error states that additional metadata can be stored or acted upon via callbacks.
machine:=stateless.NewStateMachineWithExternalStorageAndArgs(func(_ context.Context) (stateless.State, []any,error) {returnmyState.Value,myState.Args,nil},func(_ context.Context,state stateless.State,args...any)error {myState.Value=statemyState.Args=argsreturnnil},stateless.FiringQueued)
It might be necessary to perform some code before storing the object state, and likewise when restoring the object state. UseDeactivate andActivate for this. Activation should only be called once before normal operation starts, and once before state storage.
The state machine can provide a list of the triggers that can be successfully fired within the current state via theStateMachine.PermittedTriggers property.
The state machine will choose between multiple transitions based on guard clauses, e.g.:
phoneCall.Configure(stateOffHook).Permit(triggerCallDialled,stateRinging,func(_ context.Context,_...any)bool {returnIsValidNumber() }).Permit(triggerCallDialled,stateBeeping,func(_ context.Context,_...any)bool {return!IsValidNumber() })
Guard clauses within a state must be mutually exclusive (multiple guard clauses cannot be valid at the same time). Substates can override transitions by respecifying them, however substates cannot disallow transitions that are allowed by the superstate.
The guard clauses will be evaluated whenever a trigger is fired. Guards should therefor be made side effect free.
Strongly-typed parameters can be assigned to triggers:
stateMachine.SetTriggerParameters(triggerCallDialed,reflect.TypeOf(""))stateMachine.Configure(stateRinging).OnEntryFrom(triggerCallDialed,func(_ context.Context,args...any)error {fmt.Println(args[0].(string))returnnil })stateMachine.Fire(triggerCallDialed,"qmuntal")
It is runtime safe to cast parameters to the ones specified inSetTriggerParameters. If the parameters passed inFire do not match the ones specified it will panic.
Trigger parameters can be used to dynamically select the destination state using thePermitDynamic() configuration method.
Firing a trigger that does not have an allowed transition associated with it will cause a panic to be thrown.
To ignore triggers within certain states, use theIgnore(Trigger) directive:
phoneCall.Configure(stateConnected).Ignore(triggerCallDialled)
Alternatively, a state can be marked reentrant so its entry and exit events will fire even when transitioning from/to itself:
stateMachine.Configure(stateAssigned).PermitReentry(triggerAssigned).OnEntry(func(_ context.Context,_...any)error {startCallTimer()returnnil })
By default, triggers must be ignored explicitly. To override Stateless's default behaviour of throwing a panic when an unhandled trigger is fired, configure the state machine using theOnUnhandledTrigger method:
stateMachine.OnUnhandledTrigger(func (_ context.Context,stateState,_Trigger,_ []string) {})
It can be useful to visualize state machines on runtime. With this approach the code is the authoritative source and state diagrams are by-products which are always up to date.
sm:=stateMachine.Configure(stateOffHook).Permit(triggerCallDialed,stateRinging,isValidNumber)graph:=sm.ToGraph()
The StateMachine.ToGraph() method returns a string representation of the state machine in the DOT graph language, e.g.:
digraph { OffHook-> Ringing [label="CallDialled [isValidNumber]"];}
This can then be rendered by tools that support the DOT graph language, such as the dot command line tool from graphviz.org or viz.js. Seewebgraphviz.com for instant gratification. Command line example: dot -T pdf -o phoneCall.pdf phoneCall.dot to generate a PDF file.
This is the complete Phone Call graph as builded inexample_test.go.
This page is an almost-complete description of Stateless, and its explicit aim is to remain minimal.
Please use the issue tracker or the if you'd like to report problems or discuss features.
(Why the name? Stateless implements the set of rules regarding state transitions, but, at least when the delegate version of the constructor is used, doesn't maintain any internal state itself.)
About
Go library for creating finite state machines
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
Contributors8
Uh oh!
There was an error while loading.Please reload this page.
