-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfsm.go
259 lines (217 loc) · 6.24 KB
/
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
// This file is part of Botgoram
// Botgoram is free software: see LICENSE.txt for more details.
package botgoram
import (
"errors"
"fmt"
"github.com/Patrolavia/telegram"
)
// ErrStateNotFound tells you if no such state name was registered in fsm.
var ErrStateNotFound = errors.New("State not found.")
// Action describes what to do when enter/leaving a state.
type Action func(msg *telegram.Message, current State, api telegram.API) error
// FSM is a finite state machine.
type FSM interface {
// Start will "power on" the FSM.
// It will block until any worker goes wrong, stop that worker and return the error.
// At the mean time, other worker will stay working.
Start(timeout int) error
// Resume the stopped worker. Calling Resume will block until any worker goes wrong.
Resume() error
AddState(id string, enter, leave Action) (State, error)
State(id string) (State, bool)
// MakeState will register a new state with StateMaker.
// Transitors will be registered when first call to FSM.Start()
MakeState(StateMaker) (State, error)
// StateMap generate graphviz diagram from registered StateMaker
StateMap(name string) (dot string)
}
func bySender(msg *telegram.Message) *telegram.Victim {
return msg.From
}
func byChat(msg *telegram.Message) *telegram.Victim {
return msg.Chat
}
type internalStateData struct {
state State
enter Action
leave Action
}
type fsm struct {
api telegram.API
userExtractor func(*telegram.Message) *telegram.Victim
states map[string]internalStateData
storage SaveLoader
manager *manager
errorChannel chan error
sm []StateMaker
}
func newFSM(api telegram.API, ue func(*telegram.Message) *telegram.Victim, sl SaveLoader, size int, msgs chan *telegram.Message) (ret FSM) {
if msgs == nil {
msgs = make(chan *telegram.Message)
lp := &telegram.LongPollFetcher{
Message: msgs,
API: api,
}
go func(lp *telegram.LongPollFetcher) {
for {
lp.Fetch(size, 30) // just retry if error occurs
}
}(lp)
}
tmp := &fsm{
api, ue, map[string]internalStateData{
"": internalStateData{state: newState("")},
}, sl, newManager(ue, size, msgs),
make(chan error, size),
make([]StateMaker, 0),
}
for i := 0; i < size; i++ {
tmp.errorChannel <- nil
}
return tmp
}
// NewBySender creates a FSM associates with message sender.
//
// You can provide a message channel for Botgoram to read message from.
// This helps if your program needs to do some preprocessings or manage other update types like inline query.
// Leave it nil will use default implementation: 30 secs long-polling, ignoring other update types and errors.
func NewBySender(api telegram.API, sl SaveLoader, size int, msgs chan *telegram.Message) FSM {
return newFSM(api, bySender, sl, size, msgs)
}
// NewByChat creates a FSM associates with chatroom.
//
// You can provide a message channel for Botgoram to read message from.
// This helps if your program needs to do some preprocessings or manage other update types like inline query.
// Leave it nil will use default implementation: 30 secs long-polling, ignoring other update types and errors.
func NewByChat(api telegram.API, sl SaveLoader, size int, msgs chan *telegram.Message) FSM {
return newFSM(api, byChat, sl, size, msgs)
}
func (f *fsm) MakeState(sm StateMaker) (ret State, err error) {
enter, leave := sm.Actions()
if ret, err = f.AddState(sm.Name(), enter, leave); err != nil {
return
}
f.sm = append(f.sm, sm)
return
}
func (f *fsm) AddState(id string, enter, leave Action) (ret State, err error) {
if _, ok := f.states[id]; ok {
return ret, fmt.Errorf("State id %s is in use.", id)
}
ret = newState(id)
f.states[id] = internalStateData{ret, enter, leave}
return
}
func (f *fsm) State(id string) (ret State, ok bool) {
res, ok := f.states[id]
if ok {
ret = res.state
}
return
}
// register statemaker's transitors
func (f *fsm) registerStateMapTransitors() error {
for _, s := range f.sm {
for _, t := range s.Transitors() {
if t.IsHidden {
continue
}
st, ok := f.State(t.State)
if !ok {
return ErrStateNotFound
}
switch {
case t.IsFallback:
st.RegisterFallback(t.Transitor)
case t.Command != "" && t.Type == TextMsg:
st.RegisterCommand(t.Command, t.Transitor)
default:
st.Register(t.Type, t.Transitor)
}
}
}
f.sm = []StateMaker{}
return nil
}
func (f *fsm) Start(timeout int) error {
if err := f.registerStateMapTransitors(); err != nil {
return err
}
// start message manager
go f.manager.Run()
// start worker goroutines
return f.Resume()
}
func (f *fsm) Resume() error {
for err := range f.errorChannel {
if err != nil {
return err
}
go func() { f.errorChannel <- f.work() }()
}
return nil
}
func (f *fsm) work() (err error) {
msg := f.manager.Begin()
defer f.manager.Rollback(msg)
user := f.userExtractor(msg)
sid, data, err := f.storage.Load(user.Identifier())
if err != nil {
return
}
currentNode, ok := f.states[sid]
if !ok {
return fmt.Errorf("Cannot load state[%s] of user#%s", sid, user.Identifier())
}
cur := currentNode.state.clone(user)
cur.SetData(data)
doNext := func(cur State, msg *telegram.Message) (next State, err error) {
nextSID, err := cur.test(msg)
if err != nil {
return
}
return f.transit(msg, cur, nextSID)
}
next, err := doNext(cur, msg)
if err != nil {
return
}
for next.re() {
if next, err = doNext(next, msg); err != nil {
return
}
}
f.manager.Commit(msg)
return
}
func (f *fsm) transit(msg *telegram.Message, current State, id string) (next State, err error) {
user := current.User()
currentNode, ok := f.states[current.ID()]
if !ok {
return next, fmt.Errorf("Cannot load state[%s] of user#%d", current.ID(), user.Identifier())
}
nextNode, ok := f.states[id]
if !ok {
return next, fmt.Errorf("Cannot load next state[%s] of user#%d", id, user.Identifier())
}
next = nextNode.state.clone(user)
if currentNode.leave != nil {
if err = currentNode.leave(msg, current, f.api); err != nil {
return
}
}
next.SetData(current.Data())
if nextNode.enter != nil {
if err = nextNode.enter(msg, next, f.api); err != nil {
return
}
}
err = f.storage.Save(user.Identifier(), next.ID(), next.Data())
if next.next() != nil {
next, err = f.transit(msg, next, *next.next())
}
if next.re() {
}
return
}