-
Notifications
You must be signed in to change notification settings - Fork 2
/
publisher.go
307 lines (248 loc) · 8.82 KB
/
publisher.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
package firestore
import (
"context"
"sync"
"time"
"github.com/pkg/errors"
"cloud.google.com/go/firestore"
"github.com/ThreeDotsLabs/watermill"
"github.com/ThreeDotsLabs/watermill/message"
"google.golang.org/api/option"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type PublisherConfig struct {
// ProjectID is an ID of a Google Cloud project with Firestore database.
ProjectID string
// PubSubRootCollection is a name of a collection which will be used as a root collection for the PubSub.
// It defaults to "pubsub".
PubSubRootCollection string
// MessagePublishTimeout is a timeout used for a single `Publish` call.
// It defaults to 1 minute.
MessagePublishTimeout time.Duration
// SubscriptionsCacheValidityDuration is used for internal subscriptions cache
// in order to reduce fetch calls to Firestore on each `Publish` method call.
//
// If you prefer to not cache subscriptions and fetch them each time `Publish`
// is called, please set `DontCacheSubscriptions` to true.
//
// It defaults to 500 milliseconds.
SubscriptionsCacheValidityDuration time.Duration
// DontCacheSubscriptions should be set to true when you don't want
// Publisher to keep an internal cache of subscribers.
DontCacheSubscriptions bool
// GoogleClientOpts are options passed directly to firestore client.
GoogleClientOpts []option.ClientOption
// Marshaler marshals message from Watermill to Firestore format and vice versa.
Marshaler Marshaler
// CustomFirestoreClient can be used to override a default client.
CustomFirestoreClient client
}
func (c *PublisherConfig) setDefaults() {
if c.MessagePublishTimeout == 0 {
c.MessagePublishTimeout = time.Minute
}
if c.PubSubRootCollection == "" {
c.PubSubRootCollection = defaultPubSubRootCollection
}
if c.SubscriptionsCacheValidityDuration == 0 {
c.SubscriptionsCacheValidityDuration = time.Millisecond * 500
}
if c.Marshaler == nil {
c.Marshaler = DefaultMarshaler{}
}
}
type Publisher struct {
config PublisherConfig
logger watermill.LoggerAdapter
client client
subscriptionsCacheMtx *sync.RWMutex
subscriptionsCache map[string]subscriptionsCacheEntry
}
type subscriptionsCacheEntry struct {
subscriptionsNames []string
lastWrite time.Time
}
func NewPublisher(config PublisherConfig, logger watermill.LoggerAdapter) (*Publisher, error) {
config.setDefaults()
var client client
if config.CustomFirestoreClient != nil {
client = config.CustomFirestoreClient
} else {
var err error
client, err = firestore.NewClient(context.Background(), config.ProjectID, config.GoogleClientOpts...)
if err != nil {
return nil, errors.Wrap(err, "cannot create default firestore client")
}
}
return &Publisher{
client: client,
config: config,
logger: logger,
subscriptionsCacheMtx: &sync.RWMutex{},
subscriptionsCache: make(map[string]subscriptionsCacheEntry),
}, nil
}
func (p *Publisher) Publish(topic string, messages ...*message.Message) error {
ctx, cancel := context.WithTimeout(context.Background(), p.config.MessagePublishTimeout)
defer cancel()
logger := p.logger.With(watermill.LogFields{"topic": topic})
subscriptions, err := p.getSubscriptions(ctx, topic)
if err != nil {
logger.Error("Failed to get subscriptions for publishing", err, nil)
return err
}
logger = logger.With(watermill.LogFields{"subscriptions_count": len(subscriptions)})
msgsToPublish, err := p.prepareFirestoreMessages(messages)
if err != nil {
return errors.Wrap(err, "cannot prepare messages to publish")
}
logger.Trace("Publishing to topic", nil)
for _, subscription := range subscriptions {
logger := logger.With(watermill.LogFields{"subscription": subscription})
logger.Trace("Publishing to subscription", nil)
if err := p.publishInBatches(ctx, topic, subscription, msgsToPublish, logger); err != nil {
return err
}
}
logger.Debug("Published to topic", nil)
return nil
}
func (p *Publisher) PublishInTransaction(topic string, t *firestore.Transaction, messages ...*message.Message) error {
ctx, cancel := context.WithTimeout(context.Background(), p.config.MessagePublishTimeout)
defer cancel()
logger := p.logger.With(watermill.LogFields{"topic": topic})
subscriptions, err := p.getSubscriptions(ctx, topic)
if err != nil {
logger.Error("Failed to get subscriptions for publishing", err, nil)
return err
}
logger = logger.With(watermill.LogFields{"subscriptions_count": len(subscriptions)})
marshaledMessages, err := p.prepareFirestoreMessages(messages)
if err != nil {
return errors.Wrap(err, "cannot prepare messages to publish")
}
logger.Trace("Publishing to topic", nil)
for _, subscription := range subscriptions {
logger := logger.With(watermill.LogFields{"subscription": subscription})
logger.Trace("Publishing to subscription", nil)
for _, marshaledMessage := range marshaledMessages {
doc := p.client.Collection(p.config.PubSubRootCollection).Doc(topic).Collection(subscription).NewDoc()
if err := t.Create(doc, marshaledMessage.Data); err != nil {
logger.Error("Failed to add message to transaction", err, nil)
return err
}
logger.Debug("Publishing message to firestore", watermill.LogFields{
"firestore_path": doc.Path,
"firestore_doc_id": doc.ID,
"message_uuid": marshaledMessage.MessageUUID,
})
logger.Trace("Added message to transaction", nil)
}
}
return nil
}
func (p *Publisher) getSubscriptions(ctx context.Context, topic string) ([]string, error) {
logger := p.logger.With(watermill.LogFields{"topic": topic})
if p.isCacheValid(topic) {
subs := p.getSubscriptionsFromCache(topic)
logger.Trace("Read subscriptions from cache", watermill.LogFields{"subs_count": len(subs)})
return subs, nil
}
logger.Trace("Subscriptions cache is not valid", nil)
subsDocs, err := p.client.Collection(p.config.PubSubRootCollection).Doc(topic).Collection(subscriptionsCollection).Documents(ctx).GetAll()
if err != nil {
return nil, err
}
var subs []string
for _, subDoc := range subsDocs {
subs = append(subs, subDoc.Ref.ID)
}
p.cacheSubscriptions(topic, subs)
logger.Trace("Cached subscriptions", watermill.LogFields{"subs_count": len(subs)})
return subs, nil
}
func (p *Publisher) getSubscriptionsFromCache(topic string) []string {
p.subscriptionsCacheMtx.RLock()
defer p.subscriptionsCacheMtx.RUnlock()
return p.subscriptionsCache[topic].subscriptionsNames
}
func (p *Publisher) cacheSubscriptions(topic string, subs []string) {
p.subscriptionsCacheMtx.Lock()
defer p.subscriptionsCacheMtx.Unlock()
entry := subscriptionsCacheEntry{
lastWrite: time.Now(),
subscriptionsNames: subs,
}
p.subscriptionsCache[topic] = entry
}
func (p *Publisher) isCacheValid(topic string) bool {
p.subscriptionsCacheMtx.RLock()
defer p.subscriptionsCacheMtx.RUnlock()
return time.Now().Before(p.subscriptionsCache[topic].lastWrite.Add(p.config.SubscriptionsCacheValidityDuration))
}
type marshaledMessage struct {
MessageUUID string
Data interface{}
}
func (p *Publisher) prepareFirestoreMessages(messages []*message.Message) ([]marshaledMessage, error) {
var msgsToPublish []marshaledMessage
for _, msg := range messages {
firestoreMsg, err := p.config.Marshaler.Marshal(msg)
if err != nil {
return nil, err
}
msgsToPublish = append(msgsToPublish, marshaledMessage{
MessageUUID: msg.UUID,
Data: firestoreMsg,
})
}
return msgsToPublish, nil
}
func (p *Publisher) publishInBatches(
ctx context.Context,
topic,
subscription string,
marshaledMsgs []marshaledMessage,
logger watermill.LoggerAdapter,
) error {
const firestoreBatchSizeLimit = 500
for offset := 0; offset < len(marshaledMsgs); offset = offset + firestoreBatchSizeLimit {
lastInBatch := offset + firestoreBatchSizeLimit
if len(marshaledMsgs) < lastInBatch {
lastInBatch = len(marshaledMsgs)
}
logger := logger.With(watermill.LogFields{
"batch_start": offset,
"batch_end": lastInBatch,
})
logger.Trace("Publishing messages batch", nil)
batch := p.client.Batch()
for _, marshaledMsg := range marshaledMsgs[offset:lastInBatch] {
doc := p.client.Collection(p.config.PubSubRootCollection).Doc(topic).Collection(subscription).NewDoc()
batch = batch.Create(doc, marshaledMsg.Data)
logger.Debug("Publishing message to firestore", watermill.LogFields{
"firestore_path": doc.Path,
"firestore_doc_id": doc.ID,
"message_uuid": marshaledMsg.MessageUUID,
})
}
if _, err := batch.Commit(ctx); err != nil {
logger.Error("Failed to commit messages batch", err, nil)
return err
}
}
return nil
}
func (p *Publisher) Close() error {
if err := p.client.Close(); err != nil {
if status.Code(err) == codes.Canceled {
// client is already closed
p.logger.Trace("Closing when already closed", nil)
return nil
}
p.logger.Error("closing client failed", err, watermill.LogFields{})
return err
}
return nil
}