-
Notifications
You must be signed in to change notification settings - Fork 2
/
exponential_backoff_interval_policy.go
63 lines (52 loc) · 1.85 KB
/
exponential_backoff_interval_policy.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
package intervalpolicy
import (
"time"
"github.com/cenkalti/backoff/v4"
)
const (
baseFactor = 2
maxInterval = 60 * time.Second
maxNumOfConsecutiveEvaluationsBeforeNextBackoff = 3
)
// exponentialBackoffIntervalPolicy is a default interval policy.
type exponentialBackoffIntervalPolicy struct {
exponentialBackoff *backoff.ExponentialBackOff
interval time.Duration
numOfConsecutiveEvaluations int
}
// NewExponentialBackoffIntervalPolicy creates new exponential backoff interval policy.
func NewExponentialBackoffIntervalPolicy(interval time.Duration) IntervalPolicy {
exponentialBackoff := &backoff.ExponentialBackOff{
InitialInterval: interval,
RandomizationFactor: 0,
Multiplier: baseFactor,
MaxInterval: maxInterval,
MaxElapsedTime: 0,
Stop: 0,
Clock: backoff.SystemClock,
}
exponentialBackoff.Reset()
return &exponentialBackoffIntervalPolicy{
exponentialBackoff: exponentialBackoff,
interval: interval,
numOfConsecutiveEvaluations: 0,
}
}
// Evaluate reevaluates interval.
func (policy *exponentialBackoffIntervalPolicy) Evaluate() {
policy.numOfConsecutiveEvaluations++
if policy.numOfConsecutiveEvaluations == maxNumOfConsecutiveEvaluationsBeforeNextBackoff {
policy.interval = policy.exponentialBackoff.NextBackOff()
policy.numOfConsecutiveEvaluations = 0
}
}
// Reset resets the entire state of the policy.
func (policy *exponentialBackoffIntervalPolicy) Reset() {
policy.exponentialBackoff.Reset()
policy.interval = policy.exponentialBackoff.InitialInterval
policy.numOfConsecutiveEvaluations = 0
}
// GetInterval returns reevaluated interval.
func (policy *exponentialBackoffIntervalPolicy) GetInterval() time.Duration {
return policy.interval
}