package device import ( "math/rand" "time" ) // BackoffPolicy implements a backoff policy, randomizing its delays // and saturating at the final value in Millis. type BackoffPolicy struct { Millis []int } // DefaultBackoffPolicy is a backoff policy ranging up to 10 seconds. // nolint: gochecknoglobals var DefaultBackoffPolicy = BackoffPolicy{ []int{0, 100, 100, 500, 1000, 2000, 4000, 8000, 10000}, } // Duration returns the time duration of the n'th wait cycle in a // backoff policy. This is b.Millis[n], randomized to avoid thundering // herds. func (b BackoffPolicy) Duration(n int) time.Duration { if n >= len(b.Millis) { n = len(b.Millis) - 1 } return time.Duration(jitter(b.Millis[n])) * time.Millisecond } // jitter returns a random integer uniformly distributed in the range // [0.5 * millis .. 1.5 * millis] func jitter(millis int) int { if millis == 0 { return 0 } return millis/2 + rand.Intn(millis) }