-
Notifications
You must be signed in to change notification settings - Fork 9
/
retry.go
95 lines (70 loc) · 2.11 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
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2017 The toolkit Authors. All rights reserved.
// Use of this source code is governed by a MIT License
// license that can be found in the LICENSE file.
package retry
import (
"context"
"fmt"
"math"
"time"
)
type ExhaustedError struct{}
func (r *ExhaustedError) Error() string {
return "function never succeeded in Retry"
}
type Retrier interface {
Retry(ctx context.Context, do RetryableDo) error
}
type RetryableDo func() (bool, error)
func NewRetrier(initialIntervalInSeconds, maxIntervalInSeconds float64, tries uint, strategy Strategy) Retrier {
if strategy == nil {
panic("strategy is missing")
}
if initialIntervalInSeconds > maxIntervalInSeconds {
panic(fmt.Sprintf("initial interval is greater than max (initial: %f, max: %f)", initialIntervalInSeconds, maxIntervalInSeconds))
}
return &retrier{
InitialIntervalInSeconds: initialIntervalInSeconds,
maxIntervalInSeconds: maxIntervalInSeconds,
strategy: strategy,
tries: tries,
}
}
// Retry supervised do funcs which automatically handle failures when they occur by performing retries.
type retrier struct {
InitialIntervalInSeconds, maxIntervalInSeconds float64
strategy Strategy
tries uint
}
func (r *retrier) Retry(ctx context.Context, do RetryableDo) error {
if ctx == nil {
ctx = context.Background()
}
var err error
var done bool
for i := uint(0); !done && i < r.tries; i++ {
done, err = do()
if ctx.Err() != nil {
return ctx.Err()
}
if err != nil {
return err
}
if !done {
r.InitialIntervalInSeconds = r.strategy.Policy(r.InitialIntervalInSeconds, r.maxIntervalInSeconds)
}
}
if !done {
return new(ExhaustedError)
}
return nil
}
type Strategy interface {
Policy(intervalInSeconds, maxIntervalInSeconds float64) float64
}
type Exp struct{}
const expCurve float64 = 2
func (e *Exp) Policy(intervalInSeconds, maxIntervalInSeconds float64) float64 {
time.Sleep(time.Duration(intervalInSeconds) * time.Second)
return math.Min(intervalInSeconds*expCurve, maxIntervalInSeconds)
}