forked from imroc/req
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathretry.go
More file actions
68 lines (59 loc) · 2.08 KB
/
Copy pathretry.go
File metadata and controls
68 lines (59 loc) · 2.08 KB
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
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,
}
}
// RetryOption controls the retry behavior of a request.
// It is typically configured via Client.SetCommonRetry* or Request.SetRetry*
// methods and can be read from middleware with Request.GetRetryOption.
//
// MaxRetries is the maximum number of retries (not including the initial
// attempt). A negative value means retry infinitely. Zero means no retries.
// GetRetryOption may still return a non-nil option if only non-count setters
// (interval, condition, or hook) were used while leaving MaxRetries at zero.
type RetryOption struct {
MaxRetries int
GetRetryInterval GetRetryIntervalFunc
RetryConditions []RetryConditionFunc
RetryHooks []RetryHookFunc
}
// Clone returns a deep copy of RetryOption.
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
}