forked from avinassh/hedwig-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhedwig.go
378 lines (335 loc) · 8.73 KB
/
hedwig.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
package hedwig
import (
"errors"
"fmt"
"strconv"
"strings"
"sync"
"time"
amqp "github.com/rabbitmq/amqp091-go"
"github.com/sirupsen/logrus"
)
const (
PublishChannel = "publish"
SubscribeChannel = "subscribe"
)
const (
MinDeliveryLimit uint = 1
)
type Callback func(<-chan amqp.Delivery, *sync.WaitGroup)
type QueueType uint
const (
QueueType_Classic QueueType = 0
QueueType_Quorum QueueType = 1
)
func DefaultSettings() *Settings {
return &Settings{
Exchange: "hedwig",
ExchangeType: amqp.ExchangeTopic,
ExchangeArgs: nil,
HeartBeatInterval: 5 * time.Second,
SocketTimeout: 1 * time.Second,
Host: "localhost",
Port: 5672,
Consumer: &ConsumerSetting{
Queues: make(map[string]*QueueSetting)},
}
}
func DefaultQueueSetting(callback Callback, bindings ...string) *QueueSetting {
return &QueueSetting{
Bindings: bindings,
Durable: true,
Callback: callback,
QueueType: QueueType_Classic,
}
}
func New(settings *Settings) *Hedwig {
if settings == nil {
settings = DefaultSettings()
}
return &Hedwig{Settings: settings, wg: &sync.WaitGroup{}, channels: make(map[string]*amqp.Channel), consumeTags: make(map[string]bool)}
}
type QueueSetting struct {
Bindings []string
Callback Callback
Durable bool
AutoDelete bool
Exclusive bool
NoAck bool
QueueType QueueType
// DeliveryLimit specifies the maximum number of times a message can be redelivered.
// It is useful for preventing message poisoning by limiting how many times a message
// can be retried before it is considered "poisoned" and either dead-lettered or discarded.
// Note: This setting has no effect on Classic queues, which do not support delivery limits.
// Caution: Once set, the DeliveryLimit cannot be updated during the lifetime of the queue.
DeliveryLimit uint
}
type ConsumerSetting struct {
tag string
Queues map[string]*QueueSetting
}
type Settings struct {
Exchange string
ExchangeType string
ExchangeArgs amqp.Table
HeartBeatInterval time.Duration
SocketTimeout time.Duration
Host string
Port int
Vhost string
Username string
Password string
Consumer *ConsumerSetting
}
type Hedwig struct {
sync.Mutex
wg *sync.WaitGroup
Settings *Settings
Error error
conn *amqp.Connection
channels map[string]*amqp.Channel
consumeTags map[string]bool
closedChan chan *amqp.Error
customCloseChan chan *amqp.Error
}
func (h *Hedwig) AddQueue(qSetting *QueueSetting, qName string) error {
h.Lock()
defer h.Unlock()
if h == nil {
return ErrNilHedwig
}
if h.conn != nil {
return ErrAlreadyInitialized
}
if len(qSetting.Bindings) == 0 {
return ErrNoBindings
}
if h.Settings.Consumer == nil {
return ErrNoConsumerSetting
}
if qName == "" {
qName = fmt.Sprintf("AUTO-%d-%s", len(h.Settings.Consumer.Queues), strings.Join(qSetting.Bindings, "."))
qSetting.Durable = false
qSetting.Exclusive = true
}
h.Settings.Consumer.Queues[qName] = qSetting
return nil
}
func (h *Hedwig) Publish(key string, body []byte) (err error) {
return h.PublishWithHeaders(key, body, nil)
}
func (h *Hedwig) PublishWithDelay(key string, body []byte, delay time.Duration) (err error) {
// from: https://www.rabbitmq.com/blog/2015/04/16/scheduling-messages-with-rabbitmq/
// To delay a message a user must publish the message with the special header called x-delay which takes an integer
// representing the number of milliseconds the message should be delayed by RabbitMQ.
// It's worth noting that here delay means: delay message routing to queues or to other exchanges.
headers := amqp.Table{DelayHeader: delay.Milliseconds()}
return h.PublishWithHeaders(key, body, headers)
}
func (h *Hedwig) PublishWithHeaders(key string, body []byte, headers map[string]interface{}) (err error) {
h.Lock()
defer h.Unlock()
c, err := h.getChannel(PublishChannel)
if err != nil {
return err
}
if err := c.Publish(h.Settings.Exchange, key, false, false, amqp.Publishing{
Body: body,
Headers: headers,
}); err != nil {
// We already listen to closedChan [ref connect()] when connections are dropped.
// In most cases github.com/streadway/amqp reports it.
// We have observed some cases where this is not reported and we end with stale connections.
// Only way to resolve this to restart the service to reconnect.
// We manually check for error while publishing and if we get an error which says connection has been closed, we
// notify on customCloseChan so that hedwig reconnects to RMQ
if errors.Is(err, amqp.ErrClosed) {
logrus.WithError(err).Error("Publish failed, reconnecting")
h.customCloseChan <- amqp.ErrClosed
}
return err
}
return nil
}
func (h *Hedwig) Consume() error {
if h == nil {
return ErrNilHedwig
}
if h.Settings.Consumer == nil {
return ErrNoConsumerSetting
}
defer h.Disconnect()
err := h.setupListeners()
if err != nil {
return err
}
h.wg.Wait()
return h.Error
}
func (h *Hedwig) setupListeners() (err error) {
h.Lock()
defer h.Unlock()
c, err := h.getChannel(SubscribeChannel)
if err != nil {
return err
}
tag := 0
for qName, qSetting := range h.Settings.Consumer.Queues {
if len(qSetting.Bindings) == 0 {
return ErrNoBindings
}
if strings.HasPrefix(qName, "AUTO-") {
qName = ""
qSetting.Durable = false
qSetting.Exclusive = true
}
var queueArgs amqp.Table
if qSetting.QueueType == QueueType_Quorum {
queueArgs = amqp.Table{
"x-queue-type": "quorum",
}
deliveryLimit := MinDeliveryLimit
if qSetting.DeliveryLimit > deliveryLimit {
deliveryLimit = qSetting.DeliveryLimit
}
queueArgs["x-delivery-limit"] = int32(deliveryLimit)
}
q, err := c.QueueDeclare(qName, qSetting.Durable, qSetting.AutoDelete, qSetting.Exclusive, false, queueArgs)
if err != nil {
return err
}
for _, binding := range qSetting.Bindings {
err := c.QueueBind(q.Name, binding, h.Settings.Exchange, false, nil)
if err != nil {
return err
}
}
consumeTag := q.Name + "-" + strconv.Itoa(tag)
tag++
h.consumeTags[consumeTag] = true
delChan, err := c.Consume(
q.Name,
consumeTag,
qSetting.NoAck,
qSetting.Exclusive,
false,
false,
nil,
)
if err != nil {
return err
}
h.wg.Add(1)
go qSetting.Callback(delChan, h.wg)
}
return nil
}
func (h *Hedwig) getChannel(name string) (ch *amqp.Channel, err error) {
if v, ok := h.channels[name]; ok && h.channels[name] != nil {
return v, nil
}
err = h.connect()
if err != nil {
return nil, err
}
h.channels[name], err = h.conn.Channel()
if err != nil {
return nil, err
}
err = h.channels[name].ExchangeDeclare(
h.Settings.Exchange, h.Settings.ExchangeType, true,
false, false, false, h.Settings.ExchangeArgs)
if err != nil {
return nil, err
}
return h.channels[name], nil
}
func (h *Hedwig) Disconnect() error {
h.Lock()
defer h.Unlock()
if h == nil {
return ErrNilHedwig
}
if h.conn == nil {
return nil
}
// Close all listening channels
if len(h.consumeTags) > 0 {
c, err := h.getChannel(SubscribeChannel)
if err == nil {
for tag := range h.consumeTags {
go c.Cancel(tag, false)
}
}
h.wg.Wait()
h.consumeTags = make(map[string]bool)
}
err := h.conn.Close()
if err != nil && err != amqp.ErrClosed {
return err
}
return nil
}
func (h *Hedwig) connect() (err error) {
if h == nil {
return ErrNilHedwig
}
if h.conn != nil {
return
}
h.Error = nil
auth := []amqp.Authentication{
&amqp.PlainAuth{
Username: h.Settings.Username,
Password: h.Settings.Password,
},
}
h.conn, err = amqp.DialConfig(fmt.Sprintf("amqp://%s:%d", h.Settings.Host, h.Settings.Port), amqp.Config{
SASL: auth,
Vhost: h.Settings.Vhost,
Heartbeat: h.Settings.HeartBeatInterval,
Locale: "en_US",
})
if err != nil {
h.Error = err
return
}
h.closedChan = make(chan *amqp.Error)
h.customCloseChan = make(chan *amqp.Error)
h.conn.NotifyClose(h.closedChan)
go func() {
closeErr, ok := <-h.closedChan
if !ok {
logrus.Warning("closedChan is closed")
return
}
logrus.WithError(closeErr).Error("Recieved a connection closed event")
h.Lock()
defer h.Unlock()
h.conn = nil
h.channels = make(map[string]*amqp.Channel)
h.consumeTags = make(map[string]bool)
h.wg = &sync.WaitGroup{}
if h.Error == nil {
h.Error = closeErr
}
}()
go func() {
closeErr, ok := <-h.customCloseChan
if !ok {
logrus.Warning("customCloseChan is closed")
return
}
logrus.WithError(closeErr).Error("Recieved a connection closed event")
h.Lock()
defer h.Unlock()
h.conn = nil
h.channels = make(map[string]*amqp.Channel)
h.consumeTags = make(map[string]bool)
h.wg = &sync.WaitGroup{}
if h.Error == nil {
h.Error = closeErr
}
}()
return
}