forked from keybase/client
/
backoff.go
41 lines (33 loc) · 965 Bytes
/
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
package libkb
// from here:
// https://blog.gopheracademy.com/advent-2014/backoff/
import (
"math/rand"
"time"
)
// BackoffPolicy implements a backoff policy, randomizing its delays
// and saturating at the final value in Millis.
type BackoffPolicy struct {
Millis []int
}
// BackoffDefault is a backoff policy ranging up to 5 seconds.
var BackoffDefault = BackoffPolicy{
[]int{0, 10, 10, 100, 100, 500, 500, 3000, 3000, 5000},
}
// Duration returns the time duration of the n'th wait cycle in a
// backoff policy. This is b.Millis[n], randomized to avoid thundering
// herds.
func (b BackoffPolicy) Duration(n int) time.Duration {
if n >= len(b.Millis) {
n = len(b.Millis) - 1
}
return time.Duration(jitter(b.Millis[n])) * time.Millisecond
}
// jitter returns a random integer uniformly distributed in the range
// [0.5 * millis .. 1.5 * millis]
func jitter(millis int) int {
if millis == 0 {
return 0
}
return millis/2 + rand.Intn(millis)
}