-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheventmanager.go
97 lines (82 loc) · 2.06 KB
/
eventmanager.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
// Package eventmanager emits events.
package eventmanager
import (
"fmt"
I "github.com/compozed/deployadactyl/interfaces"
"github.com/go-errors/errors"
)
type Err interface {
Error() string
}
type InvalidEventType struct {
Err
}
type EventManagerConstructor func(log I.DeploymentLogger, bindings []I.Binding) I.EventManager
// EventManager has handlers for each registered event type.
type EventManager struct {
Bindings []I.Binding
Log I.Logger
}
type legacyEventBinding struct {
etype string
handler I.Handler
}
func (b legacyEventBinding) Accepts(event interface{}) bool {
levent, ok := event.(I.Event)
if !ok {
return false
}
return levent.Type == b.etype
}
func (b legacyEventBinding) Emit(event interface{}) error {
levent, ok := event.(I.Event)
if !ok {
return InvalidEventType{Err: errors.New("invalid event type")}
}
return b.handler.OnEvent(levent)
}
func NewEventManager(log I.DeploymentLogger, bindings []I.Binding) I.EventManager {
if bindings == nil {
bindings = make([]I.Binding, 0)
}
return &EventManager{
Log: log,
Bindings: bindings,
}
}
// AddHandler takes a handler and eventType and returns an error if a handler is not provided.
func (e *EventManager) AddHandler(handler I.Handler, eventType string) error {
if handler == nil {
return InvalidArgumentError{}
}
e.Bindings = append(e.Bindings, legacyEventBinding{
etype: eventType,
handler: handler,
})
e.Log.Debugf("handler for [%s] event added successfully", eventType)
return nil
}
// Emit emits an event.
func (e *EventManager) Emit(event I.Event) error {
return e.EmitEvent(event)
}
func (e *EventManager) AddBinding(binding I.Binding) {
e.Bindings = append(e.Bindings, binding)
}
func (e EventManager) EmitEvent(event I.IEvent) (err error) {
defer func() {
if r := recover(); r != nil {
e.Log.Errorf("recovered from panic")
err = errors.New(fmt.Sprintf("Recovered from a panic: %v", r))
}
}()
for _, binding := range e.Bindings {
if binding.Accepts(event) {
err = binding.Emit(event)
if err != nil {
return err
}
}
}
return nil
}