context.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package backoff
  2. import (
  3. "context"
  4. "time"
  5. )
  6. // BackOffContext is a backoff policy that stops retrying after the context
  7. // is canceled.
  8. type BackOffContext interface { // nolint: golint
  9. BackOff
  10. Context() context.Context
  11. }
  12. type backOffContext struct {
  13. BackOff
  14. ctx context.Context
  15. }
  16. // WithContext returns a BackOffContext with context ctx
  17. //
  18. // ctx must not be nil
  19. func WithContext(b BackOff, ctx context.Context) BackOffContext { // nolint: golint
  20. if ctx == nil {
  21. panic("nil context")
  22. }
  23. if b, ok := b.(*backOffContext); ok {
  24. return &backOffContext{
  25. BackOff: b.BackOff,
  26. ctx: ctx,
  27. }
  28. }
  29. return &backOffContext{
  30. BackOff: b,
  31. ctx: ctx,
  32. }
  33. }
  34. func getContext(b BackOff) context.Context {
  35. if cb, ok := b.(BackOffContext); ok {
  36. return cb.Context()
  37. }
  38. if tb, ok := b.(*backOffTries); ok {
  39. return getContext(tb.delegate)
  40. }
  41. return context.Background()
  42. }
  43. func (b *backOffContext) Context() context.Context {
  44. return b.ctx
  45. }
  46. func (b *backOffContext) NextBackOff() time.Duration {
  47. select {
  48. case <-b.ctx.Done():
  49. return Stop
  50. default:
  51. return b.BackOff.NextBackOff()
  52. }
  53. }