-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconsumer.go
317 lines (260 loc) · 6.59 KB
/
consumer.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
package tackle
import (
"errors"
"fmt"
"log"
"sync"
"time"
rabbit "github.com/rabbitmq/amqp091-go"
)
const (
StateListening = "listening"
StateNotListening = "not-listening"
ReconnectionAttempts = 50
ReconnectionDelayDuration = 2 * time.Second
PrefetchCount = 1
PrefetchSize = 0
Global = true
ConsumerName = "tackle-consumer"
Durable = true
Exclusive = false
AutoAck = false
AutoDeleted = false
Internal = false
NoWait = false
NoLocal = false
)
type ProcessorFunc func(Delivery) error
type Consumer struct {
State string
options *Options
connection *rabbit.Connection
channel *rabbit.Channel
shutdown chan bool
processor ProcessorFunc
mu sync.Mutex
logger Logger
}
func NewConsumer() *Consumer {
return &Consumer{
State: StateNotListening,
logger: &defaultLogger{},
}
}
func (c *Consumer) SetLogger(l Logger) {
c.logger = l
}
func (c *Consumer) Start(options *Options, f ProcessorFunc) error {
if c.State == StateListening {
return errors.New("consumer is already listening")
}
c.processor = f
err := c.connect(options)
if err != nil {
return err
}
defer c.close()
return c.consume()
}
func (c *Consumer) Stop() {
c.mu.Lock()
defer c.mu.Unlock()
if c.State == StateNotListening {
return
}
c.logger.Infof("Stopped listening for messages in %s", c.options.GetQueueName())
c.close()
if c.shutdown != nil {
close(c.shutdown)
}
c.shutdown = nil
c.State = StateNotListening
}
func (c *Consumer) connect(options *Options) error {
config := rabbit.Config{Properties: make(rabbit.Table)}
config.Properties["connection_name"] = options.ConnectionName
connection, err := rabbit.DialConfig(options.URL, config)
if err != nil {
return err
}
channel, err := connection.Channel()
if err != nil {
return err
}
err = channel.Qos(PrefetchCount, PrefetchSize, Global)
if err != nil {
return err
}
err = ConfigureExchanges(channel, options)
if err != nil {
return err
}
err = ConfigureQueues(channel, options)
if err != nil {
return err
}
c.connection = connection
c.channel = channel
c.options = options
return nil
}
func (c *Consumer) close() {
c.closeChannel()
c.closeConnection()
}
func (c *Consumer) closeChannel() {
if c.channel == nil {
return
}
if c.channel.IsClosed() {
return
}
err := c.channel.Close()
if err != nil {
c.logger.Errorf("failed to close channel %v", err)
}
}
func (c *Consumer) closeConnection() {
if c.connection == nil {
return
}
if c.connection.IsClosed() {
return
}
err := c.connection.Close()
if err != nil {
c.logger.Errorf("failed to close connection %s", err)
}
}
func (c *Consumer) consume() error {
deliveries, err := c.channel.Consume(
c.options.GetQueueName(),
ConsumerName,
AutoAck,
Exclusive,
NoLocal,
NoWait,
nil)
if err != nil {
return err
}
c.State = StateListening
c.shutdown = make(chan bool)
go c.handleDeliveries(deliveries)
go c.monitorConnection()
c.logger.Infof("started listening for messages in %s", c.options.GetQueueName())
<-c.shutdown
return nil
}
func (c *Consumer) monitorConnection() {
closeErr := <-c.connection.NotifyClose(make(chan *rabbit.Error))
c.Stop()
if closeErr != nil {
c.logger.Errorf("connection closed with error %v", closeErr)
retryErr := c.retryWithConstantWait("Retry RabbitMQ connection",
ReconnectionAttempts, ReconnectionDelayDuration, func() error {
return c.connect(c.options)
})
if retryErr == nil {
c.logger.Infof("Successfully reconnected to RabbitMQ")
go func() {
err := c.consume()
if err != nil {
c.logger.Errorf("failed to start consuming %v", err)
}
}()
return
}
log.Fatalf("Could not reconnect to RabbitMQ - shutting down")
}
}
func (c *Consumer) handleDeliveries(deliveries <-chan rabbit.Delivery) {
for delivery := range deliveries {
err := c.processor(NewDelivery(&delivery))
c.handleProcessingResult(&delivery, err)
}
}
func (c *Consumer) handleProcessingResult(delivery *rabbit.Delivery, err error) {
// If there were no errors while processing => send Ack
if err == nil {
c.ackOnSuccessfulSend(delivery)
return
}
// Otherwhise, handle the error
c.logger.Errorf("failed to process message, err: %s", err.Error())
if err := c.handleError(delivery, err); err != nil {
c.nackOnFailureToSend(delivery)
} else {
c.ackOnSuccessfulSend(delivery)
}
}
func (c *Consumer) handleError(delivery *rabbit.Delivery, err error) error {
value, keyExists := delivery.Headers["retry_count"]
retryCount, keyIsInteger := value.(int32)
if !keyExists || !keyIsInteger {
return c.sendToDelayQueue(1, delivery.Body)
}
if retryCount < c.options.GetRetryLimit() {
return c.sendToDelayQueue(retryCount+1, delivery.Body)
}
return c.sendToDeadQueue(delivery)
}
func (c *Consumer) ackOnSuccessfulSend(delivery *rabbit.Delivery) {
ackErr := delivery.Ack(false)
if ackErr != nil {
c.logger.Errorf("failed to Ack %v on handleError", delivery.Body)
}
}
func (c *Consumer) nackOnFailureToSend(delivery *rabbit.Delivery) {
//Nack(false, true) because otherwise the message would just be dropped.
//the second parameter is requeue.
nackErr := delivery.Nack(false, true)
if nackErr != nil {
c.logger.Errorf("failed to Nack %v on handleError", delivery.Body)
}
}
func (c *Consumer) sendToDelayQueue(retryCount int32, body []byte) error {
queueName := c.options.GetDelayQueueName()
c.logger.Infof("sending message to retry queue %s with retry count of %d", queueName, retryCount)
return c.channel.Publish(
"", // exchange
queueName,
false, // mandatory
false, // immediate
rabbit.Publishing{
ContentType: "text/plain",
Body: body,
Headers: rabbit.Table(map[string]interface{}{
"retry_count": retryCount,
}),
})
}
func (c *Consumer) sendToDeadQueue(delivery *rabbit.Delivery) error {
queueName := c.options.GetDeadQueueName()
c.logger.Infof("sending message to dead queue %s", queueName)
if c.options.OnDeadFunc != nil {
c.options.OnDeadFunc(NewDelivery(delivery))
}
return c.channel.Publish(
"", // exchange
queueName,
false, // mandatory
false, // immediate
rabbit.Publishing{
ContentType: "text/plain",
Body: delivery.Body,
})
}
func (c *Consumer) retryWithConstantWait(task string, maxAttempts int, wait time.Duration, f func() error) error {
for attempt := 1; ; attempt++ {
err := f()
if err == nil {
return nil
}
if attempt > maxAttempts {
return fmt.Errorf("[%s] failed after [%d] attempts - giving up: %v", task, attempt, err)
}
c.logger.Infof("[%s] attempt [%d] failed with [%v] - retrying in %s", task, attempt, err, wait)
time.Sleep(wait)
}
}