...
1
18
19
20
21
22 package retry
23
24 import (
25 "context"
26 "math/rand"
27 "time"
28
29 "google.golang.org/grpc/grpclog"
30 )
31
32 const (
33 maxRetryAttempts = 5
34 maxRetryForLoops = 10
35 )
36
37 type defaultBackoff struct {
38 max time.Duration
39 mul float64
40 cur time.Duration
41 }
42
43
44
45 func (b *defaultBackoff) Pause() time.Duration {
46 d := time.Duration(1 + rand.Int63n(int64(b.cur)))
47 b.cur = time.Duration(float64(b.cur) * b.mul)
48 if b.cur > b.max {
49 b.cur = b.max
50 }
51 return d
52 }
53
54
55
56 func Sleep(ctx context.Context, d time.Duration) error {
57 t := time.NewTimer(d)
58 select {
59 case <-ctx.Done():
60 t.Stop()
61 return ctx.Err()
62 case <-t.C:
63 return nil
64 }
65 }
66
67
68
69 var NewRetryer = func() *S2ARetryer {
70 return &S2ARetryer{bo: &defaultBackoff{
71 cur: 100 * time.Millisecond,
72 max: 30 * time.Second,
73 mul: 2,
74 }}
75 }
76
77 type backoff interface {
78 Pause() time.Duration
79 }
80
81
82 type S2ARetryer struct {
83 bo backoff
84 attempts int
85 }
86
87
88 func (r *S2ARetryer) Attempts() int {
89 return r.attempts
90 }
91
92
93
94 func (r *S2ARetryer) Retry(err error) (time.Duration, bool) {
95 if err == nil {
96 return 0, false
97 }
98 if r.attempts >= maxRetryAttempts {
99 return 0, false
100 }
101 r.attempts++
102 return r.bo.Pause(), true
103 }
104
105
106
107 func Run(ctx context.Context, f func() error) {
108 retryer := NewRetryer()
109 forLoopCnt := 0
110 var err error
111 for {
112 err = f()
113 if bo, shouldRetry := retryer.Retry(err); shouldRetry {
114 if grpclog.V(1) {
115 grpclog.Infof("will attempt retry: %v", err)
116 }
117 if ctx.Err() != nil {
118 if grpclog.V(1) {
119 grpclog.Infof("exit retry loop due to context error: %v", ctx.Err())
120 }
121 break
122 }
123 if errSleep := Sleep(ctx, bo); errSleep != nil {
124 if grpclog.V(1) {
125 grpclog.Infof("exit retry loop due to sleep error: %v", errSleep)
126 }
127 break
128 }
129
130 forLoopCnt++
131 if forLoopCnt > maxRetryForLoops {
132 if grpclog.V(1) {
133 grpclog.Infof("exit the for loop after too many retries")
134 }
135 break
136 }
137 continue
138 }
139 if grpclog.V(1) {
140 grpclog.Infof("retry conditions not met, exit the loop")
141 }
142 break
143 }
144 }
145
View as plain text