-
Notifications
You must be signed in to change notification settings - Fork 166
/
middleware_retry.go
92 lines (72 loc) · 1.84 KB
/
middleware_retry.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
package workers
import (
"fmt"
"math"
"math/rand"
"time"
)
const (
DEFAULT_MAX_RETRY = 25
LAYOUT = "2006-01-02 15:04:05 MST"
)
type MiddlewareRetry struct{}
func (r *MiddlewareRetry) Call(queue string, message *Msg, next func() bool) (acknowledge bool) {
defer func() {
if e := recover(); e != nil {
conn := Config.Pool.Get()
defer conn.Close()
if retry(message) {
message.Set("queue", queue)
message.Set("error_message", fmt.Sprintf("%v", e))
retryCount := incrementRetry(message)
waitDuration := durationToSecondsWithNanoPrecision(
time.Duration(
secondsToDelay(retryCount),
) * time.Second,
)
_, err := conn.Do(
"zadd",
Config.Namespace+RETRY_KEY,
nowToSecondsWithNanoPrecision()+waitDuration,
message.ToJson(),
)
// If we can't add the job to the retry queue,
// then we shouldn't acknowledge the job, otherwise
// it'll disappear into the void.
if err != nil {
acknowledge = false
}
}
panic(e)
}
}()
acknowledge = next()
return
}
func retry(message *Msg) bool {
retry := false
max := DEFAULT_MAX_RETRY
if param, err := message.Get("retry").Bool(); err == nil {
retry = param
} else if param, err := message.Get("retry").Int(); err == nil {
max = param
retry = true
}
count, _ := message.Get("retry_count").Int()
return retry && count < max
}
func incrementRetry(message *Msg) (retryCount int) {
retryCount = 0
if count, err := message.Get("retry_count").Int(); err != nil {
message.Set("failed_at", time.Now().UTC().Format(LAYOUT))
} else {
message.Set("retried_at", time.Now().UTC().Format(LAYOUT))
retryCount = count + 1
}
message.Set("retry_count", retryCount)
return
}
func secondsToDelay(count int) int {
power := math.Pow(float64(count), 4)
return int(power) + 15 + (rand.Intn(30) * (count + 1))
}