-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathgcp.go
286 lines (263 loc) · 7.14 KB
/
gcp.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 msg
import (
"cloud.google.com/go/pubsub"
"context"
"encoding/json"
"fmt"
"github.com/pkg/errors"
"github.com/viant/scy/cred"
"github.com/viant/toolbox"
context2 "golang.org/x/net/context"
"google.golang.org/api/option"
"log"
"strings"
"sync"
"sync/atomic"
"time"
)
type gcpClient struct {
ctx context.Context
client *pubsub.Client
projectId string
timeout time.Duration
}
func (s *gcpClient) createSubscription(resource *ResourceSetup) (*pubsub.Subscription, error) {
subscription, err := s.getSubscription(&resource.Resource)
if err != nil {
return nil, err
}
exists, err := subscription.Exists(s.ctx)
if err != nil {
return nil, err
}
if exists && resource.Recreate {
exists = false
if err = subscription.Delete(s.ctx); err != nil {
return nil, err
}
}
if !exists {
config := resource.Config
if config.Topic == nil {
return nil, fmt.Errorf("topic was empty")
}
topic, err := s.getTopic(config.Topic)
if err != nil {
return nil, err
}
subscriptionConfig := pubsub.SubscriptionConfig{
Labels: config.Labels,
Topic: topic,
AckDeadline: config.AckDeadline,
RetainAckedMessages: config.RetainAckedMessages,
RetentionDuration: config.RetentionDuration,
}
ID := subscription.ID()
if subscription, err = s.client.CreateSubscription(s.ctx, ID, subscriptionConfig); err != nil {
JSON, _ := json.Marshal(subscriptionConfig)
return nil, errors.Wrapf(err, "failed to create subscription: %v, %s", ID, JSON)
}
}
return subscription, err
}
func (s *gcpClient) createTopic(resource *ResourceSetup) (*pubsub.Topic, error) {
topic, err := s.getTopic(&resource.Resource)
if err != nil {
return nil, err
}
exists, err := topic.Exists(s.ctx)
if err != nil {
return nil, err
}
if exists && resource.Recreate {
exists = false
if err = topic.Delete(s.ctx); err != nil {
return nil, err
}
}
if !exists {
if topic, err = s.client.CreateTopic(s.ctx, topic.ID()); err != nil {
return nil, err
}
}
return topic, nil
}
func (s *gcpClient) SetupResource(resource *ResourceSetup) (*Resource, error) {
var err error
var result = resource.Resource
switch resource.Type {
case ResourceTypeTopic:
topic, err := s.createTopic(resource)
if err != nil {
return nil, errors.Wrapf(err, "failed to setup topic: %v", resource.URL)
}
result.ID = topic.ID()
case ResourceTypeSubscription:
subscription, err := s.createSubscription(resource)
if err != nil {
return nil, errors.Wrapf(err, "failed to setup subscription: %v", resource.URL)
}
result.ID = subscription.ID()
default:
err = fmt.Errorf("unsupported resource type: %v, %v", resource.Type, resource.URL)
}
return &result, err
}
func (s *gcpClient) DeleteResource(resource *Resource) error {
switch resource.Type {
case ResourceTypeTopic:
topic, err := s.getTopic(resource)
if err != nil {
return err
}
return topic.Delete(s.ctx)
case ResourceTypeSubscription:
subscription, err := s.getSubscription(resource)
if err != nil {
return err
}
return subscription.Delete(s.ctx)
}
return fmt.Errorf("unsupported resource type: %v, %v", resource.Type, resource.URL)
}
func (s *gcpClient) Push(ctx context.Context, dest *Resource, message *Message) (Result, error) {
topic, err := s.getTopic(dest)
if err != nil {
return nil, err
}
ok, err := topic.Exists(s.ctx)
if err != nil {
return nil, err
}
if !ok {
return nil, fmt.Errorf("topic %v does not exist", dest)
}
var pubMessage = &pubsub.Message{}
if len(message.Attributes) > 0 {
pubMessage.Attributes = make(map[string]string)
for k, v := range message.Attributes {
pubMessage.Attributes[k] = toolbox.AsString(v)
}
}
if message.Data != nil {
switch data := message.Data.(type) {
case string:
pubMessage.Data = []byte(data)
case []byte:
pubMessage.Data = data
default:
JSONText, err := toolbox.AsIndentJSONText(data)
if err != nil {
return nil, err
}
pubMessage.Data = []byte(JSONText)
}
}
response := topic.Publish(s.ctx, pubMessage)
serverId, err := response.Get(s.ctx)
if err != nil {
return response, err
}
select {
case <-response.Ready():
case <-time.After(s.timeout):
log.Printf("publish ready timeout reached: %s", s.timeout)
}
return serverId, err
}
func (s *gcpClient) PullN(ctx context.Context, source *Resource, max int, nack bool) ([]*Message, error) {
subscription, err := s.getSubscription(source)
if err != nil {
return nil, err
}
var pulledCounter int32 = 0
ctx, cancel := context.WithCancel(s.ctx)
go func() {
time.Sleep(s.timeout)
pulledCount := int(atomic.AddInt32(&pulledCounter, 1))
if pulledCount != max && max > 0 {
log.Printf("publish ready timeout reached: %s", s.timeout)
cancel()
}
}()
mutex := &sync.Mutex{}
var messages = make([]*Message, 0)
err = subscription.Receive(ctx, func(ctx context2.Context, msg *pubsub.Message) {
mutex.Lock()
defer mutex.Unlock()
pulledMessage := &Message{
ID: msg.ID,
Data: msg.Data,
}
if len(msg.Data) > 0 {
aMap := map[string]interface{}{}
_ = json.Unmarshal(msg.Data, &aMap)
if len(aMap) > 0 {
pulledMessage.Transformed = aMap
}
}
if len(msg.Attributes) > 0 {
pulledMessage.Attributes = make(map[string]interface{})
for k, v := range msg.Attributes {
pulledMessage.Attributes[k] = v
}
}
messages = append(messages, pulledMessage)
pulledCount := int(atomic.AddInt32(&pulledCounter, 1))
if max > 0 && pulledCount >= max {
cancel()
}
if nack {
msg.Nack()
} else {
msg.Ack()
}
})
return messages, err
}
func (s *gcpClient) Close() error {
return s.client.Close()
}
func (s *gcpClient) getSubscription(dest *Resource) (*pubsub.Subscription, error) {
if dest.Name == "" && dest.URL == "" {
return nil, fmt.Errorf("subscription name and URL was empty, expected /projects/[PROJECT SessionID]/subscriptions/[SUBSCRIPTION] URL or subscription name")
}
if dest.projectID == "" {
return s.client.Subscription(dest.Name), nil
}
return s.client.SubscriptionInProject(dest.Name, dest.projectID), nil
}
func (s *gcpClient) getTopic(dest *Resource) (*pubsub.Topic, error) {
if dest.Name == "" && dest.URL == "" {
return nil, fmt.Errorf("subscription name and URL was empty, expected /projects/[PROJECT SessionID]/topics/[SUBSCRIPTION] URL or topic name")
}
if dest.projectID == "" {
return s.client.Topic(dest.Name), nil
}
return s.client.TopicInProject(dest.Name, dest.projectID), nil
}
func newCloudPubSub(credConfig *cred.Generic, URL string, timeout time.Duration) (Client, error) {
ctx := context.Background()
jwtConfig, err := credConfig.NewJWTConfig(pubsub.ScopePubSub)
if err != nil {
return nil, err
}
var opts = []option.ClientOption{
option.WithTokenSource(jwtConfig.TokenSource(ctx)),
}
client, err := pubsub.NewClient(ctx, credConfig.ProjectID, opts...)
if err != nil {
return nil, fmt.Errorf("failed to create pubsub client: %v", err)
}
var projectID = extractSubPath(URL, "project")
if projectID == "" || strings.HasPrefix(projectID, "$") {
projectID = credConfig.ProjectID
}
var service = &gcpClient{
client: client,
ctx: ctx,
timeout: timeout,
projectId: projectID,
}
return service, nil
}