/
protocol.go
243 lines (201 loc) · 5.82 KB
/
protocol.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
/*
Copyright 2021 The CloudEvents Authors
SPDX-License-Identifier: Apache-2.0
*/
package pubsub
import (
"context"
"fmt"
"io"
"sync"
"cloud.google.com/go/pubsub"
"github.com/cloudevents/sdk-go/protocol/pubsub/v2/internal"
"github.com/cloudevents/sdk-go/v2/binding"
cecontext "github.com/cloudevents/sdk-go/v2/context"
"github.com/cloudevents/sdk-go/v2/protocol"
"golang.org/x/sync/errgroup"
)
const (
ProtocolName = "Pub/Sub"
)
type subscriptionWithTopic struct {
topicID string
subscriptionID string
filter string
}
// Protocol acts as both a pubsub topic and a pubsub subscription .
type Protocol struct {
// PubSub
// ReceiveSettings is used to configure Pubsub pull subscription.
ReceiveSettings *pubsub.ReceiveSettings
// AllowCreateTopic controls if the transport can create a topic if it does
// not exist.
AllowCreateTopic bool
// AllowCreateSubscription controls if the transport can create a
// subscription if it does not exist.
AllowCreateSubscription bool
// MessageOrdering enables message ordering for all topics and subscriptions.
MessageOrdering bool
projectID string
topicID string
gccMux sync.Mutex
subscriptions []subscriptionWithTopic
client *pubsub.Client
connectionsBySubscription map[string]*internal.Connection
connectionsByTopic map[string]*internal.Connection
incoming chan pubsub.Message
}
// New creates a new pubsub transport.
func New(ctx context.Context, opts ...Option) (*Protocol, error) {
t := &Protocol{}
t.incoming = make(chan pubsub.Message)
if err := t.applyOptions(opts...); err != nil {
return nil, err
}
if t.client == nil {
// Auth to pubsub.
client, err := pubsub.NewClient(ctx, t.projectID)
if err != nil {
return nil, err
}
// Success.
t.client = client
}
if t.connectionsBySubscription == nil {
t.connectionsBySubscription = make(map[string]*internal.Connection)
}
if t.connectionsByTopic == nil {
t.connectionsByTopic = make(map[string]*internal.Connection)
}
return t, nil
}
func (t *Protocol) applyOptions(opts ...Option) error {
for _, fn := range opts {
if err := fn(t); err != nil {
return err
}
}
return nil
}
// Send implements Sender.Send
func (t *Protocol) Send(ctx context.Context, in binding.Message, transformers ...binding.Transformer) error {
var err error
defer func() { _ = in.Finish(err) }()
topic := cecontext.TopicFrom(ctx)
if topic == "" {
topic = t.topicID
}
conn := t.getOrCreateConnection(ctx, topic, "", "")
msg := &pubsub.Message{
Attributes: AttributesFrom(ctx),
}
if key, ok := ctx.Value(withOrderingKey{}).(string); ok {
if !t.MessageOrdering {
return fmt.Errorf("ordering key cannot be used when message ordering is disabled")
}
msg.OrderingKey = key
}
if err := WritePubSubMessage(ctx, in, msg, transformers...); err != nil {
return err
}
if _, err := conn.Publish(ctx, msg); err != nil {
return err
}
return nil
}
func (t *Protocol) getConnection(ctx context.Context, topic, subscription string) *internal.Connection {
if subscription != "" {
if conn, ok := t.connectionsBySubscription[subscription]; ok {
return conn
}
}
if topic != "" {
if conn, ok := t.connectionsByTopic[topic]; ok {
return conn
}
}
return nil
}
func (t *Protocol) getOrCreateConnection(ctx context.Context, topic, subscription, filter string) *internal.Connection {
t.gccMux.Lock()
defer t.gccMux.Unlock()
// Get.
if conn := t.getConnection(ctx, topic, subscription); conn != nil {
return conn
}
// Create.
conn := &internal.Connection{
AllowCreateSubscription: t.AllowCreateSubscription,
AllowCreateTopic: t.AllowCreateTopic,
ReceiveSettings: t.ReceiveSettings,
Client: t.client,
ProjectID: t.projectID,
MessageOrdering: t.MessageOrdering,
TopicID: topic,
SubscriptionID: subscription,
Filter: filter,
}
// Save for later.
if subscription != "" {
t.connectionsBySubscription[subscription] = conn
}
if topic != "" {
t.connectionsByTopic[topic] = conn
}
return conn
}
// Receive implements Receiver.Receive
func (t *Protocol) Receive(ctx context.Context) (binding.Message, error) {
select {
case m, ok := <-t.incoming:
if !ok {
return nil, io.EOF
}
msg := NewMessage(&m)
return msg, nil
case <-ctx.Done():
return nil, io.EOF
}
}
func (t *Protocol) startSubscriber(ctx context.Context, sub subscriptionWithTopic) error {
logger := cecontext.LoggerFrom(ctx)
logger.Infof("starting subscriber for Topic %q, Subscription %q", sub.topicID, sub.subscriptionID)
conn := t.getOrCreateConnection(ctx, sub.topicID, sub.subscriptionID, sub.filter)
logger.Info("conn is", conn)
if conn == nil {
return fmt.Errorf("failed to find connection for Topic: %q, Subscription: %q", sub.topicID, sub.subscriptionID)
}
// Ok, ready to start pulling.
return conn.Receive(ctx, func(ctx context.Context, m *pubsub.Message) {
select {
case t.incoming <- *m:
case <-ctx.Done():
}
})
}
func (t *Protocol) OpenInbound(ctx context.Context) error {
eg, ctx := errgroup.WithContext(ctx)
// Start up each subscription.
for _, sub := range t.subscriptions {
ctx, sub := ctx, sub
eg.Go(func() error {
return t.startSubscriber(ctx, sub)
})
}
return eg.Wait()
}
// Close implements Closer.Close
func (t *Protocol) Close(ctx context.Context) error {
// TODO: Implement this.
return nil
}
// pubsub protocol implements Sender, Receiver, Closer, Opener
var _ protocol.Opener = (*Protocol)(nil)
var _ protocol.Sender = (*Protocol)(nil)
var _ protocol.Receiver = (*Protocol)(nil)
var _ protocol.Closer = (*Protocol)(nil)
type withOrderingKey struct{}
// WithOrderingKey allows to set the Pub/Sub ordering key for publishing events.
func WithOrderingKey(ctx context.Context, key string) context.Context {
return context.WithValue(ctx, withOrderingKey{}, key)
}