forked from asmcos/requests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
retry.go
178 lines (147 loc) · 3.87 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
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
// Copyright (c) 2015-2021 Jeevanandam M ([email protected]), All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package requests
import (
"context"
"math"
"math/rand"
"sync"
"time"
)
const (
defaultMaxRetries = 3
defaultWaitTime = time.Duration(100) * time.Millisecond
defaultMaxWaitTime = time.Duration(2000) * time.Millisecond
)
type (
// Option is to create convenient retry options like wait time, max retries, etc.
Option func(*Options)
// RetryConditionFunc type is for retry condition function
// input: non-nil Response OR request execution error
RetryConditionFunc func(*Response, error) bool
// OnRetryFunc is for side-effecting functions triggered on retry
OnRetryFunc func(*Response, error)
// Options struct is used to hold retry settings.
Options struct {
maxRetries int
waitTime time.Duration
maxWaitTime time.Duration
retryConditions []RetryConditionFunc
}
)
// Retries sets the max number of retries
func Retries(value int) Option {
return func(o *Options) {
o.maxRetries = value
}
}
// WaitTime sets the default wait time to sleep between requests
func WaitTime(value time.Duration) Option {
return func(o *Options) {
if value>0{
o.waitTime = value
}
}
}
// MaxWaitTime sets the max wait time to sleep between requests
func MaxWaitTime(value time.Duration) Option {
return func(o *Options) {
o.maxWaitTime = value
}
}
// RetryConditions sets the conditions that will be checked for retry.
func RetryConditions(conditions []RetryConditionFunc) Option {
return func(o *Options) {
o.retryConditions = conditions
}
}
// Backoff retries with increasing timeout duration up until X amount of retries
// (Default is 3 attempts, Override with option Retries(n))
func Backoff(operation func() (*Response, error), options ...Option) error {
// Defaults
opts := Options{
maxRetries: defaultMaxRetries,
waitTime: defaultWaitTime,
maxWaitTime: defaultMaxWaitTime,
retryConditions: []RetryConditionFunc{},
}
for _, o := range options {
o(&opts)
}
var (
resp *Response
err error
)
for attempt := 0; attempt <= opts.maxRetries; attempt++ {
resp, err = operation()
ctx := context.Background()
if resp != nil && resp.httpreq.Context() != nil {
ctx = resp.httpreq.Context()
}
if ctx.Err() != nil {
return err
}
needsRetry := err != nil
for _, condition := range opts.retryConditions {
needsRetry = condition(resp, err)
if needsRetry {
break
}
}
if !needsRetry {
return err
}
// Don't need to wait when no retries left.
if attempt == opts.maxRetries {
return err
}
waitTime, err2 := sleepDuration(opts.waitTime, opts.maxWaitTime, attempt)
if err2 != nil {
if err == nil {
err = err2
}
return err
}
select {
case <-time.After(waitTime):
case <-ctx.Done():
return ctx.Err()
}
}
return err
}
func sleepDuration(min, max time.Duration, attempt int) (time.Duration, error) {
const maxInt = 1 << (31 - 1) // max int for arch 386
if max < 0 {
max = maxInt
}
return jitterBackoff(min, max, attempt), nil
}
// Return capped exponential backoff with jitter
// http://www.awsarchitectureblog.com/2015/03/backoff.html
func jitterBackoff(min, max time.Duration, attempt int) time.Duration {
base := float64(min)
capLevel := float64(max)
temp := math.Min(capLevel, base*math.Exp2(float64(attempt)))
ri := time.Duration(temp / 2)
result := randDuration(ri)
if result < min {
result = min
}
return result
}
var rnd = newRnd()
var rndMu sync.Mutex
func randDuration(center time.Duration) time.Duration {
rndMu.Lock()
defer rndMu.Unlock()
var ri = int64(center)
var jitter = rnd.Int63n(ri)
return time.Duration(math.Abs(float64(ri + jitter)))
}
func newRnd() *rand.Rand {
var seed = time.Now().UnixNano()
var src = rand.NewSource(seed)
return rand.New(src)
}