-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
exp_backoff.go
92 lines (79 loc) · 2.35 KB
/
exp_backoff.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 retry
import (
"math"
"time"
)
// ExponentialBackoff defines a retry policy in which in we exponentially
// retry up to the provided maximum number of retries (MaxRetries).
type ExponentialBackoff struct {
retry int
MaxRetries int
TimeUnit time.Duration
}
// Done implements retry.Policy#Done() bool.
func (b ExponentialBackoff) Done() bool {
return b.retry == b.MaxRetries
}
// Duration implements retry.Policy#Duration() time.Duration.
func (b *ExponentialBackoff) Duration() time.Duration {
duration := time.Duration(pow(2, b.retry)) * b.TimeUnit
b.retry++
return duration
}
// Reset implements retry.Policy#Reset().
func (b *ExponentialBackoff) Reset() {
b.retry = 0
}
// Clone implements retry.Policy#Clone() retry.Policy.
func (b ExponentialBackoff) Clone() Policy {
return &ExponentialBackoff{
MaxRetries: b.MaxRetries,
TimeUnit: b.TimeUnit,
}
}
// TimingOutExponentialBackoff defines a retry policy in which we exponentially
// retry up to the provided maximum duration (Timeout).
type TimingOutExponentialBackoff struct {
retry int
totalTimeSoFar time.Duration
Timeout time.Duration
TimeUnit time.Duration
}
// NewTimingOutExponentialBackoff creates a new TimingOutExponentialBackoff
// with seconds as TimeUnit
func NewTimingOutExponentialBackoff(timeout time.Duration) TimingOutExponentialBackoff {
return TimingOutExponentialBackoff{
Timeout: timeout,
TimeUnit: time.Second,
}
}
// Done implements retry.Policy#Done() bool.
func (b TimingOutExponentialBackoff) Done() bool {
return b.totalTimeSoFar == b.Timeout
}
// Duration implements retry.Policy#Duration() time.Duration.
func (b *TimingOutExponentialBackoff) Duration() time.Duration {
duration := time.Duration(pow(2, b.retry)) * b.TimeUnit
b.retry++
// Cap duration so that the configured timeout is never exceeded:
if b.totalTimeSoFar+duration > b.Timeout {
duration = b.Timeout - b.totalTimeSoFar
}
b.totalTimeSoFar += duration
return duration
}
// Reset implements retry.Policy#Reset().
func (b *TimingOutExponentialBackoff) Reset() {
b.retry = 0
b.totalTimeSoFar = 0
}
// Clone implements retry.Policy#Clone() retry.Policy.
func (b TimingOutExponentialBackoff) Clone() Policy {
return &TimingOutExponentialBackoff{
Timeout: b.Timeout,
TimeUnit: b.TimeUnit,
}
}
func pow(x, y int) int32 {
return int32(math.Pow(float64(x), float64(y)))
}