-
Notifications
You must be signed in to change notification settings - Fork 0
/
amqp_queue.go
304 lines (263 loc) · 7.07 KB
/
amqp_queue.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
package main
import (
"context"
"fmt"
log "github.com/sirupsen/logrus"
"sync"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
// todo implement carrier delivery status queue in rabbitmq?
type MsgQueueType string
var MsgQueueItemType = struct {
SMS MsgQueueType
MMS MsgQueueType
}{
SMS: "sms",
MMS: "mms",
}
type MsgQueueItem struct {
To string `json:"to_number"`
From string `json:"from_number"`
ReceivedTimestamp time.Time `json:"received_timestamp"`
QueuedTimestamp time.Time `json:"queued_timestamp"`
Type MsgQueueType `json:"type"` // mms or sms
Files []MsgFile `json:"files"` // urls or encoded base64 strings
Message string `json:"message"`
SkipNumberCheck bool
LogID string `json:"log_id"`
Delivery *amqp.Delivery
}
// MsgFile represents an individual file extracted from the MIME multipart message.
type MsgFile struct {
Filename string `json:"filename,omitempty"`
ContentType string `json:"content_type,omitempty"`
Content []byte `json:"content,omitempty"`
Base64Data string `json:"base64_data,omitempty"`
}
// AMPQClient is the base struct for handling connection recovery, consumption, and publishing.
type AMPQClient struct {
m *sync.Mutex
queues []string
logger *log.Logger
connection *amqp.Connection
channel *amqp.Channel
done chan bool
notifyConnClose chan *amqp.Error
notifyChanClose chan *amqp.Error
notifyConfirm chan amqp.Confirmation
isReady bool
}
const (
reconnectDelay = 5 * time.Second
reInitDelay = 2 * time.Second
)
// Close will cleanly shut down the channel and connection.
func (client *AMPQClient) Close() error {
client.m.Lock()
// we read and write isReady in two locations, so we grab the lock and hold onto
// it until we are finished
defer client.m.Unlock()
if !client.isReady {
return fmt.Errorf("connection already closed")
}
close(client.done)
err := client.channel.Close()
if err != nil {
return err
}
err = client.connection.Close()
if err != nil {
return err
}
client.isReady = false
return nil
}
// NewMsgQueueClient creates a new AMPQClient instance and attempts to connect to the server.
func NewMsgQueueClient(addr string, queues []string) *AMPQClient {
logger := log.New()
logger.SetFormatter(&log.TextFormatter{FullTimestamp: true})
logger.SetLevel(log.InfoLevel)
client := AMPQClient{
m: &sync.Mutex{},
queues: queues,
logger: logger,
done: make(chan bool),
}
go client.handleReconnect(addr)
return &client
}
// handleReconnect handles reconnection logic
func (client *AMPQClient) handleReconnect(addr string) {
for {
client.m.Lock()
client.isReady = false
client.m.Unlock()
client.logger.Println("Attempting to connect")
conn, err := client.connect(addr)
if err != nil {
client.logger.Println("Failed to connect. Retrying...")
select {
case <-client.done:
return
case <-time.After(reconnectDelay):
}
continue
}
if done := client.handleReInit(conn); done {
break
}
}
}
// connect creates a new AMQP connection
func (client *AMPQClient) connect(addr string) (*amqp.Connection, error) {
conn, err := amqp.Dial(addr)
if err != nil {
return nil, err
}
client.changeConnection(conn)
client.logger.Println("Connected!")
return conn, nil
}
// handleReInit handles channel re-initialization
func (client *AMPQClient) handleReInit(conn *amqp.Connection) bool {
for {
client.m.Lock()
client.isReady = false
client.m.Unlock()
err := client.init(conn)
if err != nil {
client.logger.Println("Failed to initialize channel. Retrying...")
select {
case <-client.done:
return true
case <-client.notifyConnClose:
client.logger.Println("Connection closed. Reconnecting...")
return false
case <-time.After(reInitDelay):
}
continue
}
select {
case <-client.done:
return true
case <-client.notifyConnClose:
client.logger.Println("Connection closed. Reconnecting...")
return false
case <-client.notifyChanClose:
client.logger.Println("Channel closed. Re-initializing...")
}
}
}
// init initializes channel and declares all queues
func (client *AMPQClient) init(conn *amqp.Connection) error {
ch, err := conn.Channel()
if err != nil {
return err
}
err = ch.Confirm(false)
if err != nil {
return err
}
for _, queue := range client.queues {
_, err := ch.QueueDeclare(
queue,
true, // Durable
false, // Delete when unused
false, // Exclusive
false, // No-wait
nil, // Arguments
)
if err != nil {
return fmt.Errorf("failed to declare queue '%s': %w", queue, err)
}
client.logger.Printf("Declared queue: %s", queue)
}
client.changeChannel(ch)
client.m.Lock()
client.isReady = true
client.m.Unlock()
client.logger.Println("Channel setup complete!")
return nil
}
func (client *AMPQClient) changeConnection(conn *amqp.Connection) {
client.connection = conn
client.notifyConnClose = make(chan *amqp.Error, 1)
client.connection.NotifyClose(client.notifyConnClose)
}
func (client *AMPQClient) changeChannel(ch *amqp.Channel) {
client.channel = ch
client.notifyChanClose = make(chan *amqp.Error, 1)
client.notifyConfirm = make(chan amqp.Confirmation, 1)
client.channel.NotifyClose(client.notifyChanClose)
client.channel.NotifyPublish(client.notifyConfirm)
}
// Publish sends a message to the specified queue
func (client *AMPQClient) Publish(queueName string, data []byte) error {
for {
client.m.Lock()
if !client.isReady || client.channel == nil {
client.m.Unlock()
time.Sleep(2 * time.Second)
continue
}
client.m.Unlock()
err := client.UnsafePublish(queueName, data)
if err != nil {
time.Sleep(5 * time.Second)
continue
}
confirm := <-client.notifyConfirm
if confirm.Ack {
client.logger.Printf("Message published to %s", queueName)
return nil
}
}
}
// UnsafePublish publishes a message without confirmation
func (client *AMPQClient) UnsafePublish(queueName string, data []byte) error {
client.m.Lock()
defer client.m.Unlock()
if client.isReady && client.channel == nil || client.channel == nil {
return fmt.Errorf("not connected")
}
if !client.isReady {
return fmt.Errorf("not ready")
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
return client.channel.PublishWithContext(
ctx,
"", // Exchange
queueName, // Router key
false,
false,
amqp.Publishing{
ContentType: "application/json",
Body: data,
},
)
}
// ConsumeMessages starts consuming messages from a specified queue
func (client *AMPQClient) ConsumeMessages(queueName string) (<-chan amqp.Delivery, error) {
client.m.Lock()
defer client.m.Unlock()
if client.isReady && client.channel == nil || client.channel == nil {
return nil, fmt.Errorf("not connected")
}
if !client.isReady {
return nil, fmt.Errorf("not ready")
}
if err := client.channel.Qos(1, 0, false); err != nil {
return nil, fmt.Errorf("failed to set QoS: %w", err)
}
return client.channel.Consume(
queueName,
"",
false,
false,
false,
false,
nil,
)
}