This repository has been archived by the owner on Oct 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
broker.go
286 lines (251 loc) · 7.2 KB
/
broker.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
package quark
import (
"context"
"sync"
"time"
"github.com/hashicorp/go-multierror"
)
// Broker coordinates every Event operation on the running Event-Driven application.
//
// Administrates Consumer(s) supervisors and their workers wrapped with well-known concurrency and resiliency patterns.
type Broker struct {
ProviderConfig interface{}
Cluster []string
ErrorHandler ErrorHandler
Publisher Publisher
EventMux EventMux
EventWriter EventWriter
PoolSize int
MaxRetries int
RetryBackoff time.Duration
ConnRetries int
ConnRetryBackoff time.Duration
MessageIDFactory IDFactory
WorkerFactory WorkerFactory
// BaseMessageSource is the default Source of a Message based on the CNCF CloudEvents specification v1
//
// It could be a Internet-wide unique URI with a DNS authority, Universally-unique URN with a UUID or
// Application-specific identifiers
//
// e.g. https://github.com/cloudevents, urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66, /cloudevents/spec/pull/123
BaseMessageSource string
// BaseMessageContentType is the default Content type of data value. This attribute enables data to carry any type of content,
// whereby format and encoding might differ from that of the chosen event format.
//
// Must adhere to the format specified in RFC 2046
//
// e.g. application/avro, application/json, application/cloudevents+json
BaseMessageContentType string
BaseContext context.Context
supervisors map[int]*Supervisor
activeSupervisors int
activeWorkers int
mu sync.Mutex
inShutdown atomicBool
doneChan chan struct{}
}
var (
defaultPoolSize = 5
defaultMaxRetries = 1
defaultRetryBackoff = time.Second * 3
defaultConnRetries = 3
defaultConnRetryBackoff = time.Second * 5
shutdownPollInterval = time.Millisecond * 500
)
// NewBroker allocates and returns a Broker
func NewBroker(opts ...Option) *Broker {
options := newDefaultOptions()
for _, o := range opts {
o.apply(&options)
}
return &Broker{
ProviderConfig: options.providerConfig,
Cluster: options.cluster,
ErrorHandler: options.errHandler,
Publisher: options.publisher,
EventMux: options.eventMux,
EventWriter: options.eventWriter,
PoolSize: options.poolSize,
MaxRetries: options.maxRetries,
ConnRetries: options.maxConnRetries,
RetryBackoff: options.retryBackoff,
ConnRetryBackoff: options.connRetryBackoff,
MessageIDFactory: options.messageIDFactory,
WorkerFactory: options.workerFactory,
BaseMessageSource: options.baseMessageSource,
BaseMessageContentType: options.baseMessageContentType,
BaseContext: options.baseContext,
supervisors: make(map[int]*Supervisor),
mu: sync.Mutex{},
inShutdown: 0,
doneChan: nil,
}
}
// newDefaultOptions sets required default values for Broker's ops
func newDefaultOptions() options {
return options{
cluster: make([]string, 0),
eventMux: NewMux(),
poolSize: defaultPoolSize,
maxRetries: defaultMaxRetries,
maxConnRetries: defaultConnRetries,
retryBackoff: defaultRetryBackoff,
connRetryBackoff: defaultConnRetryBackoff,
messageIDFactory: defaultIDFactory,
}
}
// ListenAndServe starts listening to the given Consumer(s) concurrently-safe
func (b *Broker) ListenAndServe() error {
if b.shuttingDown() {
return ErrBrokerClosed
}
return b.Serve()
}
// Serve starts the broker components
func (b *Broker) Serve() error {
for {
if b.BaseContext == nil {
b.BaseContext = context.Background()
}
b.setDefaultMux()
if err := b.startSupervisors(b.BaseContext); err != nil {
return err
}
<-b.getDoneChanLocked()
b.Shutdown(b.BaseContext)
}
}
func (b *Broker) startSupervisors(ctx context.Context) error {
for _, consumers := range b.EventMux.List() {
for _, c := range consumers {
nodeCtx := ctx
n := newSupervisor(b, c)
if err := n.ScheduleJobs(nodeCtx); err != nil {
return err
}
b.supervisors[b.activeSupervisors] = n
b.activeWorkers += n.runningWorkers.Length()
b.activeSupervisors++
}
}
return nil
}
// Shutdown starts Broker graceful shutdown of its components
func (b *Broker) Shutdown(ctx context.Context) error {
b.inShutdown.setTrue()
b.mu.Lock()
defer b.mu.Unlock()
b.closeDoneChanLocked()
ticker := time.NewTicker(shutdownPollInterval)
defer ticker.Stop()
for {
if err := b.closeNodes(); err == nil {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
}
}
}
func (b *Broker) shuttingDown() bool {
return b.inShutdown.isSet()
}
func (b *Broker) getDoneChanLocked() chan struct{} {
if b.doneChan == nil {
b.doneChan = make(chan struct{})
}
return b.doneChan
}
func (b *Broker) closeDoneChanLocked() {
ch := b.getDoneChanLocked()
select {
case <-ch:
// Already closed. Don't close again.
default:
// Safe to close here. We're the only closer, guarded
// by s.mu.
close(ch)
}
}
func (b *Broker) closeNodes() error {
errs := new(multierror.Error)
for k, n := range b.supervisors {
if err := n.Close(); err != nil {
errs = multierror.Append(errs, err)
continue
}
b.activeSupervisors--
b.activeWorkers = n.runningWorkers.Length()
delete(b.supervisors, k)
}
return errs.ErrorOrNil()
}
// Topic adds new Consumer Supervisor to the given EventMux
func (b *Broker) Topic(topic string) *Consumer {
b.setDefaultMux()
return b.EventMux.Topic(topic)
}
// Topics adds multiple Consumer supervisors to the given EventMux
func (b *Broker) Topics(topics ...string) *Consumer {
b.setDefaultMux()
return b.EventMux.Topics(topics...)
}
// activeSupervisors returns the current number of running supervisors
func (b *Broker) ActiveSupervisors() int {
return b.activeSupervisors
}
// activeWorkers returns the current number of running workers (inside every Supervisor)
func (b *Broker) ActiveWorkers() int {
return b.activeWorkers
}
func (b *Broker) setDefaultMux() {
if b.EventMux == nil {
b.EventMux = NewMux()
}
}
func (b *Broker) setDefaultPoolSize() int {
if b.PoolSize > 0 {
return b.PoolSize
}
return defaultPoolSize
}
func (b *Broker) setDefaultMaxRetries() int {
if b.MaxRetries > 0 {
return b.MaxRetries
}
return defaultMaxRetries
}
func (b *Broker) setDefaultRetryBackoff() time.Duration {
if b.RetryBackoff > 0 {
return b.RetryBackoff
}
return defaultRetryBackoff
}
func (b *Broker) setDefaultConnRetries() int {
if b.ConnRetries > 0 {
return b.ConnRetries
}
return defaultConnRetries
}
func (b *Broker) setDefaultConnRetryBackoff() time.Duration {
if b.ConnRetryBackoff > 0 {
return b.ConnRetryBackoff
}
return defaultConnRetryBackoff
}
func (b *Broker) setDefaultMessageIDFactory() IDFactory {
if b.MessageIDFactory != nil {
return b.MessageIDFactory
}
return defaultIDFactory
}
// GetConnRetries retrieves the default connection retries
func (b *Broker) GetConnRetries() int {
return b.setDefaultConnRetries()
}
// GetConnRetryBackoff retrieves the default connection retry backoff
func (b *Broker) GetConnRetryBackoff() time.Duration {
return b.setDefaultConnRetryBackoff()
}