-
-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathhub.go
More file actions
1647 lines (1488 loc) · 46.9 KB
/
Copy pathhub.go
File metadata and controls
1647 lines (1488 loc) · 46.9 KB
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package centrifuge
import (
"context"
"io"
"sync"
"sync/atomic"
"time"
"github.com/centrifugal/centrifuge/internal/convert"
"github.com/centrifugal/centrifuge/internal/filter"
"github.com/centrifugal/protocol"
"github.com/segmentio/encoding/json"
fdelta "github.com/shadowspore/fossil-delta"
)
const numHubShards = 64
var pushPool = sync.Pool{
New: func() any {
return &protocol.Push{}
},
}
var replyPool = sync.Pool{
New: func() any {
return &protocol.Reply{}
},
}
func getPush() *protocol.Push {
return pushPool.Get().(*protocol.Push)
}
func putPush(p *protocol.Push) {
p.Channel = ""
p.Id = 0
p.Pub = nil
p.Join = nil
p.Leave = nil
p.Message = nil
p.Subscribe = nil
p.Unsubscribe = nil
p.Connect = nil
p.Disconnect = nil
p.Refresh = nil
pushPool.Put(p)
}
func getReply() *protocol.Reply {
return replyPool.Get().(*protocol.Reply)
}
func putReply(r *protocol.Reply) {
r.Id = 0
r.Error = nil
r.Push = nil
r.Connect = nil
r.Subscribe = nil
r.Unsubscribe = nil
r.Publish = nil
r.Presence = nil
r.PresenceStats = nil
r.History = nil
r.Ping = nil
r.Rpc = nil
r.Refresh = nil
r.SubRefresh = nil
replyPool.Put(r)
}
// Hub tracks Client connections on the current Node.
type Hub struct {
connShards [numHubShards]*connShard
subShards [numHubShards]*subShard
sessionsMu sync.RWMutex
sessions map[string]*Client
}
// newHub initializes Hub.
func newHub(logger *logger, metrics *metrics, maxTimeLagMilli int64) *Hub {
h := &Hub{
sessions: map[string]*Client{},
}
for i := 0; i < numHubShards; i++ {
h.connShards[i] = newConnShard()
h.subShards[i] = newSubShard(logger, metrics, maxTimeLagMilli, i)
}
return h
}
func (h *Hub) clientBySession(session string) (*Client, bool) {
h.sessionsMu.RLock()
defer h.sessionsMu.RUnlock()
c, ok := h.sessions[session]
return c, ok
}
// shutdown unsubscribes users from all channels and disconnects them.
func (h *Hub) shutdown(ctx context.Context) error {
// Limit concurrency here to prevent resource usage burst on shutdown.
sem := make(chan struct{}, hubShutdownSemaphoreSize)
var errMu sync.Mutex
var shutdownErr error
var wg sync.WaitGroup
wg.Add(numHubShards)
for i := 0; i < numHubShards; i++ {
go func(i int) {
defer wg.Done()
err := h.connShards[i].shutdown(ctx, sem)
if err != nil {
errMu.Lock()
if shutdownErr == nil {
shutdownErr = err
}
errMu.Unlock()
}
}(i)
}
wg.Wait()
return shutdownErr
}
// Add connection into clientHub connections registry.
// add registers connection in clientHub. Returns true if this is a new
// registration (uid not previously present).
func (h *Hub) add(c *Client) bool {
h.sessionsMu.Lock()
if c.sessionID() != "" {
h.sessions[c.sessionID()] = c
}
h.sessionsMu.Unlock()
return h.connShards[index(c.UserID(), numHubShards)].add(c)
}
// Remove connection from clientHub connections registry.
// Returns true if found and really removed from registry.
func (h *Hub) remove(c *Client) bool {
h.sessionsMu.Lock()
if c.sessionID() != "" {
delete(h.sessions, c.sessionID())
}
h.sessionsMu.Unlock()
return h.connShards[index(c.UserID(), numHubShards)].remove(c)
}
// Connections returns all user connections to the current Node.
func (h *Hub) Connections() map[string]*Client {
connections := make(map[string]*Client)
for _, shard := range h.connShards {
shard.mu.RLock()
for clientID, c := range shard.clients {
connections[clientID] = c
}
shard.mu.RUnlock()
}
return connections
}
// UserConnections returns all user connections to the current Node.
func (h *Hub) UserConnections(userID string) map[string]*Client {
return h.connShards[index(userID, numHubShards)].userConnections(userID)
}
func (h *Hub) refresh(userID string, clientID, sessionID string, labelFilter *FilterNode, opts ...RefreshOption) error {
return h.connShards[index(userID, numHubShards)].refresh(userID, clientID, sessionID, labelFilter, opts...)
}
func (h *Hub) subscribe(userID string, ch string, clientID string, sessionID string, labelFilter *FilterNode, opts ...SubscribeOption) error {
return h.connShards[index(userID, numHubShards)].subscribe(userID, ch, clientID, sessionID, labelFilter, opts...)
}
func (h *Hub) unsubscribe(userID string, ch string, unsubscribe Unsubscribe, clientID string, sessionID string, labelFilter *FilterNode) error {
return h.connShards[index(userID, numHubShards)].unsubscribe(userID, ch, unsubscribe, clientID, sessionID, labelFilter)
}
// refreshAcrossUsers iterates every connection on every shard, applying
// clientID/sessionID/labelFilter narrowers. Used by Node.Refresh when userID
// is empty and the allUsers flag is set. Not used through the normal per-user
// dispatch path; see Node.Refresh for the routing decision.
func (h *Hub) refreshAcrossUsers(clientID, sessionID string, labelFilter *FilterNode, opts ...RefreshOption) error {
var firstErr error
for _, shard := range h.connShards {
if err := shard.refreshAcrossUsers(clientID, sessionID, labelFilter, opts...); err != nil && firstErr == nil {
firstErr = err
}
}
return firstErr
}
// subscribeAcrossUsers — see refreshAcrossUsers.
func (h *Hub) subscribeAcrossUsers(ch string, clientID, sessionID string, labelFilter *FilterNode, opts ...SubscribeOption) error {
var firstErr error
for _, shard := range h.connShards {
if err := shard.subscribeAcrossUsers(ch, clientID, sessionID, labelFilter, opts...); err != nil && firstErr == nil {
firstErr = err
}
}
return firstErr
}
// unsubscribeAcrossUsers — see refreshAcrossUsers.
func (h *Hub) unsubscribeAcrossUsers(ch string, unsubscribe Unsubscribe, clientID, sessionID string, labelFilter *FilterNode) error {
for _, shard := range h.connShards {
_ = shard.unsubscribeAcrossUsers(ch, unsubscribe, clientID, sessionID, labelFilter)
}
return nil
}
// disconnectAcrossUsers — see refreshAcrossUsers.
func (h *Hub) disconnectAcrossUsers(disconnect Disconnect, clientID, sessionID string, whitelist []string, labelFilter *FilterNode) error {
for _, shard := range h.connShards {
_ = shard.disconnectAcrossUsers(disconnect, clientID, sessionID, whitelist, labelFilter)
}
return nil
}
func (h *Hub) disconnect(userID string, disconnect Disconnect, clientID, sessionID string, whitelist []string, labelFilter *FilterNode) error {
return h.connShards[index(userID, numHubShards)].disconnect(userID, disconnect, clientID, sessionID, whitelist, labelFilter)
}
func (h *Hub) addSub(ch string, sub subInfo) (int64, bool, error) {
return h.subShards[index(ch, numHubShards)].addSub(ch, sub)
}
// removeSub removes connection from clientHub subscriptions registry.
// Returns (isEmpty, wasRemoved, wasKeyed).
func (h *Hub) removeSub(ch string, c *Client, subGen uint64) (bool, bool, bool) {
return h.subShards[index(ch, numHubShards)].removeSub(ch, c, subGen)
}
func (h *Hub) updateServerTagsFilter(ch string, clientID string, tf *tagsFilter) (bool, bool) {
return h.subShards[index(ch, numHubShards)].updateServerTagsFilter(ch, clientID, tf)
}
func (h *Hub) removeSubID(ch string) {
h.subShards[index(ch, numHubShards)].removeSubID(ch)
}
// BroadcastPublication sends message to all clients subscribed on a channel on the current Node.
// Usually this is NOT what you need since in most cases you should use Node.Publish method which
// uses a Broker to deliver publications to all Nodes in a cluster and maintains publication history
// in a channel with incremental offset. By calling BroadcastPublication messages will only be sent
// to the current node subscribers without any defined offset semantics, without delta support.
func (h *Hub) BroadcastPublication(ch string, pub *Publication, sp StreamPosition) error {
return h.broadcastPublication(ch, sp, pub, nil, nil, ChannelBatchConfig{})
}
// BroadcastPublicationDelta is like BroadcastPublication but supports delta compression.
// When prevPub is non-nil, subscribers with delta enabled receive a computed delta
// instead of the full publication data. Only sent to the current node subscribers.
func (h *Hub) BroadcastPublicationDelta(ch string, pub *Publication, prevPub *Publication, sp StreamPosition) error {
return h.broadcastPublication(ch, sp, pub, prevPub, prevPub, ChannelBatchConfig{})
}
func (h *Hub) broadcastPublication(
ch string, sp StreamPosition, pub, prevPub, localPrevPub *Publication,
batchConfig ChannelBatchConfig,
) error {
return h.subShards[index(ch, numHubShards)].broadcastPublication(
ch, sp, pub, prevPub, localPrevPub, batchConfig)
}
// broadcastJoin sends message to all clients subscribed on channel.
func (h *Hub) broadcastJoin(ch string, info *ClientInfo, batchConfig ChannelBatchConfig) error {
return h.subShards[index(ch, numHubShards)].broadcastJoin(ch, &protocol.Join{Info: infoToProto(info)}, batchConfig)
}
func (h *Hub) broadcastLeave(ch string, info *ClientInfo, batchConfig ChannelBatchConfig) error {
return h.subShards[index(ch, numHubShards)].broadcastLeave(ch, &protocol.Leave{Info: infoToProto(info)}, batchConfig)
}
// NumSubscribers returns number of current subscribers for a given channel.
func (h *Hub) NumSubscribers(ch string) int {
return h.subShards[index(ch, numHubShards)].NumSubscribers(ch)
}
// Channels returns a slice of all active channels.
func (h *Hub) Channels() []string {
channels := make([]string, 0, h.NumChannels())
for i := 0; i < numHubShards; i++ {
channels = append(channels, h.subShards[i].Channels()...)
}
return channels
}
// NumClients returns total number of client connections.
func (h *Hub) NumClients() int {
var total int
for i := 0; i < numHubShards; i++ {
total += h.connShards[i].NumClients()
}
return total
}
// NumUsers returns a number of unique users connected.
func (h *Hub) NumUsers() int {
var total int
for i := 0; i < numHubShards; i++ {
// users do not overlap among shards.
total += h.connShards[i].NumUsers()
}
return total
}
// NumSubscriptions returns a total number of subscriptions.
func (h *Hub) NumSubscriptions() int {
var total int
for i := 0; i < numHubShards; i++ {
// users do not overlap among shards.
total += h.subShards[i].NumSubscriptions()
}
return total
}
// NumChannels returns a total number of different channels.
func (h *Hub) NumChannels() int {
var total int
for i := 0; i < numHubShards; i++ {
// channels do not overlap among shards.
total += h.subShards[i].NumChannels()
}
return total
}
type connShard struct {
mu sync.RWMutex
// match client ID with actual client connection.
clients map[string]*Client
// registry to hold active client connections grouped by user.
users map[string]map[string]struct{}
}
func newConnShard() *connShard {
return &connShard{
clients: make(map[string]*Client),
users: 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 *connShard) shutdown(ctx context.Context, sem chan struct{}) error {
advice := DisconnectShutdown
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.clients))
for _, client := range h.clients {
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 stringInSlice(str string, slice []string) bool {
for _, s := range slice {
if s == str {
return true
}
}
return false
}
// matchLabelFilter returns true when c should be included in a label-filtered
// operation. A nil filter matches every client. c.labels is set once before the
// client is published to the hub (see Client connect flow) and never mutated,
// so the read is safe without taking c.mu.
func matchLabelFilter(c *Client, f *FilterNode) bool {
if f == nil {
return true
}
ok, _ := filter.Match(f, c.labels)
return ok
}
func (h *connShard) subscribe(user string, ch string, clientID string, sessionID string, labelFilter *FilterNode, opts ...SubscribeOption) error {
userConnections := h.userConnections(user)
var firstErr error
var errMu sync.Mutex
var wg sync.WaitGroup
for _, c := range userConnections {
if clientID != "" && c.ID() != clientID {
continue
}
if sessionID != "" && c.sessionID() != sessionID {
continue
}
if !matchLabelFilter(c, labelFilter) {
continue
}
wg.Add(1)
go func(c *Client) {
defer wg.Done()
err := c.Subscribe(ch, opts...)
errMu.Lock()
defer errMu.Unlock()
if err != nil && err != io.EOF && firstErr == nil {
firstErr = err
}
}(c)
}
wg.Wait()
return firstErr
}
func (h *connShard) refresh(user string, clientID string, sessionID string, labelFilter *FilterNode, opts ...RefreshOption) error {
userConnections := h.userConnections(user)
var firstErr error
var errMu sync.Mutex
var wg sync.WaitGroup
for _, c := range userConnections {
if clientID != "" && c.ID() != clientID {
continue
}
if sessionID != "" && c.sessionID() != sessionID {
continue
}
if !matchLabelFilter(c, labelFilter) {
continue
}
wg.Add(1)
go func(c *Client) {
defer wg.Done()
err := c.Refresh(opts...)
errMu.Lock()
defer errMu.Unlock()
if err != nil && err != io.EOF && firstErr == nil {
firstErr = err
}
}(c)
}
wg.Wait()
return firstErr
}
func (h *connShard) unsubscribe(user string, ch string, unsubscribe Unsubscribe, clientID string, sessionID string, labelFilter *FilterNode) error {
userConnections := h.userConnections(user)
var wg sync.WaitGroup
for _, c := range userConnections {
if clientID != "" && c.ID() != clientID {
continue
}
if sessionID != "" && c.sessionID() != sessionID {
continue
}
if !matchLabelFilter(c, labelFilter) {
continue
}
wg.Add(1)
go func(c *Client) {
defer wg.Done()
c.Unsubscribe(ch, unsubscribe)
}(c)
}
wg.Wait()
return nil
}
// connShard.*AcrossUsers methods iterate the shard's full client map applying
// clientID/sessionID/labelFilter narrowers. Used by the fleet-wide dispatch
// path in Node ops when userID is empty AND the allUsers flag is set. The
// shard read-lock is released before invoking client operations to avoid
// holding it during downstream IO; in flight changes to the connection set
// during the loop are acceptable (the op is best-effort over a roughly-current
// snapshot of the hub, same guarantee the regular paths give).
func (h *connShard) refreshAcrossUsers(clientID, sessionID string, labelFilter *FilterNode, opts ...RefreshOption) error {
clients := h.allClientsSnapshot()
var firstErr error
var errMu sync.Mutex
var wg sync.WaitGroup
for _, c := range clients {
if clientID != "" && c.ID() != clientID {
continue
}
if sessionID != "" && c.sessionID() != sessionID {
continue
}
if !matchLabelFilter(c, labelFilter) {
continue
}
wg.Add(1)
go func(c *Client) {
defer wg.Done()
err := c.Refresh(opts...)
errMu.Lock()
defer errMu.Unlock()
if err != nil && err != io.EOF && firstErr == nil {
firstErr = err
}
}(c)
}
wg.Wait()
return firstErr
}
func (h *connShard) subscribeAcrossUsers(ch string, clientID, sessionID string, labelFilter *FilterNode, opts ...SubscribeOption) error {
clients := h.allClientsSnapshot()
var firstErr error
var errMu sync.Mutex
var wg sync.WaitGroup
for _, c := range clients {
if clientID != "" && c.ID() != clientID {
continue
}
if sessionID != "" && c.sessionID() != sessionID {
continue
}
if !matchLabelFilter(c, labelFilter) {
continue
}
wg.Add(1)
go func(c *Client) {
defer wg.Done()
err := c.Subscribe(ch, opts...)
errMu.Lock()
defer errMu.Unlock()
if err != nil && err != io.EOF && firstErr == nil {
firstErr = err
}
}(c)
}
wg.Wait()
return firstErr
}
func (h *connShard) unsubscribeAcrossUsers(ch string, unsubscribe Unsubscribe, clientID, sessionID string, labelFilter *FilterNode) error {
clients := h.allClientsSnapshot()
var wg sync.WaitGroup
for _, c := range clients {
if clientID != "" && c.ID() != clientID {
continue
}
if sessionID != "" && c.sessionID() != sessionID {
continue
}
if !matchLabelFilter(c, labelFilter) {
continue
}
wg.Add(1)
go func(c *Client) {
defer wg.Done()
c.Unsubscribe(ch, unsubscribe)
}(c)
}
wg.Wait()
return nil
}
func (h *connShard) disconnectAcrossUsers(disconnect Disconnect, clientID, sessionID string, whitelist []string, labelFilter *FilterNode) error {
clients := h.allClientsSnapshot()
for _, c := range clients {
if stringInSlice(c.ID(), whitelist) {
continue
}
if clientID != "" && c.ID() != clientID {
continue
}
if sessionID != "" && c.sessionID() != sessionID {
continue
}
if !matchLabelFilter(c, labelFilter) {
continue
}
c.Disconnect(disconnect)
}
return nil
}
// allClientsSnapshot copies the current shard's client map under read-lock,
// then releases the lock so the per-client op work isn't done under it.
func (h *connShard) allClientsSnapshot() []*Client {
h.mu.RLock()
defer h.mu.RUnlock()
out := make([]*Client, 0, len(h.clients))
for _, c := range h.clients {
out = append(out, c)
}
return out
}
func (h *connShard) disconnect(user string, disconnect Disconnect, clientID string, sessionID string, whitelist []string, labelFilter *FilterNode) error {
userConnections := h.userConnections(user)
for _, c := range userConnections {
if stringInSlice(c.ID(), whitelist) {
continue
}
if clientID != "" && c.ID() != clientID {
continue
}
if sessionID != "" && c.sessionID() != sessionID {
continue
}
if !matchLabelFilter(c, labelFilter) {
continue
}
c.Disconnect(disconnect)
}
return nil
}
// userConnections returns all connections of user with specified User.
func (h *connShard) userConnections(userID string) map[string]*Client {
h.mu.RLock()
defer h.mu.RUnlock()
userConnections, ok := h.users[userID]
if !ok {
return map[string]*Client{}
}
connections := make(map[string]*Client, len(userConnections))
for uid := range userConnections {
c, ok := h.clients[uid]
if !ok {
continue
}
connections[uid] = c
}
return connections
}
// Add connection into clientHub connections registry.
// add registers a client connection. Returns true if this was a new
// registration (the uid was not already present), so callers can keep the
// connectionsInflight gauge in lockstep with the clients map.
func (h *connShard) add(c *Client) bool {
h.mu.Lock()
defer h.mu.Unlock()
uid := c.ID()
user := c.UserID()
_, existed := h.clients[uid]
h.clients[uid] = c
if _, ok := h.users[user]; !ok {
h.users[user] = make(map[string]struct{})
}
h.users[user][uid] = struct{}{}
return !existed
}
// Remove connection from clientHub connections registry.
// Returns true if found and really removed from registry.
// remove deregisters a client connection. Returns true if the uid was present
// in the clients map — the same condition add() reports as new — so the
// connectionsInflight Dec pairs exactly with its Inc regardless of the users map.
func (h *connShard) remove(c *Client) bool {
h.mu.Lock()
defer h.mu.Unlock()
uid := c.ID()
user := c.UserID()
_, existed := h.clients[uid]
delete(h.clients, uid)
// Clean up the user grouping if present.
if userConns, ok := h.users[user]; ok {
delete(userConns, uid)
if len(userConns) == 0 {
delete(h.users, user)
}
}
return existed
}
// NumClients returns total number of client connections.
func (h *connShard) NumClients() int {
h.mu.RLock()
defer h.mu.RUnlock()
// clients holds exactly one entry per connection, which is the same total as
// summing the per-user sets. Iterating users instead would make this O(users)
// while holding the read lock — at a million connections that is a periodic
// scan (updateGauges runs every 10s) which also blocks connects/disconnects.
return len(h.clients)
}
// NumUsers returns a number of unique users connected.
func (h *connShard) NumUsers() int {
h.mu.RLock()
defer h.mu.RUnlock()
return len(h.users)
}
type DeltaType string
const (
deltaTypeNone DeltaType = ""
// DeltaTypeFossil is Fossil delta encoding. See https://fossil-scm.org/home/doc/tip/www/delta_encoder_algorithm.wiki.
DeltaTypeFossil DeltaType = "fossil"
)
var stringToDeltaType = map[string]DeltaType{
"fossil": DeltaTypeFossil,
}
type tagsFilter struct {
filter *protocol.FilterNode
hash [32]byte
}
type subInfo struct {
client *Client
deltaType DeltaType
useID bool
tagsFilter *tagsFilter
serverTagsFilter *tagsFilter
isMap bool // true for map subscriptions.
// protoType and unidirectional mirror the client's transport. Both are fixed
// for the connection's lifetime, but reading them goes through two interface
// dispatches — a cost paid once per subscriber per broadcast. Snapshotting
// them at addSub time turns the broadcast loop's per-subscriber protocol
// dispatch into plain field loads. Set by addSub, not by callers.
protoType protocol.Type
unidirectional bool
// subGen identifies this specific subscription of the client to the channel.
// A resubscribe gets a fresh subGen, so a stale unsubscribe (carrying an older
// subGen it read from c.channels) will not remove a newer subscription's hub
// entry — which is how hub routing stays consistent with c.channels without
// holding a lock across both.
subGen uint64
}
type subShard struct {
mu sync.RWMutex
// registry to hold active subscriptions of clients to channels with some additional info.
subs map[string]map[string]subInfo
// numSubs is the total number of subscriptions across subs, maintained
// incrementally under mu. Summing subs on demand would be O(channels) while
// holding the read lock, and NumSubscriptions is read periodically by the
// node gauge update.
numSubs int
maxTimeLagMilli int64
logger *logger
metrics *metrics
shardIndex int
chanIDs map[string]int64
lastChanID atomic.Int64
mapChannels map[string]bool // tracks which channels are keyed subscriptions
}
func newSubShard(logger *logger, metrics *metrics, maxTimeLagMilli int64, shardIndex int) *subShard {
return &subShard{
subs: make(map[string]map[string]subInfo),
logger: logger,
metrics: metrics,
maxTimeLagMilli: maxTimeLagMilli,
shardIndex: shardIndex,
chanIDs: make(map[string]int64),
mapChannels: make(map[string]bool),
}
}
// addSub adds connection into clientHub subscriptions registry.
// Returns (chanID, isFirst, error) where isFirst is true if this is the first subscriber.
func (s *subShard) addSub(ch string, sub subInfo) (int64, bool, error) {
// Snapshot the transport's immutable protocol properties so the broadcast
// loop reads fields instead of making interface calls per subscriber.
sub.protoType = sub.client.transport.Protocol().toProto()
sub.unidirectional = sub.client.transport.Unidirectional()
s.mu.Lock()
defer s.mu.Unlock()
uid := sub.client.ID()
_, ok := s.subs[ch]
if !ok {
s.subs[ch] = make(map[string]subInfo)
// Track if this channel is keyed (first subscriber determines this).
if sub.isMap {
s.mapChannels[ch] = true
}
}
if _, exists := s.subs[ch][uid]; !exists {
s.numSubs++
// Inflight is co-located with numSubs (same condition) so the two stay in
// lockstep. Doing it here, rather than unconditionally in addSubscription,
// avoids over-counting when a resubscribe overwrites an existing
// client+channel entry (no new subscription) — its stale generation's
// removeSub is a no-op that never Dec's, which would otherwise drift.
baseLabels := []string{sub.client.metricName, s.metrics.getChannelNamespaceLabel(ch)}
s.metrics.subscriptionsInflight.WithLabelValues(s.metrics.appendClientLabels(baseLabels, sub.client)...).Inc()
}
s.subs[ch][uid] = sub
var chanID int64
if sub.useID {
existingChanID, hasChanID := s.chanIDs[ch]
if !hasChanID {
// Generate unique ID using shard index + (counter * numHubShards)
// This ensures each shard generates non-overlapping ID ranges
counter := s.lastChanID.Add(1)
chanID = int64(s.shardIndex) + ((counter - 1) * numHubShards)
s.chanIDs[ch] = chanID
} else {
chanID = existingChanID
}
}
if !ok {
return chanID, true, nil
}
return chanID, false, nil
}
// updateServerTagsFilter updates the server-side tags filter for a specific
// client subscription. Returns (found, changed) where changed is true only
// if the filter hash differs from the current one.
func (s *subShard) updateServerTagsFilter(ch string, clientID string, tf *tagsFilter) (bool, bool) {
s.mu.Lock()
defer s.mu.Unlock()
chSubs, ok := s.subs[ch]
if !ok {
return false, false
}
sub, ok := chSubs[clientID]
if !ok {
return false, false
}
if sub.serverTagsFilter != nil && sub.serverTagsFilter.hash == tf.hash {
return true, false
}
if sub.serverTagsFilter == nil && tf == nil {
return true, false
}
sub.serverTagsFilter = tf
chSubs[clientID] = sub
return true, true
}
func (s *subShard) removeSubID(ch string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.chanIDs, ch)
}
// removeSub removes connection from clientHub subscriptions registry.
// Returns (isEmpty, wasRemoved, wasKeyed) where:
// - isEmpty: true if channel has no subscribers left
// - wasRemoved: true if subscription was found and removed
// - wasMap: true if the now-empty channel was a keyed subscription channel
// anySubGen removes whatever generation is currently registered. No production
// path passes it anymore — every rollback identity-matches its own generation
// so a stalled attempt can never remove a fresh resubscribe's entry. Kept as
// the named zero value so an accidental gen-0 removal is at least explicit in
// removeSub. Real generations start at 1.
const anySubGen uint64 = 0
func (s *subShard) removeSub(ch string, c *Client, subGen uint64) (bool, bool, bool) {
s.mu.Lock()
defer s.mu.Unlock()
uid := c.ID()
// try to find subscription to delete, return early if not found.
if _, ok := s.subs[ch]; !ok {
return true, false, false
}
sub, ok := s.subs[ch][uid]
if !ok {
return true, false, false
}
if subGen != anySubGen && sub.subGen != subGen {
// A newer subscription generation is registered for this client+channel —
// the caller is unsubscribing an older generation that a concurrent
// resubscribe already superseded. Leave the newer entry in place so hub
// routing stays consistent with c.channels. Report not-removed, not-empty.
return false, false, false
}
// actually remove subscription from hub.
delete(s.subs[ch], uid)
s.numSubs--
// Mirror of the Inc in addSub — only when a subscription is actually removed
// (matched generation), so a stale-generation removeSub does not Dec.
baseLabels := []string{c.metricName, s.metrics.getChannelNamespaceLabel(ch)}
s.metrics.subscriptionsInflight.WithLabelValues(s.metrics.appendClientLabels(baseLabels, c)...).Dec()
// clean up subs map if it's needed.
if len(s.subs[ch]) == 0 {
delete(s.subs, ch)
wasMap := s.mapChannels[ch]
delete(s.mapChannels, ch)
return true, true, wasMap
}
return false, true, false
}
type encodeError struct {
client string
user string
error error
}
type preparedKey struct {
ProtocolType protocol.Type
Unidirectional bool
DeltaType DeltaType
UseID bool
WasFiltered bool
}
type preparedData struct {
fullData []byte
brokerDeltaData []byte
localDeltaData []byte
deltaSub bool
wasFiltered bool
filteredPub *protocol.Publication
// For keyed channel lazy delta encoding (set by buildPreparedPollData).
keyedDeltaPatch []byte // raw fossil delta data (patch or full data if patch >= full)
keyedDeltaIsReal bool // true when the patch is a real delta (smaller than full)
keyedDeltaPrevVersion uint64 // version corresponding to the delta's base data (entry.version BEFORE the publish)
}
func getDeltaPub(prevPub *Publication, fullPub *protocol.Publication, key preparedKey) *protocol.Publication {
deltaPub := fullPub
if prevPub != nil && key.DeltaType == DeltaTypeFossil {
patch := fdelta.Create(prevPub.Data, fullPub.Data)
delta := true
deltaData := patch
if len(patch) >= len(fullPub.Data) {
delta = false
deltaData = fullPub.Data
}
if key.ProtocolType == protocol.TypeJSON {
deltaData = json.Escape(convert.BytesToString(deltaData))
}
deltaPub = &protocol.Publication{
Offset: fullPub.Offset,
Data: deltaData,
Info: fullPub.Info,
Tags: fullPub.Tags,
Delta: delta,
Key: fullPub.Key,
Removed: fullPub.Removed,
Score: fullPub.Score,
Channel: fullPub.Channel,
}
} else if prevPub == nil && key.ProtocolType == protocol.TypeJSON && key.DeltaType == DeltaTypeFossil {
// In JSON and Fossil case we need to send full state in JSON string format.
deltaPub = &protocol.Publication{
Offset: fullPub.Offset,
Data: json.Escape(convert.BytesToString(fullPub.Data)),
Info: fullPub.Info,
Tags: fullPub.Tags,
Key: fullPub.Key,
Removed: fullPub.Removed,
Score: fullPub.Score,