-
Notifications
You must be signed in to change notification settings - Fork 0
/
generics.go
288 lines (283 loc) · 9.39 KB
/
generics.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
/*
This file contains the generic functions for handling different providers
listener's and worker's task.
ProcessMail & ProcessLog are identical functions and can be further merged
into a single one but that would make managing the code more complex.
*/
package worker
import(
"rabbit"
"models"
"helpers"
"strings"
"strconv"
"fmt"
"time"
"doggo"
"encoding/json"
"github.com/streadway/amqp"
"github.com/gocql/gocql"
)
const MAX_RETRY_COUNT = 6
type GetEmailVars func(map[string]string, map[string]string) (string, error)
type SendRequest func(*string) (int, bool, error)
/*
Generic Function to dispatch email batches
@params:
packet : Rabbitmq packet
provider: Provider name i.e. sendgrid, mailgun
routingKey: Routing key intials i.e. "sglog.", "mglog.*"
channel: The channel to which it has to retry publishing
getEmailVarsFunc: A function which will return the body that has to be posted in request
sendRequestFunc: A send helper function which dispatches the request to the known client
*/
func ProcessMail(packet amqp.Delivery, currentChannel string, getEmailVarsFunc GetEmailVars, sendRequestFunc SendRequest){
// our batch_id is inside the routing key itself
var retryCount int = 0
var parts = strings.Split(packet.RoutingKey, ".")
batch_id := parts[1]
// This is a safe guard which helps us in preventing
// infinite to-and-fro calls to different queues of providers
if len(parts) == 4 && parts[2] == "retry" {
retryCount, _ = strconv.Atoi(parts[3])
}
fmt.Println("Recieved message, processing", batch_id)
id, err := gocql.ParseUUID(batch_id)
if err != nil {
// not a valid uuid
fmt.Println("Not a valid UUID")
packet.Ack(false)
return
}
batch := models.Batch{Batch_id: id}
success, err := batch.Exists()
if success {
if batch.Options["isBulk"] == "" {
batch.Options["isBulk"] = "false"
}
var customArgs = map[string]string{"batch_id": batch_id}
// ideally this should never, ever! fail
body, err := getEmailVarsFunc(batch.Options, customArgs)
// error Object that will be pushed in the DB in failure
errorObject := map[string]interface{}{
"status": "failed",
"last_updated": time.Now(),
"reason": "Bad Request",
"description": "Please check the input body that you have posted",
}
if err != nil {
_, err := batch.Update(errorObject)
if err != nil {
// DB failure 😔
// put back in queue for someone else to do it
packet.Nack(false, true)
return
}
packet.Ack(false)
return
}
status, requeue, err := sendRequestFunc(&body)
if requeue == true {
packet.Nack(false, true)
return
}
// check if SG server accepted our request or not
if status == 202 || status == 200 {
doggo.AddDoggoMetric(currentChannel + ".200")
_, err := batch.Update(map[string]interface{}{
"status": "queued",
"last_updated": time.Now(),
})
packet.Ack(false)
if err != nil {
// todo: Log error and push into a different queue to save it later
fmt.Println(err)
}
} else {
// Bad request, that means the format we sent the message in
// was wrong, we should ideally notify the user as well as log
// this thing
// mailgun when rate limits also throws 400 :(
if status == 400 {
doggo.AddDoggoMetric(currentChannel + ".400")
doggo.DoggoEvent(currentChannel + " failed", err , true)
_, err := batch.Update(errorObject)
if err != nil {
// DB failure 😔
// put in db_batch queue for someone else to do it
packet.Ack(false)
return
}
packet.Ack(false)
return
}
doggo.AddDoggoMetric(currentChannel + ".502")
// In other cases we can safely push them to another channel
worker, remaining := helpers.GetNextChannel(currentChannel, string(packet.Body))
routingKey := packet.RoutingKey
if worker == nil && helpers.CanRetry(MAX_RETRY_COUNT, retryCount, &routingKey) == false {
// we have exhausted all the providers, drop the packet
doggo.AddDoggoMetric(currentChannel + ".permanenetfail")
_, err := batch.Update(map[string]interface{}{
"status": "failed",
})
if err != nil {
// publish to db queue
}
packet.Ack(false)
return
}
// we can still try as MAX_RETRY_COUNT hasn't been exhausted
if worker == nil {
worker, remaining = helpers.GetNextChannel(currentChannel, remaining)
}
routingKey = worker.Namespace + batch_id + ".retry."
doggo.AddDoggoMetric(worker.Namespace + "retry")
if helpers.CanRetry(MAX_RETRY_COUNT, retryCount, &routingKey) {
// Publish it for requeue
worker.Channel.Publish(routingKey, []byte(remaining))
}
packet.Ack(false)
}
} else {
// batch doesn't exists, drop the packet, move on
packet.Ack(false)
}
}
/*
Generic Function to process logs published for retrial
@params:
packet : Rabbitmq packet
provider: Provider name i.e. sendgrid, mailgun
routingKey: Routing key intials i.e. "sglog.", "mglog.*"
channel: The channel to which it has to retry publishing
getEmailVarsFunc: A function which will return the body that has to be posted in request
sendRequestFunc: A send helper function which dispatches the request to the known client
*/
func ProcessLog(packet amqp.Delivery, provider string, getEmailVarsFunc GetEmailVars, sendRequestFunc SendRequest){
Log, Batch, log_id, batch_id, retryCount, nack, ack, err := helpers.LogListener(packet)
// packet data not valid
if err != nil {
// negative acknowledge
if nack && ack {
packet.Nack(false, true)
return
}
// drop the packet
if nack && !ack {
packet.Nack(false, false)
return
}
// acknowledge and drop
if ack {
packet.Ack(false)
}
return
}
// singular email entity
var options = map[string]string{
"to": Log.Email,
"from": Batch.Options["from"],
"name": Batch.Options["name"],
"subject": Batch.Options["subject"],
"content": Batch.Options["content"],
}
var customArgs = map[string]string{"batch_id": batch_id.String(), "log_id": Log.Log_id.String()}
body, err := getEmailVarsFunc(options, customArgs)
// This should never ever fails, but the state will become undefined here after
// so mark this as failed
if err != nil {
_, err := Log.Update(map[string]interface{}{
"last_update": time.Now(),
"status": "failed",
})
if err != nil {
// DB failure 😔
// put back in queue for someone else to do it
packet.Nack(false, true)
return
}
packet.Ack(false)
return
}
statusCode, requeue, err := sendRequestFunc(&body)
// RequestClient failed, reque for someone else
if requeue == true {
packet.Nack(false, true)
return
}
var status = Log.Status
status[provider] = true
// update object
var updateMap = map[string]interface{}{
"state": "dispatched",
"status": status,
"last_update": time.Now(),
}
// success! Save the new status
if statusCode == 202 || statusCode == 200 {
doggo.AddDoggoMetric(provider + ".200")
packet.Ack(false)
// mark sendgrid as used provider
_, err := Log.Update(updateMap)
if err != nil {
// failed db update, put in db_log queue
data, _ := json.Marshal(updateMap)
rabbit.LogDB.Publish("logdb.log." + log_id.String(), data)
}
return
} else {
// Bad JSON format, our fault, this can't be fixed on our end
// we would need human intervention in this case
// mark it as failed and exit
if statusCode == 400 {
doggo.AddDoggoMetric(provider + ".400")
doggo.DoggoEvent(provider + " failed", err , true)
errorMap := map[string]interface{}{
"state": "failed",
"status": status,
"last_update": time.Now(),
}
_, err := Log.Update(errorMap)
if err != nil {
// DB failure 😔
// failed db update, put in db_log queue
data, _ := json.Marshal(updateMap)
rabbit.LogDB.Publish("logdb.log." + log_id.String(), data)
}
packet.Ack(false)
} else {
// Other errors are server errors of provider's server
// we can requeue the message with retry flag
// and retry for MAX_RETRY_COUNT
// In other cases we can safely push them to another channel
doggo.AddDoggoMetric(provider + ".502")
worker, remaining := helpers.GetNextChannel(provider, string(packet.Body))
routingKey := packet.RoutingKey
if worker == nil && helpers.CanRetry(MAX_RETRY_COUNT, retryCount, &routingKey) == false {
// we have exhausted all the providers, drop the packet
doggo.AddDoggoMetric(provider + ".permanenetfail")
_, err := Log.Update(map[string]interface{}{
"state": "failed",
})
if err != nil {
// publish to db queue
}
packet.Ack(false)
return
}
// we can still try as MAX_RETRY_COUNT hasn't been exhausted
if worker == nil {
worker, remaining = helpers.GetNextChannel(provider, remaining)
}
fmt.Println(remaining, worker)
routingKey = "log." + worker.Namespace + log_id.String() + ".retry."
doggo.AddDoggoMetric(worker.Namespace + "retry")
if helpers.CanRetry(MAX_RETRY_COUNT, retryCount, &routingKey) {
// Publish it for requeue
worker.Channel.Publish(routingKey, []byte(remaining))
}
packet.Ack(false)
}
}
}