fsm

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2022 License: Apache-2.0 Imports: 2 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

A Finite State Machine implementation : )

Example

image

1. Basic FSM

fsm.NewFSM(
    // fsm acts according to the transition rule
    fsm.NewTransitionRule(fsm.Transitions{
        {"state0", "event01", "state1"},
        {"state0", "event02", "state2"},
        {"state0", "event03", "state3"},
        {"state2", "event24", "state4"},
        {"state2", "event25", "state5"},
        {"state5", "event56", "state6"},
        {"state5", "event57", "state7"},
    }),
).
From("state0"). // start from state0
Transfer("event01").
State() // stop at state1
2. FSM with Action

State can have Actions, which can emit Event (which may carry some data) that may trigger a follow-up transition. Because of these internal events, an external event may actually result in mutiple transitions.


fsm.NewFSM(
    fsm.NewTransitionRule(fsm.Transitions{
        {"state0", "event01", "state1"},
        {"state0", "event02", "state2"},
        {"state0", "event03", "state3"},
        {"state2", "event24", "state4"},
        {"state2", "event25", "state5"},
        {"state5", "event56", "state6"},
        {"state5", "event57", "state7"},
    }),
).
RegisterExitAction( // register ExitAction for state0
    "state0",
    func(ctx fsm.Context, event fsm.Event) fsm.Event {
        // within the action, you can:
        
        // 1. get extra data from the event triggering the current action
        triggerEventData := event.GetEventData()
        
        // 2. record info into the current state (state0 here)
        ctx.WriteIntoCurrentState(map[string]string){
            "triggerEvent": fmt.Sprintf("%+v", triggerEventData),
        })
        
        // 3. create a new event, which can carry some extra data
        emittedEvent := fsm.NewEvent("event02",
            map[string]string{
                "eventName":        "event02",
                "eventEmitter":     "state0",
            })
        
        // 4. emit the new event, which may trigger another state transition
        return emittedEvent
    }, 
).
RegisterEntryAction( // register EntryAction for state2
    "state2",
    func(ctx fsm.Context, event fsm.Event) fsm.Event {
        // emit event without extra data
        return fsm.NewEvent("event25")
    },
).
RegisterEntryAction( // register EntryAction for state5
    "state5",
    func(ctx fsm.Context, event fsm.Event) fsm.Event {
        return fsm.NewEvent("event56")
    },
).
RegisterExitAction( // register ExitAction for state5
    "state5",
    func(ctx fsm.Context, event fsm.Event) fsm.Event {
        // emit nothing, which will not trigger any state transition
        return nil
    },
).
From("state0"). // start from state0 
Transfer(
      "event01",
      map[string]string{ // carry some extra data
          "eventName":    "event01",
          "eventEmitter": "external",
      }),
).
State() // stop at state6
3. Asynchronous FSM

AsyncFSM runs continuously in a standalone goroutine, which can accept external events in a nonblocking way and provides the same abilities as the synchronous FSM does.

envoy := fsm.NewAsyncFSM( // take an envoy to communicate with the FSM
    fsm.NewTransitionRule(fsm.Transitions{
        {"state0", "event01", "state1"},
        {"state0", "event02", "state2"},
        {"state0", "event03", "state3"},
        {"state2", "event24", "state4"},
        {"state2", "event25", "state5"},
        {"state5", "event56", "state6"},
        {"state5", "event57", "state7"},
    }), 3). // event emitting buffer of size 3
    .RegisterExitAction("state0", func(ctx fsm.Context, event fsm.Event) fsm.Event {
        return NewEvent("event02")
    }).RegisterEntryAction("state2", func(ctx fsm.Context, event fsm.Event) fsm.Event {
        return NewEvent("event25")
    }).RegisterExitAction("state2", func(ctx fsm.Context, event fsm.Event) fsm.Event {
        return nil
    }).RegisterEntryAction("state5", func(ctx fsm.Context, event fsm.Event) fsm.Event {
        return NewEvent("event56")
    }).RegisterExitAction("state5", func(ctx fsm.Context, event fsm.Event) fsm.Event {
        return nil
    }).From("state0"). // start from state0
       Envoy()
    // let the FSM run in a standalone goroutine
    go envoy.Run()
    // emit event asynchronously
    envoy.EmitEvent("event01")
    // wait for a moment for the result of state transition
    time.Sleep(time.Millisecond)
    // stop at state6
    got := envoy.State().Code()
    // stop the FSM running behind the scenes
    envoy.Stop()

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AsyncFSM

type AsyncFSM interface {
	RegisterEntryAction(state StateCode, entryAction StateAction) AsyncFSM
	RegisterExitAction(state StateCode, exitAction StateAction) AsyncFSM
	From(state StateCode) AsyncFSM
	Envoy() Envoy
}

func NewAsyncFSM

func NewAsyncFSM(stateGraph TransitionRule, pipeSize ...int) AsyncFSM

NewAsyncFSM pipeSize determines the max number of events emitted concurrently. pipeSize is 0 by default, which means emitting the event in blocking mode.

type Context

type Context interface {
	WriteIntoCurrentState(stateData interface{}) FSM
	ReadFromCurrentState() interface{}
}

type Envoy

type Envoy interface {
	Run()
	Stop()
	Error() error
	State() State
	EmitEvent(eventCode EventCode, eventData ...interface{})
}

type Event

type Event interface {
	GetEventData() interface{}
	Code() EventCode
}

func NewEvent

func NewEvent(eventCode EventCode, eventData ...interface{}) Event

NewEvent event with optional data

type EventCode

type EventCode string

type FSM

type FSM interface {
	RegisterEntryAction(state StateCode, entryAction StateAction) FSM
	RegisterExitAction(state StateCode, exitAction StateAction) FSM
	From(state StateCode) FSM
	Transfer(event EventCode, eventData ...interface{}) FSM
	State() State
	Error() error
}

func NewFSM

func NewFSM(stateGraph TransitionRule) FSM

type State

type State interface {
	Code() StateCode
	GetStateData() interface{}
	// contains filtered or unexported methods
}

type StateAction

type StateAction func(ctx Context, event Event) Event

StateAction is a closure, which can take action and emit event to transfer State if there is no need to emit any event, just return nil

type StateCode

type StateCode string

type Transition

type Transition struct {
	SrcState StateCode
	Event    EventCode
	DstState StateCode
}

type TransitionRule

type TransitionRule interface {
	// contains filtered or unexported methods
}

func NewTransitionRule

func NewTransitionRule(transitions Transitions) TransitionRule

type Transitions

type Transitions []Transition

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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