-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdelay.go
43 lines (36 loc) · 1.05 KB
/
delay.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
package goretry
import (
"math/rand"
"time"
)
type (
DelayCalculator func(prevDelay time.Duration) time.Duration
)
func NewIncreasingDelayCalculator(addition time.Duration) DelayCalculator {
return func(prevDelay time.Duration) time.Duration {
return prevDelay + addition
}
}
func NewJittingDelayCalculator(around time.Duration) DelayCalculator {
return func(prevDelay time.Duration) time.Duration {
seconds := around.Seconds()
jit := moveRandomValueAtZeroWithUnitRadius()
deviationValueInSeconds := seconds * jit
deviationDuration := time.Duration(deviationValueInSeconds * float64(time.Second))
return prevDelay + deviationDuration
}
}
func moveRandomValueAtZeroWithUnitRadius() float64 {
//nolint:gosec // this is ok for jitting
return rand.Float64()*2 - 1
}
func NewConstantDelayCalculator() DelayCalculator {
return func(prevDelay time.Duration) time.Duration {
return prevDelay
}
}
func (c DelayCalculator) With(other DelayCalculator) DelayCalculator {
return func(prevDelay time.Duration) time.Duration {
return other(c(prevDelay))
}
}