2015-10-13 06:27:50 -04:00
|
|
|
package retry
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2015-12-02 03:58:00 -05:00
|
|
|
errorRetryFailed = errors.New("All retry attempts failed.")
|
2015-10-13 06:27:50 -04:00
|
|
|
)
|
|
|
|
|
2015-12-02 03:58:00 -05:00
|
|
|
// Strategy is a way to retry on a specific function.
|
2015-12-02 03:46:19 -05:00
|
|
|
type Strategy interface {
|
2015-12-02 06:47:54 -05:00
|
|
|
// On performs a retry on a specific function, until it doesn't return any error.
|
2015-10-13 06:27:50 -04:00
|
|
|
On(func() error) error
|
|
|
|
}
|
|
|
|
|
|
|
|
type retryer struct {
|
|
|
|
NextDelay func(int) int
|
|
|
|
}
|
|
|
|
|
2015-12-02 03:58:00 -05:00
|
|
|
// On implements Strategy.On.
|
2015-10-13 06:27:50 -04:00
|
|
|
func (r *retryer) On(method func() error) error {
|
|
|
|
attempt := 0
|
|
|
|
for {
|
|
|
|
err := method()
|
|
|
|
if err == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
delay := r.NextDelay(attempt)
|
|
|
|
if delay < 0 {
|
2015-12-02 03:58:00 -05:00
|
|
|
return errorRetryFailed
|
2015-10-13 06:27:50 -04:00
|
|
|
}
|
|
|
|
<-time.After(time.Duration(delay) * time.Millisecond)
|
2015-10-13 18:57:00 -04:00
|
|
|
attempt++
|
2015-10-13 06:27:50 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-02 03:58:00 -05:00
|
|
|
// Timed returns a retry strategy with fixed interval.
|
2015-12-02 03:46:19 -05:00
|
|
|
func Timed(attempts int, delay int) Strategy {
|
2015-10-13 06:27:50 -04:00
|
|
|
return &retryer{
|
|
|
|
NextDelay: func(attempt int) int {
|
|
|
|
if attempt >= attempts {
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
return delay
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|