-
Notifications
You must be signed in to change notification settings - Fork 21
/
subscriber.go
448 lines (365 loc) · 12.8 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
package nats
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
// QueueGroupPrefix is the prefix used by SubjectCalculator to derive queue group from the topic.
//
// 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.
//
// For JetStream is recommended to set it with DurablePrefix.
// For non durable queue subscribers, when the last member leaves the group,
// that group is removed. A durable queue group (DurablePrefix) 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.
QueueGroupPrefix 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.
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
// Unmarshaler is an unmarshaler used to unmarshaling messages from NATS format to Watermill format.
Unmarshaler Unmarshaler
// SubjectCalculator is a function used to transform a topic to an array of subjects on creation (defaults to topic as Primary and queueGroupPrefix as QueueGroup)
SubjectCalculator SubjectCalculator
// NakDelay sets duration after which the NACKed message will be resent.
// By default, it's NACKed without delay.
NakDelay Delay
// JetStream holds JetStream specific settings
JetStream JetStreamConfig
}
// SubscriberSubscriptionConfig is the configurationz
type SubscriberSubscriptionConfig struct {
// Unmarshaler is an unmarshaler used to unmarshaling messages from NATS format to Watermill format.
Unmarshaler Unmarshaler
// 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.
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
// SubjectCalculator is a function used to transform a topic to an array of subjects on creation (defaults to topic as Primary and queueGroupPrefix as QueueGroup)
SubjectCalculator SubjectCalculator
// NakDelay sets duration after which the NACKed message will be resent.
// By default, it's NACKed without delay.
NakDelay Delay
// JetStream holds JetStream specific settings
JetStream JetStreamConfig
// QueueGroupPrefix is the prefix used by SubjectCalculator to derive queue group from the topic.
//
// 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.
//
// For JetStream is recommended to set it with DurablePrefix.
// For non durable queue subscribers, when the last member leaves the group,
// that group is removed. A durable queue group (DurablePrefix) 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.
QueueGroupPrefix string
}
// 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,
SubscribersCount: c.SubscribersCount,
AckWaitTimeout: c.AckWaitTimeout,
CloseTimeout: c.CloseTimeout,
SubscribeTimeout: c.SubscribeTimeout,
SubjectCalculator: c.SubjectCalculator,
NakDelay: c.NakDelay,
JetStream: c.JetStream,
QueueGroupPrefix: c.QueueGroupPrefix,
}
}
func (c *SubscriberSubscriptionConfig) setDefaults() {
if c.SubjectCalculator == nil {
c.SubjectCalculator = DefaultSubjectCalculator
}
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.Unmarshaler == nil {
c.Unmarshaler = &NATSMarshaler{}
}
}
// Validate ensures configuration is valid before use
func (c *SubscriberSubscriptionConfig) Validate() error {
if c.Unmarshaler == nil {
return errors.New("SubscriberConfig.Unmarshaler is missing")
}
//TODO: how best to validate this with dynamic queue group
/*
if c.QueueGroup == "" && c.SubscribersCount > 1 {
return errors.New(
"to set SubscriberConfig.SubscribersCount " +
"you need to also set SubscriberConfig.QueueGroupPrefix, " +
"in other case you will receive duplicated messages",
)
}
*/
if c.SubjectCalculator == nil {
return errors.New("SubscriberSubscriptionConfig.SubjectCalculator is required.")
}
return nil
}
// Subscriber provides the nats implementation for watermill subscribe operations
type Subscriber struct {
conn Connection
logger watermill.LoggerAdapter
config SubscriberSubscriptionConfig
subsLock sync.RWMutex
closed bool
closing chan struct{}
outputsWg sync.WaitGroup
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{}
}
var connection Connection = conn
var interpreter *topicInterpreter
if !config.JetStream.Disabled {
js, err := conn.JetStream(config.JetStream.ConnectOptions...)
connection = &jsConnection{conn, js, config.JetStream}
if err != nil {
return nil, err
}
interpreter = newTopicInterpreter(js, config.SubjectCalculator, config.QueueGroupPrefix)
}
return &Subscriber{
conn: connection,
logger: logger,
config: config,
closing: make(chan struct{}),
topicInterpreter: interpreter,
}, 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.JetStream.ShouldAutoProvision() {
err := s.SubscribeInitialize(topic)
if err != nil {
return nil, err
}
}
subjectDetail := s.config.SubjectCalculator(s.config.QueueGroupPrefix, topic)
return s.conn.QueueSubscribe(
subjectDetail.Primary,
subjectDetail.QueueGroup,
cb,
)
}
func (s *Subscriber) processMessage(
ctx context.Context,
m *nats.Msg,
output chan *message.Message,
logFields watermill.LogFields,
) {
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
}
messageLogFields := logFields.Add(watermill.LogFields{"message_uuid": msg.UUID})
s.logger.Trace("Unmarshaled message", messageLogFields)
ctx, cancelCtx := context.WithCancel(ctx)
msg.SetContext(ctx)
defer cancelCtx()
timeout := time.NewTimer(s.config.AckWaitTimeout)
defer timeout.Stop()
if s.isClosed() {
return
}
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():
if m.Reply == "" {
s.logger.Trace("ack without a reply subject is a no-op", messageLogFields)
return
}
var err error
if s.config.JetStream.AckAsync {
err = m.Ack()
} else {
err = m.AckSync()
}
if err != nil {
s.logger.Error("Cannot send ack", err, messageLogFields)
return
}
s.logger.Trace("Message Acked", messageLogFields)
case <-msg.Nacked():
if m.Reply == "" {
s.logger.Trace("Ignoring nack without reply topic", messageLogFields)
return
}
var nakDelay time.Duration
if s.config.NakDelay != nil {
metadata, err := m.Metadata()
if err != nil {
s.logger.Error("Cannot parse nats message metadata, use nak without delay", err, messageLogFields)
} else {
nakDelay = s.config.NakDelay.WaitTime(metadata.NumDelivered)
messageLogFields = messageLogFields.Add(watermill.LogFields{
"delay": nakDelay.String(),
"retryNum": metadata.NumDelivered,
})
}
}
if nakDelay == TermSignal {
if err := m.Term(); err != nil {
s.logger.Error("Cannot send term", err, messageLogFields)
} else {
s.logger.Trace("Message Termed via -1 NakDelay calculation", messageLogFields)
}
return
}
if nakDelay > 0 {
if err := m.NakWithDelay(nakDelay); err != nil {
s.logger.Error("Cannot send nak", err, messageLogFields)
return
}
} else {
if err := m.Nak(); err != nil {
s.logger.Error("Cannot send nak", err, messageLogFields)
return
}
}
s.logger.Trace("Message Nacked", messageLogFields)
return
case <-timeout.C:
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
}