-
Notifications
You must be signed in to change notification settings - Fork 0
/
backoff.go
77 lines (60 loc) · 1.27 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
package backoff
import (
"context"
"errors"
"math"
"math/rand"
"time"
)
var (
// ErrContextDone returned when context is canceled
ErrContextDone = errors.New("context done")
)
const (
factor = 2
)
func init() {
rand.Seed(time.Now().UnixNano())
}
// Retry the given function n times jittering between max and min time.Duration
func Retry(ctx context.Context, attempts int, base, max time.Duration, f func() error) (err error) {
for attempt := 1; attempt <= attempts; attempt++ {
select {
case <-ctx.Done():
return ErrContextDone
default:
}
if err = f(); err == nil {
return nil
}
jitterSleep(attempt, base, max)
}
return err
}
// Until is like retry but retries until success
func Until(ctx context.Context, base, max time.Duration, f func() error) (err error) {
for attempt := 1; ; attempt++ {
select {
case <-ctx.Done():
return ErrContextDone
default:
}
if err := f(); err == nil {
return nil
}
jitterSleep(attempt, base, max)
if attempt == math.MaxInt64 {
attempt = 1
}
}
}
func jitterSleep(attempt int, base, max time.Duration) {
mx := float64(max)
mn := float64(base)
dur := mn * math.Pow(factor, float64(attempt))
if dur > mx {
dur = mx
}
j := time.Duration(rand.Float64()*(dur-mn) + mn)
time.Sleep(j)
}