-
Notifications
You must be signed in to change notification settings - Fork 0
/
retry.go
82 lines (65 loc) · 1.2 KB
/
retry.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
package retry
import (
"time"
)
type Retrier interface {
PassedIterationCount() int
SetDelay(duration time.Duration)
Stop()
}
type retrier struct {
iteration int
delay *time.Duration
stopped bool
execute func() error
inspect func(retrier Retrier, err error)
}
// PassedIterationCount returns number of passed iterations.
func (r *retrier) PassedIterationCount() int {
return r.iteration
}
// SetDelay sets delay for next iteration.
func (r *retrier) SetDelay(duration time.Duration) {
r.delay = &duration
}
// Stop preventing further executions.
func (r *retrier) Stop() {
r.stopped = true
}
type Option func(r *retrier)
func Execute(fn func() error) Option {
return func(r *retrier) {
r.execute = fn
}
}
func Inspect(fn func(r Retrier, err error)) Option {
return func(r *retrier) {
r.inspect = fn
}
}
func Retry(options ...Option) error {
r := &retrier{}
for _, option := range options {
option(r)
}
if r.execute == nil {
return nil
}
for {
r.iteration++
r.delay = nil
err := r.execute()
if err == nil {
return nil
}
if r.inspect != nil {
r.inspect(r, err)
}
if r.stopped {
return err
}
if r.delay != nil {
<-time.After(*r.delay)
}
}
}