Debian Codegraph @

hub.go

raw
1 package centrifuge
2
3 import (
4 "context"
5 "sync"
6
7 "github.com/centrifugal/centrifuge/internal/clientproto"
8 "github.com/centrifugal/centrifuge/internal/prepared"
9 "github.com/centrifugal/centrifuge/internal/recovery"
10
11 "github.com/centrifugal/protocol"
12 )
13
14 const numHubShards = 64
15
16 // Hub tracks Client connections on the current Node.
17 type Hub struct {
18 connShards [numHubShards]*connShard
19 subShards [numHubShards]*subShard
20 }
21
22 // newHub initializes Hub.
23 func newHub() *Hub {
24 h := &Hub{}
25 for i := 0; i < numHubShards; i++ {
26 h.connShards[i] = newConnShard()
27 h.subShards[i] = newSubShard()
28 }
29 return h
30 }
31
32 // shutdown unsubscribes users from all channels and disconnects them.
33 func (h *Hub) shutdown(ctx context.Context) error {
34 // Limit concurrency here to prevent resource usage burst on shutdown.
35 sem := make(chan struct{}, hubShutdownSemaphoreSize)
36
37 var errMu sync.Mutex
38 var shutdownErr error
39
40 var wg sync.WaitGroup
41 wg.Add(numHubShards)
42 for i := 0; i < numHubShards; i++ {
43 go func(i int) {
44 defer wg.Done()
45 err := h.connShards[i].shutdown(ctx, sem)
46 if err != nil {
47 errMu.Lock()
48 if shutdownErr == nil {
49 shutdownErr = err
50 }
51 errMu.Unlock()
52 }
53 }(i)
54 }
55 wg.Wait()
56 return shutdownErr
57 }
58
59 // add adds connection into clientHub connections registry.
60 func (h *Hub) add(c *Client) error {
61 return h.connShards[index(c.UserID(), numHubShards)].add(c)
62 }
63
64 // Remove removes connection from clientHub connections registry.
65 func (h *Hub) remove(c *Client) error {
66 return h.connShards[index(c.UserID(), numHubShards)].remove(c)
67 }
68
69 // userConnections returns all connections of user with specified UserID.
70 func (h *Hub) userConnections(userID string) map[string]*Client {
71 return h.connShards[index(userID, numHubShards)].userConnections(userID)
72 }
73
74 func (h *Hub) disconnect(user string, disconnect *Disconnect, whitelist []string) error {
75 return h.connShards[index(user, numHubShards)].disconnect(user, disconnect, whitelist)
76 }
77
78 func (h *Hub) unsubscribe(user string, ch string, opts ...UnsubscribeOption) error {
79 return h.connShards[index(user, numHubShards)].unsubscribe(user, ch, opts...)
80 }
81
82 func (h *Hub) addSub(ch string, c *Client) (bool, error) {
83 return h.subShards[index(ch, numHubShards)].addSub(ch, c)
84 }
85
86 // removeSub removes connection from clientHub subscriptions registry.
87 func (h *Hub) removeSub(ch string, c *Client) (bool, error) {
88 return h.subShards[index(ch, numHubShards)].removeSub(ch, c)
89 }
90
91 // broadcastPublication sends message to all clients subscribed on channel.
92 func (h *Hub) broadcastPublication(ch string, pub *protocol.Publication, sp StreamPosition) error {
93 return h.subShards[index(ch, numHubShards)].broadcastPublication(ch, pub, sp)
94 }
95
96 // broadcastJoin sends message to all clients subscribed on channel.
97 func (h *Hub) broadcastJoin(ch string, join *protocol.Join) error {
98 return h.subShards[index(ch, numHubShards)].broadcastJoin(ch, join)
99 }
100
101 func (h *Hub) broadcastLeave(ch string, leave *protocol.Leave) error {
102 return h.subShards[index(ch, numHubShards)].broadcastLeave(ch, leave)
103 }
104
105 // NumSubscribers returns number of current subscribers for a given channel.
106 func (h *Hub) NumSubscribers(ch string) int {
107 return h.subShards[index(ch, numHubShards)].NumSubscribers(ch)
108 }
109
110 // Channels returns a slice of all active channels.
111 func (h *Hub) Channels() []string {
112 channels := make([]string, 0, h.NumChannels())
113 for i := 0; i < numHubShards; i++ {
114 channels = append(channels, h.subShards[i].Channels()...)
115 }
116 return channels
117 }
118
119 // NumClients returns total number of client connections.
120 func (h *Hub) NumClients() int {
121 var total int
122 for i := 0; i < numHubShards; i++ {
123 total += h.connShards[i].NumClients()
124 }
125 return total
126 }
127
128 // NumUsers returns a number of unique users connected.
129 func (h *Hub) NumUsers() int {
130 var total int
131 for i := 0; i < numHubShards; i++ {
132 // users do not overlap among shards.
133 total += h.connShards[i].NumUsers()
134 }
135 return total
136 }
137
138 // NumChannels returns a total number of different channels.
139 func (h *Hub) NumChannels() int {
140 var total int
141 for i := 0; i < numHubShards; i++ {
142 // channels do not overlap among shards.
143 total += h.subShards[i].NumChannels()
144 }
145 return total
146 }
147
148 type connShard struct {
149 mu sync.RWMutex
150 // match client ID with actual client connection.
151 conns map[string]*Client
152 // registry to hold active client connections grouped by user.
153 users map[string]map[string]struct{}
154 }
155
156 func newConnShard() *connShard {
157 return &connShard{
158 conns: make(map[string]*Client),
159 users: make(map[string]map[string]struct{}),
160 }
161 }
162
163 const (
164 // hubShutdownSemaphoreSize limits graceful disconnects concurrency
165 // on node shutdown.
166 hubShutdownSemaphoreSize = 128
167 )
168
169 // shutdown unsubscribes users from all channels and disconnects them.
170 func (h *connShard) shutdown(ctx context.Context, sem chan struct{}) error {
171 advice := DisconnectShutdown
172
173 h.mu.RLock()
174 // At this moment node won't accept new client connections so we can
175 // safely copy existing clients and release lock.
176 clients := make([]*Client, 0, len(h.conns))
177 for _, client := range h.conns {
178 clients = append(clients, client)
179 }
180 h.mu.RUnlock()
181
182 closeFinishedCh := make(chan struct{}, len(clients))
183 finished := 0
184
185 if len(clients) == 0 {
186 return nil
187 }
188
189 for _, client := range clients {
190 select {
191 case sem <- struct{}{}:
192 case <-ctx.Done():
193 return ctx.Err()
194 }
195 go func(cc *Client) {
196 defer func() { <-sem }()
197 defer func() { closeFinishedCh <- struct{}{} }()
198 _ = cc.close(advice)
199 }(client)
200 }
201
202 for {
203 select {
204 case <-closeFinishedCh:
205 finished++
206 if finished == len(clients) {
207 return nil
208 }
209 case <-ctx.Done():
210 return ctx.Err()
211 }
212 }
213 }
214
215 func stringInSlice(str string, slice []string) bool {
216 for _, s := range slice {
217 if s == str {
218 return true
219 }
220 }
221 return false
222 }
223
224 func (h *connShard) disconnect(user string, disconnect *Disconnect, whitelist []string) error {
225 userConnections := h.userConnections(user)
226 for _, c := range userConnections {
227 if stringInSlice(c.ID(), whitelist) {
228 continue
229 }
230 go func(cc *Client) {
231 _ = cc.close(disconnect)
232 }(c)
233 }
234 return nil
235 }
236
237 func (h *connShard) unsubscribe(user string, ch string, opts ...UnsubscribeOption) error {
238 userConnections := h.userConnections(user)
239 for _, c := range userConnections {
240 err := c.Unsubscribe(ch, opts...)
241 if err != nil {
242 return err
243 }
244 }
245 return nil
246 }
247
248 // userConnections returns all connections of user with specified UserID.
249 func (h *connShard) userConnections(userID string) map[string]*Client {
250 h.mu.RLock()
251 defer h.mu.RUnlock()
252
253 userConnections, ok := h.users[userID]
254 if !ok {
255 return map[string]*Client{}
256 }
257
258 conns := make(map[string]*Client, len(userConnections))
259 for uid := range userConnections {
260 c, ok := h.conns[uid]
261 if !ok {
262 continue
263 }
264 conns[uid] = c
265 }
266
267 return conns
268 }
269
270 // add adds connection into clientHub connections registry.
271 func (h *connShard) add(c *Client) error {
272 h.mu.Lock()
273 defer h.mu.Unlock()
274
275 uid := c.ID()
276 user := c.UserID()
277
278 h.conns[uid] = c
279
280 if _, ok := h.users[user]; !ok {
281 h.users[user] = make(map[string]struct{})
282 }
283 h.users[user][uid] = struct{}{}
284 return nil
285 }
286
287 // Remove removes connection from clientHub connections registry.
288 func (h *connShard) remove(c *Client) error {
289 h.mu.Lock()
290 defer h.mu.Unlock()
291
292 uid := c.ID()
293 user := c.UserID()
294
295 delete(h.conns, uid)
296
297 // try to find connection to delete, return early if not found.
298 if _, ok := h.users[user]; !ok {
299 return nil
300 }
301 if _, ok := h.users[user][uid]; !ok {
302 return nil
303 }
304
305 // actually remove connection from hub.
306 delete(h.users[user], uid)
307
308 // clean up users map if it's needed.
309 if len(h.users[user]) == 0 {
310 delete(h.users, user)
311 }
312
313 return nil
314 }
315
316 // NumClients returns total number of client connections.
317 func (h *connShard) NumClients() int {
318 h.mu.RLock()
319 defer h.mu.RUnlock()
320 total := 0
321 for _, clientConnections := range h.users {
322 total += len(clientConnections)
323 }
324 return total
325 }
326
327 // NumUsers returns a number of unique users connected.
328 func (h *connShard) NumUsers() int {
329 h.mu.RLock()
330 defer h.mu.RUnlock()
331 return len(h.users)
332 }
333
334 type subShard struct {
335 mu sync.RWMutex
336 // registry to hold active subscriptions of clients to channels.
337 subs map[string]map[string]*Client
338 }
339
340 func newSubShard() *subShard {
341 return &subShard{
342 subs: make(map[string]map[string]*Client),
343 }
344 }
345
346 // addSub adds connection into clientHub subscriptions registry.
347 func (h *subShard) addSub(ch string, c *Client) (bool, error) {
348 h.mu.Lock()
349 defer h.mu.Unlock()
350
351 uid := c.ID()
352
353 _, ok := h.subs[ch]
354 if !ok {
355 h.subs[ch] = make(map[string]*Client)
356 }
357 h.subs[ch][uid] = c
358 if !ok {
359 return true, nil
360 }
361 return false, nil
362 }
363
364 // removeSub removes connection from clientHub subscriptions registry.
365 func (h *subShard) removeSub(ch string, c *Client) (bool, error) {
366 h.mu.Lock()
367 defer h.mu.Unlock()
368
369 uid := c.ID()
370
371 // try to find subscription to delete, return early if not found.
372 if _, ok := h.subs[ch]; !ok {
373 return true, nil
374 }
375 if _, ok := h.subs[ch][uid]; !ok {
376 return true, nil
377 }
378
379 // actually remove subscription from hub.
380 delete(h.subs[ch], uid)
381
382 // clean up subs map if it's needed.
383 if len(h.subs[ch]) == 0 {
384 delete(h.subs, ch)
385 return true, nil
386 }
387
388 return false, nil
389 }
390
391 // broadcastPublication sends message to all clients subscribed on channel.
392 func (h *subShard) broadcastPublication(channel string, pub *protocol.Publication, sp StreamPosition) error {
393 useSeqGen := hasFlag(CompatibilityFlags, UseSeqGen)
394 if useSeqGen {
395 pub.Seq, pub.Gen = recovery.UnpackUint64(pub.Offset)
396 }
397
398 h.mu.RLock()
399 defer h.mu.RUnlock()
400
401 // get connections currently subscribed on channel.
402 channelSubscriptions, ok := h.subs[channel]
403 if !ok {
404 return nil
405 }
406
407 var jsonPublicationReply *prepared.Reply
408 var protobufPublicationReply *prepared.Reply
409 // Iterate over channel subscribers and send message.
410 for _, c := range channelSubscriptions {
411 protoType := c.Transport().Protocol().toProto()
412 if protoType == protocol.TypeJSON {
413 if jsonPublicationReply == nil {
414 // Do not send offset to clients for now.
415 var offset uint64
416 if useSeqGen {
417 offset = pub.Offset
418 pub.Offset = 0
419 }
420 data, err := protocol.GetPushEncoder(protoType).EncodePublication(pub)
421 if err != nil {
422 return err
423 }
424 if useSeqGen {
425 pub.Offset = offset
426 }
427 messageBytes, err := protocol.GetPushEncoder(protoType).Encode(clientproto.NewPublicationPush(channel, data))
428 if err != nil {
429 return err
430 }
431 reply := &protocol.Reply{
432 Result: messageBytes,
433 }
434 jsonPublicationReply = prepared.NewReply(reply, protocol.TypeJSON)
435 }
436 _ = c.writePublication(channel, pub, jsonPublicationReply, sp)
437 } else if protoType == protocol.TypeProtobuf {
438 if protobufPublicationReply == nil {
439 // Do not send offset to clients for now.
440 var offset uint64
441 if useSeqGen {
442 offset = pub.Offset
443 pub.Offset = 0
444 }
445 data, err := protocol.GetPushEncoder(protoType).EncodePublication(pub)
446 if err != nil {
447 return err
448 }
449 if useSeqGen {
450 pub.Offset = offset
451 }
452 messageBytes, err := protocol.GetPushEncoder(protoType).Encode(clientproto.NewPublicationPush(channel, data))
453 if err != nil {
454 return err
455 }
456 reply := &protocol.Reply{
457 Result: messageBytes,
458 }
459 protobufPublicationReply = prepared.NewReply(reply, protocol.TypeProtobuf)
460 }
461 _ = c.writePublication(channel, pub, protobufPublicationReply, sp)
462 }
463 }
464 return nil
465 }
466
467 // broadcastJoin sends message to all clients subscribed on channel.
468 func (h *subShard) broadcastJoin(channel string, join *protocol.Join) error {
469 h.mu.RLock()
470 defer h.mu.RUnlock()
471
472 channelSubscriptions, ok := h.subs[channel]
473 if !ok {
474 return nil
475 }
476
477 var (
478 jsonReply *prepared.Reply
479 protobufReply *prepared.Reply
480 )
481
482 for _, c := range channelSubscriptions {
483 protoType := c.Transport().Protocol().toProto()
484 if protoType == protocol.TypeJSON {
485 if jsonReply == nil {
486 data, err := protocol.GetPushEncoder(protoType).EncodeJoin(join)
487 if err != nil {
488 return err
489 }
490 messageBytes, err := protocol.GetPushEncoder(protoType).Encode(clientproto.NewJoinPush(channel, data))
491 if err != nil {
492 return err
493 }
494 reply := &protocol.Reply{
495 Result: messageBytes,
496 }
497 jsonReply = prepared.NewReply(reply, protocol.TypeJSON)
498 }
499 _ = c.writeJoin(channel, jsonReply)
500 } else if protoType == protocol.TypeProtobuf {
501 if protobufReply == nil {
502 data, err := protocol.GetPushEncoder(protoType).EncodeJoin(join)
503 if err != nil {
504 return err
505 }
506 messageBytes, err := protocol.GetPushEncoder(protoType).Encode(clientproto.NewJoinPush(channel, data))
507 if err != nil {
508 return err
509 }
510 reply := &protocol.Reply{
511 Result: messageBytes,
512 }
513 protobufReply = prepared.NewReply(reply, protocol.TypeProtobuf)
514 }
515 _ = c.writeJoin(channel, protobufReply)
516 }
517 }
518 return nil
519 }
520
521 // broadcastLeave sends message to all clients subscribed on channel.
522 func (h *subShard) broadcastLeave(channel string, leave *protocol.Leave) error {
523 h.mu.RLock()
524 defer h.mu.RUnlock()
525
526 channelSubscriptions, ok := h.subs[channel]
527 if !ok {
528 return nil
529 }
530
531 var (
532 jsonReply *prepared.Reply
533 protobufReply *prepared.Reply
534 )
535
536 for _, c := range channelSubscriptions {
537 protoType := c.Transport().Protocol().toProto()
538 if protoType == protocol.TypeJSON {
539 if jsonReply == nil {
540 data, err := protocol.GetPushEncoder(protoType).EncodeLeave(leave)
541 if err != nil {
542 return err
543 }
544 messageBytes, err := protocol.GetPushEncoder(protoType).Encode(clientproto.NewLeavePush(channel, data))
545 if err != nil {
546 return err
547 }
548 reply := &protocol.Reply{
549 Result: messageBytes,
550 }
551 jsonReply = prepared.NewReply(reply, protocol.TypeJSON)
552 }
553 _ = c.writeLeave(channel, jsonReply)
554 } else if protoType == protocol.TypeProtobuf {
555 if protobufReply == nil {
556 data, err := protocol.GetPushEncoder(protoType).EncodeLeave(leave)
557 if err != nil {
558 return err
559 }
560 messageBytes, err := protocol.GetPushEncoder(protoType).Encode(clientproto.NewLeavePush(channel, data))
561 if err != nil {
562 return err
563 }
564 reply := &protocol.Reply{
565 Result: messageBytes,
566 }
567 protobufReply = prepared.NewReply(reply, protocol.TypeProtobuf)
568 }
569 _ = c.writeLeave(channel, protobufReply)
570 }
571 }
572 return nil
573 }
574
575 // NumChannels returns a total number of different channels.
576 func (h *subShard) NumChannels() int {
577 h.mu.RLock()
578 defer h.mu.RUnlock()
579 return len(h.subs)
580 }
581
582 // Channels returns a slice of all active channels.
583 func (h *subShard) Channels() []string {
584 h.mu.RLock()
585 defer h.mu.RUnlock()
586 channels := make([]string, len(h.subs))
587 i := 0
588 for ch := range h.subs {
589 channels[i] = ch
590 i++
591 }
592 return channels
593 }
594
595 // NumSubscribers returns number of current subscribers for a given channel.
596 func (h *subShard) NumSubscribers(ch string) int {
597 h.mu.RLock()
598 defer h.mu.RUnlock()
599 conns, ok := h.subs[ch]
600 if !ok {
601 return 0
602 }
603 return len(conns)
604 }