-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathretryer.go
69 lines (54 loc) · 1.32 KB
/
retryer.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
package retry
import (
"time"
)
var (
defaultAttempts = uint(1)
defaultBackoff = NoBackoff
defaultJitter = NoJitter
)
// Retryer defines a retryer
type Retryer struct {
// Attempts defines the number of retry attempts.
// Default 1.
Attempts uint
// Backoff defines a backoff function that returns `time.Duration`.
// This is applied on subsequent attempts.
// Default no backoff.
Backoff func(n uint, delay time.Duration) time.Duration
// Jitter defines a jitter function that returns `time.Duration`.
// Default no jitter.
Jitter func(backoff time.Duration) time.Duration
// Delay defines duration to delay.
// Default 0.
Delay time.Duration
}
// Do executes `fn` and returns success if `fn` executed succesfully and any errors that occurred
func (retryer Retryer) Do(fn func() error) (bool, Errors) {
var (
n uint
errs Errors
)
if retryer.Attempts < 1 {
retryer.Attempts = defaultAttempts
}
if retryer.Backoff == nil {
retryer.Backoff = defaultBackoff
}
if retryer.Jitter == nil {
retryer.Jitter = defaultJitter
}
for n < retryer.Attempts {
// Backoff and jitter after first attempt only
if n > 0 {
time.Sleep(retryer.Jitter(retryer.Backoff(n, retryer.Delay)))
}
err := fn()
if err == nil {
return true, errs
}
errs = append(errs, err)
n++
}
return false, errs
}