-
Notifications
You must be signed in to change notification settings - Fork 467
/
servicebus.go
462 lines (402 loc) · 14.7 KB
/
servicebus.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
package servicebus
import (
"context"
"fmt"
"strconv"
"time"
azservicebus "github.com/Azure/azure-service-bus-go"
"github.com/dapr/components-contrib/pubsub"
"github.com/dapr/dapr/pkg/logger"
)
const (
// Keys
connectionString = "connectionString"
consumerID = "consumerID"
maxDeliveryCount = "maxDeliveryCount"
timeoutInSec = "timeoutInSec"
lockDurationInSec = "lockDurationInSec"
lockRenewalInSec = "lockRenewalInSec"
defaultMessageTimeToLiveInSec = "defaultMessageTimeToLiveInSec"
autoDeleteOnIdleInSec = "autoDeleteOnIdleInSec"
disableEntityManagement = "disableEntityManagement"
maxConcurrentHandlers = "maxConcurrentHandlers"
handlerTimeoutInSec = "handlerTimeoutInSec"
prefetchCount = "prefetchCount"
maxActiveMessages = "maxActiveMessages"
maxActiveMessagesRecoveryInSec = "maxActiveMessagesRecoveryInSec"
errorMessagePrefix = "azure service bus error:"
// Defaults
defaultTimeoutInSec = 60
defaultHandlerTimeoutInSec = 60
defaultLockRenewalInSec = 20
// ASB Messages can be up to 256Kb. 10000 messages at this size would roughly use 2.56Gb.
// We should change this if performance testing suggests a more sensible default.
defaultMaxActiveMessages = 10000
defaultMaxActiveMessagesRecoveryInSec = 2
defaultDisableEntityManagement = false
maxReconnAttempts = 10
connectionRecoveryInSec = 2
)
type handler = struct{}
type azureServiceBus struct {
metadata metadata
namespace *azservicebus.Namespace
topicManager *azservicebus.TopicManager
logger logger.Logger
}
// NewAzureServiceBus returns a new Azure ServiceBus pub-sub implementation
func NewAzureServiceBus(logger logger.Logger) pubsub.PubSub {
return &azureServiceBus{
logger: logger,
}
}
func parseAzureServiceBusMetadata(meta pubsub.Metadata) (metadata, error) {
m := metadata{}
/* Required configuration settings - no defaults */
if val, ok := meta.Properties[connectionString]; ok && val != "" {
m.ConnectionString = val
} else {
return m, fmt.Errorf("%s missing connection string", errorMessagePrefix)
}
if val, ok := meta.Properties[consumerID]; ok && val != "" {
m.ConsumerID = val
} else {
return m, fmt.Errorf("%s missing consumerID", errorMessagePrefix)
}
/* Optional configuration settings - defaults will be set by the client */
m.TimeoutInSec = defaultTimeoutInSec
if val, ok := meta.Properties[timeoutInSec]; ok && val != "" {
var err error
m.TimeoutInSec, err = strconv.Atoi(val)
if err != nil {
return m, fmt.Errorf("%s invalid timeoutInSec %s, %s", errorMessagePrefix, val, err)
}
}
m.DisableEntityManagement = defaultDisableEntityManagement
if val, ok := meta.Properties[disableEntityManagement]; ok && val != "" {
var err error
m.DisableEntityManagement, err = strconv.ParseBool(val)
if err != nil {
return m, fmt.Errorf("%s invalid disableEntityManagement %s, %s", errorMessagePrefix, val, err)
}
}
m.HandlerTimeoutInSec = defaultHandlerTimeoutInSec
if val, ok := meta.Properties[handlerTimeoutInSec]; ok && val != "" {
var err error
m.HandlerTimeoutInSec, err = strconv.Atoi(val)
if err != nil {
return m, fmt.Errorf("%s invalid handlerTimeoutInSec %s, %s", errorMessagePrefix, val, err)
}
}
m.LockRenewalInSec = defaultLockRenewalInSec
if val, ok := meta.Properties[lockRenewalInSec]; ok && val != "" {
var err error
m.LockRenewalInSec, err = strconv.Atoi(val)
if err != nil {
return m, fmt.Errorf("%s invalid lockRenewalInSec %s, %s", errorMessagePrefix, val, err)
}
}
m.MaxActiveMessages = defaultMaxActiveMessages
if val, ok := meta.Properties[maxActiveMessages]; ok && val != "" {
var err error
m.MaxActiveMessages, err = strconv.Atoi(val)
if err != nil {
return m, fmt.Errorf("%s invalid maxActiveMessages %s, %s", errorMessagePrefix, val, err)
}
}
m.MaxActiveMessagesRecoveryInSec = defaultMaxActiveMessagesRecoveryInSec
if val, ok := meta.Properties[maxActiveMessagesRecoveryInSec]; ok && val != "" {
var err error
m.MaxActiveMessagesRecoveryInSec, err = strconv.Atoi(val)
if err != nil {
return m, fmt.Errorf("%s invalid recoveryInSec %s, %s", errorMessagePrefix, val, err)
}
}
/* Nullable configuration settings - defaults will be set by the server */
if val, ok := meta.Properties[maxDeliveryCount]; ok && val != "" {
valAsInt, err := strconv.Atoi(val)
if err != nil {
return m, fmt.Errorf("%s invalid maxDeliveryCount %s, %s", errorMessagePrefix, val, err)
}
m.MaxDeliveryCount = &valAsInt
}
if val, ok := meta.Properties[lockDurationInSec]; ok && val != "" {
valAsInt, err := strconv.Atoi(val)
if err != nil {
return m, fmt.Errorf("%s invalid lockDurationInSec %s, %s", errorMessagePrefix, val, err)
}
m.LockDurationInSec = &valAsInt
}
if val, ok := meta.Properties[defaultMessageTimeToLiveInSec]; ok && val != "" {
valAsInt, err := strconv.Atoi(val)
if err != nil {
return m, fmt.Errorf("%s invalid defaultMessageTimeToLiveInSec %s, %s", errorMessagePrefix, val, err)
}
m.DefaultMessageTimeToLiveInSec = &valAsInt
}
if val, ok := meta.Properties[autoDeleteOnIdleInSec]; ok && val != "" {
valAsInt, err := strconv.Atoi(val)
if err != nil {
return m, fmt.Errorf("%s invalid autoDeleteOnIdleInSecKey %s, %s", errorMessagePrefix, val, err)
}
m.AutoDeleteOnIdleInSec = &valAsInt
}
if val, ok := meta.Properties[maxConcurrentHandlers]; ok && val != "" {
var err error
valAsInt, err := strconv.Atoi(val)
if err != nil {
return m, fmt.Errorf("%s invalid maxConcurrentHandlers %s, %s", errorMessagePrefix, val, err)
}
m.MaxConcurrentHandlers = &valAsInt
}
if val, ok := meta.Properties[prefetchCount]; ok && val != "" {
var err error
valAsInt, err := strconv.Atoi(val)
if err != nil {
return m, fmt.Errorf("%s invalid prefetchCount %s, %s", errorMessagePrefix, val, err)
}
m.PrefetchCount = &valAsInt
}
return m, nil
}
func (a *azureServiceBus) Init(metadata pubsub.Metadata) error {
m, err := parseAzureServiceBusMetadata(metadata)
if err != nil {
return err
}
a.metadata = m
a.namespace, err = azservicebus.NewNamespace(azservicebus.NamespaceWithConnectionString(a.metadata.ConnectionString))
if err != nil {
return err
}
a.topicManager = a.namespace.NewTopicManager()
return nil
}
func (a *azureServiceBus) Publish(req *pubsub.PublishRequest) error {
if !a.metadata.DisableEntityManagement {
err := a.ensureTopic(req.Topic)
if err != nil {
return err
}
}
sender, err := a.namespace.NewTopic(req.Topic)
if err != nil {
return err
}
defer sender.Close(context.Background())
ctx, cancel := context.WithTimeout(context.Background(), time.Second*time.Duration(a.metadata.TimeoutInSec))
defer cancel()
err = sender.Send(ctx, azservicebus.NewMessage(req.Data))
if err != nil {
return err
}
return nil
}
func (a *azureServiceBus) Subscribe(req pubsub.SubscribeRequest, appHandler func(msg *pubsub.NewMessage) error) error {
subID := a.metadata.ConsumerID
if !a.metadata.DisableEntityManagement {
err := a.ensureSubscription(subID, req.Topic)
if err != nil {
return err
}
}
go func() {
// Limit the number of attempted reconnects we make
reconnAttempts := make(chan struct{}, maxReconnAttempts)
for i := 0; i < maxReconnAttempts; i++ {
reconnAttempts <- struct{}{}
}
// len(reconnAttempts) should be considered stale but we can afford a little error here
readAttemptsStale := func() int { return len(reconnAttempts) }
// Periodically refill the reconnect attempts channel to avoid
// exhausting all the refill attempts due to intermittent issues
// ocurring over a longer period of time.
reconnCtx, reconnCancel := context.WithCancel(context.TODO())
defer reconnCancel()
go func() {
for {
select {
case <-reconnCtx.Done():
a.logger.Debugf("Reconnect context for topic %s is done", req.Topic)
return
case <-time.After(2 * time.Minute):
attempts := readAttemptsStale()
if attempts < maxReconnAttempts {
reconnAttempts <- struct{}{}
}
a.logger.Debugf("Number of reconnect attempts remaining for topic %s: %d", req.Topic, attempts)
}
}
}()
// Reconnect loop
for {
topic, err := a.namespace.NewTopic(req.Topic)
if err != nil {
a.logger.Errorf("%s could not instantiate topic %s, %s", errorMessagePrefix, req.Topic, err)
return
}
var opts []azservicebus.SubscriptionOption
if a.metadata.PrefetchCount != nil {
opts = append(opts, azservicebus.SubscriptionWithPrefetchCount(uint32(*a.metadata.PrefetchCount)))
}
subEntity, err := topic.NewSubscription(subID, opts...)
if err != nil {
a.logger.Errorf("%s could not instantiate subscription %s for topic %s", errorMessagePrefix, subID, req.Topic)
return
}
sub := newSubscription(req.Topic, subEntity, a.metadata.MaxConcurrentHandlers, a.logger)
// ReceiveAndBlock will only return with an error
// that it cannot handle internally. The subscription
// connection is closed when this method returns.
// If that occurs, we will log the error and attempt
// to re-establish the subscription connection until
// we exhaust the number of reconnect attempts.
ctx, cancel := context.WithCancel(context.Background())
innerErr := sub.ReceiveAndBlock(ctx,
appHandler,
a.metadata.LockRenewalInSec,
a.metadata.HandlerTimeoutInSec,
a.metadata.TimeoutInSec,
a.metadata.MaxActiveMessages,
a.metadata.MaxActiveMessagesRecoveryInSec)
if innerErr != nil {
a.logger.Error(innerErr)
}
cancel() // Cancel receive context
attempts := readAttemptsStale()
if attempts == 0 {
a.logger.Errorf("Subscription to topic %s lost connection, unable to recover after %d attempts", sub.topic, maxReconnAttempts)
return
}
a.logger.Warnf("Subscription to topic %s lost connection, attempting to reconnect... [%d/%d]", sub.topic, maxReconnAttempts-attempts, maxReconnAttempts)
time.Sleep(time.Second * connectionRecoveryInSec)
<-reconnAttempts
}
}()
return nil
}
func (a *azureServiceBus) ensureTopic(topic string) error {
entity, err := a.getTopicEntity(topic)
if err != nil {
return err
}
if entity == nil {
err = a.createTopicEntity(topic)
if err != nil {
return err
}
}
return nil
}
func (a *azureServiceBus) ensureSubscription(name string, topic string) error {
err := a.ensureTopic(topic)
if err != nil {
return err
}
subManager, err := a.namespace.NewSubscriptionManager(topic)
if err != nil {
return err
}
entity, err := a.getSubscriptionEntity(subManager, topic, name)
if err != nil {
return err
}
if entity == nil {
err = a.createSubscriptionEntity(subManager, topic, name)
if err != nil {
return err
}
}
return nil
}
func (a *azureServiceBus) getTopicEntity(topic string) (*azservicebus.TopicEntity, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*time.Duration(a.metadata.TimeoutInSec))
defer cancel()
if a.topicManager == nil {
return nil, fmt.Errorf("%s init() has not been called", errorMessagePrefix)
}
topicEntity, err := a.topicManager.Get(ctx, topic)
if err != nil && !azservicebus.IsErrNotFound(err) {
return nil, fmt.Errorf("%s could not get topic %s, %s", errorMessagePrefix, topic, err)
}
return topicEntity, nil
}
func (a *azureServiceBus) createTopicEntity(topic string) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*time.Duration(a.metadata.TimeoutInSec))
defer cancel()
_, err := a.topicManager.Put(ctx, topic)
if err != nil {
return fmt.Errorf("%s could not put topic %s, %s", errorMessagePrefix, topic, err)
}
return nil
}
func (a *azureServiceBus) getSubscriptionEntity(mgr *azservicebus.SubscriptionManager, topic, subscription string) (*azservicebus.SubscriptionEntity, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*time.Duration(a.metadata.TimeoutInSec))
defer cancel()
entity, err := mgr.Get(ctx, subscription)
if err != nil && !azservicebus.IsErrNotFound(err) {
return nil, fmt.Errorf("%s could not get subscription %s, %s", errorMessagePrefix, subscription, err)
}
return entity, nil
}
func (a *azureServiceBus) createSubscriptionEntity(mgr *azservicebus.SubscriptionManager, topic, subscription string) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*time.Duration(a.metadata.TimeoutInSec))
defer cancel()
opts, err := a.createSubscriptionManagementOptions()
if err != nil {
return err
}
_, err = mgr.Put(ctx, subscription, opts...)
if err != nil {
return fmt.Errorf("%s could not put subscription %s, %s", errorMessagePrefix, subscription, err)
}
return nil
}
func (a *azureServiceBus) createSubscriptionManagementOptions() ([]azservicebus.SubscriptionManagementOption, error) {
var opts []azservicebus.SubscriptionManagementOption
if a.metadata.MaxDeliveryCount != nil {
opts = append(opts, subscriptionManagementOptionsWithMaxDeliveryCount(a.metadata.MaxDeliveryCount))
}
if a.metadata.LockDurationInSec != nil {
opts = append(opts, subscriptionManagementOptionsWithLockDuration(a.metadata.LockDurationInSec))
}
if a.metadata.DefaultMessageTimeToLiveInSec != nil {
opts = append(opts, subscriptionManagementOptionsWithDefaultMessageTimeToLive(a.metadata.DefaultMessageTimeToLiveInSec))
}
if a.metadata.AutoDeleteOnIdleInSec != nil {
opts = append(opts, subscriptionManagementOptionsWithAutoDeleteOnIdle(a.metadata.AutoDeleteOnIdleInSec))
}
return opts, nil
}
func subscriptionManagementOptionsWithMaxDeliveryCount(maxDeliveryCount *int) azservicebus.SubscriptionManagementOption {
return func(d *azservicebus.SubscriptionDescription) error {
mdc := int32(*maxDeliveryCount)
d.MaxDeliveryCount = &mdc
return nil
}
}
func subscriptionManagementOptionsWithAutoDeleteOnIdle(durationInSec *int) azservicebus.SubscriptionManagementOption {
return func(d *azservicebus.SubscriptionDescription) error {
duration := fmt.Sprintf("PT%dS", *durationInSec)
d.AutoDeleteOnIdle = &duration
return nil
}
}
func subscriptionManagementOptionsWithDefaultMessageTimeToLive(durationInSec *int) azservicebus.SubscriptionManagementOption {
return func(d *azservicebus.SubscriptionDescription) error {
duration := fmt.Sprintf("PT%dS", *durationInSec)
d.DefaultMessageTimeToLive = &duration
return nil
}
}
func subscriptionManagementOptionsWithLockDuration(durationInSec *int) azservicebus.SubscriptionManagementOption {
return func(d *azservicebus.SubscriptionDescription) error {
duration := fmt.Sprintf("PT%dS", *durationInSec)
d.LockDuration = &duration
return nil
}
}