forked from sethvargo/go-retry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
retry.go
76 lines (66 loc) · 1.76 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
// Package retry provides helpers for retrying.
//
// This package defines flexible interfaces for retrying Go functions that may
// be flakey or eventually consistent. It abstracts the "backoff" (how long to
// wait between tries) and "retry" (execute the function again) mechanisms for
// maximum flexibility. Furthermore, everything is an interface, so you can
// define your own implementations.
//
// The package is modeled after Go's built-in HTTP package, making it easy to
// customize the built-in backoff with your own custom logic. Additionally,
// callers specify which errors are retryable by wrapping them. This is helpful
// with complex operations where only certain results should retry.
package retry
import (
"context"
"errors"
"time"
)
// RetryFunc is a function passed to retry.
type RetryFunc func(ctx context.Context) error
type retryableError struct {
err error
}
// RetryableError marks an error as retryable.
func RetryableError(err error) error {
if err == nil {
return nil
}
return &retryableError{err}
}
// Unwrap implements error wrapping.
func (e *retryableError) Unwrap() error {
return e.err
}
// Error returns the error string.
func (e *retryableError) Error() string {
if e.err == nil {
return "retryable: <nil>"
}
return "retryable: " + e.err.Error()
}
// Do wraps a function with a backoff to retry. The provided context is the same
// context passed to the RetryFunc.
func Do(ctx context.Context, b Backoff, f RetryFunc) error {
for {
err := f(ctx)
if err == nil {
return nil
}
// Not retryable
var rerr *retryableError
if !errors.As(err, &rerr) {
return err
}
next, stop := b.Next()
if stop {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(next):
continue
}
}
}