-
Notifications
You must be signed in to change notification settings - Fork 0
/
localbus.go
235 lines (194 loc) · 5.99 KB
/
localbus.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
package localbus
import (
"context"
"fmt"
"github.com/AltScore/gothic/pkg/eventbus"
"github.com/AltScore/gothic/pkg/logger"
"go.uber.org/atomic"
"go.uber.org/zap"
"strings"
)
// Option is a function that configures a localBus
type Option func(bus *localBus)
// localBus is an in-memory event bus implementation of EventBus interface.
type localBus struct {
logger logger.Logger
listeners consumersMap
eventCh chan *eventbus.EventEnvelope
running atomic.Bool
size int
ctx context.Context
lifeCycleListeners []eventbus.LifeCycleListener
}
// NewLocalBus creates a new localBus instance and configures it with the given options.
func NewLocalBus(options ...Option) eventbus.EventBus {
bus := &localBus{
listeners: consumersMap{},
}
bus.applyOptions(options)
return bus
}
func (b *localBus) applyOptions(options []Option) {
for _, option := range options {
option(b)
}
}
// Start starts the localBus event processing loop.
// It is safe to call Start multiple times, but only the first call will start the event processing loop.
func (b *localBus) Start() error {
if !b.running.CompareAndSwap(false, true) {
return eventbus.ErrBusAlreadyRunning
}
if b.ctx == nil {
b.ctx = context.Background()
}
if b.logger == nil {
b.logger = logger.New()
}
b.eventCh = make(chan *eventbus.EventEnvelope, b.size)
go b.processEvents()
b.informStarted()
return nil
}
// Stop stops the localBus event processing loop.
// It is safe to call Stop multiple times, but only the first call will stop the event processing loop.
// After stopping the event processing loop, the localBus can be started again.
func (b *localBus) Stop() error {
if !b.running.CompareAndSwap(true, false) {
return eventbus.ErrBusNotRunning
}
b.informStopping()
close(b.eventCh)
return nil
}
func (b *localBus) AddLifecycleListener(listener eventbus.LifeCycleListener) {
if listener != nil {
b.lifeCycleListeners = append(b.lifeCycleListeners, listener)
if b.running.Load() {
listener.OnStart(b.ctx) // lazy listener is added after the bus was started
}
}
}
// Publish publishes an event to the localBus.
// All the registered consumers for the event will be called in a separate goroutine.
// Publish is non-blocking and returns immediately.
// If any of the consumers returns an error, the error will be returned by Publish to the configured callback.
func (b *localBus) Publish(event eventbus.Event, options ...eventbus.Option) error {
if !b.running.Load() {
return eventbus.ErrBusNotRunning
}
envelope := &eventbus.EventEnvelope{
Event: event,
Ctx: b.ctx,
}
envelope.ProcessOptions(options)
b.eventCh <- envelope
if envelope.ShouldWait {
// TODO
}
return nil
}
// Subscribe subscribes a consumer to an event.
// The consumer will be called when an event with the given name is published.
// The consumer will be called in a separate goroutine.
// If the consumer returns an error, the error will be returned by Publish to the configured callback.
// All the consumers for an event will be called in the order they were registered.
func (b *localBus) Subscribe(eventName eventbus.EventName, consumer eventbus.EventConsumer) error {
eventNameTrimmed := strings.TrimSpace(eventName)
if eventNameTrimmed == "" {
return eventbus.ErrEmptyEventName
}
b.listeners.addConsumer(eventNameTrimmed, consumer)
return nil
}
func (b *localBus) processEvents() {
b.logger.Info("Starting event bus")
for {
select {
case <-b.ctx.Done():
b.logger.Info("Stopping event bus due to context done")
return
case envelope, ok := <-b.eventCh:
if !ok {
b.logger.Info("Stopping event bus due to channel closed")
return
}
b.processEvent(envelope)
}
}
}
func (b *localBus) processEvent(envelope *eventbus.EventEnvelope) {
event := envelope.Event
listeners := b.listeners.getConsumers(event.Name())
if len(listeners) == 0 {
b.logger.Warn(
"No listeners found for event",
zap.String("name", event.Name()),
zap.String("id", event.ID().String()),
)
if envelope.Callback != nil {
// Report unhandled event error to caller
envelope.Callback(event, eventbus.NewErrUnhandledEvent(event.Name(), event.ID()))
return
}
} else {
b.logger.Debug(
"Processing event",
zap.String("name", event.Name()),
zap.String("id", event.ID().String()),
)
}
isCallCallbackPending := true
for _, listener := range listeners {
if err := b.executeWithRecovery(listener, envelope.Ctx, event); isCallCallbackPending && err != nil {
b.logger.Debug("Error while processing event", zap.Error(err))
// First callback error is the one that will be returned
// TODO: Should all errors be returned? they can be aggregated into a single error
if envelope.Callback != nil {
envelope.Callback(event, envelope.Err)
}
isCallCallbackPending = false
}
}
if isCallCallbackPending && envelope.Callback != nil {
// All callbacks run successfully
envelope.Callback(event, nil)
}
}
func (b *localBus) executeWithRecovery(listener eventbus.EventConsumer, ctx context.Context, event eventbus.Event) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic while executing event consumer: %v", r)
b.logger.Error("panic while executing event consumer", zap.Any("error", r))
}
}()
return listener(ctx, event)
}
func (b *localBus) informStarted() {
for _, listener := range b.lifeCycleListeners {
listener.OnStart(b.ctx)
}
}
func (b *localBus) informStopping() {
for _, listener := range b.lifeCycleListeners {
listener.OnStop()
}
}
// WithBufferSize sets the size of the event buffer.
// If the buffer is full, Publish will block until there is space in the buffer.
func WithBufferSize(size int) Option {
return func(bus *localBus) {
bus.size = size
}
}
// WithLogger sets the logger to use by the localBus.
func WithLogger(logger logger.Logger) Option {
return func(bus *localBus) {
bus.logger = logger
}
}
func WithContext(ctx context.Context) Option {
return func(bus *localBus) {
bus.ctx = ctx
}
}