blob: e79a1ee7d74c38d11026187b7e464c8ec2afd55a (
plain)
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
|
package backoff
import (
"math/rand"
"time"
)
// Backoff returns the backoff duration for a specific retry attempt.
type Backoff func(uint64) time.Duration
// NewExponentialWithJitter returns a backoff implementation that
// exponentially increases the backoff duration for each retry from min,
// never exceeding max. Some randomization is added to the backoff duration.
// It panics if min >= max.
func NewExponentialWithJitter(min, max time.Duration) Backoff {
if min <= 0 {
min = 100 * time.Millisecond
}
if max <= 0 {
max = 10 * time.Second
}
if min >= max {
panic("max must be larger than min")
}
return func(attempt uint64) time.Duration {
e := min << attempt
if e <= 0 || e > max {
e = max
}
return time.Duration(jitter(int64(e)))
}
}
// jitter returns a random integer distributed in the range [n/2..n).
func jitter(n int64) int64 {
if n == 0 {
return 0
}
return n/2 + rand.Int63n(n/2)
}
|