-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgen_fsm.go
244 lines (197 loc) · 4.86 KB
/
gen_fsm.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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package go_gen_fsm
import (
"errors"
"fmt"
"reflect"
"time"
)
type GenFSM struct {
fsm FSM
handlerResolver HandlerResolver
currentState State
handlers map[State][]EventHandler
eventsChannel chan EventMessage
errorChannel chan error
sync sync
timer *time.Timer
shutdown bool
}
type FSM interface {
Init(args ...interface{}) State
}
type State string
type Event string
type EventHandler struct {
event Event
handlerFunc reflect.Method
}
type EventMessage struct {
Kind Event
Data []interface{}
}
type sync struct {
req chan interface{}
resp chan interface{}
handlers map[interface{}]func() interface{}
}
const (
NOOP = "NOOP"
TIMEOUT = "Timeout"
STOP = "Stop"
genericState = State("Handle")
genericEvent = Event("Info")
)
func Start(fsm FSM, args ...interface{}) *GenFSM {
g := newGenFsm()
g.fsm = fsm
g.currentState = fsm.Init(args...)
g.registerHandlers()
go g.doStart()
return g
}
func newGenFsm() *GenFSM {
g := new(GenFSM)
g.handlers = make(map[State][]EventHandler)
g.eventsChannel = make(chan EventMessage)
g.errorChannel = make(chan error, 10)
g.sync = sync{make(chan interface{}, 1), make(chan interface{}, 1), make(map[interface{}]func() interface{})}
g.handlerResolver = NewHandlerResolver()
return g
}
func (g *GenFSM) registerHandlers() {
fsmType := reflect.TypeOf(g.fsm)
nMethods := fsmType.NumMethod()
for i := 0; i < nMethods; i++ {
m := fsmType.Method(i)
match, state, event := g.handlerResolver.Resolve(m)
if match {
eventHandler := EventHandler{event: event, handlerFunc: m}
var stateEventHandlers []EventHandler
if h, ok := g.handlers[state]; ok {
stateEventHandlers = append(h, eventHandler)
} else {
stateEventHandlers = append(stateEventHandlers, eventHandler)
}
g.handlers[state] = stateEventHandlers
}
}
//Sync handler. For now, just support noop and shutdown
g.sync.handlers[NOOP] = noopHandler(g, NOOP)
g.sync.handlers[STOP] = noopHandler(g, STOP)
}
func (g *GenFSM) doStart() {
for !g.shutdown{
select {
case e, _ := <-g.eventsChannel:
g.handleEvent(e)
case r, _ := <-g.sync.req:
g.handleSync(r)
}
}
}
func (g *GenFSM) handleEvent(e EventMessage) {
defer func() {
if r := recover(); r != nil {
g.errorChannel <- errors.New(r.(string))
}
}()
eventHandler, err := g.getHandler(e.Kind)
if err != nil {
fmt.Printf("%s\n", err.Error())
g.errorChannel <- err
fmt.Printf("Checking if there is a generic `handle_info` handler\n")
eventHandler, err = g.getGenericHandler()
if err != nil {
fmt.Printf("Cannot find a generic handler `handle_info`\n")
g.errorChannel <- err
return
}
}
g.cancelTimer()
values := []reflect.Value{reflect.ValueOf(g.fsm)}
for _, d := range e.Data {
values = append(values, reflect.ValueOf(d))
}
returnValues := eventHandler.handlerFunc.Func.Call(values)
g.currentState = State(returnValues[0].String())
if len(returnValues) == 2 {
timeout := returnValues[1].Interface().(time.Duration)
g.scheduleTimeout(timeout)
}
g.errorChannel <- nil
}
func getHandler(handlers map[State][]EventHandler, state State, event Event) (EventHandler, error) {
stateHandlers, ok := handlers[state]
if !ok {
return EventHandler{}, errors.New(fmt.Sprintf("No handlers found for state %s", state))
}
for _, h := range stateHandlers {
if h.event == event {
return h, nil
}
}
return EventHandler{}, errors.New(fmt.Sprintf("No handlers found for state `%s` and event `%s` ", state, event))
}
func (g *GenFSM) getHandler(event Event) (EventHandler, error) {
return getHandler(g.handlers, g.currentState, event)
}
func (g *GenFSM) getGenericHandler() (EventHandler, error) {
return getHandler(g.handlers, genericState, genericEvent)
}
func (g *GenFSM) handleSync(req interface{}) {
if h, ok := g.sync.handlers[req]; ok {
resp := h()
g.sync.resp <- resp
}else {
fmt.Println(req)
g.sync.resp <- 404
}
if req != nil && STOP == req.(string) {
g.shutdown = true
g.closeAllChannels()
}
}
func noopHandler(g *GenFSM, req string) func() interface{} {
return func() interface{} {
return req
}
}
func (g *GenFSM) closeAllChannels() {
close(g.eventsChannel)
close(g.errorChannel)
close(g.sync.req)
close(g.sync.resp)
}
func (g *GenFSM) scheduleTimeout(timeout time.Duration) {
if timeout == -1 {
return
}
g.timer = time.NewTimer(timeout)
go func() {
<-g.timer.C
g.SendEvent(TIMEOUT)
}()
}
func (g *GenFSM) cancelTimer() {
if g.timer != nil {
g.timer.Stop()
}
}
func (g *GenFSM) SendEvent(kind Event, data ...interface{}) {
g.eventsChannel <- EventMessage{kind, data}
}
func (g *GenFSM) SendSyncReq(req interface{}) (resp interface{}) {
g.sync.req <- req
resp = <-g.sync.resp
return resp
}
func (g *GenFSM) Wait() {
g.SendSyncReq(NOOP)
}
func (g *GenFSM) Stop() {
g.cancelTimer()
g.SendSyncReq(STOP)
}
func (g *GenFSM) GetCurrentState() State {
return g.currentState
}