-
Notifications
You must be signed in to change notification settings - Fork 1
/
board.go
111 lines (99 loc) · 2.14 KB
/
board.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
package flow
import (
"errors"
"fmt"
"sync"
)
type Board struct {
name string
bricks map[string]IBrick
errHandler func(string, error)
lc ILifeCycle
}
func NewBoard(name string) *Board {
return &Board{
name: name,
bricks: make(map[string]IBrick),
lc: &sync.WaitGroup{},
}
}
func NewBoardWithLifeCycle(name string, lc ILifeCycle) *Board {
if lc == nil {
return nil
}
return &Board{
name: name,
bricks: make(map[string]IBrick),
lc: lc,
}
}
func (b *Board) SetErrHandler(errHandler func(string, error)) {
b.errHandler = errHandler
}
func (b *Board) Add(bricks ...IBrick) *Board {
for _, brick := range bricks {
_, ok := b.bricks[brick.Name()]
if false == ok {
b.bricks[brick.Name()] = brick
// add life cycle
b.lc.Add(1)
brick.AddLifeCycle(b.lc)
if _, ok := brick.(IError); ok {
go b.onError(brick.(IBrick).Name(), brick.(IError).Errors())
}
} else {
panic(errors.New("Duplicate Brick Name:" + brick.(IBrick).Name()))
}
}
return b
}
func (b *Board) Connect(outName string, inName string) *Board {
out, ok := b.bricks[outName]
if false == ok {
panic(errors.New(fmt.Sprintf("Invalid Brick %s", outName)))
}
in, ok := b.bricks[inName]
if false == ok {
panic(errors.New(fmt.Sprintf("Invalid Brick %s", inName)))
}
in.(IInput).Linked(out.(IOutput).Output())
return b
}
func (b *Board) RouteConnect(outName string, inName string, method func(*Message) bool) *Board {
out, ok := b.bricks[outName]
if false == ok {
panic(errors.New(fmt.Sprintf("Invalid Brick %s", outName)))
}
in, ok := b.bricks[inName]
if false == ok {
panic(errors.New(fmt.Sprintf("Invalid Brick %s", inName)))
}
in.(IInput).Linked(out.(IRoute).RouteOutput(method))
return b
}
func (b *Board) Start() {
for _, brick := range b.bricks {
ob, ok := brick.(IEntry)
if ok {
go func() {
ob.Start()
}()
}
}
}
func (b *Board) Stop() {
for _, b := range b.bricks {
ob, ok := b.(IEntry)
if ok {
ob.Stop()
}
}
b.lc.Wait()
}
func (b *Board) onError(name string, inQueue <-chan error) {
for err := range inQueue {
if b.errHandler != nil {
b.errHandler(b.name+"/"+name, err)
}
}
}