dispatch/vendor/github.com/cenkalti/backoff/v4/retry.go

97 lines
2.2 KiB
Go
Raw Normal View History

2019-06-09 00:01:48 +00:00
package backoff
import "time"
// An Operation is executing by Retry() or RetryNotify().
// The operation will be retried using a backoff policy if it returns an error.
type Operation func() error
// Notify is a notify-on-error function. It receives an operation error and
// backoff delay if the operation failed (with an error).
//
// NOTE that if the backoff policy stated to stop retrying,
// the notify function isn't called.
type Notify func(error, time.Duration)
// Retry the operation o until it does not return error or BackOff stops.
// o is guaranteed to be run at least once.
//
// If o returns a *PermanentError, the operation is not retried, and the
// wrapped error is returned.
//
// Retry sleeps the goroutine for the duration returned by BackOff after a
// failed operation returns.
2020-04-29 02:23:32 +00:00
func Retry(o Operation, b BackOff) error {
return RetryNotify(o, b, nil)
}
2019-06-09 00:01:48 +00:00
// RetryNotify calls notify function with the error and wait duration
// for each failed attempt before sleep.
func RetryNotify(operation Operation, b BackOff, notify Notify) error {
2020-04-29 02:23:32 +00:00
return RetryNotifyWithTimer(operation, b, notify, nil)
}
// RetryNotifyWithTimer calls notify function with the error and wait duration using the given Timer
// for each failed attempt before sleep.
// A default timer that uses system timer is used when nil is passed.
func RetryNotifyWithTimer(operation Operation, b BackOff, notify Notify, t Timer) error {
2019-06-09 00:01:48 +00:00
var err error
var next time.Duration
2020-04-29 02:23:32 +00:00
if t == nil {
t = &defaultTimer{}
}
2019-06-09 00:01:48 +00:00
2020-04-29 02:23:32 +00:00
defer func() {
t.Stop()
}()
ctx := getContext(b)
2019-06-09 00:01:48 +00:00
b.Reset()
for {
if err = operation(); err == nil {
return nil
}
if permanent, ok := err.(*PermanentError); ok {
return permanent.Err
}
2020-04-29 02:23:32 +00:00
if next = b.NextBackOff(); next == Stop {
2019-06-09 00:01:48 +00:00
return err
}
if notify != nil {
notify(err, next)
}
2020-04-29 02:23:32 +00:00
t.Start(next)
2019-06-09 00:01:48 +00:00
select {
2020-04-29 02:23:32 +00:00
case <-ctx.Done():
return ctx.Err()
case <-t.C():
2019-06-09 00:01:48 +00:00
}
}
}
// PermanentError signals that the operation should not be retried.
type PermanentError struct {
Err error
}
func (e *PermanentError) Error() string {
return e.Err.Error()
}
2020-04-29 02:23:32 +00:00
func (e *PermanentError) Unwrap() error {
return e.Err
}
2019-06-09 00:01:48 +00:00
// Permanent wraps the given err in a *PermanentError.
func Permanent(err error) *PermanentError {
return &PermanentError{
Err: err,
}
}