/
retry.go
68 lines (57 loc) · 1.5 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
package cmd
import (
"context"
"fmt"
"math/rand"
"time"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
)
type retryManager struct {
retries int
maxRetries int
retryInterval time.Duration
commandCtx context.Context
retryCtx context.Context
cancelRetry context.CancelFunc
}
func newRetryManager(ctx context.Context, retryInterval time.Duration, maxRetries int) *retryManager {
retryCtx, cancelFunc := context.WithCancel(context.Background())
return &retryManager{
retryInterval: retryInterval,
maxRetries: maxRetries,
commandCtx: ctx,
retryCtx: retryCtx,
cancelRetry: cancelFunc,
}
}
type retryMessage struct {
SourceURL string `json:"sourceURL"`
TargetURL string `json:"targetURL"`
Retries int `json:"retries"`
}
func (r retryMessage) String() string {
return fmt.Sprintf("<INFO> Retries %d: source `%s` >> target `%s`", r.Retries, r.SourceURL, r.TargetURL)
}
func (r retryMessage) JSON() string {
jsonMessageBytes, e := json.MarshalIndent(r, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
func (r *retryManager) retry(action func(rm *retryManager) *probe.Error) {
defer r.cancelRetry()
for r.retries <= r.maxRetries {
err := action(r)
if err == nil {
return
}
select {
case <-r.retryCtx.Done():
return
case <-r.commandCtx.Done():
return
case <-time.After(r.retryInterval/2 + time.Duration(rand.Int63n(int64(r.retryInterval)))):
r.retries++
}
}
}