-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub.go
236 lines (189 loc) · 4.49 KB
/
hub.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
package hub
import (
"context"
"fmt"
"github.com/efureev/appmod"
"reflect"
"sync"
)
// MessageHub implements publish/subscribe messaging paradigm
type MessageHub interface {
appmod.AppModule
Publish(topicName topic, args ...interface{})
Close(topicName topic)
Subscribe(topicName topic, fn interface{}) error
Unsubscribe(topicName topic, fn interface{}) error
Topics() []topic
Topic(topicName topic) ([]*handler, error)
Wait()
}
type hub struct {
appmod.BaseAppModule
mtx sync.RWMutex
wg sync.WaitGroup
channels channelsMap
}
var instance MessageHub
type topic string
type channelsMap map[topic][]*handler
type handler struct {
ctx context.Context
callback reflect.Value
cancel context.CancelFunc
queue chan []reflect.Value
//queueDone chan error
}
// Publish publishes arguments to the given topic subscribers
func (h *hub) Publish(topicName topic, args ...interface{}) {
rArgs := buildHandlerArgs(args)
h.mtx.RLock()
defer h.mtx.RUnlock()
if hs, ok := h.channels[topicName]; ok {
for _, handler := range hs {
h.wg.Add(1)
handler.queue <- rArgs
}
}
}
// Subscribe subscribes to the given topic
func (h *hub) Subscribe(topicName topic, fn interface{}) error {
if reflect.TypeOf(fn).Kind() != reflect.Func {
return fmt.Errorf("%s is not a reflect.Func", reflect.TypeOf(fn))
}
ctx, cancel := context.WithCancel(context.Background())
hndr := &handler{
callback: reflect.ValueOf(fn),
ctx: ctx,
cancel: cancel,
queue: make(chan []reflect.Value),
//queueDone: make(chan error),
}
go func() {
for {
select {
case args, ok := <-hndr.queue:
if ok {
hndr.callback.Call(args)
/*res := hndr.callback.Call(args)
var err error
if len(res) > 0 {
if v := res[0].Interface(); v != nil {
err = v.(error)
}
}
*/
go func() {
h.wg.Done()
}()
/*go func(done chan<- error) {
done <- err
}(hndr.queueDone)*/
}
/*case _, ok := <-hndr.queueDone:
if ok {
h.wg.Done()
}*/
case <-hndr.ctx.Done():
return
}
}
}()
h.mtx.Lock()
defer h.mtx.Unlock()
h.channels[topicName] = append(h.channels[topicName], hndr)
return nil
}
// Unsubscribe unsubscribe handler from the given topic
func (h *hub) Unsubscribe(topicName topic, fn interface{}) error {
h.mtx.Lock()
defer h.mtx.Unlock()
if _, ok := h.channels[topicName]; ok {
rv := reflect.ValueOf(fn)
for i, ch := range h.channels[topicName] {
if ch.callback == rv {
ch.cancel()
close(ch.queue)
//close(ch.queueDone)
h.channels[topicName] = append(h.channels[topicName][:i], h.channels[topicName][i+1:]...)
}
}
return nil
}
return fmt.Errorf("topic %s doesn't exist", topicName)
}
// Topics return topic list
func (h *hub) Topics() (tt []topic) {
h.mtx.Lock()
defer h.mtx.Unlock()
for t := range h.channels {
tt = append(tt, t)
}
return tt
}
// Topic return handlers array subscribe to this topic
func (h *hub) Topic(topicName topic) ([]*handler, error) {
h.mtx.Lock()
defer h.mtx.Unlock()
if _, ok := h.channels[topicName]; ok {
return h.channels[topicName], nil
}
return nil, fmt.Errorf("topic %s doesn't exist", topicName)
}
// Wait until all message will send
func (h *hub) Wait() {
h.wg.Wait()
}
// Close unsubscribe all handlers from given topic
func (h *hub) Close(topicName topic) {
h.mtx.Lock()
defer h.mtx.Unlock()
if _, ok := h.channels[topicName]; ok {
for _, h := range h.channels[topicName] {
h.cancel()
close(h.queue)
//close(h.queueDone)
}
delete(h.channels, topicName)
return
}
}
func (h *hub) Destroy() error {
for t := range h.channels {
h.Close(t)
}
return nil
}
func buildHandlerArgs(args []interface{}) []reflect.Value {
reflectedArgs := make([]reflect.Value, 0)
for _, arg := range args {
reflectedArgs = append(reflectedArgs, reflect.ValueOf(arg))
}
return reflectedArgs
}
// Get return existing instance of Hub or create it and return
func Get() MessageHub {
if instance == nil {
instance = New()
}
return instance
}
// New create and return new instance of Hub
func New() MessageHub {
h := &hub{channels: make(channelsMap)}
h.SetConfig(appmod.NewConfig(`Hub`, `v1.0.0`))
return h
}
// Sub subscribe listeners
func Sub(topicName string, fn interface{}) error {
return Get().Subscribe(topic(topicName), fn)
}
// Event dispatch event
func Event(topicName string, args ...interface{}) {
Get().Publish(topic(topicName), args...)
}
// Reset instance
func Reset() MessageHub {
Get().Destroy()
instance = nil
return Get()
}