-
Notifications
You must be signed in to change notification settings - Fork 0
/
state_machine.go
62 lines (51 loc) · 1.38 KB
/
state_machine.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
package orchestrator
import (
"sort"
"time"
)
type (
statemachine struct {
state *State
context *context
}
State struct {
name string
transitions []Transition
action func(ctx *context) error
actionTimeout time.Duration
}
Transition struct {
to *State
priority int
shouldTakeTransition func(ctx context) bool
}
)
func (sm *statemachine) init(startState *State, ctx *context) {
sm.state = startState
sm.context = ctx
}
func (sm *statemachine) doAction() (bool, error) {
err := sm.state.action(sm.context)
// TODO: <Decision making> the priority can be dynamic according to the context values or static and cache it for performance improvement
// sort based on priority
sort.Slice(sm.state.transitions[:], func(i, j int) bool {
return sm.state.transitions[i].priority >= sm.state.transitions[j].priority
})
for _, ts := range sm.state.transitions {
if ts.shouldTakeTransition(*sm.context) {
sm.state = ts.to
return true, err
}
}
return false, err
}
func (sm *statemachine) getMemento() (*State, context) {
return sm.state, *sm.context
}
func (s *State) createTransition(to *State, priority int, shouldTakeTransition func(ctx context) bool) {
s.transitions = append(s.transitions, Transition{
to: to,
priority: priority,
shouldTakeTransition: shouldTakeTransition,
})
}