forked from trustwallet/go-libs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mq.go
executable file
·266 lines (212 loc) · 5.27 KB
/
mq.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
package mq
import (
"context"
"errors"
"fmt"
"sync"
"time"
log "github.com/sirupsen/logrus"
"github.com/streadway/amqp"
)
type (
QueueName string
ExchangeName string
ExchangeKey string
Message []byte
)
const (
reconnectionAttemptsNum = 5
reconnectionTimeout = time.Second * 30
)
type Client struct {
url string
conn *amqp.Connection
amqpChan *amqp.Channel
connClients []ConnectionClient
connCheckTimeout time.Duration
}
type Option func(c *Client) error
func Connect(url string, options ...Option) (*Client, error) {
conn, err := amqp.Dial(url)
if err != nil {
return nil, err
}
amqpChan, err := conn.Channel()
if err != nil {
return nil, err
}
c := &Client{
url: url,
conn: conn,
amqpChan: amqpChan,
connCheckTimeout: time.Second * 10, // default value
}
for _, opt := range options {
err = opt(c)
if err != nil {
return nil, err
}
}
return c, nil
}
func (c *Client) Close() error {
if c.conn != nil && !c.conn.IsClosed() {
err := c.conn.Close()
if err != nil {
return fmt.Errorf("close connection: %v", err)
}
}
return nil
}
func (c *Client) InitQueue(name QueueName) Queue {
return &queue{
name: name,
client: c,
}
}
func (c *Client) InitExchange(name ExchangeName) Exchange {
return &exchange{
name: name,
client: c,
}
}
func (c *Client) InitConsumer(queueName QueueName, options *ConsumerOptions, processor MessageProcessor) Consumer {
return &consumer{
client: c,
queue: c.InitQueue(queueName),
messageProcessor: processor,
options: options,
}
}
func (c *Client) StartConsumers(ctx context.Context, consumers ...Consumer) error {
for _, consumer := range consumers {
err := consumer.Start(ctx)
if err != nil {
return err
}
c.AddConnectionClient(consumer)
}
return nil
}
func (c *Client) AddConnectionClient(connClient ConnectionClient) {
c.connClients = append(c.connClients, connClient)
}
func (c *Client) ListenConnectionAsync(ctx context.Context, wg *sync.WaitGroup) {
wg.Add(1)
go func() {
err := c.ListenConnection(ctx)
if err != nil {
log.Fatal(err)
}
wg.Done()
}()
}
func (c *Client) initNotifyCloseListeners() (<-chan *amqp.Error, <-chan *amqp.Error) {
return c.conn.NotifyClose(make(chan *amqp.Error)),
c.amqpChan.NotifyClose(make(chan *amqp.Error))
}
func (c *Client) ListenConnection(ctx context.Context) error {
log.Info("start listen connection")
connErrCh, chanErrCh := c.initNotifyCloseListeners()
for {
select {
case <-ctx.Done():
err := c.Close()
if err != nil {
return fmt.Errorf("close mq: %v", err)
}
return nil
case err, ok := <-chanErrCh:
if !ok {
// stop receiving from this channel to avoid multiple reads from closed channel before reconnected
chanErrCh = nil
}
log.Info("received amqp channel close notification")
if err != nil {
log.Errorf("amqp channel closed with error: %v", err)
}
if c.conn.IsClosed() {
break
}
// close connection to trigger reconnect logic
// it will send notification to connErrCh
if err := c.conn.Close(); err != nil {
return fmt.Errorf("close connection: %v", err)
}
case err := <-connErrCh:
log.Info("received connection close notification")
if err != nil {
log.Errorf("connection closed with error: %v", err)
}
if err := c.reconnectWithRetry(ctx); err != nil {
return fmt.Errorf("check mq connection: %v", err)
}
// reassign listeners to new connection and channel
connErrCh, chanErrCh = c.initNotifyCloseListeners()
}
}
}
func (c *Client) reconnectWithRetry(ctx context.Context) error {
for i := 0; i < reconnectionAttemptsNum; i++ {
time.Sleep(reconnectionTimeout)
log.Info("Connecting to MQ... Attempt ", i+1)
err := c.reconnect()
if err != nil {
log.Errorf("Reconnect: %v", err)
continue
}
for _, connClient := range c.connClients {
err = connClient.Reconnect(ctx)
if err != nil {
log.Errorf("Reconnect for %+v: %v", connClient, err)
continue
}
}
log.Info("MQ connection established")
return nil
}
return fmt.Errorf("failed to establish MQ connection")
}
func (c *Client) reconnect() error {
conn, err := amqp.Dial(c.url)
if err != nil {
return err
}
amqpChan, err := conn.Channel()
if err != nil {
return err
}
c.conn = conn
c.amqpChan = amqpChan
return nil
}
func publish(amqpChan *amqp.Channel, exchange ExchangeName, key ExchangeKey, body []byte) error {
return publishWithConfig(amqpChan, exchange, key, body, PublishConfig{})
}
func publishWithConfig(amqpChan *amqp.Channel, exchange ExchangeName, key ExchangeKey, body []byte, cfg PublishConfig) error {
headers := map[string]interface{}{}
if cfg.MaxRetries != nil {
headers[headerRemainingRetries] = *cfg.MaxRetries
}
var deliveryMode uint8
if cfg.DeliveryMode == DeliveryModeTransient {
deliveryMode = amqp.Transient
} else {
deliveryMode = amqp.Persistent
}
return amqpChan.Publish(string(exchange), string(key), false, false, amqp.Publishing{
DeliveryMode: deliveryMode,
ContentType: "text/plain",
Body: body,
Headers: headers,
})
}
type ConnectionClient interface {
Reconnect(ctx context.Context) error
}
func (c *Client) HealthCheck() error {
if c.conn.IsClosed() {
return errors.New("connection is closed")
}
return nil
}