forked from yext/yext-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackoff.go
More file actions
38 lines (31 loc) · 862 Bytes
/
Copy pathbackoff.go
File metadata and controls
38 lines (31 loc) · 862 Bytes
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
package yext
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
}
// Default is a backoff policy ranging up to 5 seconds.
var DefaultBackoffPolicy = BackoffPolicy{
[]int{0, 0, 1000, 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)
}