2020-10-28 03:36:57 -05:00
|
|
|
package retryer
|
|
|
|
|
|
|
|
import (
|
2023-03-27 04:17:05 -05:00
|
|
|
"errors"
|
2020-10-28 03:36:57 -05:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type RetrySignal = int
|
|
|
|
|
|
|
|
const (
|
2023-03-27 04:17:05 -05:00
|
|
|
FuncFailure RetrySignal = iota
|
2020-10-28 03:36:57 -05:00
|
|
|
FuncComplete
|
|
|
|
FuncError
|
|
|
|
)
|
|
|
|
|
|
|
|
// Retry retries the provided function using exponential backoff, starting with `minDelay` between attempts, and increasing to
|
|
|
|
// `maxDelay` after each failure. Stops when the provided function returns `FuncComplete`, or `maxRetries` is reached.
|
|
|
|
func Retry(body func() (RetrySignal, error), maxRetries int, minDelay time.Duration, maxDelay time.Duration) error {
|
|
|
|
currentDelay := minDelay
|
2023-03-27 04:17:05 -05:00
|
|
|
var ticker *time.Ticker
|
2020-10-28 03:36:57 -05:00
|
|
|
|
|
|
|
retries := 0
|
2023-03-27 04:17:05 -05:00
|
|
|
for {
|
2020-10-28 03:36:57 -05:00
|
|
|
response, err := body()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-03-27 04:17:05 -05:00
|
|
|
if response == FuncComplete {
|
2020-10-28 03:36:57 -05:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-03-27 04:17:05 -05:00
|
|
|
retries++
|
2020-10-28 03:36:57 -05:00
|
|
|
if retries >= maxRetries {
|
2023-03-27 04:17:05 -05:00
|
|
|
return errors.New("max retries exceeded")
|
2020-10-28 03:36:57 -05:00
|
|
|
}
|
|
|
|
|
2023-03-27 04:17:05 -05:00
|
|
|
if ticker == nil {
|
|
|
|
ticker = time.NewTicker(currentDelay)
|
|
|
|
defer ticker.Stop()
|
|
|
|
} else {
|
|
|
|
currentDelay = minDuration(currentDelay*2, maxDelay)
|
|
|
|
ticker.Reset(currentDelay)
|
|
|
|
}
|
|
|
|
|
|
|
|
<-ticker.C
|
|
|
|
}
|
2020-10-28 03:36:57 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func minDuration(a time.Duration, b time.Duration) time.Duration {
|
|
|
|
if a < b {
|
|
|
|
return a
|
|
|
|
}
|
|
|
|
return b
|
|
|
|
}
|