This repository has been archived by the owner on Jul 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
pubsub.go
234 lines (193 loc) · 5.96 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
// Package pubsub provides a Google PubSub abstraction.
package pubsub
import (
"context"
"net/url"
"sync"
"sync/atomic"
"time"
"github.com/bsm/bps/internal/concurrent"
native "cloud.google.com/go/pubsub"
"github.com/bsm/bps"
"google.golang.org/api/option"
)
func init() {
bps.RegisterPublisher("pubsub", func(ctx context.Context, u *url.URL) (bps.Publisher, error) {
projectID := u.Host
query := u.Query()
if v := query.Get("project_id"); v != "" {
projectID = v
}
return NewPublisher(ctx, projectID, nil)
})
bps.RegisterSubscriber("pubsub", func(ctx context.Context, u *url.URL) (bps.Subscriber, error) {
projectID := u.Host
query := u.Query()
if v := query.Get("project_id"); v != "" {
projectID = v
}
return NewSubscriber(ctx, projectID)
})
}
// --------------------------------------------------------------------
// Publisher wraps a google pubsub client and implements the bps.Publisher interface.
type Publisher struct {
client *native.Client
settings *native.PublishSettings
topics map[string]*PubTopic
mu sync.RWMutex
}
// NewPublisher inits a publisher.
func NewPublisher(ctx context.Context, projectID string, settings *native.PublishSettings, opts ...option.ClientOption) (*Publisher, error) {
client, err := native.NewClient(ctx, projectID, opts...)
if err != nil {
return nil, err
}
return &Publisher{
client: client,
settings: settings,
topics: make(map[string]*PubTopic),
}, nil
}
// Topic implements the bps.Publisher interface.
func (p *Publisher) Topic(name string) bps.PubTopic {
p.mu.RLock()
topic, ok := p.topics[name]
p.mu.RUnlock()
if ok {
return topic
}
p.mu.Lock()
defer p.mu.Unlock()
if topic, ok = p.topics[name]; !ok {
nt := p.client.Topic(name)
if p.settings != nil {
nt.PublishSettings = *p.settings
}
topic = &PubTopic{topic: nt}
p.topics[name] = topic
}
return topic
}
// Close implements the bps.Publisher interface.
func (p *Publisher) Close() error {
p.mu.Lock()
defer p.mu.Unlock()
// stop all
for _, t := range p.topics {
t.topic.Stop()
}
// wait for all
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
defer cancel()
var err error
for name, t := range p.topics {
if e := t.wait(ctx); e != nil {
err = e
}
delete(p.topics, name)
}
return err
}
// Client exposes the native client. Use at your own risk!
func (p *Publisher) Client() *native.Client {
return p.client
}
// --------------------------------------------------------------------
// PubTopic wraps a pubsub topic.
type PubTopic struct {
topic *native.Topic
last atomic.Value
}
// Publish implements the bps.Topic interface.
func (t *PubTopic) Publish(ctx context.Context, msg *bps.PubMessage) error {
res := t.topic.Publish(ctx, &native.Message{
ID: msg.ID,
Data: msg.Data,
Attributes: msg.Attributes,
})
t.last.Store(res)
return nil
}
// Topic returns the native pubsub Topic. Use at your own risk!
func (t *PubTopic) Topic() *native.Topic {
return t.topic
}
func (t *PubTopic) wait(ctx context.Context) error {
if v := t.last.Load(); v != nil {
_, err := v.(*native.PublishResult).Get(ctx)
return err
}
return nil
}
// --------------------------------------------------------------------
// Subscriber is a Google PubSub wrapper that implements bps.Subscriber interface.
type Subscriber struct {
client *native.Client
}
// NewSubscriber inits a subscriber.
// It starts handling from the newest available message (published after subscribing).
// Google PubSub may re-deliver successfully handled messages.
func NewSubscriber(ctx context.Context, projectID string) (*Subscriber, error) {
client, err := native.NewClient(ctx, projectID)
if err != nil {
return nil, err
}
return &Subscriber{
client: client,
}, nil
}
// Topic returns a subcriber topic handle.
func (s *Subscriber) Topic(name string) bps.SubTopic {
return &subTopic{
client: s.client,
name: name,
}
}
// Close closes the client.
func (s *Subscriber) Close() error {
return s.client.Close()
}
// --------------------------------------------------------------------
type subTopic struct {
client *native.Client
name string
}
func (t *subTopic) Subscribe(handler bps.Handler, options ...bps.SubOption) (bps.Subscription, error) {
opts := (&bps.SubOptions{}).Apply(options)
// usual way to "unsubscribe" from Google PubSub is to cancel context:
ctx, cancel := context.WithCancel(context.Background())
gsub, err := t.client.CreateSubscription(ctx, bps.GenClientID(), native.SubscriptionConfig{
Topic: t.client.Topic(t.name),
})
if err != nil {
cancel()
return nil, err
}
sub := concurrent.NewGroup(ctx)
sub.Go(func() {
defer func() {
// give subscription 5s to delete:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = gsub.Delete(ctx)
}()
defer cancel()
// gsub.Receive calls handler concurrently from multiple goroutines, so synchronise it:
handler = bps.SafeHandler(handler)
// TODO: may need to suppress sub.Receive's err:
// pubsub native lib is based on streaming pull, which is expected to terminate with error:
// https://cloud.google.com/pubsub/docs/pull#streamingpull_has_a_100_error_rate_this_is_to_be_expected
// StreamingPull streams are always terminated with a non-OK status.
// Note that, unlike in regular RPCs, the status here is simply an indication that the stream has been broken, not that requests are failing.
// Therefore, while the StreamingPull API may have a seemingly surprising 100% error rate, this is by design.
// Receive returns on fatal/non-retryable errors, so thread is terminated after it, no retries:
err := gsub.Receive(ctx, func(ctx context.Context, msg *native.Message) {
defer msg.Nack() // only first call to Ack/Nack matters, so it's safe
handler.Handle(bps.RawSubMessage(msg.Data))
msg.Ack() // no error returned, msg will be re-delivered on Ack failure
})
opts.ErrorHandler(err)
})
return sub, nil
}