/
go_channel.go
89 lines (77 loc) · 1.72 KB
/
go_channel.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
package dispatcher
import (
"context"
"errors"
"runtime/trace"
"sync"
"github.com/theoden9014/evbundler"
)
// GoChannel dispatcher by go channel.
type GoChannel struct {
pool evbundler.WorkerPool
resultCh chan *evbundler.Result
metrics evbundler.Metrics
}
// NewGoChannel initialize GoChannel.
func NewGoChannel(pool evbundler.WorkerPool) *GoChannel {
d := &GoChannel{
pool: pool,
resultCh: make(chan *evbundler.Result, pool.Len()),
metrics: evbundler.NewMetrics(),
}
return d
}
// Dispatch dispatches events from a event channel.
func (d *GoChannel) Dispatch(ctx context.Context, evCh chan evbundler.Event) error {
go d.receiveResult(ctx)
return d.dispatch(ctx, evCh)
}
func (d *GoChannel) dispatch(ctx context.Context, evCh chan evbundler.Event) error {
if d.pool.Len() == 0 {
return errors.New("count of workers > 0 in worker pool")
}
var wg sync.WaitGroup
for w := d.pool.Get(); w != nil; w = d.pool.Get() {
w := w
wg.Add(1)
go func() {
defer wg.Done()
d.serveWorker(ctx, w, evCh)
}()
}
<-ctx.Done()
// wait for worker graceful shutdown
wg.Wait()
return ctx.Err()
}
func (d *GoChannel) serveWorker(ctx context.Context, w evbundler.Worker, evCh chan evbundler.Event) {
defer w.Close()
for {
select {
case ev := <-evCh:
func() {
ctx, task := trace.NewTask(ctx, "worker")
defer task.End()
if ev == nil { // close Event channel
return
}
r := w.Process(ctx, ev)
region := trace.StartRegion(ctx, "send result")
d.resultCh <- r
region.End()
}()
case <-ctx.Done():
return
}
}
}
func (d *GoChannel) receiveResult(ctx context.Context) {
for {
select {
case r := <-d.resultCh:
d.metrics.Add(r)
case <-ctx.Done():
return
}
}
}