This repository has been archived by the owner on May 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathoptions.go
89 lines (74 loc) · 2.09 KB
/
options.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
78
79
80
81
82
83
84
85
86
87
88
89
package retry
import (
"time"
"github.com/juju/errgo"
)
const (
DefaultMaxTries = 3
DefaultTimeout = time.Duration(15 * time.Second)
)
// Not is a helper to invert another .
func Not(checker func(err error) bool) func(err error) bool {
return func(err error) bool {
return !checker(err)
}
}
type RetryOption func(options *retryOptions)
// Timeout specifies the maximum time that should be used before aborting the retry loop.
// Note that this does not abort the operation in progress.
func Timeout(d time.Duration) RetryOption {
return func(options *retryOptions) {
options.Timeout = d
}
}
// MaxTries specifies the maximum number of times op will be called by Do().
func MaxTries(tries int) RetryOption {
return func(options *retryOptions) {
options.MaxTries = tries
}
}
// RetryChecker defines whether the given error is an error that can be retried.
func RetryChecker(checker func(err error) bool) RetryOption {
return func(options *retryOptions) {
options.Checker = checker
}
}
func Sleep(d time.Duration) RetryOption {
return func(options *retryOptions) {
options.Sleep = d
}
}
// AfterRetry is called after a retry and can be used e.g. to emit events.
func AfterRetry(afterRetry func(err error)) RetryOption {
return func(options *retryOptions) {
options.AfterRetry = afterRetry
}
}
// AfterRetryLimit is called after a retry limit is reached and can be used
// e.g. to emit events.
func AfterRetryLimit(afterRetryLimit func(err error)) RetryOption {
return func(options *retryOptions) {
options.AfterRetryLimit = afterRetryLimit
}
}
type retryOptions struct {
Timeout time.Duration
MaxTries int
Checker func(err error) bool
Sleep time.Duration
AfterRetry func(err error)
AfterRetryLimit func(err error)
}
func newRetryOptions(options ...RetryOption) retryOptions {
state := retryOptions{
Timeout: DefaultTimeout,
MaxTries: DefaultMaxTries,
Checker: errgo.Any,
AfterRetry: func(err error) {},
AfterRetryLimit: func(err error) {},
}
for _, option := range options {
option(&state)
}
return state
}