2021-09-28 15:05:57 +00:00
|
|
|
package backoff
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// BackOffContext is a backoff policy that stops retrying after the context
|
|
|
|
// is canceled.
|
2023-03-07 00:32:05 +00:00
|
|
|
type BackOffContext interface { // nolint: golint
|
2021-09-28 15:05:57 +00:00
|
|
|
BackOff
|
|
|
|
Context() context.Context
|
|
|
|
}
|
|
|
|
|
|
|
|
type backOffContext struct {
|
|
|
|
BackOff
|
|
|
|
ctx context.Context
|
|
|
|
}
|
|
|
|
|
|
|
|
// WithContext returns a BackOffContext with context ctx
|
|
|
|
//
|
|
|
|
// ctx must not be nil
|
2023-03-07 00:32:05 +00:00
|
|
|
func WithContext(b BackOff, ctx context.Context) BackOffContext { // nolint: golint
|
2021-09-28 15:05:57 +00:00
|
|
|
if ctx == nil {
|
|
|
|
panic("nil context")
|
|
|
|
}
|
|
|
|
|
|
|
|
if b, ok := b.(*backOffContext); ok {
|
|
|
|
return &backOffContext{
|
|
|
|
BackOff: b.BackOff,
|
|
|
|
ctx: ctx,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return &backOffContext{
|
|
|
|
BackOff: b,
|
|
|
|
ctx: ctx,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-07 00:32:05 +00:00
|
|
|
func getContext(b BackOff) context.Context {
|
2021-09-28 15:05:57 +00:00
|
|
|
if cb, ok := b.(BackOffContext); ok {
|
2023-03-07 00:32:05 +00:00
|
|
|
return cb.Context()
|
2021-09-28 15:05:57 +00:00
|
|
|
}
|
2023-03-07 00:32:05 +00:00
|
|
|
if tb, ok := b.(*backOffTries); ok {
|
|
|
|
return getContext(tb.delegate)
|
|
|
|
}
|
|
|
|
return context.Background()
|
2021-09-28 15:05:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (b *backOffContext) Context() context.Context {
|
|
|
|
return b.ctx
|
|
|
|
}
|
|
|
|
|
|
|
|
func (b *backOffContext) NextBackOff() time.Duration {
|
|
|
|
select {
|
|
|
|
case <-b.ctx.Done():
|
|
|
|
return Stop
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
next := b.BackOff.NextBackOff()
|
2023-03-07 00:32:05 +00:00
|
|
|
if deadline, ok := b.ctx.Deadline(); ok && deadline.Sub(time.Now()) < next { // nolint: gosimple
|
2021-09-28 15:05:57 +00:00
|
|
|
return Stop
|
|
|
|
}
|
|
|
|
return next
|
|
|
|
}
|