-
Notifications
You must be signed in to change notification settings - Fork 3
/
group.go
96 lines (74 loc) · 1.44 KB
/
group.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
package service
import (
"context"
"os"
"golang.org/x/sync/errgroup"
)
type runFn func(ctx context.Context) error
type Group struct {
rootCtx context.Context
rootCancel func()
startedCh chan struct{}
setupCh chan struct{}
setups []runFn
processes []runFn
}
func NewSignals(sig ...os.Signal) *Group {
return NewCtx(signalCtx(context.Background(), sig...))
}
func NewCtx(ctx context.Context) *Group {
ctx, cancel := context.WithCancel(ctx)
return &Group{
rootCtx: ctx,
rootCancel: cancel,
startedCh: make(chan struct{}),
setupCh: make(chan struct{}),
}
}
func (g *Group) Setup(fn func(ctx context.Context) error) {
g.setups = append(g.setups, fn)
}
func (g *Group) Register(fn func(ctx context.Context) error) {
g.processes = append(g.processes, fn)
}
func (g *Group) Start() error {
if g.started() {
return nil
}
close(g.startedCh)
for i := range g.setups {
fn := g.setups[i]
if err := fn(g.rootCtx); err != nil {
return err
}
}
close(g.setupCh)
errGrp, ctx := errgroup.WithContext(g.rootCtx)
for i := range g.processes {
fn := g.processes[i]
errGrp.Go(func() error {
return fn(ctx)
})
}
return errGrp.Wait()
}
func (g *Group) Close() error {
g.rootCancel()
return nil
}
func (g *Group) started() bool {
select {
case <-g.startedCh:
return true
default:
return false
}
}
func (g *Group) setup() bool {
select {
case <-g.setupCh:
return true
default:
return false
}
}