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

67 lines
1.2 KiB
Go
Raw Normal View History

2019-06-09 00:01:48 +00:00
package backoff
import (
"context"
"time"
)
// BackOffContext is a backoff policy that stops retrying after the context
// is canceled.
2020-04-29 02:23:32 +00:00
type BackOffContext interface { // nolint: golint
2019-06-09 00:01:48 +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
2020-04-29 02:23:32 +00:00
func WithContext(b BackOff, ctx context.Context) BackOffContext { // nolint: golint
2019-06-09 00:01:48 +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,
}
}
2020-04-29 02:23:32 +00:00
func getContext(b BackOff) context.Context {
2019-06-09 00:01:48 +00:00
if cb, ok := b.(BackOffContext); ok {
2020-04-29 02:23:32 +00:00
return cb.Context()
2019-06-09 00:01:48 +00:00
}
2020-04-29 02:23:32 +00:00
if tb, ok := b.(*backOffTries); ok {
return getContext(tb.delegate)
}
return context.Background()
2019-06-09 00:01:48 +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()
2020-04-29 02:23:32 +00:00
if deadline, ok := b.ctx.Deadline(); ok && deadline.Sub(time.Now()) < next { // nolint: gosimple
2019-06-09 00:01:48 +00:00
return Stop
}
return next
}