You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

59 lines
1.4 KiB

  1. /*
  2. Copyright 2017 Google LLC
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package backoff
  14. import (
  15. "math/rand"
  16. "time"
  17. )
  18. const (
  19. // minBackoff is the minimum backoff used by default.
  20. minBackoff = 20 * time.Millisecond
  21. // maxBackoff is the maximum backoff used by default.
  22. maxBackoff = 32 * time.Second
  23. // jitter is the jitter factor.
  24. jitter = 0.4
  25. // rate is the rate of exponential increase in the backoff.
  26. rate = 1.3
  27. )
  28. var DefaultBackoff = ExponentialBackoff{minBackoff, maxBackoff}
  29. type ExponentialBackoff struct {
  30. Min, Max time.Duration
  31. }
  32. // delay calculates the delay that should happen at n-th
  33. // exponential backoff in a series.
  34. func (b ExponentialBackoff) Delay(retries int) time.Duration {
  35. min, max := float64(b.Min), float64(b.Max)
  36. delay := min
  37. for delay < max && retries > 0 {
  38. delay *= rate
  39. retries--
  40. }
  41. if delay > max {
  42. delay = max
  43. }
  44. delay -= delay * jitter * rand.Float64()
  45. if delay < min {
  46. delay = min
  47. }
  48. return time.Duration(delay)
  49. }