forked from asternic/wuzapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrabbitmq.go
More file actions
298 lines (257 loc) · 7.1 KB
/
rabbitmq.go
File metadata and controls
298 lines (257 loc) · 7.1 KB
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
package main
import (
"encoding/json"
"os"
"sync"
"time"
"github.com/rabbitmq/amqp091-go"
"github.com/rs/zerolog/log"
)
var (
rabbitConn *amqp091.Connection
rabbitChannel *amqp091.Channel
rabbitEnabled bool
rabbitOnce sync.Once
rabbitQueue string
)
const (
maxRetries = 10
retryInterval = 3 * time.Second
)
// Call this in main() or initialization
func InitRabbitMQ() {
rabbitURL := os.Getenv("RABBITMQ_URL")
rabbitQueue = os.Getenv("RABBITMQ_QUEUE")
if rabbitQueue == "" {
rabbitQueue = "whatsapp_events" // default queue
}
if rabbitURL == "" {
rabbitEnabled = false
log.Info().Msg("RABBITMQ_URL is not set. RabbitMQ publishing disabled.")
return
}
// Attempt to connect with retry
for attempt := 1; attempt <= maxRetries; attempt++ {
log.Info().
Int("attempt", attempt).
Int("max_retries", maxRetries).
Msg("Attempting to connect to RabbitMQ")
conn, err := amqp091.Dial(rabbitURL)
if err != nil {
log.Warn().
Err(err).
Int("attempt", attempt).
Int("max_retries", maxRetries).
Msg("Failed to connect to RabbitMQ")
if attempt < maxRetries {
log.Info().
Dur("retry_in", retryInterval).
Msg("Retrying RabbitMQ connection")
time.Sleep(retryInterval)
continue
}
// Last attempt failed
rabbitEnabled = false
log.Error().
Err(err).
Msg("Could not connect to RabbitMQ after all retries. RabbitMQ disabled.")
return
}
// Connection successful, attempt to open channel
channel, err := conn.Channel()
if err != nil {
conn.Close()
log.Warn().
Err(err).
Int("attempt", attempt).
Msg("Failed to open RabbitMQ channel")
if attempt < maxRetries {
log.Info().
Dur("retry_in", retryInterval).
Msg("Retrying RabbitMQ connection")
time.Sleep(retryInterval)
continue
}
// Last attempt failed
rabbitEnabled = false
log.Error().
Err(err).
Msg("Could not open RabbitMQ channel after all retries. RabbitMQ disabled.")
return
}
// Success!
rabbitConn = conn
rabbitChannel = channel
rabbitEnabled = true
log.Info().
Str("queue", rabbitQueue).
Int("attempt", attempt).
Msg("RabbitMQ connection established successfully")
// Setup handler for automatic reconnection on errors
go handleConnectionErrors()
return
}
}
// Monitor connection errors and attempt reconnection
func handleConnectionErrors() {
notifyClose := rabbitConn.NotifyClose(make(chan *amqp091.Error))
for err := range notifyClose {
log.Error().
Err(err).
Msg("RabbitMQ connection closed unexpectedly. Attempting reconnection...")
rabbitEnabled = false
// Attempt to reconnect
for attempt := 1; attempt <= maxRetries; attempt++ {
log.Info().
Int("attempt", attempt).
Msg("Reconnecting to RabbitMQ")
time.Sleep(retryInterval)
rabbitURL := os.Getenv("RABBITMQ_URL")
conn, err := amqp091.Dial(rabbitURL)
if err != nil {
log.Warn().
Err(err).
Int("attempt", attempt).
Msg("Reconnection failed")
continue
}
channel, err := conn.Channel()
if err != nil {
conn.Close()
log.Warn().
Err(err).
Int("attempt", attempt).
Msg("Failed to open channel on reconnection")
continue
}
// Reconnection successful
rabbitConn = conn
rabbitChannel = channel
rabbitEnabled = true
log.Info().Msg("RabbitMQ reconnected successfully")
// Restart monitoring
go handleConnectionErrors()
return
}
log.Error().Msg("Failed to reconnect to RabbitMQ after all retries")
return
}
}
// Optionally, allow overriding the queue per message
func PublishToRabbit(data []byte, queueOverride ...string) error {
if !rabbitEnabled {
return nil
}
queueName := rabbitQueue
if len(queueOverride) > 0 && queueOverride[0] != "" {
queueName = queueOverride[0]
}
// Declare queue (idempotent)
_, err := rabbitChannel.QueueDeclare(
queueName,
true, // durable
false, // auto-delete
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
log.Error().Err(err).Str("queue", queueName).Msg("Could not declare RabbitMQ queue")
return err
}
err = rabbitChannel.Publish(
"", // exchange (default)
queueName, // routing key = queue
false, // mandatory
false, // immediate
amqp091.Publishing{
ContentType: "application/json",
Body: data,
DeliveryMode: amqp091.Persistent,
},
)
if err != nil {
log.Error().Err(err).Str("queue", queueName).Msg("Could not publish to RabbitMQ")
} else {
log.Debug().Str("queue", queueName).Msg("Published message to RabbitMQ")
}
return err
}
func sendToGlobalRabbit(jsonData []byte, token string, userID string, queueName ...string) {
if !rabbitEnabled {
// Check if RabbitMQ is configured but disabled due to connection issues
rabbitURL := os.Getenv("RABBITMQ_URL")
rabbitQueueEnv := os.Getenv("RABBITMQ_QUEUE")
if rabbitURL != "" || rabbitQueueEnv != "" {
urlSet := "no"
if rabbitURL != "" {
urlSet = "yes"
}
queueSet := "no"
if rabbitQueueEnv != "" {
queueSet = "yes"
}
log.Error().
Str("rabbitmq_url_set", urlSet).
Str("rabbitmq_queue_set", queueSet).
Msg("RabbitMQ is configured but disabled due to connection failure. Event not published to queue.")
} else {
log.Debug().Msg("RabbitMQ not configured. Event not published to queue.")
}
return
}
// Extract instance information
instance_name := ""
userinfo, found := userinfocache.Get(token)
if found {
instance_name = userinfo.(Values).Get("Name")
}
// Parse the original JSON into a map
var originalData map[string]interface{}
err := json.Unmarshal(jsonData, &originalData)
if err != nil {
log.Error().Err(err).Msg("Failed to unmarshal original JSON data for RabbitMQ")
return
}
// Add the new fields directly to the original data
originalData["userID"] = userID
originalData["instanceName"] = instance_name
// Marshal back to JSON
enhancedJSON, err := json.Marshal(originalData)
if err != nil {
log.Error().Err(err).Msg("Failed to marshal enhanced data for RabbitMQ")
return
}
err = PublishToRabbit(enhancedJSON, queueName...)
if err != nil {
log.Error().Err(err).Msg("Failed to publish to RabbitMQ")
}
}
func PublishFileErrorToQueue(payload WebhookFileErrorPayload) {
queueName := *webhookErrorQueueName
body, err := json.Marshal(payload)
if err != nil {
log.Error().Err(err).Msg("Failed to marshal file error payload for RabbitMQ")
return
}
err = PublishToRabbit(body, queueName)
if err != nil {
log.Error().Str("queue", queueName).Msg("Failed to publish file error payload to queue")
} else {
log.Info().Str("queue", queueName).Msg("File error payload successfully published to queue")
}
}
func PublishDataErrorToQueue(payload WebhookErrorPayload) {
queueName := *webhookErrorQueueName
body, err := json.Marshal(payload)
if err != nil {
log.Error().Err(err).Msg("Failed to marshal data error payload for RabbitMQ")
return
}
err = PublishToRabbit(body, queueName)
if err != nil {
log.Error().Str("queue", queueName).Msg("Failed to publish data error payload to queue")
} else {
log.Info().Str("queue", queueName).Msg("Data error payload successfully published to queue")
}
}