forked from Zenithar/go-common
-
Notifications
You must be signed in to change notification settings - Fork 0
/
local.go
187 lines (169 loc) · 5.4 KB
/
local.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
package eventbus
import (
"fmt"
"reflect"
"sync"
)
// EventBus - box for handlers and callbacks.
type eventBus struct {
handlers map[string][]*eventHandler
lock sync.Mutex // a lock for the map
wg sync.WaitGroup
}
type eventHandler struct {
callBack reflect.Value
flagOnce bool
async bool
transactional bool
called bool
sync.Mutex // lock for an event handler - useful for running async callbacks serially
}
// NewLocal returns new EventBus with empty handlers.
func NewLocal() EventBus {
return &eventBus{
make(map[string][]*eventHandler),
sync.Mutex{},
sync.WaitGroup{},
}
}
// Subscribe subscribes to a topic.
// Returns error if `fn` is not a function.
func (bus *eventBus) Subscribe(topic string, fn interface{}) error {
bus.lock.Lock()
defer bus.lock.Unlock()
if !(reflect.TypeOf(fn).Kind() == reflect.Func) {
return fmt.Errorf("%s is not of type reflect.Func", reflect.TypeOf(fn).Kind())
}
v := reflect.ValueOf(fn)
bus.handlers[topic] = append(bus.handlers[topic], &eventHandler{
v, false, false, false, false, sync.Mutex{},
})
return nil
}
// SubscribeAsync subscribes to a topic with an asynchronous callback
// Transactional determines whether subsequent callbacks for a topic are
// run serially (true) or concurrently (false)
// Returns error if `fn` is not a function.
func (bus *eventBus) SubscribeAsync(topic string, fn interface{}, transactional bool) error {
bus.lock.Lock()
defer bus.lock.Unlock()
if !(reflect.TypeOf(fn).Kind() == reflect.Func) {
return fmt.Errorf("%s is not of type reflect.Func", reflect.TypeOf(fn).Kind())
}
v := reflect.ValueOf(fn)
bus.handlers[topic] = append(bus.handlers[topic], &eventHandler{
v, false, true, transactional, false, sync.Mutex{},
})
return nil
}
// SubscribeOnce subscribes to a topic once. Handler will be removed after executing.
// Returns error if `fn` is not a function.
func (bus *eventBus) SubscribeOnce(topic string, fn interface{}) error {
bus.lock.Lock()
defer bus.lock.Unlock()
if !(reflect.TypeOf(fn).Kind() == reflect.Func) {
return fmt.Errorf("%s is not of type reflect.Func", reflect.TypeOf(fn).Kind())
}
v := reflect.ValueOf(fn)
bus.handlers[topic] = append(bus.handlers[topic], &eventHandler{
v, true, false, false, false, sync.Mutex{},
})
return nil
}
// SubscribeOnceAsync subscribes to a topic once with an asyncrhonous callback
// Handler will be removed after executing.
// Returns error if `fn` is not a function.
func (bus *eventBus) SubscribeOnceAsync(topic string, fn interface{}) error {
bus.lock.Lock()
defer bus.lock.Unlock()
if !(reflect.TypeOf(fn).Kind() == reflect.Func) {
return fmt.Errorf("%s is not of type reflect.Func", reflect.TypeOf(fn).Kind())
}
v := reflect.ValueOf(fn)
bus.handlers[topic] = append(bus.handlers[topic], &eventHandler{
v, true, true, false, false, sync.Mutex{},
})
return nil
}
// HasCallback returns true if exists any callback subscribed to the topic.
func (bus *eventBus) HasCallback(topic string) bool {
bus.lock.Lock()
defer bus.lock.Unlock()
_, ok := bus.handlers[topic]
if ok {
return len(bus.handlers[topic]) > 0
}
return false
}
// Unsubscribe removes callback defined for a topic.
// Returns error if there are no callbacks subscribed to the topic.
func (bus *eventBus) Unsubscribe(topic string, handler interface{}) error {
bus.lock.Lock()
defer bus.lock.Unlock()
if _, ok := bus.handlers[topic]; ok && len(bus.handlers[topic]) > 0 {
bus.removeHandler(topic, reflect.ValueOf(handler))
return nil
}
return fmt.Errorf("topic %s doesn't exist", topic)
}
// Publish executes callback defined for a topic. Any addional argument will be tranfered to the callback.
func (bus *eventBus) Publish(topic string, args ...interface{}) {
bus.lock.Lock() // will unlock if handler is not found or always after setUpPublish
defer bus.lock.Unlock()
if handlers, ok := bus.handlers[topic]; ok {
for _, handler := range handlers {
if !handler.async {
bus.doPublish(handler, topic, args...)
} else {
bus.wg.Add(1)
go bus.doPublishAsync(handler, topic, args...)
}
}
}
}
func (bus *eventBus) doPublish(handler *eventHandler, topic string, args ...interface{}) {
passedArguments := bus.setUpPublish(topic, args...)
if handler.flagOnce {
bus.removeHandler(topic, handler.callBack)
if handler.called {
return
}
}
handler.called = true
handler.callBack.Call(passedArguments)
}
func (bus *eventBus) doPublishAsync(handler *eventHandler, topic string, args ...interface{}) {
defer bus.wg.Done()
if handler.transactional {
handler.Lock()
defer handler.Unlock()
}
bus.doPublish(handler, topic, args...)
}
func (bus *eventBus) findHandlerIdx(topic string, callback reflect.Value) int {
if _, ok := bus.handlers[topic]; ok {
for idx, handler := range bus.handlers[topic] {
if handler.callBack == callback {
return idx
}
}
}
return -1
}
func (bus *eventBus) removeHandler(topic string, callback reflect.Value) {
i := bus.findHandlerIdx(topic, callback)
if i >= 0 {
bus.handlers[topic] = append(bus.handlers[topic][:i], bus.handlers[topic][i+1:]...)
}
}
func (bus *eventBus) setUpPublish(topic string, args ...interface{}) []reflect.Value {
var passedArguments = make([]reflect.Value, 0)
for _, arg := range args {
passedArguments = append(passedArguments, reflect.ValueOf(arg))
}
return passedArguments
}
// WaitAsync waits for all async callbacks to complete
func (bus *eventBus) WaitAsync() {
bus.wg.Wait()
}