null.go 967 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package backoff
  2. import (
  3. "context"
  4. "sync"
  5. )
  6. // NullPolicy does not do any backoff. It allows the caller
  7. // to execute the desired code once, and no more
  8. type NullPolicy struct{}
  9. func NewNull() *NullPolicy {
  10. return &NullPolicy{}
  11. }
  12. func (p *NullPolicy) Start(ctx context.Context) Controller {
  13. return newNullController(ctx)
  14. }
  15. type nullController struct {
  16. mu *sync.RWMutex
  17. ctx context.Context
  18. next chan struct{}
  19. }
  20. func newNullController(ctx context.Context) *nullController {
  21. cctx, cancel := context.WithCancel(ctx)
  22. c := &nullController{
  23. mu: &sync.RWMutex{},
  24. ctx: cctx,
  25. next: make(chan struct{}), // NO BUFFER
  26. }
  27. go func(ch chan struct{}, cancel func()) {
  28. ch <- struct{}{}
  29. close(ch)
  30. cancel()
  31. }(c.next, cancel)
  32. return c
  33. }
  34. func (c *nullController) Done() <-chan struct{} {
  35. c.mu.RLock()
  36. defer c.mu.RUnlock()
  37. return c.ctx.Done()
  38. }
  39. func (c *nullController) Next() <-chan struct{} {
  40. c.mu.RLock()
  41. defer c.mu.RUnlock()
  42. return c.next
  43. }