retry_with_deadline.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. Copyright 2022 The Kubernetes Authors.
  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 cache
  14. import (
  15. "k8s.io/utils/clock"
  16. "time"
  17. )
  18. type RetryWithDeadline interface {
  19. After(error)
  20. ShouldRetry() bool
  21. }
  22. type retryWithDeadlineImpl struct {
  23. firstErrorTime time.Time
  24. lastErrorTime time.Time
  25. maxRetryDuration time.Duration
  26. minResetPeriod time.Duration
  27. isRetryable func(error) bool
  28. clock clock.Clock
  29. }
  30. func NewRetryWithDeadline(maxRetryDuration, minResetPeriod time.Duration, isRetryable func(error) bool, clock clock.Clock) RetryWithDeadline {
  31. return &retryWithDeadlineImpl{
  32. firstErrorTime: time.Time{},
  33. lastErrorTime: time.Time{},
  34. maxRetryDuration: maxRetryDuration,
  35. minResetPeriod: minResetPeriod,
  36. isRetryable: isRetryable,
  37. clock: clock,
  38. }
  39. }
  40. func (r *retryWithDeadlineImpl) reset() {
  41. r.firstErrorTime = time.Time{}
  42. r.lastErrorTime = time.Time{}
  43. }
  44. func (r *retryWithDeadlineImpl) After(err error) {
  45. if r.isRetryable(err) {
  46. if r.clock.Now().Sub(r.lastErrorTime) >= r.minResetPeriod {
  47. r.reset()
  48. }
  49. if r.firstErrorTime.IsZero() {
  50. r.firstErrorTime = r.clock.Now()
  51. }
  52. r.lastErrorTime = r.clock.Now()
  53. }
  54. }
  55. func (r *retryWithDeadlineImpl) ShouldRetry() bool {
  56. if r.maxRetryDuration <= time.Duration(0) {
  57. return false
  58. }
  59. if r.clock.Now().Sub(r.firstErrorTime) <= r.maxRetryDuration {
  60. return true
  61. }
  62. r.reset()
  63. return false
  64. }