/
pubsub.go
361 lines (315 loc) · 10.5 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
// Copyright 2021 Nitric Pty Ltd.
//
// 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_queue_service
import (
"context"
"encoding/json"
"fmt"
ifaces_pubsub "github.com/nitric-dev/membrane/pkg/ifaces/pubsub"
"cloud.google.com/go/pubsub"
pubsubbase "cloud.google.com/go/pubsub/apiv1"
"github.com/nitric-dev/membrane/pkg/plugins/errors"
"github.com/nitric-dev/membrane/pkg/plugins/errors/codes"
"github.com/nitric-dev/membrane/pkg/plugins/queue"
"golang.org/x/oauth2/google"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1"
)
type PubsubQueueService struct {
queue.UnimplementedQueuePlugin
client ifaces_pubsub.PubsubClient
newSubscriberClient func(ctx context.Context, opts ...option.ClientOption) (ifaces_pubsub.SubscriberClient, error)
projectId string
messages []*pubsub.Message
}
// TODO: clearly document the reason for this subscription.
// Get the default Nitric Queue Subscription name for a given queue name.
func generateQueueSubscription(queue string) string {
return fmt.Sprintf("%s-nitricqueue", queue)
}
func (s *PubsubQueueService) Send(queue string, task queue.NitricTask) error {
newErr := errors.ErrorsWithScope(
"PubsubQueueService.Send",
map[string]interface{}{
"queue": queue,
"task": task,
},
)
// We'll be using pubsub with pull subscribers to facilitate queue functionality
ctx := context.TODO()
topic := s.client.Topic(queue)
if exists, err := topic.Exists(ctx); !exists || err != nil {
return newErr(
codes.NotFound,
"queue not found",
err,
)
}
if taskBytes, err := json.Marshal(task); err == nil {
msg := ifaces_pubsub.AdaptPubsubMessage(&pubsub.Message{
Data: taskBytes,
})
result := topic.Publish(ctx, msg)
if _, err := result.Get(ctx); err != nil {
return newErr(
codes.Internal,
"error retrieving publish result",
err,
)
}
} else {
return newErr(
codes.Internal,
"error marshalling the task",
err,
)
}
return nil
}
func (s *PubsubQueueService) SendBatch(q string, tasks []queue.NitricTask) (*queue.SendBatchResponse, error) {
newErr := errors.ErrorsWithScope(
"PubsubQueueService.SendBatch",
map[string]interface{}{
"queue": q,
"tasks.len": len(tasks),
},
)
// We'll be using pubsub with pull subscribers to facilitate queue functionality
ctx := context.TODO()
topic := s.client.Topic(q)
if exists, err := topic.Exists(ctx); !exists || err != nil {
return nil, newErr(
codes.NotFound,
"queue not found",
err,
)
}
// SendBatch once we've published all tasks to the client
// TODO: We may want to revisit this, and chunk up our publishing in a way that makes more sense...
results := make([]ifaces_pubsub.PublishResult, 0)
failedTasks := make([]*queue.FailedTask, 0)
publishedTasks := make([]queue.NitricTask, 0)
for _, task := range tasks {
if taskBytes, err := json.Marshal(task); err == nil {
msg := ifaces_pubsub.AdaptPubsubMessage(&pubsub.Message{
Data: taskBytes,
})
results = append(results, topic.Publish(ctx, msg))
publishedTasks = append(publishedTasks, task)
} else {
failedTasks = append(failedTasks, &queue.FailedTask{
Task: &task,
Message: "Error unmarshalling message for queue",
})
}
}
for idx, result := range results {
// Iterate over the results to check for successful publishing...
if _, err := result.Get(ctx); err != nil {
// Add this to our failures list in our results...
failedTasks = append(failedTasks, &queue.FailedTask{
Task: &publishedTasks[idx],
Message: err.Error(),
})
}
}
return &queue.SendBatchResponse{
FailedTasks: failedTasks,
}, nil
}
// Retrieves the Nitric "Queue Subscription" for the specified queue (PubSub Topic).
//
// GCP PubSub requires a Subscription in order to Pull messages from a Topic.
// we use this behavior to emulate a queue.
//
// This retrieves the default Nitric Pull subscription for the Topic base on convention.
func (s *PubsubQueueService) getQueueSubscription(q string) (ifaces_pubsub.Subscription, error) {
ctx := context.Background()
topic := s.client.Topic(q)
subsIt := topic.Subscriptions(ctx)
for {
sub, err := subsIt.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, fmt.Errorf("failed to retrieve pull subscription for topic: %s\n%s", topic.ID(), err)
}
queueSubName := generateQueueSubscription(q)
if sub.ID() == queueSubName {
return sub, nil
}
}
return nil, fmt.Errorf("pull subscription not found, pull subscribers may not be configured for this topic")
}
// Receives a collection of tasks off a given queue.
func (s *PubsubQueueService) Receive(options queue.ReceiveOptions) ([]queue.NitricTask, error) {
newErr := errors.ErrorsWithScope(
"PubsubQueueService.Receive",
map[string]interface{}{
"options": options,
},
)
if err := options.Validate(); err != nil {
return nil, newErr(
codes.InvalidArgument,
"invalid receive options provided",
err,
)
}
ctx := context.Background()
// Find the generic pull subscription for the provided topic (queue)
queueSubscription, err := s.getQueueSubscription(options.QueueName)
if err != nil {
return nil, newErr(
codes.NotFound,
"could not find queue subscription",
err,
)
}
// Using base client, so that asynchronous message acknowledgement can take place without needing to keep messages
// in a stateful service. Standard PubSub go library do not provide access to the acknowledge ID of the messages or
// an independent acknowledge function. It's only provided as a method on message objects.
client, err := s.newSubscriberClient(ctx)
if err != nil {
return nil, newErr(
codes.Internal,
"failed to create subscriber client",
err,
)
}
defer client.Close()
// Retrieve the requested number of messages from the subscription (queue)
req := pubsubpb.PullRequest{
Subscription: queueSubscription.String(),
MaxMessages: int32(*options.Depth),
}
res, err := client.Pull(ctx, &req)
if err != nil {
// TODO: catch standard grpc errors, like NotFound.
return nil, newErr(
codes.Internal,
"failed to pull messages",
err,
)
}
// An empty list is returned from PubSub if no messages are available
// we return our own empty list in turn.
if len(res.ReceivedMessages) == 0 {
return []queue.NitricTask{}, nil
}
// Convert the PubSub messages into Nitric tasks
var tasks []queue.NitricTask
for _, m := range res.ReceivedMessages {
var nitricTask queue.NitricTask
err := json.Unmarshal(m.Message.Data, &nitricTask)
if err != nil {
// TODO: append error to error list and Nack the message.
continue
}
tasks = append(tasks, queue.NitricTask{
ID: nitricTask.ID,
Payload: nitricTask.Payload,
PayloadType: nitricTask.PayloadType,
LeaseID: m.AckId,
})
}
return tasks, nil
}
// Completes a previously popped queue item
func (s *PubsubQueueService) Complete(q string, leaseId string) error {
newErr := errors.ErrorsWithScope(
"PubsubQueueService.Complete",
map[string]interface{}{
"queue": q,
"leaseId": leaseId,
},
)
ctx := context.Background()
// Find the generic pull subscription for the provided topic (queue)
queueSubscription, err := s.getQueueSubscription(q)
if err != nil {
return newErr(
codes.NotFound,
"could not find queue subscription",
err,
)
}
// Using base client, so that asynchronous message acknowledgement can take place without needing to keep messages
// in a stateful service. Standard PubSub go library is stateful and don't provide access to the acknowledge ID of
// the messages or an independent acknowledge function. It's only provided as a method on message objects.
client, err := s.newSubscriberClient(ctx)
if err != nil {
return newErr(
codes.Internal,
"failed to create subscriberclient",
err,
)
}
defer client.Close()
// Acknowledge the queue item so it's removed from the queue
req := pubsubpb.AcknowledgeRequest{
Subscription: queueSubscription.String(),
AckIds: []string{leaseId},
}
err = client.Acknowledge(ctx, &req)
if err != nil {
// TODO: catch standard grpc errors, like NotFound.
return newErr(
codes.Internal,
"failed to de-queue task",
err,
)
}
return nil
}
// adaptNewClient - Adapts the pubsubbase.NewSubscriberClient func to one that implements the SubscriberClient
// interface. This is used to enable substitution of the base pubsub client, primarily for mocking support.
func adaptNewClient(f func(context.Context, ...option.ClientOption) (*pubsubbase.SubscriberClient, error)) func(ctx context.Context, opts ...option.ClientOption) (ifaces_pubsub.SubscriberClient, error) {
return func(c context.Context, opts ...option.ClientOption) (ifaces_pubsub.SubscriberClient, error) {
return f(c, opts...)
}
}
// New - Constructs a new GCP pubsub client with defaults
func New() (queue.QueueService, error) {
ctx := context.Background()
credentials, credentialsError := google.FindDefaultCredentials(ctx, pubsub.ScopeCloudPlatform)
if credentialsError != nil {
return nil, fmt.Errorf("GCP credentials error: %v", credentialsError)
}
client, clientError := pubsub.NewClient(ctx, credentials.ProjectID)
if clientError != nil {
return nil, fmt.Errorf("pubsub client error: %v", clientError)
}
return &PubsubQueueService{
client: ifaces_pubsub.AdaptPubsubClient(client),
// TODO: replace this with a better mechanism for mocking the client.
newSubscriberClient: adaptNewClient(pubsubbase.NewSubscriberClient),
projectId: credentials.ProjectID,
}, nil
}
func NewWithClient(client ifaces_pubsub.PubsubClient) queue.QueueService {
return &PubsubQueueService{
client: client,
newSubscriberClient: nil,
}
}
//*pubsubbase.SubscriberClient
func NewWithClients(client ifaces_pubsub.PubsubClient, subscriberClientGenerator func(ctx context.Context, opts ...option.ClientOption) (ifaces_pubsub.SubscriberClient, error)) queue.QueueService {
return &PubsubQueueService{
client: client,
newSubscriberClient: subscriberClientGenerator,
}
}