All Projects → qmuntal → Stateless

qmuntal / Stateless

Licence: bsd-2-clause
Go library for creating state machines

Programming Languages

go
31211 projects - #10 most used programming language
golang
3204 projects

Projects that are alternatives of or similar to Stateless

Jstate
Advanced state machines in Java.
Stars: ✭ 84 (-65.99%)
Mutual labels:  state-machine, fsm
Fluent State Machine
Fluent API for creating state machines in C#
Stars: ✭ 195 (-21.05%)
Mutual labels:  state-machine, fsm
Finity
A finite state machine library for Node.js and the browser with a friendly configuration DSL.
Stars: ✭ 88 (-64.37%)
Mutual labels:  state-machine, fsm
Stately.js
Stately.js is a JavaScript based finite-state machine (FSM) engine for Node.js and the browser.
Stars: ✭ 785 (+217.81%)
Mutual labels:  state-machine, fsm
Hfsm2
High-Performance Hierarchical Finite State Machine Framework
Stars: ✭ 134 (-45.75%)
Mutual labels:  state-machine, fsm
Rust fsm macros
FSM in Rust's macros.
Stars: ✭ 20 (-91.9%)
Mutual labels:  state-machine, fsm
Ws Machine
WS-Machine is a websocket finite state machine for client websocket connections (Go)
Stars: ✭ 110 (-55.47%)
Mutual labels:  state-machine, fsm
qm
QM model-based design tool and code generator based on UML state machines
Stars: ✭ 54 (-78.14%)
Mutual labels:  fsm, state-machine
Squirrel
squirrel-foundation is a State Machine library, which provided a lightweight, easy use, type safe and programmable state machine implementation for Java.
Stars: ✭ 1,789 (+624.29%)
Mutual labels:  state-machine, fsm
Qpcpp
QP/C++ real-time embedded framework/RTOS for embedded systems based on active objects (actors) and hierarchical state machines
Stars: ✭ 124 (-49.8%)
Mutual labels:  state-machine, fsm
Fsm As Promised
A finite state machine library using ES6 promises
Stars: ✭ 446 (+80.57%)
Mutual labels:  state-machine, fsm
Nanostate
🚦- Small Finite State Machines
Stars: ✭ 151 (-38.87%)
Mutual labels:  state-machine, fsm
Statecharts.github.io
There is no state but what we make. Feel free to pitch in.
Stars: ✭ 265 (+7.29%)
Mutual labels:  state-machine, fsm
Rosmaro
Visual automata-based programming in functional JavaScript
Stars: ✭ 176 (-28.74%)
Mutual labels:  state-machine, fsm
fea state machines
A Buffet Of C++17 State Machines
Stars: ✭ 19 (-92.31%)
Mutual labels:  fsm, state-machine
Qpn
QP-nano real-time embedded framework/RTOS for embedded systems based on active objects (actors) and hierarchical state machines
Stars: ✭ 107 (-56.68%)
Mutual labels:  state-machine, fsm
ember-fsm
[Maintenance Mode] A promise-aware finite state machine implementation for Ember
Stars: ✭ 37 (-85.02%)
Mutual labels:  fsm, state-machine
xstate-cpp-generator
C++ State Machine generator for Xstate
Stars: ✭ 33 (-86.64%)
Mutual labels:  fsm, state-machine
Afsm
C++14 Finite State Machine library
Stars: ✭ 113 (-54.25%)
Mutual labels:  state-machine, fsm
Django Fsm
Django friendly finite state machine support
Stars: ✭ 1,898 (+668.42%)
Mutual labels:  state-machine, fsm

Stateless logo. Fire gopher designed by https://www.deviantart.com/quasilyte

Build Status Code Coverage Go Report Card go.dev Licenses Mentioned in Awesome Go

Stateless

Create state machines and lightweight state 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 ...interface{}) error {
    onDialed(args[0].(string))
    return nil
  }).
  Permit(triggerCallConnected, stateConnected)

phoneCall.Configure(stateConnected).
  OnEntry(func(_ context.Context, _ ...interface{}) error {
    startCallTimer()
    return nil
  }).
  OnExit(func(_ context.Context, _ ...interface{}) error {
    stopCallTimer()
    return nil
  }).
  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 of dotnet-state-machine/stateless, which is written in C#.

The state machine implemented in this library is based on the theory of UML 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.

Features

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

Hierarchical States

In the example below, the OnHold state is a substate of the Connected state. This means that an OnHold call is still connected.

phoneCall.Configure(stateOnHold).
  SubstateOf(stateConnected).
  Permit(triggerTakenOffHold, stateConnected).
  Permit(triggerPhoneHurledAgainstWall, statePhoneDestroyed)

In addition to the StateMachine.State property, which will report the precise current state, an IsInState(State) method is provided. IsInState(State) will take substates into account, so that if the example above was in the OnHold state, IsInState(State.Connected) would also evaluate to true.

Entry/Exit Events

In the example, the StartCallTimer() method will be executed when a call is connected. The StopCallTimer() will be executed when call completes (by either hanging up or hurling the phone against the wall.)

The call can move between the Connected and OnHold states without the StartCallTimer() and StopCallTimer() methods being called repeatedly because the OnHold state is a substate of the Connected state.

Entry/Exit event handlers can be supplied with a parameter of type Transition that describes the trigger, source and destination states.

Initial state transitions

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);

External State Storage

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, the StateMachine 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) {
  return myState.Value, nil
}, func(_ context.Context, state stateless.State) error {
  myState.Value  = state
  return nil
}, stateless.FiringQueued)

In this example the state machine will use the myState object for state storage.

Activation / Deactivation

It might be necessary to perform some code before storing the object state, and likewise when restoring the object state. Use Deactivate and Activate for this. Activation should only be called once before normal operation starts, and once before state storage.

Introspection

The state machine can provide a list of the triggers that can be successfully fired within the current state via the StateMachine.PermittedTriggers property.

Guard Clauses

The state machine will choose between multiple transitions based on guard clauses, e.g.:

phoneCall.Configure(stateOffHook).
  Permit(triggerCallDialled, stateRinging, func(_ context.Context, _ ...interface{}) bool {
    return IsValidNumber()
  }).
  Permit(triggerCallDialled, stateBeeping, func(_ context.Context, _ ...interface{}) 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.

Parameterised Triggers

Strongly-typed parameters can be assigned to triggers:

stateMachine.SetTriggerParameters(triggerCallDialed, reflect.TypeOf(""))

stateMachine.Configure(stateRinging).
  OnEntryFrom(triggerCallDialed, func(_ context.Context, args ...interface{}) error {
    fmt.Println(args[0].(string))
    return nil
  })

stateMachine.Fire(triggerCallDialed, "qmuntal")

It is runtime safe to cast parameters to the ones specified in SetTriggerParameters. If the parameters passed in Fire do not match the ones specified it will panic.

Trigger parameters can be used to dynamically select the destination state using the PermitDynamic() configuration method.

Ignored Transitions and Reentrant States

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 the Ignore(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, _ ...interface{}) error {
    startCallTimer()
    return nil
  })

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 the OnUnhandledTrigger method:

stateMachine.OnUnhandledTrigger( func (_ context.Context, state State, _ Trigger, _ []string) {})

Export to DOT graph

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. See webgraphviz.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 in example_test.go.

Phone Call graph

Project Goals

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.)

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].