chore: ⬆️ updated deps
This commit is contained in:
+19
-27
@@ -8,12 +8,13 @@ import (
|
||||
// ContextWatcher watches a context and performs an action when the context is canceled. It can watch one context at a
|
||||
// time.
|
||||
type ContextWatcher struct {
|
||||
handler Handler
|
||||
unwatchChan chan struct{}
|
||||
handler Handler
|
||||
|
||||
lock sync.Mutex
|
||||
watchInProgress bool
|
||||
onCancelWasCalled bool
|
||||
// Lock protects the members below.
|
||||
lock sync.Mutex
|
||||
// Stop is the handle for an "after func". See [context.AfterFunc].
|
||||
stop func() bool
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
// NewContextWatcher returns a ContextWatcher. onCancel will be called when a watched context is canceled.
|
||||
@@ -21,8 +22,7 @@ type ContextWatcher struct {
|
||||
// onCancel called.
|
||||
func NewContextWatcher(handler Handler) *ContextWatcher {
|
||||
cw := &ContextWatcher{
|
||||
handler: handler,
|
||||
unwatchChan: make(chan struct{}),
|
||||
handler: handler,
|
||||
}
|
||||
|
||||
return cw
|
||||
@@ -33,25 +33,16 @@ func (cw *ContextWatcher) Watch(ctx context.Context) {
|
||||
cw.lock.Lock()
|
||||
defer cw.lock.Unlock()
|
||||
|
||||
if cw.watchInProgress {
|
||||
panic("Watch already in progress")
|
||||
if cw.stop != nil {
|
||||
panic("watch already in progress")
|
||||
}
|
||||
|
||||
cw.onCancelWasCalled = false
|
||||
|
||||
if ctx.Done() != nil {
|
||||
cw.watchInProgress = true
|
||||
go func() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
cw.handler.HandleCancel(ctx)
|
||||
cw.onCancelWasCalled = true
|
||||
<-cw.unwatchChan
|
||||
case <-cw.unwatchChan:
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
cw.watchInProgress = false
|
||||
cw.done = make(chan struct{})
|
||||
cw.stop = context.AfterFunc(ctx, func() {
|
||||
cw.handler.HandleCancel(ctx)
|
||||
close(cw.done)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,12 +52,13 @@ func (cw *ContextWatcher) Unwatch() {
|
||||
cw.lock.Lock()
|
||||
defer cw.lock.Unlock()
|
||||
|
||||
if cw.watchInProgress {
|
||||
cw.unwatchChan <- struct{}{}
|
||||
if cw.onCancelWasCalled {
|
||||
if cw.stop != nil {
|
||||
if !cw.stop() {
|
||||
<-cw.done
|
||||
cw.handler.HandleUnwatchAfterCancel()
|
||||
}
|
||||
cw.watchInProgress = false
|
||||
cw.stop = nil
|
||||
cw.done = nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user