forked from centrifugal/centrifuge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhub.go
476 lines (415 loc) · 10.9 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
package centrifuge
import (
"context"
"sync"
"github.com/centrifugal/centrifuge/internal/clientproto"
"github.com/centrifugal/centrifuge/internal/prepared"
"github.com/centrifugal/centrifuge/internal/recovery"
"github.com/centrifugal/protocol"
)
// Hub manages client connections.
type Hub struct {
mu sync.RWMutex
// match client ID with actual client connection.
conns map[string]*Client
// registry to hold active client connections grouped by user.
users map[string]map[string]struct{}
// registry to hold active subscriptions of clients to channels.
subs map[string]map[string]struct{}
}
// newHub initializes Hub.
func newHub() *Hub {
return &Hub{
conns: make(map[string]*Client),
users: make(map[string]map[string]struct{}),
subs: make(map[string]map[string]struct{}),
}
}
const (
// hubShutdownSemaphoreSize limits graceful disconnects concurrency on
// node shutdown.
hubShutdownSemaphoreSize = 128
)
// shutdown unsubscribes users from all channels and disconnects them.
func (h *Hub) shutdown(ctx context.Context) error {
advice := DisconnectShutdown
// Limit concurrency here to prevent resource usage burst on shutdown.
sem := make(chan struct{}, hubShutdownSemaphoreSize)
h.mu.RLock()
// At this moment node won't accept new client connections so we can
// safely copy existing clients and release lock.
clients := make([]*Client, 0, len(h.conns))
for _, client := range h.conns {
clients = append(clients, client)
}
h.mu.RUnlock()
closeFinishedCh := make(chan struct{}, len(clients))
finished := 0
if len(clients) == 0 {
return nil
}
for _, client := range clients {
select {
case sem <- struct{}{}:
case <-ctx.Done():
return ctx.Err()
}
go func(cc *Client) {
defer func() { <-sem }()
defer func() { closeFinishedCh <- struct{}{} }()
_ = cc.Close(advice)
}(client)
}
for {
select {
case <-closeFinishedCh:
finished++
if finished == len(clients) {
return nil
}
case <-ctx.Done():
return ctx.Err()
}
}
}
func (h *Hub) disconnect(user string, reconnect bool) error {
userConnections := h.userConnections(user)
advice := DisconnectForceNoReconnect
if reconnect {
advice = DisconnectForceReconnect
}
for _, c := range userConnections {
go func(cc *Client) {
_ = cc.Close(advice)
}(c)
}
return nil
}
func (h *Hub) unsubscribe(user string, ch string, opts ...UnsubscribeOption) error {
userConnections := h.userConnections(user)
for _, c := range userConnections {
err := c.Unsubscribe(ch, opts...)
if err != nil {
return err
}
}
return nil
}
// add adds connection into clientHub connections registry.
func (h *Hub) add(c *Client) error {
h.mu.Lock()
defer h.mu.Unlock()
uid := c.ID()
user := c.UserID()
h.conns[uid] = c
if _, ok := h.users[user]; !ok {
h.users[user] = make(map[string]struct{})
}
h.users[user][uid] = struct{}{}
return nil
}
// Remove removes connection from clientHub connections registry.
func (h *Hub) remove(c *Client) error {
h.mu.Lock()
defer h.mu.Unlock()
uid := c.ID()
user := c.UserID()
delete(h.conns, uid)
// try to find connection to delete, return early if not found.
if _, ok := h.users[user]; !ok {
return nil
}
if _, ok := h.users[user][uid]; !ok {
return nil
}
// actually remove connection from hub.
delete(h.users[user], uid)
// clean up users map if it's needed.
if len(h.users[user]) == 0 {
delete(h.users, user)
}
return nil
}
// userConnections returns all connections of user with specified UserID.
func (h *Hub) userConnections(userID string) map[string]*Client {
h.mu.RLock()
defer h.mu.RUnlock()
userConnections, ok := h.users[userID]
if !ok {
return map[string]*Client{}
}
conns := make(map[string]*Client, len(userConnections))
for uid := range userConnections {
c, ok := h.conns[uid]
if !ok {
continue
}
conns[uid] = c
}
return conns
}
// addSub adds connection into clientHub subscriptions registry.
func (h *Hub) addSub(ch string, c *Client) (bool, error) {
h.mu.Lock()
defer h.mu.Unlock()
uid := c.ID()
h.conns[uid] = c
_, ok := h.subs[ch]
if !ok {
h.subs[ch] = make(map[string]struct{})
}
h.subs[ch][uid] = struct{}{}
if !ok {
return true, nil
}
return false, nil
}
// removeSub removes connection from clientHub subscriptions registry.
func (h *Hub) removeSub(ch string, c *Client) (bool, error) {
h.mu.Lock()
defer h.mu.Unlock()
uid := c.ID()
// try to find subscription to delete, return early if not found.
if _, ok := h.subs[ch]; !ok {
return true, nil
}
if _, ok := h.subs[ch][uid]; !ok {
return true, nil
}
// actually remove subscription from hub.
delete(h.subs[ch], uid)
// clean up subs map if it's needed.
if len(h.subs[ch]) == 0 {
delete(h.subs, ch)
return true, nil
}
return false, nil
}
// broadcastPublication sends message to all clients subscribed on channel.
func (h *Hub) broadcastPublication(channel string, pub *protocol.Publication, chOpts *ChannelOptions) error {
useSeqGen := hasFlag(CompatibilityFlags, UseSeqGen)
if useSeqGen {
pub.Seq, pub.Gen = recovery.UnpackUint64(pub.Offset)
}
h.mu.RLock()
defer h.mu.RUnlock()
// get connections currently subscribed on channel.
channelSubscriptions, ok := h.subs[channel]
if !ok {
return nil
}
var jsonPublicationReply *prepared.Reply
var protobufPublicationReply *prepared.Reply
// Iterate over channel subscribers and send message.
for uid := range channelSubscriptions {
c, ok := h.conns[uid]
if !ok {
continue
}
protoType := c.Transport().Protocol().toProto()
if protoType == protocol.TypeJSON {
if jsonPublicationReply == nil {
// Do not send offset to clients for now.
var offset uint64
if useSeqGen {
offset = pub.Offset
pub.Offset = 0
}
data, err := protocol.GetPushEncoder(protoType).EncodePublication(pub)
if err != nil {
return err
}
if useSeqGen {
pub.Offset = offset
}
messageBytes, err := protocol.GetPushEncoder(protoType).Encode(clientproto.NewPublicationPush(channel, data))
if err != nil {
return err
}
reply := &protocol.Reply{
Result: messageBytes,
}
jsonPublicationReply = prepared.NewReply(reply, protocol.TypeJSON)
}
_ = c.writePublication(channel, pub, jsonPublicationReply, chOpts)
} else if protoType == protocol.TypeProtobuf {
if protobufPublicationReply == nil {
// Do not send offset to clients for now.
var offset uint64
if useSeqGen {
offset = pub.Offset
pub.Offset = 0
}
data, err := protocol.GetPushEncoder(protoType).EncodePublication(pub)
if err != nil {
return err
}
if useSeqGen {
pub.Offset = offset
}
messageBytes, err := protocol.GetPushEncoder(protoType).Encode(clientproto.NewPublicationPush(channel, data))
if err != nil {
return err
}
reply := &protocol.Reply{
Result: messageBytes,
}
protobufPublicationReply = prepared.NewReply(reply, protocol.TypeProtobuf)
}
_ = c.writePublication(channel, pub, protobufPublicationReply, chOpts)
}
}
return nil
}
// broadcastJoin sends message to all clients subscribed on channel.
func (h *Hub) broadcastJoin(channel string, join *protocol.Join) error {
h.mu.RLock()
defer h.mu.RUnlock()
channelSubscriptions, ok := h.subs[channel]
if !ok {
return nil
}
var (
jsonReply *prepared.Reply
protobufReply *prepared.Reply
)
for uid := range channelSubscriptions {
c, ok := h.conns[uid]
if !ok {
continue
}
protoType := c.Transport().Protocol().toProto()
if protoType == protocol.TypeJSON {
if jsonReply == nil {
data, err := protocol.GetPushEncoder(protoType).EncodeJoin(join)
if err != nil {
return err
}
messageBytes, err := protocol.GetPushEncoder(protoType).Encode(clientproto.NewJoinPush(channel, data))
if err != nil {
return err
}
reply := &protocol.Reply{
Result: messageBytes,
}
jsonReply = prepared.NewReply(reply, protocol.TypeJSON)
}
_ = c.writeJoin(channel, jsonReply)
} else if protoType == protocol.TypeProtobuf {
if protobufReply == nil {
data, err := protocol.GetPushEncoder(protoType).EncodeJoin(join)
if err != nil {
return err
}
messageBytes, err := protocol.GetPushEncoder(protoType).Encode(clientproto.NewJoinPush(channel, data))
if err != nil {
return err
}
reply := &protocol.Reply{
Result: messageBytes,
}
protobufReply = prepared.NewReply(reply, protocol.TypeProtobuf)
}
_ = c.writeJoin(channel, protobufReply)
}
}
return nil
}
// broadcastLeave sends message to all clients subscribed on channel.
func (h *Hub) broadcastLeave(channel string, leave *protocol.Leave) error {
h.mu.RLock()
defer h.mu.RUnlock()
channelSubscriptions, ok := h.subs[channel]
if !ok {
return nil
}
var (
jsonReply *prepared.Reply
protobufReply *prepared.Reply
)
for uid := range channelSubscriptions {
c, ok := h.conns[uid]
if !ok {
continue
}
protoType := c.Transport().Protocol().toProto()
if protoType == protocol.TypeJSON {
if jsonReply == nil {
data, err := protocol.GetPushEncoder(protoType).EncodeLeave(leave)
if err != nil {
return err
}
messageBytes, err := protocol.GetPushEncoder(protoType).Encode(clientproto.NewLeavePush(channel, data))
if err != nil {
return err
}
reply := &protocol.Reply{
Result: messageBytes,
}
jsonReply = prepared.NewReply(reply, protocol.TypeJSON)
}
_ = c.writeLeave(channel, jsonReply)
} else if protoType == protocol.TypeProtobuf {
if protobufReply == nil {
data, err := protocol.GetPushEncoder(protoType).EncodeLeave(leave)
if err != nil {
return err
}
messageBytes, err := protocol.GetPushEncoder(protoType).Encode(clientproto.NewLeavePush(channel, data))
if err != nil {
return err
}
reply := &protocol.Reply{
Result: messageBytes,
}
protobufReply = prepared.NewReply(reply, protocol.TypeProtobuf)
}
_ = c.writeLeave(channel, protobufReply)
}
}
return nil
}
// NumClients returns total number of client connections.
func (h *Hub) NumClients() int {
h.mu.RLock()
defer h.mu.RUnlock()
total := 0
for _, clientConnections := range h.users {
total += len(clientConnections)
}
return total
}
// NumUsers returns a number of unique users connected.
func (h *Hub) NumUsers() int {
h.mu.RLock()
defer h.mu.RUnlock()
return len(h.users)
}
// NumChannels returns a total number of different channels.
func (h *Hub) NumChannels() int {
h.mu.RLock()
defer h.mu.RUnlock()
return len(h.subs)
}
// Channels returns a slice of all active channels.
func (h *Hub) Channels() []string {
h.mu.RLock()
defer h.mu.RUnlock()
channels := make([]string, len(h.subs))
i := 0
for ch := range h.subs {
channels[i] = ch
i++
}
return channels
}
// NumSubscribers returns number of current subscribers for a given channel.
func (h *Hub) NumSubscribers(ch string) int {
h.mu.RLock()
defer h.mu.RUnlock()
conns, ok := h.subs[ch]
if !ok {
return 0
}
return len(conns)
}