forked from olahol/melody
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhub.go
290 lines (271 loc) · 6.74 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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package melody
import (
"encoding/json"
"log"
"sync"
"time"
"unsafe"
"github.com/gomodule/redigo/redis"
)
var (
gRedisConn = func(uri string) (redis.Conn, error) {
redisConn, err := redis.Dial("tcp", uri,
redis.DialConnectTimeout(time.Duration(10*time.Second)),
redis.DialReadTimeout(time.Duration(0)),
redis.DialWriteTimeout(time.Duration(0)))
return redisConn, err
}
forkInHub = true
routeMapping = true
bucketDebugDump = false
)
type hub struct {
sessions map[*Session]bool
broadcast []chan *envelope
register chan *Session
exit chan *envelope
unregister chan *Session
persistRecv []chan bool
open bool
rwmutex *sync.RWMutex
redisPool *redis.Pool
redisConn redis.Conn
pubRedisConn redis.Conn
pubSubConn []*redis.PubSubConn
regMutex *sync.RWMutex
allocConnMutex *sync.Mutex
routeMaps []map[interface{}]map[*Session]*Session
}
func newRedisPool() *redis.Pool {
statRedis := newStatsRedis(RedisURL)
numRedisConn := statRedis.MaxActive
if DebugRedisPoolConn != 0 {
numRedisConn = DebugRedisPoolConn
}
log.Println("Configured max active redis conn:", numRedisConn)
return &redis.Pool{
MaxIdle: statRedis.MaxIdle,
MaxActive: numRedisConn,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", statRedis.URL,
redis.DialConnectTimeout(time.Duration(statRedis.ConnectTimeout)),
redis.DialReadTimeout(time.Duration(statRedis.ReadTimeout)),
redis.DialWriteTimeout(time.Duration(statRedis.WriteTimeout)))
if err != nil {
log.Println(err)
return nil, err
}
return c, nil
},
// Use the TestOnBorrow function to check the health of an idle connection
// before the connection is returned to the application.
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := c.Do("PING")
return err
},
IdleTimeout: 300 * time.Second,
// If Wait is true and the pool is at the MaxActive limit,
// then Get() waits for a connection to be returned to the pool before returning
Wait: true,
}
}
func newHub() *hub {
redisPool := newRedisPool()
redisURI := RedisURL
log.Printf("Connect to redis server:[%s]\n", redisURI)
log.Println("Configured max recv redis conn:", RedisRcvConn)
routeMaps := make([]map[interface{}]map[*Session]*Session, RedisRcvConn)
pubSubConn := make([]*redis.PubSubConn, RedisRcvConn)
broadcast := make([]chan *envelope, RedisRcvConn)
persistRecv := make([]chan bool, RedisRcvConn)
regRefMaps := make([]map[string]*int, RedisRcvConn)
for i := 0; i < RedisRcvConn; i++ {
redisConn, err := gRedisConn(redisURI)
pubSubConn[i] = &redis.PubSubConn{Conn: redisConn}
if err != nil {
panic(err)
}
broadcast[i] = make(chan *envelope)
regRefMaps[i] = make(map[string]*int)
routeMaps[i] = make(map[interface{}]map[*Session]*Session)
persistRecv[i] = make(chan bool)
}
//defer redisConn.Close()
//defer pubSubConn.Close()
return &hub{
sessions: make(map[*Session]bool),
broadcast: broadcast,
register: make(chan *Session),
unregister: make(chan *Session),
exit: make(chan *envelope),
persistRecv: persistRecv,
open: true,
rwmutex: &sync.RWMutex{},
redisPool: redisPool,
pubSubConn: pubSubConn,
regMutex: &sync.RWMutex{},
routeMaps: routeMaps,
}
}
func (h *hub) run(index int) {
loop:
for {
select {
case s := <-h.register:
h.rwmutex.Lock()
h.sessions[s] = true
h.rwmutex.Unlock()
case s := <-h.unregister:
h.rwmutex.Lock()
if _, ok := h.sessions[s]; ok {
delete(h.sessions, s)
}
h.rwmutex.Unlock()
case m := <-h.broadcast[index]:
handler := func() {
h.rwmutex.RLock()
if false {
log.Println(m)
}
if routeMapping {
h.regMutex.Lock()
for s := range h.routeMaps[index][m.To] {
if m.filter != nil {
if m.filter(s) {
s.writeMessage(m)
}
} else {
s.writeMessage(m)
}
}
h.regMutex.Unlock()
} else {
for s := range h.sessions {
if m.filter != nil {
if m.filter(s) {
s.writeMessage(m)
}
} else {
s.writeMessage(m)
}
}
}
h.rwmutex.RUnlock()
}
if forkInHub {
go handler()
} else {
handler()
}
case m := <-h.exit:
h.rwmutex.Lock()
for s := range h.sessions {
s.writeMessage(m)
delete(h.sessions, s)
s.Close()
}
h.open = false
h.rwmutex.Unlock()
for i := 0; i < RedisRcvConn; i++ {
h.persistRecv[i] <- false
}
break loop
}
}
}
func (h *hub) closed() bool {
h.rwmutex.RLock()
defer h.rwmutex.RUnlock()
return !h.open
}
func (h *hub) len() int {
h.rwmutex.RLock()
defer h.rwmutex.RUnlock()
return len(h.sessions)
}
func (h *hub) registered(session *Session) bool {
h.rwmutex.RLock()
defer h.rwmutex.RUnlock()
return h.sessions[session]
}
func (h *hub) readRedisConn(index int) {
if bucketDebugDump {
go func() {
for {
h.regMutex.Lock()
if len(h.routeMaps[index]) > 0 {
log.Println("-------------------------------------")
log.Printf("h.routeMaps[%d]:%d", index, len(h.routeMaps[index]))
}
h.regMutex.Unlock()
time.Sleep(5 * time.Second)
}
}()
}
for {
switch v := h.pubSubConn[index].Receive().(type) {
case redis.Message:
handler := func() {
e := &envelope{}
json.Unmarshal(v.Data, e)
message := &envelope{T: e.T, Msg: []byte(e.Msg), filter: func(s *Session) bool {
if e.From != 0 && e.From == uintptr(unsafe.Pointer(s)) {
return false
}
if routeMapping {
return true
}
s.regMapMutex.RLock()
for _, element := range s.RegMap {
if element == e.To {
s.regMapMutex.RUnlock()
return true
}
}
s.regMapMutex.RUnlock()
return false
}, To: e.To}
h.broadcast[index] <- message
}
if forkInHub {
go handler()
} else {
handler()
}
case redis.Subscription:
if EnableDebug {
log.Printf("subscription message:[%s] count:[%d] recvThread[%d]\n", v.Channel, v.Count, index)
}
case error:
log.Println("error pub/sub on connection, delivery has stopped, err[", v, "]")
var persistRecv = true
select {
case persistRecv = <-h.persistRecv[index]:
case <-time.After(time.Duration(RedisRcvRetryInterval) * time.Second):
}
if persistRecv {
redisURI := RedisURL
redisConn, err := gRedisConn(redisURI)
h.pubSubConn[index] = &redis.PubSubConn{Conn: redisConn}
if err == nil {
log.Println("Re-connect redis")
} else {
continue
}
h.regMutex.Lock()
for key := range h.routeMaps[index] {
if err := h.pubSubConn[index].Subscribe(key); err != nil {
h.regMutex.Unlock()
panic(err)
}
}
h.regMutex.Unlock()
} else {
return
}
}
}
}