-
Notifications
You must be signed in to change notification settings - Fork 0
/
process.go
145 lines (124 loc) · 2.36 KB
/
process.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package process
import (
"context"
"sync"
)
type groupKeyType int
const groupKey groupKeyType = iota
type Process interface {
Done() <-chan struct{}
Err() error
}
type Group interface {
context.Context
Run(func(context.Context) error) Process
Loop(func(context.Context) error) Process
Done() <-chan struct{}
Join() <-chan struct{}
Err() error
}
type process struct {
Context
cancel CancelFunc
}
type group struct {
Context
cancel CancelFunc
join chan struct{}
mu sync.Mutex
processes []Process
}
func NewGroup(ctx context.Context) Group {
groupCtx, groupCancel := WithCancel(ctx)
g := &group{
Context: groupCtx,
cancel: groupCancel,
join: make(chan struct{}),
}
go g.joinAfterDone()
return g
}
func (g *group) joinAfterDone() {
<-g.Context.Done()
g.mu.Lock()
processes := g.processes
g.mu.Unlock()
for _, process := range processes {
<-process.Done()
}
close(g.join)
}
func (g *group) Join() <-chan struct{} {
return g.join
}
func (g *group) Run(f func(ctx context.Context) error) Process {
g.mu.Lock()
defer g.mu.Unlock()
processCtx, processCancel := NewContext()
proc := &process{
Context: processCtx,
cancel: processCancel,
}
select {
case <-g.Context.Done():
processCancel(g.Context.Err())
default:
go func() {
err := f(g)
if err != nil {
g.cancel(err)
processCancel(err)
}
}()
g.processes = append(g.processes, proc)
}
return proc
}
func (g *group) Loop(f func(ctx context.Context) error) Process {
g.mu.Lock()
defer g.mu.Unlock()
processCtx, processCancel := NewContext()
proc := &process{
Context: processCtx,
cancel: processCancel,
}
select {
case <-g.Context.Done():
processCancel(g.Context.Err())
default:
go func() {
for {
err := f(g)
if err != nil {
g.cancel(err)
processCancel(err)
return
}
}
}()
g.processes = append(g.processes, proc)
}
return proc
}
func (g *group) Value(key interface{}) interface{} {
if key == groupKey {
return g
}
return g.Value(key)
}
type traceGroup struct {
Group
trace Context
}
func (t traceGroup) Err() error {
return t.trace.Err()
}
func GroupFromContext(ctx context.Context) Group {
if g, ok := ctx.(*group); ok {
return traceGroup{Group: g, trace: WithTrace(g)}
}
if g, ok := ctx.Value(groupKey).(*group); ok {
return traceGroup{Group: g, trace: WithTrace(g)}
}
return NewGroup(ctx)
}