k8s.io/client-go@v0.31.1/tools/cache/retry_with_deadline.go (about) 1 /* 2 Copyright 2022 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package cache 18 19 import ( 20 "k8s.io/utils/clock" 21 "time" 22 ) 23 24 type RetryWithDeadline interface { 25 After(error) 26 ShouldRetry() bool 27 } 28 29 type retryWithDeadlineImpl struct { 30 firstErrorTime time.Time 31 lastErrorTime time.Time 32 maxRetryDuration time.Duration 33 minResetPeriod time.Duration 34 isRetryable func(error) bool 35 clock clock.Clock 36 } 37 38 func NewRetryWithDeadline(maxRetryDuration, minResetPeriod time.Duration, isRetryable func(error) bool, clock clock.Clock) RetryWithDeadline { 39 return &retryWithDeadlineImpl{ 40 firstErrorTime: time.Time{}, 41 lastErrorTime: time.Time{}, 42 maxRetryDuration: maxRetryDuration, 43 minResetPeriod: minResetPeriod, 44 isRetryable: isRetryable, 45 clock: clock, 46 } 47 } 48 49 func (r *retryWithDeadlineImpl) reset() { 50 r.firstErrorTime = time.Time{} 51 r.lastErrorTime = time.Time{} 52 } 53 54 func (r *retryWithDeadlineImpl) After(err error) { 55 if r.isRetryable(err) { 56 if r.clock.Now().Sub(r.lastErrorTime) >= r.minResetPeriod { 57 r.reset() 58 } 59 60 if r.firstErrorTime.IsZero() { 61 r.firstErrorTime = r.clock.Now() 62 } 63 r.lastErrorTime = r.clock.Now() 64 } 65 } 66 67 func (r *retryWithDeadlineImpl) ShouldRetry() bool { 68 if r.maxRetryDuration <= time.Duration(0) { 69 return false 70 } 71 72 if r.clock.Now().Sub(r.firstErrorTime) <= r.maxRetryDuration { 73 return true 74 } 75 76 r.reset() 77 return false 78 }