-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy patheventbus.go
379 lines (344 loc) · 11.8 KB
/
eventbus.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
/*
* Copyright (c) 2021-2023 boot-go
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package boot
import (
"errors"
"fmt"
"reflect"
"sync"
)
// eventBus internal implementation
type eventBus struct {
Runtime Runtime `boot:"wire"`
handlers map[string][]*busListener // contains all handler for a given type
lock sync.RWMutex // a mutex for the handlers map and the isStarted flag
isStarted bool
queue []any // the queue which will receive the events until the init phase is changed
queueLock sync.RWMutex // a mutex for the queue of events
}
// Handler is a function which has one argument. This argument is usually a published event. An error
// may be optional provided. E.g. func(e MyEvent) err
type Handler any
// Event is published and can be any type
type Event any
// EventBus provides the ability to decouple components. It is designed as a replacement for direct
// methode calls, so components can subscribe for messages produced by other components.
type EventBus interface {
// Subscribe subscribes to a message type.
// Returns error if handler fails.
Subscribe(handler Handler) error
// Unsubscribe removes handler defined for a message type.
// Returns error if there are no handlers subscribed to the message type.
Unsubscribe(handler Handler) error
// Publish executes handler defined for a message type.
Publish(event Event) (err error)
// HasHandler returns true if exists any handler subscribed to the message type.
HasHandler(event Handler) bool
}
var _ Component = (*eventBus)(nil) // Verify conformity to Component
var (
// ErrHandlerMustNotBeNil is returned if the handler is nil, which is not allowed
ErrHandlerMustNotBeNil = errors.New("handler must not be nil")
// ErrEventMustNotBeNil is returned if the event is nil, which is not sensible
ErrEventMustNotBeNil = errors.New("event must not be nil")
// ErrUnknownEventType is returned if the event type could not be determined
ErrUnknownEventType = errors.New("couldn't determiner the message type")
// ErrHandlerNotFound is returned if the handler to be removed could not be found
ErrHandlerNotFound = errors.New("handler not found to remove")
)
// Init is described in the Component interface
func (bus *eventBus) Init() error {
bus.lock.Lock()
defer bus.lock.Unlock()
bus.isStarted = false
return nil
}
func (bus *eventBus) activate() error {
bus.lock.Lock()
bus.isStarted = true
bus.lock.Unlock()
// republishing queued events
bus.queueLock.RLock()
defer bus.queueLock.RUnlock()
Logger.Debug.Printf("eventbus started with %d queued events\n", len(bus.queue))
pubErr := newPublicError()
for _, event := range bus.queue {
err := bus.Publish(event)
if err != nil {
Logger.Error.Printf("publishing queued event failed on eventbus start: %v", err.Error())
if p, ok := err.(*PublishError); ok { //nolint:errorlint // casting required
pubErr.addPublishError(p)
} else {
Logger.Error.Printf("unrecoverable error occurred while activating eventbus %v", err)
return err
}
}
}
if pubErr.hasErrors() {
return pubErr
}
return nil
}
// busListener contains the reference to one subscribed member
type busListener struct {
handler reflect.Value
qualifiedName string
eventTypeName string
}
// newBusListener will validate the handler and return the name of the event type, which is provided
// as an argument to the handler
func newBusListener(handler Handler) (*busListener, error) {
if handler == nil {
return nil, ErrHandlerMustNotBeNil
}
if reflect.TypeOf(handler).Kind() != reflect.Func {
return nil, fmt.Errorf("handler is not a function - detail: %s is not of type reflect.Func", reflect.TypeOf(handler).Kind())
}
// validate argument
argValue := reflect.ValueOf(handler)
if argValue.Type().NumIn() != 1 {
return nil, fmt.Errorf("handler function has unsupported argument, found %d but requires 1" + fmt.Sprintf("%v", argValue.Type().NumIn()))
}
// validate return value type
switch argValue.Type().NumOut() {
case 0:
case 1:
retType := argValue.Type().Out(0)
if _, ok := reflect.New(retType).Interface().(*error); !ok {
return nil, fmt.Errorf("handler function return type is not an error")
}
default:
return nil, fmt.Errorf("handler function has more than one return value, found %d but requires 1" + fmt.Sprintf("%v", argValue.Type().NumOut()))
}
path := argValue.Type().In(0).PkgPath()
name := argValue.Type().In(0).Name()
if len(path) == 0 && len(name) == 0 {
return nil, ErrUnknownEventType
}
eventTypeName := path + "/" + name
return &busListener{
handler: argValue,
qualifiedName: QualifiedName(handler),
eventTypeName: eventTypeName,
}, nil
}
// newEventbus returns new an eventBus.
func newEventbus() *eventBus {
return &eventBus{
handlers: make(map[string][]*busListener),
lock: sync.RWMutex{},
queue: nil,
}
}
// Subscribe subscribes to a message type.
// Returns error if `fn` is not a function.
func (bus *eventBus) Subscribe(handler Handler) error {
eventHandler, err := newBusListener(handler)
if err != nil {
errRet := fmt.Errorf("%s seems not to be a regular handler function: %w", QualifiedName(handler), err)
Logger.Error.Printf(errRet.Error())
return errRet
}
defer bus.lock.Unlock()
bus.lock.Lock()
bus.handlers[eventHandler.eventTypeName] = append(bus.handlers[eventHandler.eventTypeName], eventHandler)
Logger.Debug.Printf("handler %s subscribed\n", eventHandler.qualifiedName)
return nil
}
// HasHandler returns true if exists any subscribed message handler.
func (bus *eventBus) HasHandler(handler Handler) bool {
bus.lock.Lock()
defer bus.lock.Unlock()
eventType := QualifiedName(handler)
_, ok := bus.handlers[eventType]
if ok {
return len(bus.handlers[eventType]) > 0
}
return false
}
// Unsubscribe removes handler defined for a message type.
// Returns error if there are no handlers subscribed to the message type.
func (bus *eventBus) Unsubscribe(handler Handler) error {
eventHandler, err := newBusListener(handler)
if err != nil {
errRet := fmt.Errorf("%s seems not to be an regular handler function: %w", QualifiedName(handler), err)
Logger.Error.Printf(errRet.Error())
return errRet
}
bus.lock.Lock()
defer bus.lock.Unlock()
if _, ok := bus.handlers[eventHandler.eventTypeName]; ok && len(bus.handlers[eventHandler.eventTypeName]) > 0 {
if ok := bus.removeHandler(eventHandler.eventTypeName, bus.findHandler(eventHandler.eventTypeName, handler)); !ok {
return ErrHandlerNotFound
}
Logger.Debug.Printf("handler %s unsubscribed \n", eventHandler.qualifiedName)
return nil
}
return fmt.Errorf("eventType %s doesn't exist", QualifiedName(handler))
}
// PublishError will be provided by the
type PublishError struct {
failedListeners map[Event]map[*busListener]error
}
func newPublicError() *PublishError {
return &PublishError{
failedListeners: make(map[Event]map[*busListener]error),
}
}
func (err *PublishError) hasErrors() bool {
return len(err.failedListeners) > 0
}
func (err *PublishError) addPublishError(pubErr *PublishError) {
for event, m := range pubErr.failedListeners {
for key, pErr := range m {
err.addError(event, key, pErr)
}
}
}
func (err *PublishError) addError(e Event, bl *busListener, pubErr error) {
m := err.failedListeners[e]
if m == nil {
m = make(map[*busListener]error)
err.failedListeners[e] = m
}
m[bl] = pubErr
}
// Error is used to confirm to the error interface
func (err *PublishError) Error() string {
str := "publish failed for "
for event, m := range err.failedListeners {
str += fmt.Sprintf("event: %s", QualifiedName(event))
for key, pErr := range m {
str = fmt.Sprintf("%s [%s: %s]", str, key.qualifiedName, pErr.Error())
}
}
return str
}
var _ error = (*PublishError)(nil) // force error to confirm to error interface
// Publish executes handler defined for a message type. Any additional argument will be transferred to the handler.
func (bus *eventBus) Publish(event Event) (err error) {
// if the bus is processing already, the upcoming messages will be queued
var eventType string
defer func() {
if r := recover(); r != nil {
switch v := r.(type) {
case error:
err = v
case string:
err = errors.New(v)
default:
err = fmt.Errorf("unsupported error type found %s", QualifiedName(v))
}
}
if err != nil {
Logger.Error.Printf("publishing event %s failed: %s\n", eventType, err.Error())
}
}()
if event == nil {
return ErrEventMustNotBeNil
}
eventType = QualifiedName(event)
bus.lock.RLock()
started := bus.isStarted
bus.lock.RUnlock()
if !started {
Logger.Debug.Printf("queuing event %s\n", eventType)
bus.queueLock.Lock()
defer bus.queueLock.Unlock()
bus.queue = append(bus.queue, event)
return nil
}
Logger.Debug.Printf("publishing event %s\n", eventType)
if handlers, ok := bus.handlers[eventType]; ok && 0 < len(handlers) {
// Handlers slice may be changed by removeHandler and Unsubscribe during iteration,
// so make a copy and iterate the copied slice.
bus.lock.RLock()
copyHandlers := make([]*busListener, len(handlers))
copy(copyHandlers, handlers)
bus.lock.RUnlock()
pErr := bus.publish(event, copyHandlers)
if pErr != nil {
return pErr
}
}
return err
}
// publish the event to all provided bus listeners
func (bus *eventBus) publish(event Event, listeners []*busListener) *PublishError {
errPublish := newPublicError()
for _, listener := range listeners {
passedArguments := bus.prepare(event)
ret := listener.handler.Call(passedArguments)
// a handler may return an error... validation will verify
if len(ret) == 1 {
err, ok := ret[0].Interface().(error)
if ok && err != nil {
errPublish.addError(event, listener, err)
}
}
}
if len(errPublish.failedListeners) > 0 {
return errPublish
}
return nil
}
func (bus *eventBus) removeHandler(eventTypeName string, index int) bool {
l := len(bus.handlers[eventTypeName])
if !(0 <= index && index < l) {
return false
}
copy(bus.handlers[eventTypeName][index:], bus.handlers[eventTypeName][index+1:])
bus.handlers[eventTypeName][l-1] = nil // or the zero value of T
bus.handlers[eventTypeName] = bus.handlers[eventTypeName][:l-1]
return true
}
func (bus *eventBus) findHandler(eventTypeName string, handler any) int {
if _, ok := bus.handlers[eventTypeName]; ok {
for index, h := range bus.handlers[eventTypeName] {
if h.qualifiedName == QualifiedName(handler) {
return index
}
}
}
return -1
}
func (bus *eventBus) prepare(event any) []reflect.Value {
callArgs := make([]reflect.Value, 1)
callArgs[0] = reflect.ValueOf(event)
return callArgs
}
// testableEventBus box for handlers and callbacks.
type testableEventBus struct {
eventBus
}
// newTestableEventBus can be used for unit testing.
func newTestableEventBus() *testableEventBus {
return &testableEventBus{eventBus{
Runtime: &runtime{
modes: []Flag{UnitTestFlag},
},
handlers: make(map[string][]*busListener),
lock: sync.RWMutex{},
queue: nil,
}}
}