-
Notifications
You must be signed in to change notification settings - Fork 0
/
RedisRepository.go
417 lines (351 loc) · 11.2 KB
/
RedisRepository.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package recipientsRepository
import (
"fmt"
"github.com/garyburd/redigo/redis"
"strconv"
"encoding/json"
"os"
"bufio"
)
type RedisRepository struct {
Pool *redis.Pool
}
func (this *RedisRepository) GetRandomOpenJob() (jobId string, err error) {
connection := this.Pool.Get()
defer connection.Close()
response, err := connection.Do("SRANDMEMBER", getOpenJobsKey())
jobId = this.responseToString(response)
return
}
func (this *RedisRepository) CreateJob(jobId string, htmlTemplate string) error {
connection := this.Pool.Get()
defer connection.Close()
luaScript := `
local jobsKey = KEYS[1];
local jobStatusKey = KEYS[2];
local jobStateHtmlTemplateKey = KEYS[3];
local jobId = ARGV[1];
local htmlTemplate = ARGV[2];
local jobExists = redis.call('EXISTS', jobStatusKey);
if jobExists == 1 then
error('job already exists');
else
redis.call('SADD', jobsKey, jobId);
redis.call('SET', jobStatusKey, 'preparing');
redis.call('SET', jobStateHtmlTemplateKey, htmlTemplate);
end
`
_, err := connection.Do("EVAL", luaScript, 3,
getJobsKey(),
getJobStatusKey(jobId),
getJobTemplateKey(jobId),
jobId,
htmlTemplate,
)
return err
}
func (this *RedisRepository) AbortAndRemoveJob(jobId string) error {
connection := this.Pool.Get()
defer connection.Close()
luaScript := `
local jobsKey = KEYS[1];
local openJobsKey = KEYS[2];
local jobId = ARGV[1];
redis.call('SREM', openJobsKey, jobId);
redis.call('SREM', jobsKey, jobId);
for i = 3, #KEYS do
redis.call('DEL', KEYS[i]);
end
`
_, err := connection.Do("EVAL", luaScript, 12,
getJobsKey(),
getOpenJobsKey(),
getRecipientsRemainingKey(jobId),
getRecipientsSendingKey(jobId),
getRecipientsFailedKey(jobId),
getJobStatusKey(jobId),
getJobTemplateKey(jobId),
getJobStatusMessageKey(jobId),
getJobNumberOfSentMailsKey(jobId),
getJobNumberOfSendingFailuresKey(jobId),
getJobNumberOfRecipientsKey(jobId),
getJobStateKey(jobId),
jobId,
)
return err
}
func (this *RedisRepository) GetJobStatus(jobIds []string) (status JobStatus, err error) {
connection := this.Pool.Get()
defer connection.Close()
status = JobStatus{
Jobs: map[string]IndividualJobStatus{},
Summary: IndividualJobStatus{
Status: "summary",
},
}
err = nil
// get status for individual jobs
for _, jobId := range jobIds {
_, exists := status.Jobs[jobId]
if exists { continue }
jobStatus := IndividualJobStatus{}
var response interface{}
response, err = connection.Do("GET", getJobStatusKey(jobId))
jobStatus.Status = this.responseToString(response)
if err != nil { return }
response, err = connection.Do("GET", getJobStatusMessageKey(jobId))
jobStatus.Message = this.responseToString(response)
if err != nil { return }
response, err = connection.Do("GET", getJobNumberOfRecipientsKey(jobId))
if err != nil { return }
jobStatus.NumberOfRecipients, err = this.responseToInt(response)
if err != nil { return }
response, err = connection.Do("GET", getJobNumberOfSentMailsKey(jobId))
if err != nil { return }
jobStatus.NumberOfSentMails, err = this.responseToInt(response)
if err != nil { return }
response, err = connection.Do("GET", getJobNumberOfSendingFailuresKey(jobId))
if err != nil { return }
jobStatus.NumberOfSendingFailures, err = this.responseToInt(response)
if err != nil { return }
response, err = connection.Do("SCARD", getRecipientsSendingKey(jobId))
if err != nil { return }
jobStatus.NumberOfCurrentlySendingMails = response.(int64)
if err != nil { return }
status.Jobs[jobId] = jobStatus
}
// sum up
for _, jobStatus := range status.Jobs {
status.Summary.NumberOfRecipients += jobStatus.NumberOfRecipients
status.Summary.NumberOfSentMails += jobStatus.NumberOfSentMails
status.Summary.NumberOfSendingFailures += jobStatus.NumberOfSendingFailures
status.Summary.NumberOfCurrentlySendingMails += jobStatus.NumberOfCurrentlySendingMails
}
return
}
func (this *RedisRepository) WriteSendingFailuresToFile(targetFile string, jobIds []string) (err error) {
file, err := os.Create(targetFile)
if err != nil { return }
defer file.Close()
writer := bufio.NewWriter(file)
defer writer.Flush()
for _, jobId := range jobIds {
err = this.appendSendingFailuresToFile(writer, jobId)
if err != nil { return }
}
return
}
func (this *RedisRepository) appendSendingFailuresToFile(targetFile *bufio.Writer, jobId string) (err error) {
size := 50000
lastResult := size
for offset := 0; lastResult == size; offset += size {
failures, err := this.getSendingFailures(jobId, offset, size)
if err != nil { return err }
lastResult = len(failures)
for _, failure := range failures {
targetFile.WriteString(fmt.Sprintf("%s %s\n", failure.Recipient, failure.Cause))
}
}
return
}
func (this *RedisRepository) getSendingFailures(jobId string, offset, size int) (failures []MailSendingFailure, err error) {
connection := this.Pool.Get()
defer connection.Close()
response, err := connection.Do("LRANGE", getRecipientsFailedKey(jobId), offset, offset + size - 1)
if err != nil { return }
failuresJson := this.responseToSlice(response)
failures = make([]MailSendingFailure, len(failuresJson))
for index, failureJson := range failuresJson {
var failure MailSendingFailure
err = json.Unmarshal(failureJson.([]byte), &failure)
if err != nil { return }
failures[index] = failure
}
return
}
func (this *RedisRepository) FinishPreparation(jobId string, numberOfRecipients int) error {
connection := this.Pool.Get()
defer connection.Close()
luaScript := `
local openJobsKey = KEYS[1];
local jobStatusKey = KEYS[2];
local numberOfRecipientsKey = KEYS[3];
local jobId = ARGV[1];
local totalCount = ARGV[2];
if totalCount == '0' then
redis.call('SET', jobStatusKey, 'done');
else
redis.call('SET', jobStatusKey, 'prepared');
redis.call('SADD', openJobsKey, jobId);
end
redis.call('SET', numberOfRecipientsKey, totalCount);
`
_, err := connection.Do("EVAL", luaScript, 3,
getOpenJobsKey(),
getJobStatusKey(jobId),
getJobNumberOfRecipientsKey(jobId),
jobId,
numberOfRecipients,
)
return err
}
func (this *RedisRepository) MarkJobAsFailed(jobId, reason string) error {
connection := this.Pool.Get()
defer connection.Close()
luaScript := `
local openJobsKey = KEYS[1];
local jobStatusKey = KEYS[2];
local jobStatusMessageKey = KEYS[3];
local jobId = ARGV[1];
local jobStatusMessage = ARGV[2];
redis.call('SET', jobStatusKey, 'failed');
redis.call('SET', jobStatusMessageKey, jobStatusMessage);
redis.call('SREM', openJobsKey, jobId);
`
_, err := connection.Do("EVAL", luaScript, 3,
getOpenJobsKey(),
getJobStatusKey(jobId),
getJobStatusMessageKey(jobId),
jobId,
reason,
)
return err
}
func (this *RedisRepository) AddRecipient(jobId, recipient string) error {
connection := this.Pool.Get()
defer connection.Close()
_, err := connection.Do("RPUSH", getRecipientsRemainingKey(jobId), recipient)
return err
}
func (this *RedisRepository) GetNextOpenRecipient(jobId string) (recipient string, err error) {
connection := this.Pool.Get()
defer connection.Close()
luaScript := `
local remainingKey = KEYS[1];
local sendingKey = KEYS[2];
local leaseKeyPrefix = KEYS[3];
local recipient = redis.call('LPOP', remainingKey);
if recipient then
redis.call('SADD', sendingKey, recipient);
redis.call('SETEX', leaseKeyPrefix .. recipient, 30, 1);
return recipient
else
-- try to re-use a recipient if its lease is expired
local sending = redis.call('SMEMBERS', sendingKey);
for index, recipient in pairs(sending) do
local lease = redis.call('GET', leaseKeyPrefix .. recipient);
if not lease then
redis.call('SETEX', leaseKeyPrefix .. recipient, 30, 1);
return recipient;
end
end
end
return nil;
`
response, err := connection.Do("EVAL", luaScript, 3,
getRecipientsRemainingKey(jobId),
getRecipientsSendingKey(jobId),
getRecipientsLeaseKeyPrefix(jobId),
)
recipient = this.responseToString(response)
return
}
func (this *RedisRepository) ExtendLease(jobId, recipient string) error {
connection := this.Pool.Get()
defer connection.Close()
_, err := connection.Do("SETEX", getRecipientLeaseKey(jobId, recipient), 30, 1)
return err
}
func (this *RedisRepository) MarkRecipientAsDone(jobId, recipient string) error {
return this.markRecipientAsProcessed(jobId, recipient, "")
}
func (this *RedisRepository) MarkRecipientAsFailed(jobId, recipient, recipientId string, cause error) error {
sendingFailure := MailSendingFailure{
Recipient: recipientId,
Cause: cause.Error(),
}
sendingFailureJson, err := json.Marshal(sendingFailure)
if err != nil { return err }
return this.markRecipientAsProcessed(jobId, recipient, string(sendingFailureJson))
}
func (this *RedisRepository) markRecipientAsProcessed(jobId, recipient, sendingFailureJson string) error {
connection := this.Pool.Get()
defer connection.Close()
luaScript := `
local openJobsKey = KEYS[1];
local jobStatusKey = KEYS[2];
local sendingKey = KEYS[3];
local leaseKey = KEYS[4];
local numberOfSentKey = KEYS[5];
local numberOfRecipientsKey = KEYS[6];
local numberOfFailedKey = KEYS[7];
local sendingFailuresKey = KEYS[8];
local jobId = ARGV[1];
local recipient = ARGV[2];
local sendingFailure = ARGV[3];
redis.call('SREM', sendingKey, recipient);
redis.call('DEL', leaseKey);
local sentDelta = 1;
local failedDelta = 0;
if sendingFailure ~= '' then
sentDelta = 0;
failedDelta = 1;
redis.call('RPUSH', sendingFailuresKey, sendingFailure)
end
local sentCount = redis.call('INCRBY', numberOfSentKey, sentDelta);
local failedCount = redis.call('INCRBY', numberOfFailedKey, failedDelta);
-- we have to get this value as an integer for comparison
local totalCount = redis.call('INCRBY', numberOfRecipientsKey, 0);
if totalCount == sentCount + failedCount then
redis.call('SREM', openJobsKey, jobId);
redis.call('SET', jobStatusKey, 'done');
end
`
_, err := connection.Do("EVAL", luaScript, 8,
getOpenJobsKey(),
getJobStatusKey(jobId),
getRecipientsSendingKey(jobId),
getRecipientLeaseKey(jobId, recipient),
getJobNumberOfSentMailsKey(jobId),
getJobNumberOfRecipientsKey(jobId),
getJobNumberOfSendingFailuresKey(jobId),
getRecipientsFailedKey(jobId),
jobId,
recipient,
sendingFailureJson,
)
return err
}
func (this *RedisRepository) GetTemplates(jobId string) (templates Templates, err error) {
connection := this.Pool.Get()
defer connection.Close()
response, err := connection.Do("GET", getJobTemplateKey(jobId))
if err != nil { return }
templatesJson := fmt.Sprintf("%s", response)
var templatesString TemplatesString
err = json.Unmarshal([]byte(templatesJson), &templatesString)
if err != nil { return }
templates, err = templatesString.Parse()
return
}
func (this *RedisRepository) responseToInt(response interface{}) (value int, err error) {
if response == nil {
return 0, nil
} else {
return strconv.Atoi(this.responseToString(response))
}
}
func (this *RedisRepository) responseToString(response interface{}) string {
if response == nil {
return ""
} else {
return string(response.([]byte))
}
}
func (this *RedisRepository) responseToSlice(response interface{}) (result []interface{}) {
if response == nil {
return []interface{}{}
} else {
return response.([]interface{})
}
}