-
Notifications
You must be signed in to change notification settings - Fork 13
/
pubsub.go
295 lines (260 loc) · 7.02 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
// Copyright 2024 The Bucketeer 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"
"errors"
"strings"
"time"
"cloud.google.com/go/pubsub"
"go.uber.org/zap"
"github.com/bucketeer-io/bucketeer/pkg/backoff"
"github.com/bucketeer-io/bucketeer/pkg/metrics"
"github.com/bucketeer-io/bucketeer/pkg/pubsub/publisher"
"github.com/bucketeer-io/bucketeer/pkg/pubsub/puller"
)
var (
ErrInvalidTopic = errors.New("pubsub: invalid topic")
)
const (
rpcErrAlreadyExists = "AlreadyExists"
)
type Client struct {
*pubsub.Client
opts *options
logger *zap.Logger
}
type options struct {
backoff backoff.Backoff
retries int
metrics metrics.Registerer
logger *zap.Logger
}
func defaultOptions() *options {
return &options{
backoff: backoff.NewExponential(time.Second, 20*time.Second),
retries: 3,
logger: zap.NewNop(),
}
}
type Option func(*options)
func WithBackoff(bf backoff.Backoff) Option {
return func(opts *options) {
opts.backoff = bf
}
}
func WithRetries(retries int) Option {
return func(opts *options) {
opts.retries = retries
}
}
func WithMetrics(registerer metrics.Registerer) Option {
return func(opts *options) {
opts.metrics = registerer
}
}
func WithLogger(l *zap.Logger) Option {
return func(opts *options) {
opts.logger = l
}
}
type receiveOptions = pubsub.ReceiveSettings
type ReceiveOption func(*receiveOptions)
func WithMaxExtension(d time.Duration) ReceiveOption {
return func(opts *receiveOptions) {
opts.MaxExtension = d
}
}
func WithMaxOutstandingMessages(n int) ReceiveOption {
return func(opts *receiveOptions) {
opts.MaxOutstandingMessages = n
}
}
func WithMaxOutstandingBytes(b int) ReceiveOption {
return func(opts *receiveOptions) {
opts.MaxOutstandingBytes = b
}
}
func WithNumGoroutines(n int) ReceiveOption {
return func(opts *receiveOptions) {
opts.NumGoroutines = n
}
}
type publishOptions = pubsub.PublishSettings
type PublishOption func(*publishOptions)
func WithPublishNumGoroutines(n int) PublishOption {
return func(opts *publishOptions) {
opts.NumGoroutines = n
}
}
func WithPublishTimeout(timeout time.Duration) PublishOption {
return func(opts *publishOptions) {
opts.Timeout = timeout
}
}
func NewClient(ctx context.Context, project string, opts ...Option) (*Client, error) {
c, err := pubsub.NewClient(ctx, project)
if err != nil {
return nil, err
}
options := defaultOptions()
for _, opt := range opts {
opt(options)
}
return &Client{
Client: c,
opts: options,
logger: options.logger.Named("pubsub"),
}, nil
}
func (c *Client) CreatePublisher(topic string, opts ...PublishOption) (publisher.Publisher, error) {
t, err := c.topic(topic)
if err != nil {
c.logger.Error("Failed to create topic",
zap.String("topic", topic),
zap.Error(err))
return nil, err
}
return c.createPublisher(t, opts...)
}
func (c *Client) CreatePublisherInProject(topic, project string, opts ...PublishOption) (publisher.Publisher, error) {
t, err := c.topicInProject(topic, project)
if err != nil {
c.logger.Error("Failed to create topic",
zap.String("topic", topic),
zap.String("project", project),
zap.Error(err))
return nil, err
}
return c.createPublisher(t, opts...)
}
func (c *Client) createPublisher(topic *pubsub.Topic, opts ...PublishOption) (publisher.Publisher, error) {
settings := (publishOptions)(pubsub.DefaultPublishSettings)
for _, opt := range opts {
opt(&settings)
}
topic.PublishSettings = settings
options := []publisher.Option{publisher.WithLogger(c.logger)}
if c.opts.metrics != nil {
options = append(options, publisher.WithMetrics(c.opts.metrics))
}
return publisher.NewPublisher(topic, options...), nil
}
func (c *Client) CreatePuller(subscription, topic string, opts ...ReceiveOption) (puller.Puller, error) {
s, err := c.subscription(subscription, topic)
if err != nil {
c.logger.Error("Failed to create puller",
zap.String("subscription", subscription),
zap.String("topic", topic),
zap.Error(err))
return nil, err
}
options := (receiveOptions)(pubsub.DefaultReceiveSettings)
for _, opt := range opts {
opt(&options)
}
s.ReceiveSettings = options
c.logger.Info("Create a new puller", zap.Any("receiveSettings", options))
return puller.NewPuller(
s,
puller.WithLogger(c.logger),
), nil
}
func (c *Client) topic(id string) (*pubsub.Topic, error) {
topic := c.Client.Topic(id)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
ok, err := topic.Exists(ctx)
if err != nil {
return nil, err
}
if ok {
return topic, nil
}
return nil, ErrInvalidTopic
}
func (c *Client) topicInProject(topicID, projectID string) (*pubsub.Topic, error) {
topic := c.Client.TopicInProject(topicID, projectID)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
ok, err := topic.Exists(ctx)
if err != nil {
return nil, err
}
if ok {
return topic, nil
}
return nil, ErrInvalidTopic
}
// TODO: add metrics
func (c *Client) subscription(id, topicID string) (*pubsub.Subscription, error) {
sub := c.Client.Subscription(id)
topic := c.Client.Topic(topicID)
var lastErr error
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
retry := backoff.NewRetry(ctx, c.opts.retries, c.opts.backoff.Clone())
for retry.WaitNext() {
ok, err := sub.Exists(ctx)
if err != nil {
lastErr = err
continue
}
if ok {
return sub, nil
}
_, err = c.Client.CreateSubscription(ctx, id, pubsub.SubscriptionConfig{
Topic: topic,
})
if err == nil {
return sub, nil
}
if strings.Contains(err.Error(), rpcErrAlreadyExists) {
c.logger.Debug("Subscription already exists, use it directly",
zap.String("subscription", id),
zap.String("topic", topicID),
)
return sub, nil
}
lastErr = err
}
return nil, lastErr
}
func (c *Client) SubscriptionExists(id string) (bool, error) {
sub := c.Client.Subscription(id)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
exists, err := sub.Exists(ctx)
if err != nil {
return false, err
}
return exists, nil
}
func (c *Client) DeleteSubscription(id string) error {
sub := c.Client.Subscription(id)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return sub.Delete(ctx)
}
func (c *Client) DeleteSubscriptionIfExist(id string) error {
exists, err := c.SubscriptionExists(id)
if err != nil {
return err
}
if !exists {
c.logger.Debug("Subscription does not exist", zap.String("subscription", id))
return nil
}
return c.DeleteSubscription(id)
}