-
Notifications
You must be signed in to change notification settings - Fork 55
/
retry.go
85 lines (70 loc) · 1.55 KB
/
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
package zutil
import (
"math/rand"
"time"
)
type RetryConf struct {
// maxRetry is the maximum number of retries
maxRetry int
// Interval is the interval between retries
Interval time.Duration
// MaxRetryInterval is the maximum interval between retries
MaxRetryInterval time.Duration
// Timeout is the timeout of the entire retry
Timeout time.Duration
// BackOffDelay is whether to increase the interval between retries
BackOffDelay bool
}
// DoRetry is a general retry function
func DoRetry(sum int, fn func() bool, opt ...func(*RetryConf)) (ok bool) {
o := RetryConf{
maxRetry: sum,
Interval: time.Second,
MaxRetryInterval: time.Minute,
}
for i := range opt {
opt[i](&o)
}
ok = fn()
if ok {
return
}
if o.maxRetry == 0 {
return false
}
i, now := 1, time.Now()
for ; ; i++ {
if o.maxRetry > 0 && i > o.maxRetry {
break
}
if o.Timeout > 0 && time.Since(now) > o.Timeout {
break
}
ok = fn()
if ok {
break
}
var interval time.Duration
if o.BackOffDelay {
interval = BackOffDelay(i, o.MaxRetryInterval)
} else {
interval = o.Interval
}
time.Sleep(interval)
}
return
}
func BackOffDelay(attempt int, maxRetryInterval time.Duration) time.Duration {
attempt = attempt - 1
if attempt < 0 {
return 0
}
retryFactor := 1 << uint(attempt)
jitter := rand.Float64()
waitDuration := time.Duration(retryFactor) * time.Second
waitDuration = waitDuration + time.Duration(jitter*float64(waitDuration))
if waitDuration > maxRetryInterval {
return maxRetryInterval
}
return waitDuration
}