-
Notifications
You must be signed in to change notification settings - Fork 1
/
route_brick.go
84 lines (73 loc) · 1.45 KB
/
route_brick.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 flow
import (
"github.com/RyouZhang/async-go"
)
type routeItem struct {
method func(*Message) bool
outQueue chan *Message
}
type RouteBrick struct {
name string
lc ILifeCycle
chanSize int
errQueue chan error
outQueues []*routeItem
}
func (b *RouteBrick) Name() string {
return b.name
}
func (b *RouteBrick) AddLifeCycle(lc ILifeCycle) {
b.lc = lc
}
func (b *RouteBrick) Linked(inQueue <-chan *Message) {
go b.loop(inQueue)
}
func (b *RouteBrick) Errors() <-chan error {
return b.errQueue
}
func (b *RouteBrick) RouteOutput(method func(*Message) bool) <-chan *Message {
output := make(chan *Message, b.chanSize)
b.outQueues = append(b.outQueues, &routeItem{
method: method,
outQueue: output,
})
return output
}
func (b *RouteBrick) loop(inQueue <-chan *Message) {
defer func() {
close(b.errQueue)
b.lc.Done()
}()
for msg := range inQueue {
for _, item := range b.outQueues {
if item.method == nil {
continue
}
res, err := async.Safety(func() (interface{}, error) {
res := item.method(msg)
return res, nil
})
if err != nil {
b.errQueue <- err
} else {
if res.(bool) {
item.outQueue <- msg
break
}
}
}
}
for _, item := range b.outQueues {
close(item.outQueue)
}
}
func NewRouteBrick(
name string,
chanSize int) *RouteBrick {
return &RouteBrick{
name: name,
chanSize: chanSize,
outQueues: make([]*routeItem, 0),
errQueue: make(chan error, 8),
}
}