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

63 lines
1.1 KiB
Go
Raw Normal View History

2021-10-20 10:08:56 +02:00
package backoff
import (
"context"
"time"
)
// BackOffContext is a backoff policy that stops retrying after the context
// is canceled.
2021-11-16 15:32:13 +01:00
type BackOffContext interface { // nolint: golint
2021-10-20 10:08:56 +02:00
BackOff
Context() context.Context
}
type backOffContext struct {
BackOff
ctx context.Context
}
// WithContext returns a BackOffContext with context ctx
//
// ctx must not be nil
2021-11-16 15:32:13 +01:00
func WithContext(b BackOff, ctx context.Context) BackOffContext { // nolint: golint
2021-10-20 10:08:56 +02: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,
}
}
2021-11-16 15:32:13 +01:00
func getContext(b BackOff) context.Context {
2021-10-20 10:08:56 +02:00
if cb, ok := b.(BackOffContext); ok {
2021-11-16 15:32:13 +01:00
return cb.Context()
2021-10-20 10:08:56 +02:00
}
2021-11-16 15:32:13 +01:00
if tb, ok := b.(*backOffTries); ok {
return getContext(tb.delegate)
}
return context.Background()
2021-10-20 10:08:56 +02:00
}
func (b *backOffContext) Context() context.Context {
return b.ctx
}
func (b *backOffContext) NextBackOff() time.Duration {
select {
case <-b.ctx.Done():
return Stop
default:
2021-11-16 15:32:13 +01:00
return b.BackOff.NextBackOff()
2021-10-20 10:08:56 +02:00
}
}