forked from dapr/components-contrib
/
pubsub.go
377 lines (319 loc) · 11.3 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
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pubsub
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"sync"
"sync/atomic"
"time"
gcppubsub "cloud.google.com/go/pubsub"
"google.golang.org/api/option"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
contribMetadata "github.com/dapr/components-contrib/metadata"
"github.com/dapr/components-contrib/pubsub"
"github.com/dapr/kit/logger"
)
const (
errorMessagePrefix = "gcp pubsub error:"
// Metadata keys.
metadataConsumerIDKey = "consumerID"
metadataTypeKey = "type"
metadataProjectIDKey = "projectId"
metadataIdentityProjectIDKey = "identityProjectId"
metadataPrivateKeyIDKey = "privateKeyId"
metadataClientEmailKey = "clientEmail"
metadataClientIDKey = "clientId"
metadataAuthURIKey = "authUri"
metadataTokenURIKey = "tokenUri"
metadataAuthProviderX509CertURLKey = "authProviderX509CertUrl"
metadataClientX509CertURLKey = "clientX509CertUrl"
metadataPrivateKeyKey = "privateKey"
metadataDisableEntityManagementKey = "disableEntityManagement"
metadataEnableMessageOrderingKey = "enableMessageOrdering"
metadataMaxReconnectionAttemptsKey = "maxReconnectionAttempts"
metadataConnectionRecoveryInSecKey = "connectionRecoveryInSec"
// Defaults.
defaultMaxReconnectionAttempts = 30
defaultConnectionRecoveryInSec = 2
)
// GCPPubSub type.
type GCPPubSub struct {
client *gcppubsub.Client
metadata *metadata
logger logger.Logger
closed atomic.Bool
closeCh chan struct{}
wg sync.WaitGroup
}
type GCPAuthJSON struct {
ProjectID string `json:"project_id"`
PrivateKeyID string `json:"private_key_id"`
PrivateKey string `json:"private_key"`
ClientEmail string `json:"client_email"`
ClientID string `json:"client_id"`
AuthURI string `json:"auth_uri"`
TokenURI string `json:"token_uri"`
AuthProviderCertURL string `json:"auth_provider_x509_cert_url"`
ClientCertURL string `json:"client_x509_cert_url"`
Type string `json:"type"`
}
type WhatNow struct {
Type string `json:"type"`
}
// NewGCPPubSub returns a new GCPPubSub instance.
func NewGCPPubSub(logger logger.Logger) pubsub.PubSub {
return &GCPPubSub{logger: logger, closeCh: make(chan struct{})}
}
func createMetadata(pubSubMetadata pubsub.Metadata) (*metadata, error) {
// TODO: Add the rest of the metadata here, add defaults where applicable
result := metadata{
DisableEntityManagement: false,
Type: "service_account",
MaxReconnectionAttempts: defaultMaxReconnectionAttempts,
ConnectionRecoveryInSec: defaultConnectionRecoveryInSec,
}
err := contribMetadata.DecodeMetadata(pubSubMetadata.Properties, &result)
if err != nil {
return nil, err
}
if result.ProjectID == "" {
return &result, fmt.Errorf("%s missing attribute %s", errorMessagePrefix, metadataProjectIDKey)
}
return &result, nil
}
// Init parses metadata and creates a new Pub Sub client.
func (g *GCPPubSub) Init(ctx context.Context, meta pubsub.Metadata) error {
metadata, err := createMetadata(meta)
if err != nil {
return err
}
pubsubClient, err := g.getPubSubClient(ctx, metadata)
if err != nil {
return fmt.Errorf("%s error creating pubsub client: %w", errorMessagePrefix, err)
}
g.client = pubsubClient
g.metadata = metadata
return nil
}
func (g *GCPPubSub) getPubSubClient(ctx context.Context, metadata *metadata) (*gcppubsub.Client, error) {
var pubsubClient *gcppubsub.Client
var err error
if metadata.PrivateKeyID != "" {
// TODO: validate that all auth json fields are filled
authJSON := &GCPAuthJSON{
ProjectID: metadata.IdentityProjectID,
PrivateKeyID: metadata.PrivateKeyID,
PrivateKey: metadata.PrivateKey,
ClientEmail: metadata.ClientEmail,
ClientID: metadata.ClientID,
AuthURI: metadata.AuthURI,
TokenURI: metadata.TokenURI,
AuthProviderCertURL: metadata.AuthProviderCertURL,
ClientCertURL: metadata.ClientCertURL,
Type: metadata.Type,
}
gcpCompatibleJSON, _ := json.Marshal(authJSON)
g.logger.Debugf("Using explicit credentials for GCP")
clientOptions := option.WithCredentialsJSON(gcpCompatibleJSON)
pubsubClient, err = gcppubsub.NewClient(ctx, metadata.ProjectID, clientOptions)
if err != nil {
return pubsubClient, err
}
} else {
g.logger.Debugf("Using implicit credentials for GCP")
pubsubClient, err = gcppubsub.NewClient(ctx, metadata.ProjectID)
if err != nil {
return pubsubClient, err
}
}
return pubsubClient, nil
}
// Publish the topic to GCP Pubsub.
func (g *GCPPubSub) Publish(ctx context.Context, req *pubsub.PublishRequest) error {
if g.closed.Load() {
return errors.New("component is closed")
}
if !g.metadata.DisableEntityManagement {
err := g.ensureTopic(ctx, req.Topic)
if err != nil {
return fmt.Errorf("%s could not get valid topic %s, %s", errorMessagePrefix, req.Topic, err)
}
}
topic := g.getTopic(req.Topic)
_, err := topic.Publish(ctx, &gcppubsub.Message{
Data: req.Data,
}).Get(ctx)
return err
}
// Subscribe to the GCP Pubsub topic.
func (g *GCPPubSub) Subscribe(parentCtx context.Context, req pubsub.SubscribeRequest, handler pubsub.Handler) error {
if g.closed.Load() {
return errors.New("component is closed")
}
if !g.metadata.DisableEntityManagement {
topicErr := g.ensureTopic(parentCtx, req.Topic)
if topicErr != nil {
return fmt.Errorf("%s could not get valid topic %s, %s", errorMessagePrefix, req.Topic, topicErr)
}
subError := g.ensureSubscription(parentCtx, g.metadata.ConsumerID, req.Topic)
if subError != nil {
return fmt.Errorf("%s could not get valid subscription %s, %s", errorMessagePrefix, g.metadata.ConsumerID, subError)
}
}
topic := g.getTopic(req.Topic)
sub := g.getSubscription(g.metadata.ConsumerID + "-" + req.Topic)
subscribeCtx, cancel := context.WithCancel(parentCtx)
g.wg.Add(2)
go func() {
defer g.wg.Done()
defer cancel()
select {
case <-subscribeCtx.Done():
case <-g.closeCh:
}
}()
go func() {
defer g.wg.Done()
g.handleSubscriptionMessages(subscribeCtx, topic, sub, handler)
}()
return nil
}
func (g *GCPPubSub) handleSubscriptionMessages(parentCtx context.Context, topic *gcppubsub.Topic, sub *gcppubsub.Subscription, handler pubsub.Handler) error {
// Limit the number of attempted reconnects we make.
reconnAttempts := make(chan struct{}, g.metadata.MaxReconnectionAttempts)
for i := 0; i < g.metadata.MaxReconnectionAttempts; i++ {
reconnAttempts <- struct{}{}
}
readReconnectAttemptsRemaining := func() int { return len(reconnAttempts) }
// Periodically refill the reconnect attempts channel to avoid
// exhausting all the refill attempts due to intermittent issues
// occurring over a longer period of time.
g.wg.Add(1)
go func() {
defer g.wg.Done()
reconnCtx, reconnCancel := context.WithCancel(parentCtx)
defer reconnCancel()
// Calculate refill interval relative to MaxReconnectionAttempts and ConnectionRecoveryInSec
// in order to allow reconnection attempts to be exhausted in case of a permanent issue (e.g. wrong subscription name).
refillInterval := time.Duration(2*g.metadata.MaxReconnectionAttempts*g.metadata.ConnectionRecoveryInSec) * time.Second
for {
select {
case <-reconnCtx.Done():
g.logger.Debugf("Reconnect context for subscription %s is done", sub.ID())
return
case <-time.After(refillInterval):
attempts := readReconnectAttemptsRemaining()
if attempts < g.metadata.MaxReconnectionAttempts {
reconnAttempts <- struct{}{}
}
g.logger.Debugf("Number of reconnect attempts remaining for subscription %s: %d", sub.ID(), attempts)
}
}
}()
// Reconnect loop.
var receiveErr error = nil
for {
receiveErr = sub.Receive(parentCtx, func(ctx context.Context, m *gcppubsub.Message) {
msg := &pubsub.NewMessage{
Data: m.Data,
Topic: topic.ID(),
}
err := handler(ctx, msg)
if err == nil {
m.Ack()
} else {
m.Nack()
}
})
g.logger.Infof("Lost connection to subscription %s", sub.ID())
// Exit out of reconnect loop if Receive method returns without error.
if receiveErr == nil || receiveErr == context.Canceled {
g.logger.Infof("Subscription was cancelled, not reconnecting.")
break
}
// If we get to here - there was an error returned from the Receive method.
g.logger.Warnf("Connection to subscription %s closed with error: %s", sub.ID(), receiveErr)
reconnectionAttemptsRemaining := readReconnectAttemptsRemaining()
if reconnectionAttemptsRemaining == 0 {
g.logger.Errorf("Reconnection attempts exhausted for subscription %s, giving up after %d attempts.", sub.ID(), g.metadata.MaxReconnectionAttempts)
break
}
g.logger.Infof("Sleeping for %d seconds before attempting to reconnect to subscription %s ... [%d/%d]", g.metadata.ConnectionRecoveryInSec, sub.ID(), g.metadata.MaxReconnectionAttempts-reconnectionAttemptsRemaining, g.metadata.MaxReconnectionAttempts)
select {
case <-time.After(time.Second * time.Duration(g.metadata.ConnectionRecoveryInSec)):
case <-parentCtx.Done():
break
}
<-reconnAttempts
}
return receiveErr
}
func (g *GCPPubSub) ensureTopic(parentCtx context.Context, topic string) error {
entity := g.getTopic(topic)
exists, err := entity.Exists(parentCtx)
if err != nil {
return err
}
if !exists {
_, err = g.client.CreateTopic(parentCtx, topic)
if status.Code(err) == codes.AlreadyExists {
return nil
}
return err
}
return nil
}
func (g *GCPPubSub) getTopic(topic string) *gcppubsub.Topic {
return g.client.Topic(topic)
}
func (g *GCPPubSub) ensureSubscription(parentCtx context.Context, subscription string, topic string) error {
err := g.ensureTopic(parentCtx, topic)
if err != nil {
return err
}
managedSubscription := subscription + "-" + topic
entity := g.getSubscription(managedSubscription)
exists, subErr := entity.Exists(parentCtx)
if !exists {
_, subErr = g.client.CreateSubscription(parentCtx, managedSubscription, gcppubsub.SubscriptionConfig{
Topic: g.getTopic(topic),
EnableMessageOrdering: g.metadata.EnableMessageOrdering,
})
}
return subErr
}
func (g *GCPPubSub) getSubscription(subscription string) *gcppubsub.Subscription {
return g.client.Subscription(subscription)
}
func (g *GCPPubSub) Close() error {
defer g.wg.Wait()
if g.closed.CompareAndSwap(false, true) {
close(g.closeCh)
}
return g.client.Close()
}
func (g *GCPPubSub) Features() []pubsub.Feature {
return nil
}
// GetComponentMetadata returns the metadata of the component.
func (g *GCPPubSub) GetComponentMetadata() map[string]string {
metadataStruct := metadata{}
metadataInfo := map[string]string{}
contribMetadata.GetMetadataInfoFromStructType(reflect.TypeOf(metadataStruct), &metadataInfo, contribMetadata.PubSubType)
return metadataInfo
}