Updates Backoff

This commit is contained in:
Ludovic Fernandez 2019-02-04 16:38:08 +01:00 committed by Traefiker Bot
parent 0561a20c06
commit f19c497621
32 changed files with 47 additions and 46 deletions

View file

@ -1,9 +1,8 @@
package backoff
import (
"context"
"time"
"golang.org/x/net/context"
)
// BackOffContext is a backoff policy that stops retrying after the context
@ -52,9 +51,13 @@ func (b *backOffContext) Context() context.Context {
func (b *backOffContext) NextBackOff() time.Duration {
select {
case <-b.Context().Done():
case <-b.ctx.Done():
return Stop
default:
return b.BackOff.NextBackOff()
}
next := b.BackOff.NextBackOff()
if deadline, ok := b.ctx.Deadline(); ok && deadline.Sub(time.Now()) < next {
return Stop
}
return next
}

View file

@ -63,7 +63,6 @@ type ExponentialBackOff struct {
currentInterval time.Duration
startTime time.Time
random *rand.Rand
}
// Clock is an interface that returns current time for BackOff.
@ -89,7 +88,6 @@ func NewExponentialBackOff() *ExponentialBackOff {
MaxInterval: DefaultMaxInterval,
MaxElapsedTime: DefaultMaxElapsedTime,
Clock: SystemClock,
random: rand.New(rand.NewSource(time.Now().UnixNano())),
}
b.Reset()
return b
@ -118,10 +116,7 @@ func (b *ExponentialBackOff) NextBackOff() time.Duration {
return Stop
}
defer b.incrementCurrentInterval()
if b.random == nil {
b.random = rand.New(rand.NewSource(time.Now().UnixNano()))
}
return getRandomValueFromInterval(b.RandomizationFactor, b.random.Float64(), b.currentInterval)
return getRandomValueFromInterval(b.RandomizationFactor, rand.Float64(), b.currentInterval)
}
// GetElapsedTime returns the elapsed time since an ExponentialBackOff instance

View file

@ -15,7 +15,6 @@ 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.
// It is the caller's responsibility to reset b after Retry returns.
//
// If o returns a *PermanentError, the operation is not retried, and the
// wrapped error is returned.
@ -29,6 +28,7 @@ func Retry(o Operation, b BackOff) error { return RetryNotify(o, b, nil) }
func RetryNotify(operation Operation, b BackOff, notify Notify) error {
var err error
var next time.Duration
var t *time.Timer
cb := ensureContext(b)
@ -42,7 +42,7 @@ func RetryNotify(operation Operation, b BackOff, notify Notify) error {
return permanent.Err
}
if next = b.NextBackOff(); next == Stop {
if next = cb.NextBackOff(); next == Stop {
return err
}
@ -50,11 +50,15 @@ func RetryNotify(operation Operation, b BackOff, notify Notify) error {
notify(err, next)
}
t := time.NewTimer(next)
if t == nil {
t = time.NewTimer(next)
defer t.Stop()
} else {
t.Reset(next)
}
select {
case <-cb.Context().Done():
t.Stop()
return err
case <-t.C:
}

View file

@ -1,7 +1,6 @@
package backoff
import (
"runtime"
"sync"
"time"
)
@ -34,7 +33,6 @@ func NewTicker(b BackOff) *Ticker {
}
t.b.Reset()
go t.run()
runtime.SetFinalizer(t, (*Ticker).Stop)
return t
}