-
Notifications
You must be signed in to change notification settings - Fork 7
/
backoff.go
86 lines (69 loc) · 1.77 KB
/
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
package cast
import (
"math"
"math/rand"
"time"
)
type backoffStrategy interface {
backoff(retry int) time.Duration
}
type linearBackoffStrategy struct {
slope time.Duration
}
func (stg linearBackoffStrategy) backoff(retry int) time.Duration {
return time.Duration(retry) * stg.slope
}
type constantBackOffStrategy struct {
interval time.Duration
}
func (stg constantBackOffStrategy) backoff(retry int) time.Duration {
return stg.interval
}
type exponentialBackoff struct {
base time.Duration
cap time.Duration
}
func (backoff exponentialBackoff) expo(retry int) float64 {
c := float64(backoff.cap)
b := float64(backoff.base)
r := float64(retry)
return math.Min(c, math.Exp2(r)*b)
}
type exponentialBackoffStrategy struct {
exponentialBackoff
}
func (stg exponentialBackoffStrategy) backoff(retry int) time.Duration {
return time.Duration(stg.expo(retry))
}
type exponentialBackoffEqualJitterStrategy struct {
exponentialBackoff
}
func (stg exponentialBackoffEqualJitterStrategy) backoff(retry int) time.Duration {
v := stg.expo(retry)
u := uniform(0, v/2.0)
return time.Duration(v/2.0 + u)
}
type exponentialBackoffFullJitterStrategy struct {
exponentialBackoff
}
func (stg exponentialBackoffFullJitterStrategy) backoff(retry int) time.Duration {
v := stg.expo(retry)
u := uniform(0, v)
return time.Duration(u)
}
type exponentialBackoffDecorrelatedJitterStrategy struct {
exponentialBackoff
sleep time.Duration
}
// uniform returns a number in [min, max)
func uniform(min, max float64) float64 {
return min + rand.Float64()*(max-min)
}
func (stg exponentialBackoffDecorrelatedJitterStrategy) backoff(retry int) time.Duration {
c := float64(stg.cap)
b := float64(stg.base)
s := float64(stg.sleep)
u := uniform(b, 3*s)
s = math.Min(c, u)
return time.Duration(s)
}