/
waiter.go
97 lines (78 loc) · 1.71 KB
/
waiter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package waiter
import (
"context"
"os"
"os/signal"
"syscall"
"golang.org/x/sync/errgroup"
)
type (
WaitFunc func(ctx context.Context) error
CleanupFunc func()
Waiter interface {
// Add a function to wait for
Add(fns ...WaitFunc)
// Cleanup with a function after waiting
Cleanup(fns ...CleanupFunc)
Wait() error
Context() context.Context
CancelFunc() context.CancelFunc
}
waiter struct {
ctx context.Context
waitFuncs []WaitFunc
cleanupFuncs []CleanupFunc
cancel context.CancelFunc
}
waiterCfg struct {
parentCtx context.Context
catchSignals bool
}
)
func New(options ...WaiterOption) Waiter {
cfg := &waiterCfg{
parentCtx: context.Background(),
catchSignals: false,
}
for _, option := range options {
option(cfg)
}
w := &waiter{
waitFuncs: []WaitFunc{},
cleanupFuncs: []CleanupFunc{},
}
w.ctx, w.cancel = context.WithCancel(cfg.parentCtx)
if cfg.catchSignals {
w.ctx, w.cancel = signal.NotifyContext(w.ctx, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
}
return w
}
func (w *waiter) Add(fns ...WaitFunc) {
w.waitFuncs = append(w.waitFuncs, fns...)
}
func (w *waiter) Cleanup(fns ...CleanupFunc) {
w.cleanupFuncs = append(w.cleanupFuncs, fns...)
}
func (w *waiter) Wait() (err error) {
g, ctx := errgroup.WithContext(w.ctx)
g.Go(func() error {
<-ctx.Done()
w.cancel()
return nil
})
for _, fn := range w.waitFuncs {
waitFunc := fn
g.Go(func() error { return waitFunc(ctx) })
}
for _, fn := range w.cleanupFuncs {
cleanupFunc := fn
defer cleanupFunc()
}
return g.Wait()
}
func (w *waiter) Context() context.Context {
return w.ctx
}
func (w *waiter) CancelFunc() context.CancelFunc {
return w.cancel
}