| 1 |
// Package retrier implements the "retriable" resiliency pattern for Go. |
| 2 |
package retrier |
| 3 |
|
| 4 |
import ( |
| 5 |
"context" |
| 6 |
"math/rand" |
| 7 |
"sync" |
| 8 |
"time" |
| 9 |
) |
| 10 |
|
| 11 |
// Retrier implements the "retriable" resiliency pattern, abstracting out the process of retrying a failed action |
| 12 |
// a certain number of times with an optional back-off between each retry. |
| 13 |
type Retrier struct { |
| 14 |
backoff []time.Duration |
| 15 |
infiniteRetry bool |
| 16 |
surfaceWorkErrors bool |
| 17 |
class Classifier |
| 18 |
jitter float64 |
| 19 |
rand *rand.Rand |
| 20 |
randMu sync.Mutex |
| 21 |
} |
| 22 |
|
| 23 |
// New constructs a Retrier with the given backoff pattern and classifier. The length of the backoff pattern |
| 24 |
// indicates how many times an action will be retried, and the value at each index indicates the amount of time |
| 25 |
// waited before each subsequent retry. The classifier is used to determine which errors should be retried and |
| 26 |
// which should cause the retrier to fail fast. The DefaultClassifier is used if nil is passed. |
| 27 |
func New(backoff []time.Duration, class Classifier) *Retrier { |
| 28 |
if class == nil { |
| 29 |
class = DefaultClassifier{} |
| 30 |
} |
| 31 |
|
| 32 |
return &Retrier{ |
| 33 |
backoff: backoff, |
| 34 |
class: class, |
| 35 |
rand: rand.New(rand.NewSource(time.Now().UnixNano())), |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
// WithInfiniteRetry set the retrier to loop infinitely on the last backoff duration. Using this option, |
| 40 |
// the program will not exit until the retried function has been executed successfully. |
| 41 |
// WARNING : This may run indefinitely. |
| 42 |
func (r *Retrier) WithInfiniteRetry() *Retrier { |
| 43 |
r.infiniteRetry = true |
| 44 |
return r |
| 45 |
} |
| 46 |
|
| 47 |
// WithSurfaceWorkErrors configures the retrier to always return the last error received from work function |
| 48 |
// even if a context timeout/deadline is hit. |
| 49 |
func (r *Retrier) WithSurfaceWorkErrors() *Retrier { |
| 50 |
r.surfaceWorkErrors = true |
| 51 |
return r |
| 52 |
} |
| 53 |
|
| 54 |
// Run executes the given work function by executing RunCtx without context.Context. |
| 55 |
func (r *Retrier) Run(work func() error) error { |
| 56 |
return r.RunFn(context.Background(), func(c context.Context, r int) error { |
| 57 |
// never use ctx |
| 58 |
return work() |
| 59 |
}) |
| 60 |
} |
| 61 |
|
| 62 |
// RunCtx executes the given work function, then classifies its return value based on the classifier used |
| 63 |
// to construct the Retrier. If the result is Succeed or Fail, the return value of the work function is |
| 64 |
// returned to the caller. If the result is Retry, then Run sleeps according to the its backoff policy |
| 65 |
// before retrying. If the total number of retries is exceeded then the return value of the work function |
| 66 |
// is returned to the caller regardless. |
| 67 |
func (r *Retrier) RunCtx(ctx context.Context, work func(ctx context.Context) error) error { |
| 68 |
return r.RunFn(ctx, func(c context.Context, r int) error { |
| 69 |
return work(c) |
| 70 |
}) |
| 71 |
} |
| 72 |
|
| 73 |
// RunFn executes the given work function, then classifies its return value based on the classifier used |
| 74 |
// to construct the Retrier. If the result is Succeed or Fail, the return value of the work function is |
| 75 |
// returned to the caller. If the result is Retry, then Run sleeps according to the backoff policy |
| 76 |
// before retrying. If the total number of retries is exceeded then the return value of the work function |
| 77 |
// is returned to the caller regardless. The work function takes 2 args, the context and |
| 78 |
// the number of attempted retries. |
| 79 |
func (r *Retrier) RunFn(ctx context.Context, work func(ctx context.Context, retries int) error) error { |
| 80 |
retries := 0 |
| 81 |
for { |
| 82 |
ret := work(ctx, retries) |
| 83 |
|
| 84 |
switch r.class.Classify(ret) { |
| 85 |
case Succeed, Fail: |
| 86 |
return ret |
| 87 |
case Retry: |
| 88 |
if !r.infiniteRetry && retries >= len(r.backoff) { |
| 89 |
return ret |
| 90 |
} |
| 91 |
|
| 92 |
timer := time.NewTimer(r.calcSleep(retries)) |
| 93 |
if err := r.sleep(ctx, timer); err != nil { |
| 94 |
if r.surfaceWorkErrors { |
| 95 |
return ret |
| 96 |
} |
| 97 |
return err |
| 98 |
} |
| 99 |
|
| 100 |
retries++ |
| 101 |
} |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
func (r *Retrier) sleep(ctx context.Context, timer *time.Timer) error { |
| 106 |
select { |
| 107 |
case <-timer.C: |
| 108 |
return nil |
| 109 |
case <-ctx.Done(): |
| 110 |
timer.Stop() |
| 111 |
return ctx.Err() |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
func (r *Retrier) calcSleep(i int) time.Duration { |
| 116 |
if i >= len(r.backoff) { |
| 117 |
i = len(r.backoff) - 1 |
| 118 |
} |
| 119 |
// lock unsafe rand prng |
| 120 |
r.randMu.Lock() |
| 121 |
defer r.randMu.Unlock() |
| 122 |
// take a random float in the range (-r.jitter, +r.jitter) and multiply it by the base amount |
| 123 |
return r.backoff[i] + time.Duration(((r.rand.Float64()*2)-1)*r.jitter*float64(r.backoff[i])) |
| 124 |
} |
| 125 |
|
| 126 |
// SetJitter sets the amount of jitter on each back-off to a factor between 0.0 and 1.0 (values outside this range |
| 127 |
// are silently ignored). When a retry occurs, the back-off is adjusted by a random amount up to this value. |
| 128 |
func (r *Retrier) SetJitter(jit float64) { |
| 129 |
if jit < 0 || jit > 1 { |
| 130 |
return |
| 131 |
} |
| 132 |
r.jitter = jit |
| 133 |
} |