forked from slack-go/slack
-
Notifications
You must be signed in to change notification settings - Fork 4
/
backoff.go
57 lines (47 loc) · 1.26 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
package slack
import (
"math/rand"
"time"
)
// This one was ripped from https://github.com/jpillora/backoff/blob/master/backoff.go
// Backoff is a time.Duration counter. It starts at Min. After every
// call to Duration() it is multiplied by Factor. It is capped at
// Max. It returns to Min on every call to Reset(). Used in
// conjunction with the time package.
type backoff struct {
attempts int
// Initial value to scale out
Initial time.Duration
// Jitter value randomizes an additional delay between 0 and Jitter
Jitter time.Duration
// Max maximum values of the backoff
Max time.Duration
}
// Returns the current value of the counter and then multiplies it
// Factor
func (b *backoff) Duration() (dur time.Duration) {
// Zero-values are nonsensical, so we use
// them to apply defaults
if b.Max == 0 {
b.Max = 10 * time.Second
}
if b.Initial == 0 {
b.Initial = 100 * time.Millisecond
}
// calculate this duration
if dur = time.Duration(1 << uint(b.attempts)); dur > 0 {
dur = dur * b.Initial
} else {
dur = b.Max
}
if b.Jitter > 0 {
dur = dur + time.Duration(rand.Intn(int(b.Jitter)))
}
// bump attempts count
b.attempts++
return dur
}
//Resets the current value of the counter back to Min
func (b *backoff) Reset() {
b.attempts = 0
}