-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathroutine.go
254 lines (223 loc) · 4.97 KB
/
routine.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package routine
import (
"context"
"fmt"
"io"
"os"
"runtime/trace"
"sync"
"github.com/x-mod/errors"
"github.com/x-mod/event"
"github.com/x-mod/sigtrap"
)
type options struct {
args []interface{}
prepare Executor
cleanup Executor
childs []Executor
traceOut io.Writer
sigtraps []*SigTrap
csignals []os.Signal
}
//Opt interface
type Opt func(*options)
//Arguments Opt for Main
func Arguments(args ...interface{}) Opt {
return func(opts *options) {
opts.args = args
}
}
type SigHandler func()
type SigTrap struct {
sig os.Signal
handler SigHandler
}
//Signal Opt for Main
func Signal(sig os.Signal, handler SigHandler) Opt {
return func(opts *options) {
if handler != nil {
opts.sigtraps = append(opts.sigtraps, &SigTrap{sig: sig, handler: handler})
}
}
}
//CancelSignals Opt for Main
func CancelSignals(sigs ...os.Signal) Opt {
return func(opts *options) {
opts.csignals = append(opts.csignals, sigs...)
}
}
//Prepare Opt for Main
func Prepare(exec Executor) Opt {
return func(opts *options) {
opts.prepare = exec
}
}
//Execute Opt for Main
func Go(exec Executor) Opt {
return func(opts *options) {
if exec != nil {
opts.childs = append(opts.childs, exec)
}
}
}
//Cleanup Opt for Main
func Cleanup(exec Executor) Opt {
return func(opts *options) {
opts.cleanup = exec
}
}
//Trace support
func Trace(wr io.Writer) Opt {
return func(opts *options) {
opts.traceOut = wr
}
}
//Routine Definition
type Routine struct {
opts *options
exec Executor
group sync.WaitGroup
caps *sigtrap.Capture
close chan struct{}
serving *event.Event
stopped *event.Event
}
//New a routine instance
func New(exec Executor, opts ...Opt) *Routine {
mopts := &options{
args: []interface{}{},
sigtraps: []*SigTrap{},
csignals: []os.Signal{},
}
for _, opt := range opts {
opt(mopts)
}
routine := &Routine{
opts: mopts,
exec: exec,
close: make(chan struct{}),
serving: event.New(),
stopped: event.New(),
}
return routine
}
//Execute running the routine
func (r *Routine) Execute(ctx context.Context) error {
if ctx == nil {
return errors.New("context required")
}
if err := r.prepare(ctx); err != nil {
return err
}
defer r.cleanup(ctx)
ctx, task := trace.NewTask(ctx, "main/Go")
defer task.End()
//ctx, cancel
ctx, cancel := context.WithCancel(ctx)
defer cancel()
//argments
if len(r.opts.args) > 0 {
ctx = WithArgments(ctx, r.opts.args...)
}
//signals
if len(r.opts.csignals) > 0 {
handler := SigHandler(cancel)
for _, sig := range r.opts.csignals {
r.opts.sigtraps = append(r.opts.sigtraps, &SigTrap{sig: sig, handler: handler})
}
}
if len(r.opts.sigtraps) > 0 {
sopts := make([]sigtrap.CaptureOpt, 0, len(r.opts.sigtraps))
for _, trap := range r.opts.sigtraps {
sopts = append(sopts, sigtrap.Trap(trap.sig, sigtrap.Handler(trap.handler)))
}
r.caps = sigtrap.New(sopts...)
r.childGo("sigtrap", ctx, ExecutorFunc(r.caps.Serve))
}
// executor
ch := r.mainGo(ctx, r.exec)
// go executors
for _, exec := range r.opts.childs {
r.childGo("child", ctx, exec)
}
// events
defer r.stopped.Fire()
r.serving.Fire()
// signals outside
select {
case <-ctx.Done():
trace.Logf(ctx, "routine", "context done: %v", ctx.Err())
return ctx.Err()
case err := <-ch:
trace.Logf(ctx, "routine", "main executed: %v", err)
return err
case <-r.close:
trace.Logf(ctx, "routine", "close invoked")
return nil
}
}
func (r *Routine) Serving() <-chan struct{} {
return r.serving.Done()
}
//Stop trigger the routine to stop
func (r *Routine) Close() <-chan struct{} {
if r.serving.HasFired() {
close(r.close)
r.group.Wait()
return r.stopped.Done()
}
return event.Done()
}
func (r *Routine) prepare(ctx context.Context) error {
if r.opts.traceOut != nil {
if err := trace.Start(r.opts.traceOut); err != nil {
return errors.Annotate(err, "trace start")
}
}
if r.opts.prepare != nil {
ctx, task := trace.NewTask(ctx, "prepare")
defer task.End()
if err := r.opts.prepare.Execute(ctx); err != nil {
trace.Logf(ctx, "routine", "prepare failed: %v", err)
return err
}
}
return nil
}
func (r *Routine) cleanup(ctx context.Context) {
r.group.Wait()
if r.opts.cleanup != nil {
ctx, task := trace.NewTask(ctx, "cleanup")
defer task.End()
if err := r.opts.cleanup.Execute(ctx); err != nil {
trace.Logf(ctx, "routine", "cleanup failed: %v", err)
}
}
if trace.IsEnabled() {
trace.Stop()
}
}
func (r *Routine) mainGo(ctx context.Context, exec Executor) chan error {
ch := make(chan error, 1)
r.group.Add(1)
go func() {
defer r.group.Done()
trace.WithRegion(ctx, "Executor", func() {
ch <- exec.Execute(ctx)
})
}()
return ch
}
func (r *Routine) childGo(name string, ctx context.Context, exec Executor) chan error {
ctx, task := trace.NewTask(ctx, fmt.Sprintf("%s/Go", name))
ch := make(chan error, 1)
r.group.Add(1)
go func() {
defer r.group.Done()
defer task.End()
trace.WithRegion(ctx, "Executor", func() {
ch <- exec.Execute(ctx)
})
}()
return ch
}