-
Notifications
You must be signed in to change notification settings - Fork 16
/
machine.go
161 lines (130 loc) · 3.58 KB
/
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package statemachine
import (
"context"
"reflect"
"sync/atomic"
"github.com/filecoin-project/go-statestore"
xerrors "golang.org/x/xerrors"
logging "github.com/ipfs/go-log/v2"
)
var log = logging.Logger("evtsm")
var ErrTerminated = xerrors.New("normal shutdown of state machine")
type Event struct {
User interface{}
}
// Planner processes in queue events
// It returns:
// 1. a handler of type -- func(ctx Context, st <T>) (func(*<T>), error), where <T> is the typeOf(User) param
// 2. the number of events processed
// 3. an error if occured
type Planner func(events []Event, user interface{}) (interface{}, uint64, error)
type StateMachine struct {
planner Planner
eventsIn chan Event
name interface{}
st *statestore.StoredState
stateType reflect.Type
closing chan struct{}
closed chan struct{}
busy int32
}
func (fsm *StateMachine) run() {
defer close(fsm.closed)
var pendingEvents []Event
stageDone := make(chan struct{})
for {
// NOTE: This requires at least one event to be sent to trigger a stage
// This means that after restarting the state machine users of this
// code must send a 'restart' event
select {
case evt := <-fsm.eventsIn:
pendingEvents = append(pendingEvents, evt)
log.Debugw("appended new pending evt", "len(pending)", len(pendingEvents))
case <-stageDone:
if len(pendingEvents) == 0 {
continue
}
case <-fsm.closing:
return
}
select {
case <-fsm.closing:
return
default:
}
if atomic.CompareAndSwapInt32(&fsm.busy, 0, 1) {
log.Debugw("sm run in critical zone", "len(pending)", len(pendingEvents))
var nextStep interface{}
var ustate interface{}
var processed uint64
var terminated bool
err := fsm.mutateUser(func(user interface{}) (err error) {
nextStep, processed, err = fsm.planner(pendingEvents, user)
ustate = user
if xerrors.Is(err, ErrTerminated) {
terminated = true
return nil
}
return err
})
if terminated {
return
}
if err != nil {
log.Errorf("Executing event planner failed: %+v", err)
return
}
if processed < uint64(len(pendingEvents)) {
pendingEvents = pendingEvents[processed:]
} else {
pendingEvents = nil
}
ctx := Context{
ctx: context.TODO(),
send: func(evt interface{}) error {
return fsm.send(Event{User: evt})
},
}
go func() {
defer log.Debugw("leaving critical zone and resetting atomic var to zero")
if nextStep != nil {
res := reflect.ValueOf(nextStep).Call([]reflect.Value{reflect.ValueOf(ctx), reflect.ValueOf(ustate).Elem()})
if res[0].Interface() != nil {
log.Errorf("executing step: %+v", res[0].Interface().(error)) // TODO: propagate top level
return
}
}
atomic.StoreInt32(&fsm.busy, 0)
select {
case stageDone <- struct{}{}:
case <-fsm.closed:
}
}()
}
}
}
func (fsm *StateMachine) mutateUser(cb func(user interface{}) error) error {
mutt := reflect.FuncOf([]reflect.Type{reflect.PtrTo(fsm.stateType)}, []reflect.Type{reflect.TypeOf(new(error)).Elem()}, false)
mutf := reflect.MakeFunc(mutt, func(args []reflect.Value) (results []reflect.Value) {
err := cb(args[0].Interface())
return []reflect.Value{reflect.ValueOf(&err).Elem()}
})
return fsm.st.Mutate(mutf.Interface())
}
func (fsm *StateMachine) send(evt Event) error {
select {
case <-fsm.closed:
return ErrTerminated
case fsm.eventsIn <- evt: // TODO: ctx, at least
return nil
}
}
func (fsm *StateMachine) stop(ctx context.Context) error {
close(fsm.closing)
select {
case <-fsm.closed:
return nil
case <-ctx.Done():
return ctx.Err()
}
}