retry-continous.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * MinIO Go Library for Amazon S3 Compatible Cloud Storage
  3. * Copyright 2015-2017 MinIO, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package minio
  18. import "time"
  19. // newRetryTimerContinous creates a timer with exponentially increasing delays forever.
  20. func (c Client) newRetryTimerContinous(unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int {
  21. attemptCh := make(chan int)
  22. // normalize jitter to the range [0, 1.0]
  23. if jitter < NoJitter {
  24. jitter = NoJitter
  25. }
  26. if jitter > MaxJitter {
  27. jitter = MaxJitter
  28. }
  29. // computes the exponential backoff duration according to
  30. // https://www.awsarchitectureblog.com/2015/03/backoff.html
  31. exponentialBackoffWait := func(attempt int) time.Duration {
  32. // 1<<uint(attempt) below could overflow, so limit the value of attempt
  33. maxAttempt := 30
  34. if attempt > maxAttempt {
  35. attempt = maxAttempt
  36. }
  37. //sleep = random_between(0, min(cap, base * 2 ** attempt))
  38. sleep := unit * time.Duration(1<<uint(attempt))
  39. if sleep > cap {
  40. sleep = cap
  41. }
  42. if jitter != NoJitter {
  43. sleep -= time.Duration(c.random.Float64() * float64(sleep) * jitter)
  44. }
  45. return sleep
  46. }
  47. go func() {
  48. defer close(attemptCh)
  49. var nextBackoff int
  50. for {
  51. select {
  52. // Attempts starts.
  53. case attemptCh <- nextBackoff:
  54. nextBackoff++
  55. case <-doneCh:
  56. // Stop the routine.
  57. return
  58. }
  59. time.Sleep(exponentialBackoffWait(nextBackoff))
  60. }
  61. }()
  62. return attemptCh
  63. }