-
Notifications
You must be signed in to change notification settings - Fork 0
/
backoff_constant.go
55 lines (44 loc) · 1.26 KB
/
backoff_constant.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
package recovererr
import "time"
// ConstantBackoff implements backoff strategy using constant delay and max attempts.
type ConstantBackoff struct {
interval time.Duration
maxAttempts int
attempt int
}
// NewConstantBackoff creates new constant backoff using provided parameters.
func NewConstantBackoff(opts ...ConstantBackoffOption) *ConstantBackoff {
cb := ConstantBackoff{}
for _, opt := range opts {
opt(&cb)
}
if cb.interval == 0 {
cb.interval = time.Second
}
if cb.maxAttempts == 0 {
cb.maxAttempts = 3
}
return &cb
}
// ConstantBackoffOption configures constant backoff parameters.
type ConstantBackoffOption func(*ConstantBackoff)
// WithInterval configure constant backoff with specified backoff interval.
func WithInterval(d time.Duration) ConstantBackoffOption {
return func(cb *ConstantBackoff) {
cb.interval = d
}
}
// WithMaxAttempts configure constant backoff with specified max backoff attempts.
func WithMaxAttempts(n int) ConstantBackoffOption {
return func(cb *ConstantBackoff) {
cb.maxAttempts = n
}
}
// Next implements the BackoffStrategy.Next method.
func (cb *ConstantBackoff) Next() (time.Duration, bool) {
cb.attempt++
if cb.maxAttempts > 0 && cb.attempt > cb.maxAttempts {
return 0, false
}
return cb.interval, true
}