khenaidoo | 5e4fca3 | 2021-05-12 16:02:23 -0400 | [diff] [blame^] | 1 | package backoff |
| 2 | |
| 3 | import "time" |
| 4 | |
| 5 | /* |
| 6 | WithMaxRetries creates a wrapper around another BackOff, which will |
| 7 | return Stop if NextBackOff() has been called too many times since |
| 8 | the last time Reset() was called |
| 9 | |
| 10 | Note: Implementation is not thread-safe. |
| 11 | */ |
| 12 | func WithMaxRetries(b BackOff, max uint64) BackOff { |
| 13 | return &backOffTries{delegate: b, maxTries: max} |
| 14 | } |
| 15 | |
| 16 | type backOffTries struct { |
| 17 | delegate BackOff |
| 18 | maxTries uint64 |
| 19 | numTries uint64 |
| 20 | } |
| 21 | |
| 22 | func (b *backOffTries) NextBackOff() time.Duration { |
| 23 | if b.maxTries > 0 { |
| 24 | if b.maxTries <= b.numTries { |
| 25 | return Stop |
| 26 | } |
| 27 | b.numTries++ |
| 28 | } |
| 29 | return b.delegate.NextBackOff() |
| 30 | } |
| 31 | |
| 32 | func (b *backOffTries) Reset() { |
| 33 | b.numTries = 0 |
| 34 | b.delegate.Reset() |
| 35 | } |