2015-02-28 09:21:18 +03:00
|
|
|
package backoff
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2015-03-03 01:01:21 +03:00
|
|
|
//Backoff is a time.Duration counter. It starts at Min.
|
|
|
|
//After every call to Duration() it is multiplied by Factor.
|
|
|
|
//It is capped at Max. It returns to Min on every call to Reset().
|
|
|
|
//Used in conjunction with the time package.
|
2015-02-28 09:21:18 +03:00
|
|
|
type Backoff struct {
|
2015-03-03 01:01:21 +03:00
|
|
|
//Factor is the multiplying factor for each increment step
|
2015-02-28 09:21:18 +03:00
|
|
|
attempts, Factor int
|
2015-03-03 01:01:21 +03:00
|
|
|
//Min and Max are the minimum and maximum values of the counter
|
|
|
|
curr, Min, Max time.Duration
|
2015-02-28 09:21:18 +03:00
|
|
|
}
|
|
|
|
|
2015-03-03 01:01:21 +03:00
|
|
|
//Returns the current value of the counter and then
|
|
|
|
//multiplies it Factor
|
2015-02-28 09:21:18 +03:00
|
|
|
func (b *Backoff) Duration() time.Duration {
|
2015-03-03 01:01:21 +03:00
|
|
|
//Zero-values are nonsensical, so we use
|
|
|
|
//them to apply defaults
|
2015-02-28 09:21:18 +03:00
|
|
|
if b.Min == 0 {
|
|
|
|
b.Min = 100 * time.Millisecond
|
|
|
|
}
|
|
|
|
if b.Max == 0 {
|
|
|
|
b.Max = 10 * time.Second
|
|
|
|
}
|
|
|
|
if b.Factor == 0 {
|
|
|
|
b.Factor = 2
|
|
|
|
}
|
|
|
|
if b.curr == 0 {
|
|
|
|
b.curr = b.Min
|
|
|
|
}
|
|
|
|
|
|
|
|
//calculate next duration in ms
|
|
|
|
ms := float64(b.curr) * math.Pow(float64(b.Factor), float64(b.attempts))
|
|
|
|
//bump attempts count
|
|
|
|
b.attempts++
|
|
|
|
//return as a time.Duration
|
|
|
|
return time.Duration(math.Min(ms, float64(b.Max)))
|
|
|
|
}
|
|
|
|
|
2015-03-03 01:01:21 +03:00
|
|
|
//Resets the current value of the counter back to Min
|
2015-02-28 09:21:18 +03:00
|
|
|
func (b *Backoff) Reset() {
|
|
|
|
b.attempts = 0
|
|
|
|
}
|