-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathretryloop.go
84 lines (70 loc) · 1.92 KB
/
retryloop.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
package main
import (
"context"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/sirupsen/logrus"
)
// loopWithRetries calls a function repeately until context is cancelled; in
// case of a failure retries are scheduled using the given back-off algorithm
func loopWithRetries(ctx context.Context, logger logrus.FieldLogger,
delay time.Duration, retryBackOff backoff.BackOff,
fn func(context.Context) error) error {
const maxInitialInterval = 10 * time.Second
var pending bool
// Use existing code to introduce jitter for normal retries
normalBackOff := backoff.NewExponentialBackOff()
normalBackOff.InitialInterval = delay
if normalBackOff.InitialInterval > maxInitialInterval {
// Run more often when starting calls at normal interval
normalBackOff.InitialInterval = maxInitialInterval
}
normalBackOff.RandomizationFactor = 0.1
normalBackOff.MaxInterval = delay
normalBackOff.Multiplier = 1.1
normalBackOff.MaxElapsedTime = 0
normalBackOff.Reset()
for {
if err := fn(ctx); err == nil {
pending = false
} else {
if permanent, ok := err.(*backoff.PermanentError); ok {
logger.Debugf("Giving up on retries due to permanent error: %s", permanent.Err)
pending = false
} else {
logger.Debugf("Operation failed: %s", err)
if !pending {
// Start with retries
pending = true
retryBackOff.Reset()
}
}
}
select {
case <-ctx.Done():
return ctx.Err()
default:
}
timerDuration := normalBackOff.NextBackOff()
if timerDuration == backoff.Stop {
timerDuration = delay
normalBackOff.Reset()
}
if pending {
if next := retryBackOff.NextBackOff(); next == backoff.Stop {
logger.Debug("Giving up on retries")
pending = false
} else {
timerDuration = next
}
}
logger.Debugf("Sleeping for %s", timerDuration)
timer := time.NewTimer(timerDuration)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
}
}