-
Notifications
You must be signed in to change notification settings - Fork 19
/
event_callback_def.go
101 lines (84 loc) · 2.49 KB
/
event_callback_def.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
package statemachine
import (
"fmt"
"reflect"
)
type EventCallbackFuncDef struct {
RegisteredFunc string `json:",omitempty" hcl:"registered_func" hcle:"omitempty"`
Func EventCallbackFunc `json:"-" hcle:"omit"`
}
type EventCallbackDef struct {
On []string `json:",omitempty" hcl:"on" hcle:"omitempty"`
ExceptOn []string `json:",omitempty" hcl:"except_on" hcle:"omitempty"`
Do []*EventCallbackFuncDef `json:",omitempty" hcl:"do" hcle:"omitempty"`
validateFor string `json:"-" hcle:"omit"`
}
func (s *EventCallbackDef) MatchesEvent(event string) bool {
for _, e := range s.ExceptOn {
if e == event {
return false
}
}
if len(s.On) == 0 {
return true
}
for _, e := range s.On {
if e == event {
return true
}
}
return false
}
func (s *EventCallbackDef) SetOn(events ...string) {
for _, event := range events {
s.On = append(s.On, event)
}
}
func (s *EventCallbackDef) SetOnAnyEventExcept(exceptEvents ...string) {
for _, exceptEvent := range exceptEvents {
s.ExceptOn = append(s.ExceptOn, exceptEvent)
}
}
func (s *EventCallbackDef) AddCallbackFunc(callbackFunc EventCallbackFunc) {
s.assertCallbackKind(callbackFunc)
s.Do = append(s.Do, &EventCallbackFuncDef{Func: callbackFunc})
}
func (s *EventCallbackDef) assertCallbackKind(callbackFunc EventCallbackFunc) {
t := reflect.TypeOf(callbackFunc)
switch t.Kind() {
case reflect.Func:
if t.NumOut() != 0 {
panic("callback func must not return anything")
}
optionalArgs := make(map[reflect.Type]struct{})
requiredArgs := make(map[reflect.Type]struct{})
switch s.validateFor {
case "AfterFailure":
optionalArgs[reflect.TypeOf(new(Event))] = struct{}{}
requiredArgs[reflect.TypeOf(new(error))] = struct{}{}
}
// ensure all args are of expected types, whether optional or required
for i := 0; i < t.NumIn(); i++ {
argType := t.In(i)
if _, ok := optionalArgs[reflect.PtrTo(argType)]; ok {
continue
}
if _, ok := requiredArgs[reflect.PtrTo(argType)]; ok {
continue
}
panic(fmt.Sprintf("unexpected argument with type '%s' in %s callback", argType, s.validateFor))
}
outer:
// ensure required args are present
for requiredArg := range requiredArgs {
for i := 0; i < t.NumIn(); i++ {
if requiredArg.Elem() == t.In(i) {
continue outer
}
}
panic(fmt.Sprintf("missing required arg '%s' in %s callback", requiredArg.Elem().String(), s.validateFor))
}
return
}
panic("callback must be a compatible func")
}