blob: 5d157092544fdbc8225327191883c46876faab94 [file] [log] [blame]
Serge Bazanskicc25bdf2018-10-25 14:02:58 +02001package backoff
2
3import (
4 "time"
5
6 "golang.org/x/net/context"
7)
8
9// BackOffContext is a backoff policy that stops retrying after the context
10// is canceled.
11type BackOffContext interface {
12 BackOff
13 Context() context.Context
14}
15
16type backOffContext struct {
17 BackOff
18 ctx context.Context
19}
20
21// WithContext returns a BackOffContext with context ctx
22//
23// ctx must not be nil
24func WithContext(b BackOff, ctx context.Context) BackOffContext {
25 if ctx == nil {
26 panic("nil context")
27 }
28
29 if b, ok := b.(*backOffContext); ok {
30 return &backOffContext{
31 BackOff: b.BackOff,
32 ctx: ctx,
33 }
34 }
35
36 return &backOffContext{
37 BackOff: b,
38 ctx: ctx,
39 }
40}
41
42func ensureContext(b BackOff) BackOffContext {
43 if cb, ok := b.(BackOffContext); ok {
44 return cb
45 }
46 return WithContext(b, context.Background())
47}
48
49func (b *backOffContext) Context() context.Context {
50 return b.ctx
51}
52
53func (b *backOffContext) NextBackOff() time.Duration {
54 select {
55 case <-b.Context().Done():
56 return Stop
57 default:
58 return b.BackOff.NextBackOff()
59 }
60}