-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathbackoff.go
More file actions
98 lines (84 loc) · 2.51 KB
/
Copy pathbackoff.go
File metadata and controls
98 lines (84 loc) · 2.51 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package posthog
import (
"math"
"math/rand"
"time"
)
// Backoff calculates exponential retry delays with optional jitter and a maximum cap.
type Backoff struct {
base time.Duration
factor uint8
jitter float64
cap time.Duration
}
// NewBackoff creates a Backoff with the provided base duration, exponential
// factor, jitter ratio, and maximum cap duration.
func NewBackoff(base time.Duration, factor uint8, jitter float64, cap time.Duration) *Backoff {
return &Backoff{base, factor, jitter, cap}
}
// defaultMaxBackoff is the single ceiling for capture retry waits: it caps the
// default exponential backoff and clamps a server Retry-After to the same value.
// Keeps the max retry wait bounded and unifies the default with posthog-rs /
// posthog-python (all 30s).
const defaultMaxBackoff = 30 * time.Second
// DefaultBackoff creates a Backoff with the SDK's default retry policy:
//
// base: 100 milliseconds
// factor: 2
// jitter: 0
// cap: 30 seconds
func DefaultBackoff() *Backoff {
return NewBackoff(time.Millisecond*100, 2, 0, defaultMaxBackoff)
}
// Duration returns the backoff interval for the given attempt.
func (b *Backoff) Duration(attempt int) time.Duration {
duration := float64(b.base) * math.Pow(float64(b.factor), float64(attempt))
if b.jitter != 0 {
random := rand.Float64()
deviation := math.Floor(random * b.jitter * duration)
if (int(math.Floor(random*10)) & 1) == 0 {
duration = duration - deviation
} else {
duration = duration + deviation
}
}
duration = math.Min(float64(duration), float64(b.cap))
return time.Duration(duration)
}
// Sleep pauses the current goroutine for the backoff interval for the given attempt.
func (b *Backoff) Sleep(attempt int) {
duration := b.Duration(attempt)
time.Sleep(duration)
}
// Ticker delivers ticks using successive durations from a Backoff.
type Ticker struct {
done chan struct{}
// C receives the time for each backoff tick and is closed after Stop.
C <-chan time.Time
}
// NewTicker starts a ticker that waits Duration(0), Duration(1), and so on between ticks.
func (b *Backoff) NewTicker() *Ticker {
c := make(chan time.Time, 1)
ticker := &Ticker{
done: make(chan struct{}, 1),
C: c,
}
go func() {
for i := 0; ; i++ {
timer := time.NewTimer(b.Duration(i))
select {
case t := <-timer.C:
c <- t
case <-ticker.done:
timer.Stop()
close(c)
return
}
}
}()
return ticker
}
// Stop stops the ticker goroutine and closes C. Stop should be called at most once.
func (t *Ticker) Stop() {
t.done <- struct{}{}
}