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