forked from trustmaster/goflow
/
component.go
201 lines (182 loc) · 5.21 KB
/
component.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
// The flow package is a framework for Flow-based programming in Go.
package flow
import (
"reflect"
"sync"
)
const (
ComponentModeUndefined = iota
ComponentModeAsync
ComponentModeSync
)
var DefaultComponentMode = ComponentModeAsync
// Component is a generic flow component that has to be contained in concrete components.
// It stores network-specific information.
type Component struct {
// Net is a pointer to network to inform it when the process is started and over
// or to change its structure at run time.
Net *Graph
Mode int8
}
// Initalizable is the interface implemented by components/graphs with custom initialization code.
type Initializable interface {
Init()
}
// Finalizable is the interface implemented by components/graphs with extra finalization code.
type Finalizable interface {
Finish()
}
// Shutdowner is the interface implemented by components overriding default Shutdown() behavior.
type Shutdowner interface {
Shutdown()
}
// RunProc runs event handling loop on component ports.
// It returns true on success or panics with error message and returns false on error.
func RunProc(c interface{}) bool {
// Check if passed interface is a valid pointer to struct
v := reflect.ValueOf(c)
if v.Kind() != reflect.Ptr || v.IsNil() {
panic("Argument of flow.Run() is not a valid pointer")
return false
}
vp := v
v = v.Elem()
if v.Kind() != reflect.Struct {
panic("Argument of flow.Run() is not a valid pointer to structure. Got type: " + vp.Type().Name())
return false
}
t := v.Type()
// Get internal state lock if available
hasLock := false
var locker sync.Locker
if lockField := v.FieldByName("StateLock"); lockField.IsValid() && lockField.Elem().IsValid() {
locker, hasLock = lockField.Interface().(sync.Locker)
}
// Call user init function if exists
if initable, ok := c.(Initializable); ok {
initable.Init()
}
// A group to wait for all inputs to be closed
inputsClose := new(sync.WaitGroup)
// A group to wait for all recv handlers to finish
handlersDone := new(sync.WaitGroup)
emptyArr := [0]reflect.Value{}
empty := emptyArr[:]
// Get the embedded flow.Component
vCom := v.FieldByName("Component")
isComponent := vCom.IsValid() && vCom.Type().Name() == "Component"
// Get the component mode
componentMode := DefaultComponentMode
if isComponent {
if vComMode := vCom.FieldByName("Mode"); vComMode.IsValid() {
componentMode = int(vComMode.Int())
}
}
// Bind channel event handlers
// Iterate over struct fields
for i := 0; i < t.NumField(); i++ {
fv := v.Field(i)
ff := t.Field(i)
ft := fv.Type()
// Detect control channels
if fv.IsValid() && fv.Kind() == reflect.Chan && !fv.IsNil() && (ft.ChanDir()&reflect.RecvDir) != 0 {
// Bind handlers for an input channel
onClose := vp.MethodByName("On" + ff.Name + "Close")
hasClose := onClose.IsValid()
onRecv := vp.MethodByName("On" + ff.Name)
hasRecv := onRecv.IsValid()
if hasClose || hasRecv {
// Add the input to the wait group
inputsClose.Add(1)
// Listen on an input channel
go func() {
for {
val, ok := fv.Recv()
if !ok {
// The channel closed
if hasClose {
// Lock the state and call OnClose handler
if hasLock {
locker.Lock()
}
onClose.Call(empty)
if hasLock {
locker.Unlock()
}
}
inputsClose.Done()
return
}
if hasRecv {
// Call the receival handler for this channel
handlersDone.Add(1)
if componentMode == ComponentModeAsync {
go func() {
if hasLock {
locker.Lock()
}
valArr := [1]reflect.Value{val}
onRecv.Call(valArr[:])
if hasLock {
locker.Unlock()
}
handlersDone.Done()
}()
} else {
valArr := [1]reflect.Value{val}
onRecv.Call(valArr[:])
handlersDone.Done()
}
}
}
}()
}
}
}
go func() {
// Wait for all inputs to be closed
inputsClose.Wait()
// Wait all inport handlers to finish their job
handlersDone.Wait()
// Call shutdown handler (user or default)
shutdownProc(c)
// Get the embedded flow.Component and check if it belongs to a network
if isComponent {
if vNet := vCom.FieldByName("Net"); vNet.IsValid() && !vNet.IsNil() {
if vNetCtr, hasNet := vNet.Interface().(netController); hasNet {
// Remove the instance from the network's WaitGroup
vNetCtr.getWait().Done()
}
}
}
}()
return true
}
// closePorts closes all output channels of a process.
func closePorts(c interface{}) {
v := reflect.ValueOf(c).Elem()
t := v.Type()
// Iterate over struct fields
for i := 0; i < t.NumField(); i++ {
fv := v.Field(i)
ft := fv.Type()
// Detect and close send-only channels
if fv.IsValid() && fv.Kind() == reflect.Chan && (ft.ChanDir()&reflect.SendDir) != 0 && (ft.ChanDir()&reflect.RecvDir) == 0 {
fv.Close()
}
}
}
// shutdownProc represents a standard process shutdown procedure.
func shutdownProc(c interface{}) {
if s, ok := c.(Shutdowner); ok {
// Custom shutdown behavior
s.Shutdown()
} else {
// Call user finish function if exists
if finable, ok := c.(Finalizable); ok {
finable.Finish()
}
// Close all output ports
closePorts(c)
}
}