/
strategy_exponential_backoff.go
45 lines (37 loc) · 1.19 KB
/
strategy_exponential_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
package actor
import (
"math/rand"
"time"
)
// NewExponentialBackoffStrategy creates a new Supervisor strategy that restarts a faulting child using an exponential
// back off algorithm:
//
// delay =
func NewExponentialBackoffStrategy(backoffWindow time.Duration, initialBackoff time.Duration) SupervisorStrategy {
return &exponentialBackoffStrategy{
backoffWindow: backoffWindow,
initialBackoff: initialBackoff,
}
}
type exponentialBackoffStrategy struct {
backoffWindow time.Duration
initialBackoff time.Duration
}
func (strategy *exponentialBackoffStrategy) HandleFailure(supervisor Supervisor, child *PID, rs *RestartStatistics, reason interface{}, message interface{}) {
strategy.setFailureCount(rs)
backoff := rs.FailureCount * int(strategy.initialBackoff.Nanoseconds())
noise := rand.Intn(500)
dur := time.Duration(backoff + noise)
time.AfterFunc(dur, func() {
supervisor.RestartChildren(child)
})
}
func (strategy *exponentialBackoffStrategy) setFailureCount(rs *RestartStatistics) {
rs.Fail()
// if we are within the backoff window, exit early
if rs.IsWithinDuration(strategy.backoffWindow) {
return
}
//we are past the backoff limit, reset the failure counter
rs.Reset()
}