context_watcher.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package ctxwatch
  2. import (
  3. "context"
  4. "sync"
  5. )
  6. // ContextWatcher watches a context and performs an action when the context is canceled. It can watch one context at a
  7. // time.
  8. type ContextWatcher struct {
  9. handler Handler
  10. unwatchChan chan struct{}
  11. lock sync.Mutex
  12. watchInProgress bool
  13. onCancelWasCalled bool
  14. }
  15. // NewContextWatcher returns a ContextWatcher. onCancel will be called when a watched context is canceled.
  16. // OnUnwatchAfterCancel will be called when Unwatch is called and the watched context had already been canceled and
  17. // onCancel called.
  18. func NewContextWatcher(handler Handler) *ContextWatcher {
  19. cw := &ContextWatcher{
  20. handler: handler,
  21. unwatchChan: make(chan struct{}),
  22. }
  23. return cw
  24. }
  25. // Watch starts watching ctx. If ctx is canceled then the onCancel function passed to NewContextWatcher will be called.
  26. func (cw *ContextWatcher) Watch(ctx context.Context) {
  27. cw.lock.Lock()
  28. defer cw.lock.Unlock()
  29. if cw.watchInProgress {
  30. panic("Watch already in progress")
  31. }
  32. cw.onCancelWasCalled = false
  33. if ctx.Done() != nil {
  34. cw.watchInProgress = true
  35. go func() {
  36. select {
  37. case <-ctx.Done():
  38. cw.handler.HandleCancel(ctx)
  39. cw.onCancelWasCalled = true
  40. <-cw.unwatchChan
  41. case <-cw.unwatchChan:
  42. }
  43. }()
  44. } else {
  45. cw.watchInProgress = false
  46. }
  47. }
  48. // Unwatch stops watching the previously watched context. If the onCancel function passed to NewContextWatcher was
  49. // called then onUnwatchAfterCancel will also be called.
  50. func (cw *ContextWatcher) Unwatch() {
  51. cw.lock.Lock()
  52. defer cw.lock.Unlock()
  53. if cw.watchInProgress {
  54. cw.unwatchChan <- struct{}{}
  55. if cw.onCancelWasCalled {
  56. cw.handler.HandleUnwatchAfterCancel()
  57. }
  58. cw.watchInProgress = false
  59. }
  60. }
  61. type Handler interface {
  62. // HandleCancel is called when the context that a ContextWatcher is currently watching is canceled. canceledCtx is the
  63. // context that was canceled.
  64. HandleCancel(canceledCtx context.Context)
  65. // HandleUnwatchAfterCancel is called when a ContextWatcher that called HandleCancel on this Handler is unwatched.
  66. HandleUnwatchAfterCancel()
  67. }