-
Notifications
You must be signed in to change notification settings - Fork 1
/
pubsub.go
706 lines (584 loc) · 20.7 KB
/
pubsub.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
package goutils
import (
"context"
"fmt"
"sync"
"time"
"cloud.google.com/go/pubsub"
"github.com/apex/log"
"google.golang.org/api/iterator"
)
/*
CreateBasicGCPPubSubClient define a basic GCP PubSub client
@param ctxt context.Context - execution context
@param projectID string - GCP project ID
@returns new client
*/
func CreateBasicGCPPubSubClient(ctxt context.Context, projectID string) (*pubsub.Client, error) {
return pubsub.NewClient(ctxt, projectID)
}
// ==========================================================================================
// Client Interface
// PubSubMessageHandler callback to trigger when PubSub message received
type PubSubMessageHandler func(
ctxt context.Context, pubTimestamp time.Time, msg []byte, metadata map[string]string,
) error
// PubSubClient is a wrapper interface around the PubSub API with some ease-of-use features
type PubSubClient interface {
/*
UpdateLocalTopicCache sync local topic cache with existing topics in project
@param ctxt context.Context - execution context
*/
UpdateLocalTopicCache(ctxt context.Context) error
/*
UpdateLocalSubscriptionCache sync local subscription cache with existing subscriptions in project
@param ctxt context.Context - execution context
*/
UpdateLocalSubscriptionCache(ctxt context.Context) error
/*
CreateTopic create PubSub topic
@param ctxt context.Context - execution context
@param topic string - topic name
@param config *pubsub.TopicConfig - optionally, provide config on the topic
*/
CreateTopic(ctxt context.Context, topic string, config *pubsub.TopicConfig) error
/*
DeleteTopic delete PubSub topic
@param ctxt context.Context - execution context
@param topic string - topic name
*/
DeleteTopic(ctxt context.Context, topic string) error
/*
GetTopic get the topic config for a topic
@param ctxt context.Context - execution context
@param topic string - topic name
@returns if topic is known, the topic config
*/
GetTopic(ctxt context.Context, topic string) (pubsub.TopicConfig, error)
/*
UpdateTopic update the topic config
@param ctxt context.Context - execution context
@param topic string - topic name
@param newConfig pubsub.TopicConfigToUpdate - the new config
*/
UpdateTopic(ctxt context.Context, topic string, newConfig pubsub.TopicConfigToUpdate) error
/*
CreateSubscription create PubSub subscription to attach to topic
@param ctxt context.Context - execution context
@param targetTopic string - target topic
@param subscription string - subscription name
@param config pubsub.SubscriptionConfig - subscription config
*/
CreateSubscription(
ctxt context.Context, targetTopic, subscription string, config pubsub.SubscriptionConfig,
) error
/*
DeleteSubscription delete PubSub subscription
@param ctxt context.Context - execution context
@param subscription string - subscription name
*/
DeleteSubscription(ctxt context.Context, subscription string) error
/*
GetSubscription get the subscription config for a subscription
@param ctxt context.Context - execution context
@param subscription string - subscription name
@returns if subscription is known, the subscription config
*/
GetSubscription(ctxt context.Context, subscription string) (pubsub.SubscriptionConfig, error)
/*
UpdateSubscription update the subscription config
@param ctxt context.Context - execution context
@param subscription string - subscription name
@param newConfig pubsub.SubscriptionConfigToUpdate - the new config
*/
UpdateSubscription(
ctxt context.Context, subscription string, newConfig pubsub.SubscriptionConfigToUpdate,
) error
/*
Publish publish a message to a topic
@param ctxt context.Context - execution context
@param topic string - topic name
@param message []byte - message content
@param metadata map[string]string - message metadata, which will be sent using attributes
@param blocking bool - whether the call is blocking until publish is complete
@returns when non-blocking, the async result object to check on publish status
*/
Publish(
ctxt context.Context, topic string, message []byte, metadata map[string]string, blocking bool,
) (*pubsub.PublishResult, error)
/*
Subscribe subscribe for message on a subscription
THIS CALL IS BLOCKING!!
@param ctxt context.Context - execution context
@param subscription string - subscription name
@param handler PubSubMessageHandler - RX message callback
*/
Subscribe(ctxt context.Context, subscription string, handler PubSubMessageHandler) error
/*
Close close and clean up the client
@param ctxt context.Context - execution context
*/
Close(ctxt context.Context) error
}
// pubsubClientImpl implements PubSubClient
type pubsubClientImpl struct {
Component
client *pubsub.Client
topicLock sync.RWMutex
topics map[string]*pubsub.Topic
subLock sync.RWMutex
subscriptions map[string]*pubsub.Subscription
metricsHelper PubSubMetricHelper
}
/*
GetNewPubSubClientInstance get PubSub wrapper client
@param client *pubsub.Client - core PubSub client
@param logTags log.Fields - metadata fields to include in the logs
@param metricsHelper PubSubMetricHelper - metric collection helper agent
@returns new PubSubClient instance
*/
func GetNewPubSubClientInstance(
client *pubsub.Client, logTags log.Fields, metricsHelper PubSubMetricHelper,
) (PubSubClient, error) {
return &pubsubClientImpl{
Component: Component{LogTags: logTags},
client: client,
topicLock: sync.RWMutex{},
topics: make(map[string]*pubsub.Topic),
subLock: sync.RWMutex{},
subscriptions: make(map[string]*pubsub.Subscription),
metricsHelper: metricsHelper,
}, nil
}
// ==========================================================================================
// Maintenance
// updateLocalTopicCacheCore independent function for updating local topic cache for reuse
func (p *pubsubClientImpl) updateLocalTopicCacheCore(ctxt context.Context) error {
logTag := p.GetLogTagsForContext(ctxt)
topicItr := p.client.Topics(ctxt)
for {
topicEntry, err := topicItr.Next()
if err == iterator.Done {
break
}
if err != nil {
log.WithError(err).WithFields(logTag).Error("Topic iterator query failure")
return err
}
p.topics[topicEntry.ID()] = topicEntry
log.WithFields(logTag).Debugf("Found topic '%s'", topicEntry.ID())
}
return nil
}
/*
UpdateLocalTopicCache sync local topic cache with existing topics in project
@param ctxt context.Context - execution context
*/
func (p *pubsubClientImpl) UpdateLocalTopicCache(ctxt context.Context) error {
p.topicLock.Lock()
defer p.topicLock.Unlock()
return p.updateLocalTopicCacheCore(ctxt)
}
/*
UpdateLocalSubscriptionCache sync local subscription cache with existing subscriptions in project
@param ctxt context.Context - execution context
*/
func (p *pubsubClientImpl) UpdateLocalSubscriptionCache(ctxt context.Context) error {
logTag := p.GetLogTagsForContext(ctxt)
p.subLock.Lock()
defer p.subLock.Unlock()
subItr := p.client.Subscriptions(ctxt)
for {
subEntry, err := subItr.Next()
if err == iterator.Done {
break
}
if err != nil {
log.WithError(err).WithFields(logTag).Error("Topic iterator query failure")
return err
}
p.subscriptions[subEntry.ID()] = subEntry
log.WithFields(logTag).Debugf("Found subscription '%s'", subEntry.ID())
}
return nil
}
/*
Close close and clean up the client
@param ctxt context.Context - execution context
*/
func (p *pubsubClientImpl) Close(ctxt context.Context) error {
logTag := p.GetLogTagsForContext(ctxt)
{
// Stop all the topics
p.topicLock.Lock()
defer p.topicLock.Unlock()
for topicName, topic := range p.topics {
log.WithFields(logTag).Debugf("Stopping topic '%s'", topicName)
topic.Stop()
log.WithFields(logTag).Infof("Stopped topic '%s'", topicName)
}
}
return nil
}
// ==========================================================================================
// Topics
/*
CreateTopic create PubSub topic
@param ctxt context.Context - execution context
@param topic string - topic name
@param config *pubsub.TopicConfig - optionally, provide config on the topic
*/
func (p *pubsubClientImpl) CreateTopic(
ctxt context.Context, topic string, config *pubsub.TopicConfig,
) error {
p.topicLock.Lock()
defer p.topicLock.Unlock()
logTag := p.GetLogTagsForContext(ctxt)
// If this instance has created this topic before
if _, ok := p.topics[topic]; ok {
log.WithFields(logTag).Infof("Topic '%s' already exist", topic)
return nil
}
log.WithFields(logTag).Debugf("Creating topic '%s'", topic)
topicHandle, err := p.client.CreateTopicWithConfig(ctxt, topic, config)
if err != nil {
log.WithError(err).WithFields(logTag).Errorf("Topic '%s' creation failed", topic)
return err
}
log.WithFields(logTag).Infof("Created topic '%s'", topic)
p.topics[topic] = topicHandle
return nil
}
// getTopicHandle get topic handle
func (p *pubsubClientImpl) getTopicHandle(
ctxt context.Context, topic string, doLock bool,
) (*pubsub.Topic, error) {
logTag := p.GetLogTagsForContext(ctxt)
if doLock {
p.topicLock.RLock()
defer p.topicLock.RUnlock()
}
t, ok := p.topics[topic]
if !ok {
// Update the local topic cache
if err := p.updateLocalTopicCacheCore(ctxt); err != nil {
log.WithError(err).WithFields(logTag).Error("Failed syncing local topic cache")
return nil, err
}
t, ok = p.topics[topic]
if !ok {
// Topic is really missing
err := fmt.Errorf("topic '%s' is unknown", topic)
return nil, err
}
}
return t, nil
}
/*
DeleteTopic delete PubSub topic
@param ctxt context.Context - execution context
@param topic string - topic name
*/
func (p *pubsubClientImpl) DeleteTopic(ctxt context.Context, topic string) error {
p.topicLock.Lock()
defer p.topicLock.Unlock()
logTag := p.GetLogTagsForContext(ctxt)
topicHandle, err := p.getTopicHandle(ctxt, topic, false)
if err != nil {
log.WithError(err).WithFields(logTag).Errorf("Unable to delete topic '%s'", topic)
return err
}
// This instance has initialized this topic
log.WithFields(logTag).Infof("Stopping handler for topic '%s'", topic)
topicHandle.Stop()
log.WithFields(logTag).Debugf("Deleting topic '%s'", topic)
if err := topicHandle.Delete(ctxt); err != nil {
log.WithError(err).WithFields(logTag).Errorf("Unable to delete topic '%s'", topic)
return err
}
log.WithFields(logTag).Infof("Deleted topic '%s'", topic)
// Forgot the handle
delete(p.topics, topic)
return nil
}
/*
GetTopic get the topic config for a topic
@param ctxt context.Context - execution context
@param topic string - topic name
@returns if topic is known, the topic config
*/
func (p *pubsubClientImpl) GetTopic(ctxt context.Context, topic string) (pubsub.TopicConfig, error) {
p.topicLock.RLock()
defer p.topicLock.RUnlock()
logTag := p.GetLogTagsForContext(ctxt)
topicHandle, err := p.getTopicHandle(ctxt, topic, false)
if err != nil {
log.WithError(err).WithFields(logTag).Errorf("Unable to find topic '%s'", topic)
return pubsub.TopicConfig{}, err
}
log.WithFields(logTag).Debugf("Reading topic '%s' config", topic)
config, err := topicHandle.Config(ctxt)
if err != nil {
log.WithError(err).WithFields(logTag).Errorf("Unable to read topic '%s' config", topic)
return pubsub.TopicConfig{}, err
}
log.WithFields(logTag).Infof("Read topic '%s' config", topic)
return config, nil
}
/*
UpdateTopic update the topic config
@param ctxt context.Context - execution context
@param topic string - topic name
@param newConfig pubsub.TopicConfigToUpdate - the new config
*/
func (p *pubsubClientImpl) UpdateTopic(
ctxt context.Context, topic string, newConfig pubsub.TopicConfigToUpdate,
) error {
p.topicLock.Lock()
defer p.topicLock.Unlock()
logTag := p.GetLogTagsForContext(ctxt)
topicHandle, err := p.getTopicHandle(ctxt, topic, false)
if err != nil {
log.WithError(err).WithFields(logTag).Errorf("Unable to find topic '%s'", topic)
return err
}
log.WithFields(logTag).Debugf("Updating topic '%s' config", topic)
if _, err := topicHandle.Update(ctxt, newConfig); err != nil {
log.WithError(err).WithFields(logTag).Errorf("Unable to update topic '%s'", topic)
return err
}
log.WithFields(logTag).Infof("Updated topic '%s' config", topic)
return nil
}
// ==========================================================================================
// Subscriptions
/*
CreateSubscription create PubSub subscription to attach to topic
@param ctxt context.Context - execution context
@param targetTopic string - target topic
@param subscription string - subscription name
@param config pubsub.SubscriptionConfig - subscription config
*/
func (p *pubsubClientImpl) CreateSubscription(
ctxt context.Context, targetTopic, subscription string, config pubsub.SubscriptionConfig,
) error {
logTag := p.GetLogTagsForContext(ctxt)
// Get the topic handle
topic, err := p.getTopicHandle(ctxt, targetTopic, true)
if err != nil {
log.WithError(err).WithFields(logTag).Errorf("Unable to create subscription '%s'", subscription)
return err
}
// Create the subscription
config.Topic = topic
{
p.subLock.Lock()
defer p.subLock.Unlock()
// If this instance has created this topic before
if _, ok := p.subscriptions[subscription]; ok {
log.WithFields(logTag).Infof("Subscription '%s' already exist", subscription)
return nil
}
log.WithFields(logTag).Debugf("Creating subscription '%s'", subscription)
subHandle, err := p.client.CreateSubscription(ctxt, subscription, config)
if err != nil {
log.WithError(err).WithFields(logTag).Errorf("Unable to create subscription '%s'", subscription)
return err
}
log.WithFields(logTag).Infof("Created subscription '%s'", subscription)
p.subscriptions[subscription] = subHandle
}
return nil
}
/*
DeleteSubscription delete PubSub subscription
@param ctxt context.Context - execution context
@param subscription string - subscription name
*/
func (p *pubsubClientImpl) DeleteSubscription(ctxt context.Context, subscription string) error {
p.subLock.Lock()
defer p.subLock.Unlock()
logTag := p.GetLogTagsForContext(ctxt)
subHandle, ok := p.subscriptions[subscription]
if !ok {
err := fmt.Errorf("this instance does not know of subscription '%s'", subscription)
log.WithError(err).WithFields(logTag).Errorf("Unable to delete subscription '%s'", subscription)
return err
}
log.WithFields(logTag).Debugf("Deleting subscription '%s'", subscription)
if err := subHandle.Delete(ctxt); err != nil {
log.WithError(err).WithFields(logTag).Errorf("Unable to delete subscription '%s'", subscription)
return err
}
log.WithFields(logTag).Infof("Deleted subscription '%s'", subscription)
// Forgot the handle
delete(p.subscriptions, subscription)
return nil
}
/*
GetSubscription get the subscription config for a subscription
@param ctxt context.Context - execution context
@param subscription string - subscription name
@returns if subscription is known, the subscription config
*/
func (p *pubsubClientImpl) GetSubscription(
ctxt context.Context, subscription string,
) (pubsub.SubscriptionConfig, error) {
p.subLock.Lock()
defer p.subLock.Unlock()
logTag := p.GetLogTagsForContext(ctxt)
subHandle, ok := p.subscriptions[subscription]
if !ok {
err := fmt.Errorf("this instance does not know of subscription '%s'", subscription)
log.WithError(err).WithFields(logTag).Errorf("Unable to find subscription '%s'", subscription)
return pubsub.SubscriptionConfig{}, err
}
log.WithFields(logTag).Debugf("Reading subscription '%s' config", subscription)
config, err := subHandle.Config(ctxt)
if err != nil {
log.
WithError(err).
WithFields(logTag).
Errorf("Unable to read subscription '%s' config", subscription)
return pubsub.SubscriptionConfig{}, err
}
log.WithFields(logTag).Infof("Read subscription '%s' config", subscription)
return config, nil
}
/*
UpdateSubscription update the subscription config
@param ctxt context.Context - execution context
@param subscription string - subscription name
@param newConfig pubsub.SubscriptionConfigToUpdate - the new config
*/
func (p *pubsubClientImpl) UpdateSubscription(
ctxt context.Context, subscription string, newConfig pubsub.SubscriptionConfigToUpdate,
) error {
p.subLock.Lock()
defer p.subLock.Unlock()
logTag := p.GetLogTagsForContext(ctxt)
subHandle, ok := p.subscriptions[subscription]
if !ok {
err := fmt.Errorf("this instance does not know of subscription '%s'", subscription)
log.WithError(err).WithFields(logTag).Errorf("Unable to find subscription '%s'", subscription)
return err
}
log.WithFields(logTag).Debugf("Updating subscription '%s' config", subscription)
if _, err := subHandle.Update(ctxt, newConfig); err != nil {
log.WithError(err).WithFields(logTag).Errorf("Unable to update subscription '%s'", subscription)
return err
}
log.WithFields(logTag).Infof("Updated subscription '%s' config", subscription)
return nil
}
// ==========================================================================================
// Message Passing
/*
Publish publish a message to a topic
@param ctxt context.Context - execution context
@param topic string - topic name
@param message []byte - message content
@param metadata map[string]string - message metadata, which will be sent using attributes
@param blocking bool - whether the call is blocking until publish is complete
@returns when non-blocking, the async result object to check on publish status
*/
func (p *pubsubClientImpl) Publish(
ctxt context.Context, topic string, message []byte, metadata map[string]string, blocking bool,
) (*pubsub.PublishResult, error) {
logTag := p.GetLogTagsForContext(ctxt)
// Get the topic handle
topicHandle, err := p.getTopicHandle(ctxt, topic, true)
if err != nil {
log.WithError(err).WithFields(logTag).Errorf("Publish on topic '%s' failed", topic)
if p.metricsHelper != nil {
p.metricsHelper.RecordPublish(topic, false, int64(len(message)))
}
return nil, err
}
log.WithFields(logTag).Debugf("Publishing message on topic '%s'", topic)
txHandle := topicHandle.Publish(ctxt, &pubsub.Message{Data: message, Attributes: metadata})
if blocking {
// Wait for publish to finish
txID, err := txHandle.Get(ctxt)
if err != nil {
log.WithError(err).WithFields(logTag).Errorf("Publish on topic '%s' failed", topic)
if p.metricsHelper != nil {
p.metricsHelper.RecordPublish(topic, false, int64(len(message)))
}
return nil, err
}
log.WithFields(logTag).Debugf("Published message [%s] on topic '%s'", txID, topic)
} else {
log.WithFields(logTag).Debugf("Published message on topic '%s'", topic)
}
if p.metricsHelper != nil {
p.metricsHelper.RecordPublish(topic, true, int64(len(message)))
}
return txHandle, nil
}
// getSubscriptionHandle get subscription handle
func (p *pubsubClientImpl) getSubscriptionHandle(_ context.Context, subscription string) (*pubsub.Subscription, error) {
p.subLock.RLock()
defer p.subLock.RUnlock()
s, ok := p.subscriptions[subscription]
if !ok {
err := fmt.Errorf("subscription '%s' is unknown", subscription)
return nil, err
}
return s, nil
}
/*
Subscribe subscribe for message on a subscription.
THIS CALL IS BLOCKING!!
@param ctxt context.Context - execution context
@param subscription string - subscription name
@param handler PubSubMessageHandler - RX message callback
*/
func (p *pubsubClientImpl) Subscribe(
ctxt context.Context, subscription string, handler PubSubMessageHandler,
) error {
logTag := p.GetLogTagsForContext(ctxt)
// Get the subscription handle
subscriptionHandle, err := p.getSubscriptionHandle(ctxt, subscription)
if err != nil {
log.WithError(err).WithFields(logTag).Errorf("Listen on subscription '%s' failed", subscription)
return err
}
// Get the associated topic handle
subConfig, err := subscriptionHandle.Config(ctxt)
if err != nil {
log.WithError(err).WithFields(logTag).Errorf("Listen on subscription '%s' failed", subscription)
return err
}
topicHandle := subConfig.Topic
// Install subscription receive
if err := subscriptionHandle.Receive(ctxt, func(ctx context.Context, m *pubsub.Message) {
if err := handler(ctx, m.PublishTime, m.Data, m.Attributes); err != nil {
log.
WithError(err).
WithFields(logTag).
WithField("topic", topicHandle.ID()).
WithField("subscription", subscription).
Errorf("Failed to process message [%s]", m.ID)
if p.metricsHelper != nil {
p.metricsHelper.RecordReceive(topicHandle.ID(), false, int64(len(m.Data)))
}
m.Nack()
} else {
log.
WithError(err).
WithFields(logTag).
WithField("topic", topicHandle.ID()).
WithField("subscription", subscription).
Debugf("Processed message [%s]", m.ID)
if p.metricsHelper != nil {
p.metricsHelper.RecordReceive(topicHandle.ID(), true, int64(len(m.Data)))
}
m.Ack()
}
}); err != nil {
log.WithError(err).WithFields(logTag).Errorf("Listen on subscription '%s' failed", subscription)
return err
}
return nil
}