-
Notifications
You must be signed in to change notification settings - Fork 201
/
backoff.go
73 lines (57 loc) · 1.06 KB
/
backoff.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
package utils
import (
"context"
"time"
)
func Sleep(ctx context.Context, t time.Duration) bool {
select {
case <-time.After(t):
return true
case <-ctx.Done():
return false
}
}
type BackoffConfig struct {
Multiplier int
Limit int
Timeout time.Duration
}
func DefaultBackoffConfig() BackoffConfig {
const (
defaultMultiplier = 10
defaultLimit = 6
)
return BackoffConfig{Multiplier: defaultMultiplier, Limit: defaultLimit, Timeout: time.Microsecond}
}
type BackoffController struct {
BackoffConfig
count int
}
func (c BackoffController) GetTimeout() time.Duration {
result := c.Timeout
for i := 0; i < c.count; i++ {
result *= time.Duration(c.Multiplier)
}
return result
}
func (c *BackoffController) Increment() *BackoffController {
if c.count < c.Limit {
c.count++
}
// return pointer to itself for usability
return c
}
func (c *BackoffController) Reset() {
c.count = 0
}
type Counter struct {
Count int
iter int
}
func (c *Counter) Next() bool {
if c.Count <= 0 {
return true
}
c.iter++
return c.iter <= c.Count
}