Serge Bazanski | cc25bdf | 2018-10-25 14:02:58 +0200 | [diff] [blame] | 1 | package backoff |
| 2 | |
| 3 | import ( |
| 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. |
| 11 | type BackOffContext interface { |
| 12 | BackOff |
| 13 | Context() context.Context |
| 14 | } |
| 15 | |
| 16 | type 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 |
| 24 | func 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 | |
| 42 | func ensureContext(b BackOff) BackOffContext { |
| 43 | if cb, ok := b.(BackOffContext); ok { |
| 44 | return cb |
| 45 | } |
| 46 | return WithContext(b, context.Background()) |
| 47 | } |
| 48 | |
| 49 | func (b *backOffContext) Context() context.Context { |
| 50 | return b.ctx |
| 51 | } |
| 52 | |
| 53 | func (b *backOffContext) NextBackOff() time.Duration { |
| 54 | select { |
| 55 | case <-b.Context().Done(): |
| 56 | return Stop |
| 57 | default: |
| 58 | return b.BackOff.NextBackOff() |
| 59 | } |
| 60 | } |