/
machine.go
381 lines (300 loc) · 9.06 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
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package hsm
import (
"fmt"
"reflect"
"sync"
)
// HSM represents a finite state machine.
type HSM[C any] struct {
// human-readable name of this machine
name string
// serves as machine's extended states
// see: https://en.wikipedia.org/wiki/UML_state_machine#Extended_states
context C
// list of states within this machine
states map[string]*Vertex[C]
// pointer to the current state
currentState *Vertex[C]
// pointer to a state that will be entered whenever an error occurs in the state
// machine.
errorState *Vertex[C]
// holds a history of (successfully) triggered signals in this HSM
signalsHistory []string
// holds a sequence history of states this HSM has been passing through
statesHistory []string
// guards access to HSM Signal() method
signalMutex sync.RWMutex
// guards to HSM current state
currentMutex sync.RWMutex
}
// Snapshot provides a public snapshot.
type Snapshot struct {
// Current state ID
StateID string
// Whether current state is final or not
Final bool
// History of signals applied to this HSM
SignalsHistory []string
// History of states this HSM been at
StatesHistory []string
}
// Current retrieves HSM`s current state.
func (h *HSM[C]) Current() *Vertex[C] {
h.currentMutex.RLock()
defer h.currentMutex.RUnlock()
return h.currentState
}
// At returns true if HSM is currently at the given state, false otherwise.
//
// This method returns true when asserting a parent state and HSM is currently at any of
// its children. For instance, given the following hierarchy of states where current state
// is `F`:
//
// A
// /|\
// B C D
// / /\
// [F] G H
// /
// I
//
// This method will return TRUE when checking for states {A, B, F} and FALSE for
// states {C, D, G, H, I}.
func (h *HSM[C]) At(vertex *Vertex[C]) bool {
h.currentMutex.RLock()
defer h.currentMutex.RUnlock()
if vertex.id == h.currentState.id {
return true
}
// check hierarchy
parent := h.currentState.parent
for parent != nil {
if vertex.id == parent.id {
return true
}
parent = parent.parent
}
return false
}
// Finished whether HSM is at a final state.
func (h *HSM[C]) Finished() bool {
h.currentMutex.RLock()
defer h.currentMutex.RUnlock()
return h.currentState.Final()
}
// Failed whether HSM is at error state.
func (h *HSM[C]) Failed() bool {
h.currentMutex.RLock()
defer h.currentMutex.RUnlock()
return h.currentState == h.errorState
}
// Can check whether the given trigger CAN be signaled, that is, it will produce a
// transition.
func (h *HSM[C]) Can(signal Signal) bool {
h.currentMutex.RLock()
defer h.currentMutex.RUnlock()
for _, t := range h.AvailableSignals() {
if h.kind(t) == h.kind(signal) {
return true
}
}
return false
}
// Signal sends the given signal and fires corresponding transitions if available from
// current state.
func (h *HSM[C]) Signal(signal Signal) error {
h.signalMutex.Lock()
defer h.signalMutex.Unlock()
if err := h.tryProgress(); err != nil {
return err
}
return h.apply(signal)
}
// Snapshot returns a serializable snapshot of this HSM.
func (h *HSM[C]) Snapshot() Snapshot {
h.currentMutex.RLock()
defer h.currentMutex.RUnlock()
return Snapshot{
StateID: h.currentState.id,
Final: h.currentState.Final(),
SignalsHistory: h.signalsHistory,
StatesHistory: h.statesHistory,
}
}
// AvailableSignals returns a set of events **susceptible** of producing a transition from the outside considering
// HSM`s current state; signals that could be used.
func (h *HSM[C]) AvailableSignals() []Signal {
var (
signals = make(map[string]Signal)
results = make([]Signal, 0)
)
for _, t := range h.currentState.edges.list() {
if t.guard == nil || t.guard.method(h.context) {
signals[h.kind(t.signal)] = t.signal
}
}
parent := h.currentState.parent
for parent != nil {
for _, t := range parent.edges.list() {
if t.guard == nil || t.guard.method(h.context) {
signals[h.kind(t.signal)] = t.signal
}
}
parent = parent.parent
}
for _, evt := range signals {
results = append(results, evt)
}
return results
}
// apply Applies the given signal on this HSM.
func (h *HSM[C]) apply(signal Signal) error {
// do while
var nextState = h.currentState
for ok := true; ok; ok = nextState != nil {
transition := h.getTransition(nextState, signal)
// If there were no transitions for the given signal for the current
// state, check if there are any transitions for any of the parent
// states (if any):
if transition == nil {
nextState = nextState.parent
continue
}
// A transition must have a next state defined. If the user has not
// defined the next state, go to error state:
if transition.nextStatePtr == nil {
h.goToErrorState(signal)
return fmt.Errorf("transition has no next state defined, hsm `%s`", h.name)
}
nextState = transition.nextStatePtr
switch transition.kind {
case transitionKindInternal:
return h.doInternalTransition(nextState, transition, signal)
case transitionKindNormal:
return h.doNormalTransition(nextState, transition, signal)
}
}
return fmt.Errorf("no transition was found from state `%s` and signal `%s`, hsm `%s`", h.currentState.id, h.kind(signal), h.name)
}
func (h *HSM[C]) doInternalTransition(nextState *Vertex[C], transition *Transition[C], signal Signal) error {
// Run transition effect (if any)
if transition.effect != nil {
if err := transition.effect.method(h.context, signal); err != nil {
h.goToErrorState(signal)
return err
}
}
// Record in history this successfully applied signal
h.signalsHistory = append(h.signalsHistory, h.kind(signal))
// success
return nil
}
func (h *HSM[C]) doNormalTransition(nextState *Vertex[C], transition *Transition[C], signal Signal) error {
// If the new state is a parent state, enter its entry state (if it has one).
// Step down through the whole family tree until a state without an entry state is found:
for nextState.entryState != nil {
nextState = nextState.entryState
}
// Run exit actions only if the current state is left (only if it does not return to itself):
if h.currentState.onExit != nil {
if err := h.currentState.onExit.method(h.context, signal); err != nil {
h.goToErrorState(signal)
return err
}
}
// Call the current state's parent state exit action if it has one
// and if new parent state is different than the current state's parent
if h.currentState.parent != nil &&
h.currentState.parent.onExit != nil &&
nextState.parent != h.currentState.parent {
if err := h.currentState.parent.onExit.method(h.context, signal); err != nil {
h.goToErrorState(signal)
return err
}
}
// Run transition effect (if any)
if transition.effect != nil {
if err := transition.effect.method(h.context, signal); err != nil {
h.goToErrorState(signal)
return err
}
}
// Call the new state's parent state entry action if it has one
// and if its parent state is different than the current states parent
// state
if nextState.parent != nil &&
nextState.parent.onEntry != nil &&
nextState.parent != h.currentState.parent {
if err := nextState.parent.onEntry.method(h.context, signal); err != nil {
h.goToErrorState(signal)
return err
}
}
// Call the new state's entry actions if it has any:
if nextState.onEntry != nil {
if err := nextState.onEntry.method(h.context, signal); err != nil {
h.goToErrorState(signal)
return err
}
}
h.write(nextState, true)
if h.currentState == h.errorState {
return fmt.Errorf("error state reached, hsm `%s`", h.name)
}
// Record in history this successfully applied signal
h.signalsHistory = append(h.signalsHistory, h.kind(signal))
// If next state is a choice pseudo-state then evaluate its branches and transition accordingly
if h.currentState.kind == vertexKindChoice {
return h.apply(nil)
}
if unconditional := h.getTransition(nextState, nil); unconditional != nil {
return h.apply(nil)
}
// success condition
return nil
}
func (h *HSM[C]) goToErrorState(signal Signal) {
h.write(h.errorState, true)
if s := h.currentState; s != nil && s.onEntry != nil {
if err := s.onEntry.method(h.context, signal); err != nil {
println("error while entering error state:", err.Error())
}
}
}
func (h *HSM[C]) getTransition(from *Vertex[C], signal Signal) *Transition[C] {
for _, t := range from.edges.bySignal(signal) {
if t.guard == nil {
return t
}
if t.guard.method(h.context) {
return t
}
}
return nil
}
// tryProgress forces hsm to progress if nil signal can be triggered.
func (h *HSM[C]) tryProgress() error {
transitions := h.currentState.edges.bySignal(nil)
if len(transitions) > 0 {
return h.apply(nil)
}
return nil
}
// kind returns the name of type for the given element.
func (h *HSM[C]) kind(i interface{}) string {
t := reflect.TypeOf(i)
if t == nil {
return "nil"
}
if t.Kind() == reflect.Ptr {
return "*" + t.Elem().Name()
}
return t.Name()
}
// write changes machine state, it is the only point in the code where this occurs.
func (h *HSM[C]) write(vertex *Vertex[C], log bool) {
if log {
h.statesHistory = append(h.statesHistory, vertex.id)
}
h.currentState = vertex
}