-
Notifications
You must be signed in to change notification settings - Fork 466
/
pubsub.go
158 lines (137 loc) · 4.2 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
/*
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"
"cloud.google.com/go/pubsub"
"google.golang.org/api/option"
"github.com/dapr/components-contrib/bindings"
contribMetadata "github.com/dapr/components-contrib/metadata"
"github.com/dapr/kit/logger"
)
const (
id = "id"
publishTime = "publishTime"
topic = "topic"
)
// GCPPubSub is an input/output binding for GCP Pub Sub.
type GCPPubSub struct {
client *pubsub.Client
metadata *pubSubMetadata
logger logger.Logger
closed atomic.Bool
closeCh chan struct{}
wg sync.WaitGroup
}
type pubSubMetadata struct {
Topic string `json:"topic"`
Subscription string `json:"subscription"`
Type string `json:"type"`
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"`
}
// NewGCPPubSub returns a new GCPPubSub instance.
func NewGCPPubSub(logger logger.Logger) bindings.InputOutputBinding {
return &GCPPubSub{
logger: logger,
closeCh: make(chan struct{}),
}
}
// Init parses metadata and creates a new Pub Sub client.
func (g *GCPPubSub) Init(ctx context.Context, metadata bindings.Metadata) error {
b, err := g.parseMetadata(metadata)
if err != nil {
return err
}
var pubsubMeta pubSubMetadata
err = json.Unmarshal(b, &pubsubMeta)
if err != nil {
return err
}
clientOptions := option.WithCredentialsJSON(b)
pubsubClient, err := pubsub.NewClient(ctx, pubsubMeta.ProjectID, clientOptions)
if err != nil {
return fmt.Errorf("error creating pubsub client: %s", err)
}
g.client = pubsubClient
g.metadata = &pubsubMeta
return nil
}
func (g *GCPPubSub) parseMetadata(metadata bindings.Metadata) ([]byte, error) {
return json.Marshal(metadata.Properties)
}
func (g *GCPPubSub) Read(ctx context.Context, handler bindings.Handler) error {
if g.closed.Load() {
return errors.New("binding is closed")
}
g.wg.Add(1)
go func() {
defer g.wg.Done()
sub := g.client.Subscription(g.metadata.Subscription)
err := sub.Receive(ctx, func(c context.Context, m *pubsub.Message) {
_, err := handler(c, &bindings.ReadResponse{
Data: m.Data,
Metadata: map[string]string{id: m.ID, publishTime: m.PublishTime.String()},
})
if err != nil {
m.Nack()
return
}
m.Ack()
})
if err != nil {
g.logger.Errorf("error receiving messages: %v", err)
}
}()
return nil
}
func (g *GCPPubSub) Operations() []bindings.OperationKind {
return []bindings.OperationKind{bindings.CreateOperation}
}
func (g *GCPPubSub) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bindings.InvokeResponse, error) {
topicName := g.metadata.Topic
if val, ok := req.Metadata[topic]; ok && val != "" {
topicName = val
}
t := g.client.Topic(topicName)
_, err := t.Publish(ctx, &pubsub.Message{
Data: req.Data,
}).Get(ctx)
return nil, err
}
func (g *GCPPubSub) Close() error {
if g.closed.CompareAndSwap(false, true) {
close(g.closeCh)
}
defer g.wg.Wait()
return g.client.Close()
}
// GetComponentMetadata returns the metadata of the component.
func (g *GCPPubSub) GetComponentMetadata() (metadataInfo contribMetadata.MetadataMap) {
metadataStruct := pubSubMetadata{}
contribMetadata.GetMetadataInfoFromStructType(reflect.TypeOf(metadataStruct), &metadataInfo, contribMetadata.BindingType)
return
}