2016-09-28 21:06:42 -04:00
|
|
|
package common
|
2016-05-24 20:13:36 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"math"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
var RetryExhaustedError error = fmt.Errorf("Function never succeeded in Retry")
|
|
|
|
|
2017-06-12 20:34:32 -04:00
|
|
|
// RetryableFunc performs an action and returns a bool indicating whether the
|
2017-10-25 13:17:08 -04:00
|
|
|
// function is done, or if it should keep retrying, and an error which will
|
2017-06-12 20:34:32 -04:00
|
|
|
// abort the retry and be returned by the Retry function. The 0-indexed attempt
|
|
|
|
// is passed with each call.
|
|
|
|
type RetryableFunc func(uint) (bool, error)
|
2017-03-24 02:58:15 -04:00
|
|
|
|
2017-10-25 13:17:08 -04:00
|
|
|
/*
|
|
|
|
Retry retries a function up to numTries times with exponential backoff.
|
|
|
|
If numTries == 0, retry indefinitely.
|
|
|
|
If interval == 0, Retry will not delay retrying and there will be no
|
|
|
|
exponential backoff.
|
|
|
|
If maxInterval == 0, maxInterval is set to +Infinity.
|
|
|
|
Intervals are in seconds.
|
|
|
|
Returns an error if initial > max intervals, if retries are exhausted, or if the passed function returns
|
|
|
|
an error.
|
|
|
|
*/
|
2017-03-24 02:58:15 -04:00
|
|
|
func Retry(initialInterval float64, maxInterval float64, numTries uint, function RetryableFunc) error {
|
2016-05-24 20:13:36 -04:00
|
|
|
if maxInterval == 0 {
|
|
|
|
maxInterval = math.Inf(1)
|
|
|
|
} else if initialInterval < 0 || initialInterval > maxInterval {
|
|
|
|
return fmt.Errorf("Invalid retry intervals (negative or initial < max). Initial: %f, Max: %f.", initialInterval, maxInterval)
|
|
|
|
}
|
|
|
|
|
|
|
|
var err error
|
|
|
|
done := false
|
|
|
|
interval := initialInterval
|
|
|
|
for i := uint(0); !done && (numTries == 0 || i < numTries); i++ {
|
2017-06-12 20:34:32 -04:00
|
|
|
done, err = function(i)
|
2016-05-24 20:13:36 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-09-28 21:06:42 -04:00
|
|
|
|
2016-05-24 20:13:36 -04:00
|
|
|
if !done {
|
|
|
|
// Retry after delay. Calculate next delay.
|
|
|
|
time.Sleep(time.Duration(interval) * time.Second)
|
2016-09-28 21:06:42 -04:00
|
|
|
interval = math.Min(interval*2, maxInterval)
|
2016-05-24 20:13:36 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if !done {
|
2016-09-28 21:06:42 -04:00
|
|
|
return RetryExhaustedError
|
2016-05-24 20:13:36 -04:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|