-
Notifications
You must be signed in to change notification settings - Fork 0
/
rabbitmq.go
366 lines (315 loc) · 7.35 KB
/
rabbitmq.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
package rabbitmq
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/Moranilt/http-utils/logger"
amqp "github.com/rabbitmq/amqp091-go"
)
type Credentials struct {
Host string `mapstructure:"host"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
}
func (r *Credentials) SourceString() string {
return fmt.Sprintf("amqp://%s:%s@%s/", r.Username, r.Password, r.Host)
}
const (
reconnectDelay = 5 * time.Second
reInitDelay = 2 * time.Second
resendDelay = 5 * time.Second
)
var (
errNotConnected = errors.New("not connected to a server")
errAlreadyClosed = errors.New("already closed: not connected to the server")
errShutdown = errors.New("client is shutting down")
)
var (
rabbitMQClient *Client
)
type ReadMsgCallback func(ctx context.Context, d RabbitDelivery) error
type RabbitMQClient interface {
Check(ctx context.Context) error
ReadMsgs(ctx context.Context, maxAmount int, wait time.Duration, callback ReadMsgCallback)
Push(ctx context.Context, data []byte) error
UnsafePush(ctx context.Context, data []byte) error
Consume() (<-chan amqp.Delivery, error)
Close() error
}
type Client struct {
logger logger.Logger
queueName string
connection *amqp.Connection
channel *amqp.Channel
done chan bool
notifyConnClose chan *amqp.Error
notifyChanClose chan *amqp.Error
notifyConfirm chan amqp.Confirmation
isReady bool
readyCh chan bool
mu sync.Mutex
}
func (c *Client) setIsReady(ready bool) {
c.mu.Lock()
c.isReady = ready
c.mu.Unlock()
go func(ch chan bool, ready bool) {
ch <- ready
}(c.readyCh, ready)
}
func (c *Client) getIsReady() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.isReady
}
func (c *Client) Check(ctx context.Context) error {
if c.connection.IsClosed() {
return errors.New("connection closed")
}
if c.channel.IsClosed() {
return errors.New("channel closed")
}
return nil
}
func Init(ctx context.Context, queueName string, log logger.Logger, creds *Credentials) RabbitMQClient {
client := Client{
logger: log,
queueName: queueName,
done: make(chan bool),
readyCh: make(chan bool, 1),
}
go client.handleReconnect(ctx, creds.SourceString())
rabbitMQClient = &client
return &client
}
func (client *Client) handleReconnect(ctx context.Context, addr string) {
for {
client.setIsReady(false)
client.logger.InfoContext(ctx, "Attempting to connect")
conn, err := client.connect(addr)
if err != nil {
client.logger.InfoContext(ctx, "Failed to connect. Retrying...")
select {
case <-client.done:
return
case <-time.After(reconnectDelay):
}
continue
}
if done := client.handleReInit(ctx, conn); done {
break
}
}
}
func (client *Client) connect(addr string) (*amqp.Connection, error) {
conn, err := amqp.Dial(addr)
if err != nil {
return nil, err
}
client.changeConnection(conn)
client.logger.Info("Connected!")
return conn, nil
}
func (client *Client) handleReInit(ctx context.Context, conn *amqp.Connection) bool {
for {
client.setIsReady(false)
err := client.init(conn)
if err != nil {
client.logger.InfoContext(ctx, "Failed to initialize channel. Retrying...")
select {
case <-ctx.Done():
return true
case <-client.done:
return true
case <-client.notifyConnClose:
client.logger.InfoContext(ctx, "Connection closed. Reconnecting...")
return false
case <-time.After(reInitDelay):
}
continue
}
select {
case <-ctx.Done():
return true
case <-client.done:
return true
case <-client.notifyConnClose:
client.logger.InfoContext(ctx, "Connection closed. Reconnecting...")
return false
case <-client.notifyChanClose:
client.logger.InfoContext(ctx, "Channel closed. Re-running init...")
}
}
}
func (client *Client) init(conn *amqp.Connection) error {
ch, err := conn.Channel()
if err != nil {
return err
}
err = ch.Confirm(false)
if err != nil {
return err
}
_, err = ch.QueueDeclare(
client.queueName,
true,
false,
false,
false,
nil,
)
if err != nil {
return err
}
client.changeChannel(ch)
client.setIsReady(true)
client.logger.Info("Setup!")
return nil
}
func (client *Client) ReadMsgs(ctx context.Context, maxAmount int, wait time.Duration, callback ReadMsgCallback) {
stopReceive := make(chan bool, 1)
for {
select {
case <-ctx.Done():
close(stopReceive)
return
case ready := <-client.readyCh:
if !ready {
if len(stopReceive) == 0 {
stopReceive <- true
} else {
<-stopReceive
}
client.logger.Info("Connection closed. Unable to receive messages. Waiting to reconnect...")
<-time.After(2 * time.Second)
continue
} else {
if len(stopReceive) != 0 {
<-stopReceive
}
go func(done <-chan bool) {
client.logger.Info("Run consumer...")
deliveries, err := client.Consume()
if err != nil {
client.logger.Infof("Could not start consuming: %s\n", err)
return
}
counter := 1
for {
select {
case <-done:
client.logger.Info("Consumer stopped...")
return
case d := <-deliveries:
if counter == maxAmount {
counter = 1
<-time.After(wait)
} else {
counter++
}
err := callback(ctx, NewDelivery(d))
if err != nil {
continue
}
}
}
}(stopReceive)
}
}
}
}
func (client *Client) changeConnection(connection *amqp.Connection) {
client.connection = connection
client.notifyConnClose = make(chan *amqp.Error, 1)
client.connection.NotifyClose(client.notifyConnClose)
}
func (client *Client) changeChannel(channel *amqp.Channel) {
client.channel = channel
client.notifyChanClose = make(chan *amqp.Error, 1)
client.notifyConfirm = make(chan amqp.Confirmation, 1)
client.channel.NotifyClose(client.notifyChanClose)
client.channel.NotifyPublish(client.notifyConfirm)
}
func (client *Client) Push(ctx context.Context, data []byte) error {
if !client.isReady {
return errors.New("failed to push: not connected")
}
for {
err := client.UnsafePush(ctx, data)
if err != nil {
client.logger.InfoContext(ctx, "Push failed. Retrying...")
select {
case <-client.done:
return errShutdown
case <-time.After(resendDelay):
}
continue
}
confirm := <-client.notifyConfirm
if confirm.Ack {
client.logger.Infof("Push confirmed [%d]!", confirm.DeliveryTag)
return nil
}
}
}
func (client *Client) UnsafePush(ctx context.Context, data []byte) error {
if !client.isReady {
return errNotConnected
}
msg := amqp.Publishing{
ContentType: "application/json",
Body: data,
}
return client.channel.PublishWithContext(
ctx,
"",
client.queueName,
false,
false,
msg,
)
}
func (client *Client) Consume() (<-chan amqp.Delivery, error) {
loopReady:
for !client.isReady {
<-time.After(resendDelay)
continue loopReady
}
if err := client.channel.Qos(
2,
0,
false,
); err != nil {
return nil, err
}
return client.channel.Consume(
client.queueName,
"",
false,
false,
false,
false,
nil,
)
}
func (client *Client) Close() error {
if !client.getIsReady() {
return errAlreadyClosed
}
close(client.done)
err := client.channel.Close()
if err != nil {
return err
}
err = client.connection.Close()
if err != nil {
return err
}
for len(client.readyCh) > 0 {
<-client.readyCh
}
close(client.readyCh)
return nil
}