package module
Version: v0.0.0-...-3dc1bc0 Latest Latest

This package is not in the latest version of its module.

Go to latest
Published: Jan 10, 2016 License: MIT Imports: 1 Imported by: 1



Codeship Status for ryanfaerman/fsm GoDoc

FSM provides a lightweight finite state machine for Golang. It runs allows any number of transition checks you'd like the it runs them in parallel. It's tested and benchmarked too.


go get github.com/ryanfaerman/fsm


package main

import (

type Thing struct {
    State fsm.State

    // our machine cache
    machine *fsm.Machine

// Add methods to comply with the fsm.Stater interface
func (t *Thing) CurrentState() fsm.State { return t.State }
func (t *Thing) SetState(s fsm.State)    { t.State = s }

// A helpful function that lets us apply arbitrary rulesets to this
// instances state machine without reallocating the machine. While not
// required, it's something I like to have.
func (t *Thing) Apply(r *fsm.Ruleset) *fsm.Machine {
    if t.machine == nil {
        t.machine = &fsm.Machine{Subject: t}

    t.machine.Rules = r
    return t.machine

func main() {
    var err error

    some_thing := Thing{State: "pending"} // Our subject

    // Establish some rules for our FSM
    rules := fsm.Ruleset{}
    rules.AddTransition(fsm.T{"pending", "started"})
    rules.AddTransition(fsm.T{"started", "finished"})

    err = some_thing.Apply(&rules).Transition("started")
    if err != nil {


Note: FSM makes no effort to determine the default state for any ruleset. That's your job.

The Apply(r *fsm.Ruleset) *fsm.Machine method is absolutely optional. I like having it though. It solves a pretty common problem I usually have when working with permissions - some users aren't allowed to transition between certain states.

Since the rules are applied to the the subject (through the machine) I can have a simple lookup to determine the ruleset that the subject has to follow for a given user. As a result, I rarely need to use any complicated guards but I can if need be. I leave the lookup and the maintaining of independent rulesets as an exercise of the user.


Golang makes it easy enough to benchmark things... why not do a few general benchmarks?

$ go test -bench=.
BenchmarkRulesetParallelGuarding      100000   13163 ns/op
BenchmarkRulesetTransitionPermitted  1000000    1805 ns/op
BenchmarkRulesetTransitionDenied    10000000     284 ns/op
BenchmarkRulesetRuleForbids          1000000    1717 ns/op
ok    github.com/ryanfaerman/fsm 14.864s

I think that's pretty good. So why do I go through the trouble of running the guards in parallel? Consider the benchmarks below:

$ go test -bench=.
BenchmarkRulesetParallelGuarding    100000       13261 ns/op
ok  github.com/ryanfaerman/fsm 1.525s

$ go test -bench=.
BenchmarkRulesetSerialGuarding         1  1003140956 ns/op
ok  github.com/ryanfaerman/fsm 1.007s

For the Parallel vs Serial benchmarks I had a guard that slept for 1 second. While I don't imagine most guards will take that long, the point remains true. Some guards will be comparatively slow -- they'll be accessing the database or consulting with some other outside service -- and why not get an answer back as soon as possible?




This section is empty.


View Source
var (
	InvalidTransition = errors.New("invalid transition")


func WithRules

func WithRules(r Ruleset) func(*Machine)

WithRules is intended to be passed to New to set the Rules

func WithSubject

func WithSubject(s Stater) func(*Machine)

WithSubject is intended to be passed to New to set the Subject


type Guard

type Guard func(subject Stater, goal State) bool

Guard provides protection against transitioning to the goal State. Returning true/false indicates if the transition is permitted or not.

type Machine

type Machine struct {
	Rules   *Ruleset
	Subject Stater

Machine is a pairing of Rules and a Subject. The subject or rules may be changed at any time within the machine's lifecycle.

func New

func New(opts ...func(*Machine)) Machine

New initializes a machine

func (Machine) Transition

func (m Machine) Transition(goal State) error

Transition attempts to move the Subject to the Goal state.

type Ruleset

type Ruleset map[Transition][]Guard

Ruleset stores the rules for the state machine.

func CreateRuleset

func CreateRuleset(transitions ...Transition) Ruleset

CreateRuleset will establish a ruleset with the provided transitions. This eases initialization when storing within another structure.

func (Ruleset) AddRule

func (r Ruleset) AddRule(t Transition, guards ...Guard)

AddRule adds Guards for the given Transition

func (Ruleset) AddTransition

func (r Ruleset) AddTransition(t Transition)

AddTransition adds a transition with a default rule

func (Ruleset) Permitted

func (r Ruleset) Permitted(subject Stater, goal State) bool

Permitted determines if a transition is allowed. This occurs in parallel. NOTE: Guards are not halted if they are short-circuited for some transition. They may continue running *after* the outcome is determined.

type State

type State string

type Stater

type Stater interface {
	CurrentState() State

Stater can be passed into the FSM. The Stater is reponsible for setting its own default state. Behavior of a Stater without a State is undefined.

type T

type T struct {
	O, E State

T implements the Transition interface; it provides a default implementation of a Transition.

func (T) Exit

func (t T) Exit() State

func (T) Origin

func (t T) Origin() State

type Transition

type Transition interface {
	Origin() State
	Exit() State

Transition is the change between States

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL