-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathstatemachine.go
76 lines (64 loc) · 2.05 KB
/
statemachine.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package stateswitch
import (
"github.com/pkg/errors"
)
var (
NoConditionPassedToRunTransaction = errors.New("no condition found to run transition")
NoMatchForTransitionType = errors.New("no match for transition type")
)
type StateMachine interface {
// AddTransitionRule adds a new transition rule to the state machine
AddTransitionRule(rule TransitionRule)
// AddTransition is a deprecated method, use AddTransitionRule instead
AddTransition(rule TransitionRule)
// Run transition by type
Run(transitionType TransitionType, stateSwitch StateSwitch, args TransitionArgs) error
StateMachineDocumentation
}
// Create new default state machine
func NewStateMachine() *stateMachine {
sm := stateMachine{
transitionRules: map[TransitionType]TransitionRules{},
}
initStateMachineDocumentation(&sm)
return &sm
}
type stateMachine struct {
transitionRules map[TransitionType]TransitionRules
stateMachineDocumentation
}
// Run transition by type, will search for the first transition that will pass a condition.
func (sm *stateMachine) Run(transitionType TransitionType, stateSwitch StateSwitch, args TransitionArgs) error {
transByType, ok := sm.transitionRules[transitionType]
if !ok {
return NoMatchForTransitionType
}
for _, tr := range transByType {
allow, err := tr.IsAllowedToRun(stateSwitch, args)
if err != nil {
return err
}
if allow {
if tr.Transition != nil {
if err := tr.Transition(stateSwitch, args); err != nil {
return err
}
}
if err := stateSwitch.SetState(tr.DestinationState); err != nil {
return err
}
if tr.PostTransition != nil {
return tr.PostTransition(stateSwitch, args)
}
return nil
}
}
return errors.Wrapf(NoConditionPassedToRunTransaction, "transition type [%s] source state [%s]",
transitionType, stateSwitch.State())
}
func (sm *stateMachine) AddTransition(rule TransitionRule) {
sm.AddTransitionRule(rule)
}
func (sm *stateMachine) AddTransitionRule(rule TransitionRule) {
sm.transitionRules[rule.TransitionType] = append(sm.transitionRules[rule.TransitionType], rule)
}