-
Notifications
You must be signed in to change notification settings - Fork 0
/
runner.go
84 lines (70 loc) · 1.25 KB
/
runner.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
package runner
import (
"context"
"sync"
)
type Runner interface {
Run(func() error)
Stopping() <-chan struct{}
Context() context.Context
Wait() error
Stop()
Errors() []error
}
type runner struct {
stoppingMutex sync.Mutex
stopping chan struct{}
errorsMutex sync.Mutex
errors []error
wg sync.WaitGroup
ctx context.Context
cancelCtx func()
}
func New() Runner {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
return &runner{
stopping: make(chan struct{}),
ctx: ctx,
cancelCtx: cancel,
}
}
func (r *runner) Stop() {
// So we don't close an already closed channel.
r.stoppingMutex.Lock()
select {
case <-r.stopping:
default:
close(r.stopping)
r.cancelCtx()
}
r.stoppingMutex.Unlock()
}
func (r *runner) Run(f func() error) {
r.wg.Add(1)
go func() {
if err := f(); err != nil {
r.errorsMutex.Lock()
r.errors = append(r.errors, err)
r.errorsMutex.Unlock()
r.Stop()
}
r.wg.Done()
}()
}
func (r *runner) Context() context.Context {
return r.ctx
}
func (r *runner) Stopping() <-chan struct{} {
return r.stopping
}
func (r *runner) Wait() error {
r.wg.Wait()
if len(r.errors) > 0 {
return r.errors[0]
}
return nil
}
func (r *runner) Errors() []error {
return r.errors
}