-
Notifications
You must be signed in to change notification settings - Fork 2
/
backoff.go
58 lines (45 loc) · 989 Bytes
/
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
package internal
import (
"math"
"time"
)
const (
baseReconnectionDelayMs = 20
maxReconnectionDelayMs = 30_000
)
type BackoffPolicy interface {
Reset()
// Returns the next delay
Next() time.Duration
}
// Represents a default reconnection strategy
type exponentialBackoff struct {
index int
}
func newExponentialBackoff() *exponentialBackoff {
return &exponentialBackoff{}
}
func (p *exponentialBackoff) Reset() {
p.index = 0
}
// Returns an exponential delay
func (p *exponentialBackoff) Next() time.Duration {
p.index++
delayMs := maxReconnectionDelayMs
if p.index < 53 {
delayMs = int(math.Pow(2, float64(p.index))) * baseReconnectionDelayMs
if delayMs > maxReconnectionDelayMs {
delayMs = maxReconnectionDelayMs
}
}
return time.Duration(delayMs) * time.Millisecond
}
type fixedBackoff struct {
delay time.Duration
}
func (p *fixedBackoff) Reset() {
}
// Returns an exponential delay
func (p *fixedBackoff) Next() time.Duration {
return p.delay
}