-
-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathshared_poll_test.go
More file actions
2979 lines (2616 loc) · 95.5 KB
/
Copy pathshared_poll_test.go
File metadata and controls
2979 lines (2616 loc) · 95.5 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 (
"bytes"
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/centrifugal/protocol"
"github.com/stretchr/testify/require"
)
// controllableBroker is a test broker with atomic counters and synchronization
// hooks for testing race conditions in SharedPollManager broker subscribe/unsubscribe.
type controllableBroker struct {
subscribeCount atomic.Int32
unsubscribeCount atomic.Int32
subscribeMu sync.Mutex
subscribeErr error // returned by Subscribe when non-nil
subscribeCh chan struct{} // if non-nil, Subscribe blocks until this is closed
subscribeFunc func(ch string) error // if non-nil, called instead of default behavior
unsubscribeMu sync.Mutex
unsubscribeErr error
unsubscribeFunc func(ch string) error
}
func (b *controllableBroker) RegisterBrokerEventHandler(_ BrokerEventHandler) error { return nil }
func (b *controllableBroker) Publish(_ string, _ []byte, _ PublishOptions) (PublishResult, error) {
return PublishResult{}, nil
}
func (b *controllableBroker) PublishJoin(_ string, _ *ClientInfo) error { return nil }
func (b *controllableBroker) PublishLeave(_ string, _ *ClientInfo) error { return nil }
func (b *controllableBroker) PublishControl(_ []byte, _, _ string) error { return nil }
func (b *controllableBroker) History(_ string, _ HistoryOptions) ([]*Publication, StreamPosition, error) {
return nil, StreamPosition{}, nil
}
func (b *controllableBroker) RemoveHistory(_ string) error { return nil }
func (b *controllableBroker) Subscribe(channels ...string) error {
for _, ch := range channels {
b.subscribeCount.Add(1)
b.subscribeMu.Lock()
fn := b.subscribeFunc
err := b.subscribeErr
waitCh := b.subscribeCh
b.subscribeMu.Unlock()
if waitCh != nil {
<-waitCh
}
if fn != nil {
if err := fn(ch); err != nil {
return err
}
continue
}
if err != nil {
return err
}
}
return nil
}
func (b *controllableBroker) Unsubscribe(channels ...string) error {
for _, ch := range channels {
b.unsubscribeCount.Add(1)
b.unsubscribeMu.Lock()
fn := b.unsubscribeFunc
err := b.unsubscribeErr
b.unsubscribeMu.Unlock()
if fn != nil {
if err := fn(ch); err != nil {
return err
}
continue
}
if err != nil {
return err
}
}
return nil
}
func TestSharedPollManager_TrackCreatesChannel(t *testing.T) {
t.Parallel()
node := newTestNodeWithSharedPoll(t)
setupSharedPollHandlers(node)
require.NotNil(t, node.sharedPollManager)
require.Empty(t, node.sharedPollManager.channels)
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
})
node.sharedPollManager.mu.RLock()
_, ok := node.sharedPollManager.channels["test:channel"]
node.sharedPollManager.mu.RUnlock()
require.True(t, ok)
}
func TestSharedPollManager_UntrackRemovesFromIndex(t *testing.T) {
t.Parallel()
node := newTestNodeWithSharedPoll(t)
setupSharedPollHandlers(node)
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
{Key: "key2", Version: 0},
})
// Untrack key1 — it's the last subscriber.
untrackSharedPollClient(t, client, "test:channel", []string{"key1"})
node.sharedPollManager.mu.RLock()
s := node.sharedPollManager.channels["test:channel"]
node.sharedPollManager.mu.RUnlock()
require.NotNil(t, s)
s.mu.Lock()
_, hasKey1 := s.itemIndex["key1"]
_, hasKey2 := s.itemIndex["key2"]
s.mu.Unlock()
require.False(t, hasKey1)
require.True(t, hasKey2)
}
func TestSharedPollManager_HasChannel(t *testing.T) {
t.Parallel()
node := newTestNodeWithSharedPoll(t)
setupSharedPollHandlers(node)
require.False(t, node.sharedPollManager.hasChannel("test:channel"))
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
})
require.True(t, node.sharedPollManager.hasChannel("test:channel"))
}
func TestSharedPollManager_WorkerStartsOnTrack(t *testing.T) {
t.Parallel()
node := newTestNodeWithSharedPoll(t)
setupSharedPollHandlers(node)
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
})
node.sharedPollManager.mu.RLock()
s := node.sharedPollManager.channels["test:channel"]
node.sharedPollManager.mu.RUnlock()
s.mu.Lock()
require.True(t, s.workerRunning)
s.mu.Unlock()
}
func TestSharedPollManager_Close(t *testing.T) {
t.Parallel()
node, err := New(Config{
LogLevel: LogLevelTrace,
LogHandler: func(entry LogEntry) {},
SharedPoll: SharedPollConfig{
GetSharedPollChannelOptions: func(channel string) (SharedPollChannelOptions, bool) {
return SharedPollChannelOptions{
RefreshInterval: 100 * time.Millisecond,
MaxKeysPerConnection: 100,
}, true
},
},
})
require.NoError(t, err)
node.OnSharedPoll(func(ctx context.Context, event SharedPollEvent) (SharedPollResult, error) {
return SharedPollResult{}, nil
})
err = node.Run()
require.NoError(t, err)
setupSharedPollHandlers(node)
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
})
// Give worker time to start.
time.Sleep(50 * time.Millisecond)
// Shutdown should complete without hanging.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err = node.Shutdown(ctx)
require.NoError(t, err)
}
func TestSharedPollNotify_TriggersRefresh(t *testing.T) {
t.Parallel()
callCh := make(chan SharedPollEvent, 10)
node := newTestNodeWithSharedPoll(t, SharedPollChannelOptions{
RefreshInterval: 10 * time.Second, // Long interval so timer doesn't fire.
RefreshBatchSize: 100,
MaxKeysPerConnection: 100,
NotificationBatchMaxSize: 10,
NotificationBatchMaxDelay: 50 * time.Millisecond,
})
node.OnSharedPoll(func(ctx context.Context, event SharedPollEvent) (SharedPollResult, error) {
callCh <- event
items := make([]SharedPollRefreshItem, len(event.Items))
for i, item := range event.Items {
items[i] = SharedPollRefreshItem{
Key: item.Key,
Data: []byte(`{"v":1}`),
Version: 1,
}
}
return SharedPollResult{Items: items}, nil
})
setupSharedPollHandlers(node)
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
{Key: "key2", Version: 0},
})
// Send notification for key1 only.
node.SharedPollNotify([]SharedPollNotificationItem{
{Channel: "test:channel", Key: "key1"},
})
// Should trigger a backend call within batch delay.
select {
case event := <-callCh:
// Should contain key1.
found := false
for _, item := range event.Items {
if item.Key == "key1" {
found = true
}
}
require.True(t, found, "notified key should be in poll event")
case <-time.After(2 * time.Second):
t.Fatal("expected notified refresh call")
}
}
func TestSharedPollNotify_BatchBySize(t *testing.T) {
t.Parallel()
callCh := make(chan SharedPollEvent, 10)
node := newTestNodeWithSharedPoll(t, SharedPollChannelOptions{
RefreshInterval: 10 * time.Second,
RefreshBatchSize: 100,
MaxKeysPerConnection: 100,
NotificationBatchMaxSize: 3,
NotificationBatchMaxDelay: 5 * time.Second, // Long delay — batch should fire by size.
})
node.OnSharedPoll(func(ctx context.Context, event SharedPollEvent) (SharedPollResult, error) {
callCh <- event
items := make([]SharedPollRefreshItem, len(event.Items))
for i, item := range event.Items {
items[i] = SharedPollRefreshItem{
Key: item.Key,
Data: []byte(`{"v":1}`),
Version: 1,
}
}
return SharedPollResult{Items: items}, nil
})
setupSharedPollHandlers(node)
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
{Key: "key2", Version: 0},
{Key: "key3", Version: 0},
})
// Send 3 notifications — should trigger immediately by size.
node.SharedPollNotify([]SharedPollNotificationItem{
{Channel: "test:channel", Key: "key1"},
{Channel: "test:channel", Key: "key2"},
{Channel: "test:channel", Key: "key3"},
})
select {
case event := <-callCh:
require.Len(t, event.Items, 3)
case <-time.After(2 * time.Second):
t.Fatal("expected batch to fire by size")
}
}
func TestSharedPollNotify_DeduplicatesKeys(t *testing.T) {
t.Parallel()
callCh := make(chan SharedPollEvent, 10)
node := newTestNodeWithSharedPoll(t, SharedPollChannelOptions{
RefreshInterval: 10 * time.Second,
RefreshBatchSize: 100,
MaxKeysPerConnection: 100,
NotificationBatchMaxSize: 50,
NotificationBatchMaxDelay: 50 * time.Millisecond,
})
node.OnSharedPoll(func(ctx context.Context, event SharedPollEvent) (SharedPollResult, error) {
callCh <- event
items := make([]SharedPollRefreshItem, len(event.Items))
for i, item := range event.Items {
items[i] = SharedPollRefreshItem{
Key: item.Key,
Data: []byte(`{"v":1}`),
Version: 1,
}
}
return SharedPollResult{Items: items}, nil
})
setupSharedPollHandlers(node)
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
})
// Send duplicate notifications for same key.
node.SharedPollNotify([]SharedPollNotificationItem{
{Channel: "test:channel", Key: "key1"},
{Channel: "test:channel", Key: "key1"},
{Channel: "test:channel", Key: "key1"},
})
select {
case event := <-callCh:
// Should be deduplicated to 1 key.
require.Len(t, event.Items, 1)
require.Equal(t, "key1", event.Items[0].Key)
case <-time.After(2 * time.Second):
t.Fatal("expected notified refresh call")
}
}
func TestSharedPollNotify_UnknownChannelDropped(t *testing.T) {
t.Parallel()
node := newTestNodeWithSharedPoll(t)
setupSharedPollHandlers(node)
// Should not panic or error.
node.SharedPollNotify([]SharedPollNotificationItem{
{Channel: "nonexistent:channel", Key: "key1"},
})
}
func TestSharedPollNotify_FullFlow_DataDelivered(t *testing.T) {
t.Parallel()
// Full flow: client subscribes + tracks → notification arrives →
// backend polled for notified keys → data delivered to client
// (per-connection version updated). Timer interval is long so
// only the notification path triggers the backend call.
node := newTestNodeWithSharedPoll(t, SharedPollChannelOptions{
Mode: SharedPollModeVersioned,
RefreshInterval: 30 * time.Second, // Won't fire during test.
RefreshBatchSize: 100,
MaxKeysPerConnection: 100,
NotificationBatchMaxSize: 50,
NotificationBatchMaxDelay: 50 * time.Millisecond,
})
node.OnSharedPoll(func(ctx context.Context, event SharedPollEvent) (SharedPollResult, error) {
items := make([]SharedPollRefreshItem, 0, len(event.Items))
for _, item := range event.Items {
switch item.Key {
case "key1":
items = append(items, SharedPollRefreshItem{
Key: "key1", Data: []byte(`{"score":42}`), Version: 10,
})
case "key2":
items = append(items, SharedPollRefreshItem{
Key: "key2", Data: []byte(`{"score":99}`), Version: 20,
})
}
}
return SharedPollResult{Items: items}, nil
})
setupSharedPollHandlers(node)
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
{Key: "key2", Version: 0},
{Key: "key3", Version: 0}, // key3 won't be notified.
})
// Notify only key1 and key2.
node.SharedPollNotify([]SharedPollNotificationItem{
{Channel: "test:channel", Key: "key1"},
{Channel: "test:channel", Key: "key2"},
})
// Verify data was delivered to client: per-connection versions updated.
require.Eventually(t, func() bool {
client.mu.RLock()
defer client.mu.RUnlock()
chanKeys := client.keyed.trackedKeys["test:channel"]
k1 := chanKeys["key1"]
k2 := chanKeys["key2"]
k3 := chanKeys["key3"]
return k1 != nil && k1.version == 10 &&
k2 != nil && k2.version == 20 &&
(k3 == nil || k3.version == 0) // key3 not notified — still at 0.
}, 2*time.Second, 10*time.Millisecond)
}
func TestSharedPollNotify_FullFlow_TwoClients(t *testing.T) {
t.Parallel()
// Two clients track the same key. Notification triggers backend poll.
// Both clients should receive the update.
node := newTestNodeWithSharedPoll(t, SharedPollChannelOptions{
Mode: SharedPollModeVersioned,
RefreshInterval: 30 * time.Second,
RefreshBatchSize: 100,
MaxKeysPerConnection: 100,
NotificationBatchMaxSize: 50,
NotificationBatchMaxDelay: 50 * time.Millisecond,
})
node.OnSharedPoll(func(ctx context.Context, event SharedPollEvent) (SharedPollResult, error) {
items := make([]SharedPollRefreshItem, 0, len(event.Items))
for _, item := range event.Items {
if item.Key == "key1" {
items = append(items, SharedPollRefreshItem{
Key: "key1", Data: []byte(`{"v":7}`), Version: 7,
})
}
}
return SharedPollResult{Items: items}, nil
})
setupSharedPollHandlers(node)
client1 := newTestClientV2(t, node, "user1")
connectClientV2(t, client1)
subscribeSharedPollClient(t, client1, "test:channel")
trackSharedPollClient(t, client1, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 2},
})
client2 := newTestClientV2(t, node, "user2")
connectClientV2(t, client2)
subscribeSharedPollClient(t, client2, "test:channel")
trackSharedPollClient(t, client2, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 5},
})
node.SharedPollNotify([]SharedPollNotificationItem{
{Channel: "test:channel", Key: "key1"},
})
// Both clients should receive version 7.
require.Eventually(t, func() bool {
client1.mu.RLock()
k1 := client1.keyed.trackedKeys["test:channel"]["key1"]
var v1 uint64
if k1 != nil {
v1 = k1.version
}
client1.mu.RUnlock()
client2.mu.RLock()
k2 := client2.keyed.trackedKeys["test:channel"]["key1"]
var v2 uint64
if k2 != nil {
v2 = k2.version
}
client2.mu.RUnlock()
return v1 == 7 && v2 == 7
}, 2*time.Second, 10*time.Millisecond)
}
func TestSharedPollNotify_FullFlow_Removal(t *testing.T) {
t.Parallel()
// Backend returns Removed=true for a notified key.
// Client should see the item removed.
node := newTestNodeWithSharedPoll(t, SharedPollChannelOptions{
Mode: SharedPollModeVersioned,
RefreshInterval: 30 * time.Second,
RefreshBatchSize: 100,
MaxKeysPerConnection: 100,
NotificationBatchMaxSize: 50,
NotificationBatchMaxDelay: 50 * time.Millisecond,
})
node.OnSharedPoll(func(ctx context.Context, event SharedPollEvent) (SharedPollResult, error) {
items := make([]SharedPollRefreshItem, 0, len(event.Items))
for _, item := range event.Items {
if item.Key == "key1" {
items = append(items, SharedPollRefreshItem{
Key: "key1", Removed: true,
})
}
}
return SharedPollResult{Items: items}, nil
})
setupSharedPollHandlers(node)
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 3},
})
node.SharedPollNotify([]SharedPollNotificationItem{
{Channel: "test:channel", Key: "key1"},
})
// key1 should be removed from itemIndex and hub.
require.Eventually(t, func() bool {
node.sharedPollManager.mu.RLock()
s, ok := node.sharedPollManager.channels["test:channel"]
node.sharedPollManager.mu.RUnlock()
if !ok {
return true
}
s.mu.Lock()
_, exists := s.itemIndex["key1"]
s.mu.Unlock()
return !exists
}, 2*time.Second, 10*time.Millisecond)
// Client should no longer track key1.
hub := node.keyedManager.getHub("test:channel")
require.NotNil(t, hub)
require.Equal(t, 0, hub.subscriberCount("key1"))
}
func TestSharedPollNotify_UntrackedKeyFiltered(t *testing.T) {
t.Parallel()
callCh := make(chan SharedPollEvent, 10)
node := newTestNodeWithSharedPoll(t, SharedPollChannelOptions{
RefreshInterval: 10 * time.Second,
RefreshBatchSize: 100,
MaxKeysPerConnection: 100,
NotificationBatchMaxSize: 50,
NotificationBatchMaxDelay: 50 * time.Millisecond,
})
node.OnSharedPoll(func(ctx context.Context, event SharedPollEvent) (SharedPollResult, error) {
callCh <- event
return SharedPollResult{}, nil
})
setupSharedPollHandlers(node)
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
})
// Drain auto-notify event for cold key "key1" (triggered by track).
select {
case <-callCh:
case <-time.After(500 * time.Millisecond):
}
// Notify for a key that is NOT tracked.
node.SharedPollNotify([]SharedPollNotificationItem{
{Channel: "test:channel", Key: "unknown_key"},
})
// The notification should be sent to notifCh, but runNotifiedRefreshCycle
// filters it out since "unknown_key" is not in itemIndex.
// Wait a bit — no backend call should happen.
select {
case <-callCh:
t.Fatal("should not call backend for untracked key")
case <-time.After(200 * time.Millisecond):
// Expected — no call.
}
}
func TestKeyedManager_GetOrCreateChannel(t *testing.T) {
t.Parallel()
node := defaultNodeNoHandlers()
defer func() { _ = node.Shutdown(context.Background()) }()
m := node.keyedManager
opts := keyedChannelOptions{MaxTrackedPerConnection: 42}
s1 := m.getOrCreateChannel("ch1", opts)
require.NotNil(t, s1)
s2 := m.getOrCreateChannel("ch1", opts)
require.True(t, s1 == s2, "same channel should return same instance")
s3 := m.getOrCreateChannel("ch2", opts)
require.True(t, s1 != s3, "different channels should return different instances")
}
func TestKeyedManager_MaxTrackedPerConnection(t *testing.T) {
t.Parallel()
node := defaultNodeNoHandlers()
defer func() { _ = node.Shutdown(context.Background()) }()
m := node.keyedManager
// Not created yet — default 5000.
require.Equal(t, 5000, m.maxTrackedPerConnection("nonexistent"))
// Create with custom limit.
m.getOrCreateChannel("ch1", keyedChannelOptions{MaxTrackedPerConnection: 100})
require.Equal(t, 100, m.maxTrackedPerConnection("ch1"))
// Zero limit — default 5000.
m.getOrCreateChannel("ch2", keyedChannelOptions{MaxTrackedPerConnection: 0})
require.Equal(t, 5000, m.maxTrackedPerConnection("ch2"))
}
func TestKeyedManager_RemoveChannel(t *testing.T) {
t.Parallel()
node := defaultNodeNoHandlers()
defer func() { _ = node.Shutdown(context.Background()) }()
m := node.keyedManager
m.getOrCreateChannel("ch1", keyedChannelOptions{})
require.NotNil(t, m.getHub("ch1"))
m.removeChannel("ch1")
require.Nil(t, m.getHub("ch1"))
}
func TestSharedPollPublish_LocalOnly(t *testing.T) {
t.Parallel()
// Publish without PublishEnabled — data delivered locally to subscriber.
node := newTestNodeWithSharedPoll(t, SharedPollChannelOptions{
Mode: SharedPollModeVersioned,
RefreshInterval: 30 * time.Second, // Won't fire during test.
RefreshBatchSize: 100,
MaxKeysPerConnection: 100,
KeepLatestData: true,
})
node.OnSharedPoll(func(ctx context.Context, event SharedPollEvent) (SharedPollResult, error) {
return SharedPollResult{}, nil
})
setupSharedPollHandlers(node)
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
})
err := node.SharedPollPublish(context.Background(), "test:channel", "key1", 5, "", []byte(`{"v":5}`))
require.NoError(t, err)
// Client should receive the publication.
require.Eventually(t, func() bool {
client.mu.RLock()
defer client.mu.RUnlock()
k := client.keyed.trackedKeys["test:channel"]["key1"]
return k != nil && k.version == 5
}, 2*time.Second, 10*time.Millisecond)
}
func TestSharedPollPublish_FreshFromPublish_SkipsTimerPoll(t *testing.T) {
t.Parallel()
// Publish data, verify next timer cycle skips the key.
callCh := make(chan SharedPollEvent, 10)
node := newTestNodeWithSharedPoll(t, SharedPollChannelOptions{
Mode: SharedPollModeVersioned,
RefreshInterval: 200 * time.Millisecond,
RefreshBatchSize: 100,
MaxKeysPerConnection: 100,
KeepLatestData: true,
})
node.OnSharedPoll(func(ctx context.Context, event SharedPollEvent) (SharedPollResult, error) {
callCh <- event
return SharedPollResult{}, nil
})
setupSharedPollHandlers(node)
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
{Key: "key2", Version: 0},
})
// Wait for at least one timer poll that includes both keys.
// Auto-notify may fire first for cold keys (1 item each) — skip those.
var timerEvent SharedPollEvent
require.Eventually(t, func() bool {
select {
case event := <-callCh:
if len(event.Items) == 2 {
timerEvent = event
return true
}
return false // auto-notify event, keep waiting
default:
return false
}
}, 2*time.Second, 10*time.Millisecond)
require.Len(t, timerEvent.Items, 2)
// Publish to key1 — should mark it fresh.
err := node.SharedPollPublish(context.Background(), "test:channel", "key1", 10, "", []byte(`{"v":10}`))
require.NoError(t, err)
// Next timer poll should only include key2 (key1 is fresh). Under -race
// the 200ms cycle can stretch, so allow a generous deadline.
select {
case event := <-callCh:
require.Len(t, event.Items, 1)
require.Equal(t, "key2", event.Items[0].Key)
case <-time.After(5 * time.Second):
t.Fatal("expected timer poll after publish")
}
// Following poll should include both keys again (flag cleared).
select {
case event := <-callCh:
require.Len(t, event.Items, 2)
case <-time.After(5 * time.Second):
t.Fatal("expected full timer poll after flag cleared")
}
}
func TestSharedPollPublish_FreshFromPublish_NotSkippedByNotify(t *testing.T) {
t.Parallel()
// Publish data, then notify same key — notification should still trigger poll.
callCh := make(chan SharedPollEvent, 10)
node := newTestNodeWithSharedPoll(t, SharedPollChannelOptions{
Mode: SharedPollModeVersioned,
RefreshInterval: 30 * time.Second, // Won't fire during test.
RefreshBatchSize: 100,
MaxKeysPerConnection: 100,
KeepLatestData: true,
NotificationBatchMaxSize: 50,
NotificationBatchMaxDelay: 50 * time.Millisecond,
})
node.OnSharedPoll(func(ctx context.Context, event SharedPollEvent) (SharedPollResult, error) {
callCh <- event
items := make([]SharedPollRefreshItem, len(event.Items))
for i, item := range event.Items {
items[i] = SharedPollRefreshItem{
Key: item.Key,
Data: []byte(`{"v":20}`),
Version: 20,
}
}
return SharedPollResult{Items: items}, nil
})
setupSharedPollHandlers(node)
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
})
// Publish v10 to key1.
err := node.SharedPollPublish(context.Background(), "test:channel", "key1", 10, "", []byte(`{"v":10}`))
require.NoError(t, err)
// Wait for publish to be applied.
require.Eventually(t, func() bool {
client.mu.RLock()
defer client.mu.RUnlock()
k := client.keyed.trackedKeys["test:channel"]["key1"]
return k != nil && k.version == 10
}, 2*time.Second, 10*time.Millisecond)
// Now notify key1 — should trigger a backend poll despite freshFromPublish.
node.SharedPollNotify([]SharedPollNotificationItem{
{Channel: "test:channel", Key: "key1"},
})
select {
case event := <-callCh:
found := false
for _, item := range event.Items {
if item.Key == "key1" {
found = true
}
}
require.True(t, found, "notified key should be polled even after publish")
case <-time.After(2 * time.Second):
t.Fatal("expected notification-triggered poll")
}
}
func TestSharedPollPublish_UnknownChannel(t *testing.T) {
t.Parallel()
// Versioned + !PublishEnabled means publish() goes through the local
// path, which no-ops without channel state. This exercises the "no
// track yet" case while staying on a non-versionless mode (publish in
// versionless mode is explicitly rejected).
node := newTestNodeWithSharedPoll(t, SharedPollChannelOptions{
Mode: SharedPollModeVersioned,
RefreshInterval: 30 * time.Second,
RefreshBatchSize: 100,
MaxKeysPerConnection: 100,
})
setupSharedPollHandlers(node)
// Publish to untracked channel — should be a no-op.
err := node.SharedPollPublish(context.Background(), "nonexistent:channel", "key1", 1, "", []byte(`{}`))
require.NoError(t, err)
}
func TestSharedPollPublish_UntrackedKey(t *testing.T) {
t.Parallel()
node := newTestNodeWithSharedPoll(t, SharedPollChannelOptions{
Mode: SharedPollModeVersioned,
RefreshInterval: 30 * time.Second,
MaxKeysPerConnection: 100,
})
node.OnSharedPoll(func(ctx context.Context, event SharedPollEvent) (SharedPollResult, error) {
return SharedPollResult{}, nil
})
setupSharedPollHandlers(node)
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
})
// Publish for a key not tracked — should be a no-op.
err := node.SharedPollPublish(context.Background(), "test:channel", "unknown_key", 1, "", []byte(`{}`))
require.NoError(t, err)
}
func TestSharedPollPublish_DeltaWithKeepLatestData(t *testing.T) {
t.Parallel()
// With KeepLatestData=true, two publishes → second should use delta.
node := newTestNodeWithSharedPoll(t, SharedPollChannelOptions{
Mode: SharedPollModeVersioned,
RefreshInterval: 30 * time.Second,
RefreshBatchSize: 100,
MaxKeysPerConnection: 100,
KeepLatestData: true,
})
node.OnSharedPoll(func(ctx context.Context, event SharedPollEvent) (SharedPollResult, error) {
return SharedPollResult{}, nil
})
setupSharedPollHandlers(node)
client := newTestClientV2(t, node, "user1")
connectClientV2(t, client)
subscribeSharedPollClient(t, client, "test:channel")
trackSharedPollClient(t, client, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
})
// First publish.
err := node.SharedPollPublish(context.Background(), "test:channel", "key1", 1, "", []byte(`{"score":10}`))
require.NoError(t, err)
require.Eventually(t, func() bool {
client.mu.RLock()
defer client.mu.RUnlock()
k := client.keyed.trackedKeys["test:channel"]["key1"]
return k != nil && k.version == 1
}, 2*time.Second, 10*time.Millisecond)
// Second publish with different data — delta should be available.
err = node.SharedPollPublish(context.Background(), "test:channel", "key1", 2, "", []byte(`{"score":20}`))
require.NoError(t, err)
require.Eventually(t, func() bool {
client.mu.RLock()
defer client.mu.RUnlock()
k := client.keyed.trackedKeys["test:channel"]["key1"]
return k != nil && k.version == 2
}, 2*time.Second, 10*time.Millisecond)
// Check that entry data is updated in itemIndex.
node.sharedPollManager.mu.RLock()
s := node.sharedPollManager.channels["test:channel"]
node.sharedPollManager.mu.RUnlock()
s.mu.Lock()
entry := s.itemIndex["key1"]
require.NotNil(t, entry)
require.Equal(t, uint64(2), entry.version)
require.Equal(t, []byte(`{"score":20}`), entry.data)
s.mu.Unlock()
}
func TestSharedPollPublish_MultipleClients(t *testing.T) {
t.Parallel()
// Two clients tracking same key, publish delivers to both.
node := newTestNodeWithSharedPoll(t, SharedPollChannelOptions{
Mode: SharedPollModeVersioned,
RefreshInterval: 30 * time.Second,
RefreshBatchSize: 100,
MaxKeysPerConnection: 100,
})
node.OnSharedPoll(func(ctx context.Context, event SharedPollEvent) (SharedPollResult, error) {
return SharedPollResult{}, nil
})
setupSharedPollHandlers(node)
client1 := newTestClientV2(t, node, "user1")
connectClientV2(t, client1)
subscribeSharedPollClient(t, client1, "test:channel")
trackSharedPollClient(t, client1, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
})
client2 := newTestClientV2(t, node, "user2")
connectClientV2(t, client2)
subscribeSharedPollClient(t, client2, "test:channel")
trackSharedPollClient(t, client2, "test:channel", []*protocol.KeyedItem{
{Key: "key1", Version: 0},
})
err := node.SharedPollPublish(context.Background(), "test:channel", "key1", 5, "", []byte(`{"v":5}`))
require.NoError(t, err)
// Both clients should receive version 5.
require.Eventually(t, func() bool {
client1.mu.RLock()
k1 := client1.keyed.trackedKeys["test:channel"]["key1"]
var v1 uint64
if k1 != nil {
v1 = k1.version
}
client1.mu.RUnlock()
client2.mu.RLock()
k2 := client2.keyed.trackedKeys["test:channel"]["key1"]
var v2 uint64
if k2 != nil {
v2 = k2.version
}
client2.mu.RUnlock()
return v1 == 5 && v2 == 5
}, 2*time.Second, 10*time.Millisecond)
}
func TestSharedPollPublish_BrokerSubscribeOnTrack(t *testing.T) {
t.Parallel()
// With PublishEnabled=true, track key → verify broker subscription.
node := newTestNodeWithSharedPoll(t, SharedPollChannelOptions{
Mode: SharedPollModeVersioned,
RefreshInterval: 30 * time.Second,
MaxKeysPerConnection: 100,
PublishEnabled: true,
})
node.OnSharedPoll(func(ctx context.Context, event SharedPollEvent) (SharedPollResult, error) {
return SharedPollResult{}, nil
})
setupSharedPollHandlers(node)