forked from ThreeDotsLabs/watermill-jetstream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscriber.go
451 lines (368 loc) · 13.3 KB
/
subscriber.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
package jetstream
import (
"context"
"sync"
"time"
"github.com/ThreeDotsLabs/watermill"
"github.com/ThreeDotsLabs/watermill/message"
watermillSync "github.com/ThreeDotsLabs/watermill/pubsub/sync"
"github.com/nats-io/nats.go"
"github.com/pkg/errors"
)
// SubscriberConfig is the configuration to create a subscriber
type SubscriberConfig struct {
// URL is the URL to the broker
URL string
// QueueGroup is the JetStream queue group.
//
// All subscriptions with the same queue name (regardless of the connection they originate from)
// will form a queue group. Each message will be delivered to only one subscriber per queue group,
// using queuing semantics.
//
// It is recommended to set it with DurableName.
// For non durable queue subscribers, when the last member leaves the group,
// that group is removed. A durable queue group (DurableName) allows you to have all members leave
// but still maintain state. When a member re-joins, it starts at the last position in that group.
//
// When QueueGroup is empty, subscribe without QueueGroup will be used.
QueueGroup string
// DurableName is the JetStream durable name.
//
// Subscriptions may also specify a “durable name” which will survive client restarts.
// Durable subscriptions cause the server to track the last acknowledged message
// sequence number for a client and durable name. When the client restarts/resubscribes,
// and uses the same client ID and durable name, the server will resume delivery beginning
// with the earliest unacknowledged message for this durable subscription.
//
// Doing this causes the JetStream server to track
// the last acknowledged message for that ClientID + DurableName.
DurableName string
// SubscribersCount determines how many concurrent subscribers should be started.
SubscribersCount int
// CloseTimeout determines how long subscriber will wait for Ack/Nack on close.
// When no Ack/Nack is received after CloseTimeout, subscriber will be closed.
CloseTimeout time.Duration
// How long subscriber should wait for Ack/Nack. When no Ack/Nack was received, message will be redelivered.
// It is mapped to stan.AckWait option.
AckWaitTimeout time.Duration
// SubscribeTimeout determines how long subscriber will wait for a successful subscription
SubscribeTimeout time.Duration
// NatsOptions are custom []nats.Option passed to the connection.
// It is also used to provide connection parameters, for example:
// nats.URL("nats://localhost:4222")
NatsOptions []nats.Option
// JetstreamOptions are custom Jetstream options for a connection.
JetstreamOptions []nats.JSOpt
// Unmarshaler is an unmarshaler used to unmarshaling messages from NATS format to Watermill format.
Unmarshaler Unmarshaler
// SubscribeOptions defines nats options to be used when subscribing
SubscribeOptions []nats.SubOpt
// SubjectCalculator is a function used to transform a topic to an array of subjects on creation (defaults to "{topic}.*")
SubjectCalculator SubjectCalculator
// AutoProvision bypasses client validation and provisioning of streams
AutoProvision bool
// AckSync enables synchronous acknowledgement (needed for exactly once processing)
AckSync bool
}
// SubscriberSubscriptionConfig is the configurationz
type SubscriberSubscriptionConfig struct {
// Unmarshaler is an unmarshaler used to unmarshaling messages from NATS format to Watermill format.
Unmarshaler Unmarshaler
// QueueGroup is the JetStream queue group.
//
// All subscriptions with the same queue name (regardless of the connection they originate from)
// will form a queue group. Each message will be delivered to only one subscriber per queue group,
// using queuing semantics.
//
// It is recommended to set it with DurableName.
// For non durable queue subscribers, when the last member leaves the group,
// that group is removed. A durable queue group (DurableName) allows you to have all members leave
// but still maintain state. When a member re-joins, it starts at the last position in that group.
//
// When QueueGroup is empty, subscribe without QueueGroup will be used.
QueueGroup string
// DurableName is the JetStream durable name.
//
// Subscriptions may also specify a “durable name” which will survive client restarts.
// Durable subscriptions cause the server to track the last acknowledged message
// sequence number for a client and durable name. When the client restarts/resubscribes,
// and uses the same client ID and durable name, the server will resume delivery beginning
// with the earliest unacknowledged message for this durable subscription.
//
// Doing this causes the JetStream server to track
// the last acknowledged message for that ClientID + DurableName.
DurableName string
// SubscribersCount determines wow much concurrent subscribers should be started.
SubscribersCount int
// How long subscriber should wait for Ack/Nack. When no Ack/Nack was received, message will be redelivered.
// It is mapped to stan.AckWait option.
AckWaitTimeout time.Duration
// CloseTimeout determines how long subscriber will wait for Ack/Nack on close.
// When no Ack/Nack is received after CloseTimeout, subscriber will be closed.
CloseTimeout time.Duration
// SubscribeTimeout determines how long subscriber will wait for a successful subscription
SubscribeTimeout time.Duration
// JetstreamOptions are custom Jetstream options for a connection.
JetstreamOptions []nats.JSOpt
// SubscribeOptions defines nats options to be used when subscribing
SubscribeOptions []nats.SubOpt
// SubjectCalculator is a function used to transform a topic to an array of subjects on creation (defaults to "{topic}.*")
SubjectCalculator SubjectCalculator
// AutoProvision bypasses client validation and provisioning of streams
AutoProvision bool
// AckSync enables synchronous acknowledgement (needed for exactly once processing)
AckSync bool
}
// GetSubscriberSubscriptionConfig gets the configuration subset needed for individual subscribe calls once a connection has been established
func (c *SubscriberConfig) GetSubscriberSubscriptionConfig() SubscriberSubscriptionConfig {
return SubscriberSubscriptionConfig{
Unmarshaler: c.Unmarshaler,
QueueGroup: c.QueueGroup,
DurableName: c.DurableName,
SubscribersCount: c.SubscribersCount,
AckWaitTimeout: c.AckWaitTimeout,
CloseTimeout: c.CloseTimeout,
SubscribeTimeout: c.SubscribeTimeout,
SubscribeOptions: c.SubscribeOptions,
SubjectCalculator: c.SubjectCalculator,
AutoProvision: c.AutoProvision,
JetstreamOptions: c.JetstreamOptions,
AckSync: c.AckSync,
}
}
func (c *SubscriberSubscriptionConfig) setDefaults() {
if c.SubscribersCount <= 0 {
c.SubscribersCount = 1
}
if c.CloseTimeout <= 0 {
c.CloseTimeout = time.Second * 30
}
if c.AckWaitTimeout <= 0 {
c.AckWaitTimeout = time.Second * 30
}
if c.SubscribeTimeout <= 0 {
c.SubscribeTimeout = time.Second * 30
}
if c.SubjectCalculator == nil {
c.SubjectCalculator = defaultSubjectCalculator
}
}
// Validate ensures configuration is valid before use
func (c *SubscriberSubscriptionConfig) Validate() error {
if c.Unmarshaler == nil {
return errors.New("SubscriberConfig.Unmarshaler is missing")
}
if c.QueueGroup == "" && c.SubscribersCount > 1 {
return errors.New(
"to set SubscriberConfig.SubscribersCount " +
"you need to also set SubscriberConfig.QueueGroup, " +
"in other case you will receive duplicated messages",
)
}
if c.SubjectCalculator == nil {
return errors.New("SubscriberSubscriptionConfig.SubjectCalculator is required.")
}
return nil
}
// Subscriber provides the jetstream implementation for watermill subscribe operations
type Subscriber struct {
conn *nats.Conn
logger watermill.LoggerAdapter
config SubscriberSubscriptionConfig
subsLock sync.RWMutex
closed bool
closing chan struct{}
outputsWg sync.WaitGroup
js nats.JetStream
topicInterpreter *topicInterpreter
}
// NewSubscriber creates a new Subscriber.
func NewSubscriber(config SubscriberConfig, logger watermill.LoggerAdapter) (*Subscriber, error) {
conn, err := nats.Connect(config.URL, config.NatsOptions...)
if err != nil {
return nil, errors.Wrap(err, "cannot connect to NATS")
}
return NewSubscriberWithNatsConn(conn, config.GetSubscriberSubscriptionConfig(), logger)
}
// NewSubscriberWithNatsConn creates a new Subscriber with the provided nats connection.
func NewSubscriberWithNatsConn(conn *nats.Conn, config SubscriberSubscriptionConfig, logger watermill.LoggerAdapter) (*Subscriber, error) {
config.setDefaults()
if err := config.Validate(); err != nil {
return nil, err
}
if logger == nil {
logger = watermill.NopLogger{}
}
js, err := conn.JetStream(config.JetstreamOptions...)
if err != nil {
return nil, err
}
return &Subscriber{
conn: conn,
logger: logger,
config: config,
closing: make(chan struct{}),
js: js,
topicInterpreter: newTopicInterpreter(js, config.SubjectCalculator),
}, nil
}
// Subscribe subscribes messages from JetStream.
func (s *Subscriber) Subscribe(ctx context.Context, topic string) (<-chan *message.Message, error) {
output := make(chan *message.Message)
s.outputsWg.Add(1)
outputWg := &sync.WaitGroup{}
for i := 0; i < s.config.SubscribersCount; i++ {
outputWg.Add(1)
subscriberLogFields := watermill.LogFields{
"subscriber_num": i,
"topic": topic,
}
s.logger.Debug("Starting subscriber", subscriberLogFields)
sub, err := s.subscribe(topic, func(msg *nats.Msg) {
s.processMessage(ctx, msg, output, subscriberLogFields)
})
if err != nil {
return nil, errors.Wrap(err, "cannot subscribe")
}
go func(subscriber *nats.Subscription, subscriberLogFields watermill.LogFields) {
defer outputWg.Done()
select {
case <-s.closing:
// unblock
case <-ctx.Done():
// unblock
}
if err := sub.Unsubscribe(); err != nil {
s.logger.Error("Cannot unsubscribe", err, subscriberLogFields)
}
}(sub, subscriberLogFields)
}
go func() {
defer s.outputsWg.Done()
outputWg.Wait()
close(output)
}()
return output, nil
}
// SubscribeInitialize offers a way to ensure the stream for a topic exists prior to subscribe
func (s *Subscriber) SubscribeInitialize(topic string) error {
err := s.topicInterpreter.ensureStream(topic)
if err != nil {
return errors.Wrap(err, "cannot initialize subscribe")
}
return nil
}
func (s *Subscriber) subscribe(topic string, cb nats.MsgHandler) (*nats.Subscription, error) {
if s.config.AutoProvision {
err := s.SubscribeInitialize(topic)
if err != nil {
return nil, err
}
}
primarySubject := s.config.SubjectCalculator(topic).Primary
opts := s.config.SubscribeOptions
if s.config.DurableName != "" {
opts = append(opts, nats.Durable(s.config.DurableName))
} else {
opts = append(opts, nats.BindStream(""))
}
if s.config.QueueGroup != "" {
return s.js.QueueSubscribe(
primarySubject,
s.config.QueueGroup,
cb,
opts...,
)
}
return s.js.Subscribe(
primarySubject,
cb,
opts...,
)
}
func (s *Subscriber) processMessage(
ctx context.Context,
m *nats.Msg,
output chan *message.Message,
logFields watermill.LogFields,
) {
if s.isClosed() {
return
}
s.logger.Trace("Received message", logFields)
msg, err := s.config.Unmarshaler.Unmarshal(m)
if err != nil {
s.logger.Error("Cannot unmarshal message", err, logFields)
return
}
ctx, cancelCtx := context.WithCancel(ctx)
msg.SetContext(ctx)
defer cancelCtx()
messageLogFields := logFields.Add(watermill.LogFields{"message_uuid": msg.UUID})
s.logger.Trace("Unmarshaled message", messageLogFields)
select {
case <-s.closing:
s.logger.Trace("Closing, message discarded", messageLogFields)
return
case <-ctx.Done():
s.logger.Trace("Context cancelled, message discarded", messageLogFields)
return
// if this is first can risk 'send on closed channel' errors
case output <- msg:
s.logger.Trace("Message sent to consumer", messageLogFields)
}
select {
case <-msg.Acked():
var err error
if s.config.AckSync {
err = m.AckSync()
} else {
err = m.Ack()
}
if err != nil {
s.logger.Error("Cannot send ack", err, messageLogFields)
return
}
s.logger.Trace("Message Acked", messageLogFields)
case <-msg.Nacked():
if err := m.Nak(); err != nil {
s.logger.Error("Cannot send nak", err, messageLogFields)
return
}
s.logger.Trace("Message Nacked", messageLogFields)
return
case <-time.After(s.config.AckWaitTimeout):
s.logger.Trace("Ack timeout", messageLogFields)
return
case <-s.closing:
s.logger.Trace("Closing, message discarded before ack", messageLogFields)
return
case <-ctx.Done():
s.logger.Trace("Context cancelled, message discarded before ack", messageLogFields)
return
}
}
// Close closes the publisher and the underlying connection. It will attempt to wait for in-flight messages to complete.
func (s *Subscriber) Close() error {
s.subsLock.Lock()
defer s.subsLock.Unlock()
if s.closed {
return nil
}
s.closed = true
s.logger.Debug("Closing subscriber", nil)
defer s.logger.Info("Subscriber closed", nil)
close(s.closing)
if watermillSync.WaitGroupTimeout(&s.outputsWg, s.config.CloseTimeout) {
return errors.New("output wait group did not finish")
}
if err := s.conn.Drain(); err != nil {
return errors.Wrap(err, "cannot close conn")
}
return nil
}
func (s *Subscriber) isClosed() bool {
s.subsLock.RLock()
defer s.subsLock.RUnlock()
return s.closed
}