-
Notifications
You must be signed in to change notification settings - Fork 349
/
retry.go
59 lines (50 loc) · 1.53 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
package req
import (
"math"
"math/rand"
"time"
)
func defaultGetRetryInterval(resp *Response, attempt int) time.Duration {
return 100 * time.Millisecond
}
// RetryConditionFunc is a retry condition, which determines
// whether the request should retry.
type RetryConditionFunc func(resp *Response, err error) bool
// RetryHookFunc is a retry hook which will be executed before a retry.
type RetryHookFunc func(resp *Response, err error)
// GetRetryIntervalFunc is a function that determines how long should
// sleep between retry attempts.
type GetRetryIntervalFunc func(resp *Response, attempt int) time.Duration
func backoffInterval(min, max time.Duration) GetRetryIntervalFunc {
base := float64(min)
capLevel := float64(max)
return func(resp *Response, attempt int) time.Duration {
temp := math.Min(capLevel, base*math.Exp2(float64(attempt)))
halfTemp := int64(temp / 2)
sleep := halfTemp + rand.Int63n(halfTemp)
return time.Duration(sleep)
}
}
func newDefaultRetryOption() *retryOption {
return &retryOption{
GetRetryInterval: defaultGetRetryInterval,
}
}
type retryOption struct {
MaxRetries int
GetRetryInterval GetRetryIntervalFunc
RetryConditions []RetryConditionFunc
RetryHooks []RetryHookFunc
}
func (ro *retryOption) Clone() *retryOption {
if ro == nil {
return nil
}
o := &retryOption{
MaxRetries: ro.MaxRetries,
GetRetryInterval: ro.GetRetryInterval,
}
o.RetryConditions = append(o.RetryConditions, ro.RetryConditions...)
o.RetryHooks = append(o.RetryHooks, ro.RetryHooks...)
return o
}