-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhub_test.go
More file actions
825 lines (670 loc) · 21.4 KB
/
hub_test.go
File metadata and controls
825 lines (670 loc) · 21.4 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
// ABOUTME: Tests for WebSocket connection hub.
// ABOUTME: Validates client registration, login, and unregistration.
package websocket_test
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/bingo-project/websocket"
)
func TestHub_RegisterAndUnregister(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := websocket.NewHub()
go hub.Run(ctx)
// Create mock client
client := &websocket.Client{
Addr: "127.0.0.1:8080",
Send: make(chan []byte, 10),
}
// Register client (goes to anonymous)
hub.Register <- client
time.Sleep(10 * time.Millisecond)
assert.Equal(t, 1, hub.AnonymousCount())
// Unregister client
hub.Unregister <- client
time.Sleep(10 * time.Millisecond)
assert.Equal(t, 0, hub.AnonymousCount())
}
func TestHub_Login(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := websocket.NewHub()
go hub.Run(ctx)
client := &websocket.Client{
Addr: "127.0.0.1:8080",
Send: make(chan []byte, 10),
}
// Register first
hub.Register <- client
time.Sleep(10 * time.Millisecond)
// Login
hub.Login <- &websocket.LoginEvent{
Client: client,
UserID: "user-123",
Platform: websocket.PlatformIOS,
}
time.Sleep(10 * time.Millisecond)
// Verify user is tracked
assert.Equal(t, 1, hub.UserCount())
assert.NotNil(t, hub.GetUserClient(websocket.PlatformIOS, "user-123"))
}
func TestHub_Broadcast(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := websocket.NewHub()
go hub.Run(ctx)
client1 := &websocket.Client{Addr: "client1", Send: make(chan []byte, 10)}
client2 := &websocket.Client{Addr: "client2", Send: make(chan []byte, 10)}
hub.Register <- client1
hub.Register <- client2
time.Sleep(10 * time.Millisecond)
// Login both clients to make them authenticated
hub.Login <- &websocket.LoginEvent{Client: client1, UserID: "user1", Platform: websocket.PlatformIOS}
hub.Login <- &websocket.LoginEvent{Client: client2, UserID: "user2", Platform: websocket.PlatformWeb}
time.Sleep(10 * time.Millisecond)
// Broadcast message
hub.Broadcast <- []byte("hello")
time.Sleep(10 * time.Millisecond)
// Both clients should receive
assert.Equal(t, 1, len(client1.Send))
assert.Equal(t, 1, len(client2.Send))
}
func TestHub_AnonymousCount(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := websocket.NewHubWithConfig(websocket.DefaultHubConfig())
go hub.Run(ctx)
client := &websocket.Client{
Addr: "127.0.0.1:8080",
Send: make(chan []byte, 10),
}
hub.Register <- client
time.Sleep(10 * time.Millisecond)
// Client is in anonymous state
assert.Equal(t, 1, hub.AnonymousCount())
assert.Equal(t, 0, hub.ClientCount())
}
func TestHub_AnonymousToAuthenticated(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := websocket.NewHubWithConfig(websocket.DefaultHubConfig())
go hub.Run(ctx)
client := &websocket.Client{
Addr: "127.0.0.1:8080",
Send: make(chan []byte, 10),
}
hub.Register <- client
time.Sleep(10 * time.Millisecond)
assert.Equal(t, 1, hub.AnonymousCount())
// Login moves client from anonymous to authenticated
hub.Login <- &websocket.LoginEvent{
Client: client,
UserID: "user-123",
Platform: websocket.PlatformIOS,
}
time.Sleep(10 * time.Millisecond)
assert.Equal(t, 0, hub.AnonymousCount())
assert.Equal(t, 1, hub.ClientCount())
assert.Equal(t, 1, hub.UserCount())
}
func TestHub_KickPreviousSession(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := websocket.NewHubWithConfig(websocket.DefaultHubConfig())
go hub.Run(ctx)
// First client logs in
client1 := &websocket.Client{
Addr: "client1",
Send: make(chan []byte, 10),
FirstTime: time.Now().Unix(),
}
hub.Register <- client1
time.Sleep(10 * time.Millisecond)
hub.Login <- &websocket.LoginEvent{
Client: client1,
UserID: "user-123",
Platform: websocket.PlatformIOS,
}
time.Sleep(10 * time.Millisecond)
// Second client logs in with same user/platform
client2 := &websocket.Client{
Addr: "client2",
Send: make(chan []byte, 10),
FirstTime: time.Now().Unix(),
}
hub.Register <- client2
time.Sleep(10 * time.Millisecond)
hub.Login <- &websocket.LoginEvent{
Client: client2,
UserID: "user-123",
Platform: websocket.PlatformIOS,
}
time.Sleep(150 * time.Millisecond) // Wait for kick delay
// First client should receive kick notification
select {
case msg := <-client1.Send:
assert.Contains(t, string(msg), "session.kicked")
default:
t.Error("client1 should receive kick notification")
}
// Only client2 should remain
assert.Equal(t, 1, hub.ClientCount())
assert.Equal(t, 1, hub.UserCount())
assert.Equal(t, client2, hub.GetUserClient(websocket.PlatformIOS, "user-123"))
}
func TestHub_AnonymousTimeout(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Use short timeout for testing
cfg := &websocket.HubConfig{
AnonymousTimeout: 50 * time.Millisecond,
AnonymousCleanup: 20 * time.Millisecond,
HeartbeatTimeout: 60 * time.Second,
HeartbeatCleanup: 30 * time.Second,
PingPeriod: 54 * time.Second,
PongWait: 60 * time.Second,
}
hub := websocket.NewHubWithConfig(cfg)
go hub.Run(ctx)
client := &websocket.Client{
Addr: "127.0.0.1:8080",
Send: make(chan []byte, 10),
FirstTime: time.Now().Unix(),
}
hub.Register <- client
time.Sleep(10 * time.Millisecond)
assert.Equal(t, 1, hub.AnonymousCount())
// Wait for timeout + cleanup
time.Sleep(100 * time.Millisecond)
// Should be cleaned up
assert.Equal(t, 0, hub.AnonymousCount())
}
func TestHub_Subscribe(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := websocket.NewHubWithConfig(websocket.DefaultHubConfig())
go hub.Run(ctx)
client := &websocket.Client{
Addr: "127.0.0.1:8080",
Send: make(chan []byte, 10),
FirstTime: time.Now().Unix(),
}
hub.Register <- client
hub.Login <- &websocket.LoginEvent{
Client: client,
UserID: "user-123",
Platform: websocket.PlatformIOS,
}
time.Sleep(10 * time.Millisecond)
// Subscribe to topics
result := make(chan []string, 1)
hub.Subscribe <- &websocket.SubscribeEvent{
Client: client,
Topics: []string{"group:123", "room:lobby"},
Result: result,
}
subscribed := <-result
assert.ElementsMatch(t, []string{"group:123", "room:lobby"}, subscribed)
// Verify topic count
assert.Equal(t, 2, hub.TopicCount())
}
func TestHub_PushToTopic(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := websocket.NewHubWithConfig(websocket.DefaultHubConfig())
go hub.Run(ctx)
// Create and login two clients
client1 := &websocket.Client{Addr: "client1", Send: make(chan []byte, 10), FirstTime: time.Now().Unix()}
client2 := &websocket.Client{Addr: "client2", Send: make(chan []byte, 10), FirstTime: time.Now().Unix()}
hub.Register <- client1
hub.Register <- client2
time.Sleep(10 * time.Millisecond)
hub.Login <- &websocket.LoginEvent{Client: client1, UserID: "user1", Platform: websocket.PlatformIOS}
hub.Login <- &websocket.LoginEvent{Client: client2, UserID: "user2", Platform: websocket.PlatformWeb}
time.Sleep(10 * time.Millisecond)
// Subscribe client1 to topic
result := make(chan []string, 1)
hub.Subscribe <- &websocket.SubscribeEvent{Client: client1, Topics: []string{"group:123"}, Result: result}
<-result
// Push to topic
hub.PushToTopic("group:123", "message.new", map[string]string{"content": "hello"})
time.Sleep(10 * time.Millisecond)
// Only client1 should receive
assert.Equal(t, 1, len(client1.Send))
assert.Equal(t, 0, len(client2.Send))
msg := <-client1.Send
assert.Contains(t, string(msg), "message.new")
assert.Contains(t, string(msg), "hello")
}
func TestHub_PushToUser(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := websocket.NewHubWithConfig(websocket.DefaultHubConfig())
go hub.Run(ctx)
client := &websocket.Client{Addr: "client1", Send: make(chan []byte, 10), FirstTime: time.Now().Unix()}
hub.Register <- client
hub.Login <- &websocket.LoginEvent{Client: client, UserID: "user-123", Platform: websocket.PlatformIOS}
time.Sleep(10 * time.Millisecond)
hub.PushToUser(websocket.PlatformIOS, "user-123", "order.created", map[string]string{"order_id": "123"})
time.Sleep(10 * time.Millisecond)
assert.Equal(t, 1, len(client.Send))
msg := <-client.Send
assert.Contains(t, string(msg), "order.created")
}
func TestHub_PushToUserAllPlatforms(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := websocket.NewHubWithConfig(websocket.DefaultHubConfig())
go hub.Run(ctx)
// Same user on two platforms
client1 := &websocket.Client{Addr: "client1", Send: make(chan []byte, 10), FirstTime: time.Now().Unix()}
client2 := &websocket.Client{Addr: "client2", Send: make(chan []byte, 10), FirstTime: time.Now().Unix()}
hub.Register <- client1
hub.Register <- client2
time.Sleep(10 * time.Millisecond)
hub.Login <- &websocket.LoginEvent{Client: client1, UserID: "user-123", Platform: websocket.PlatformIOS}
hub.Login <- &websocket.LoginEvent{Client: client2, UserID: "user-123", Platform: websocket.PlatformWeb}
time.Sleep(10 * time.Millisecond)
hub.PushToUserAllPlatforms("user-123", "security.alert", map[string]string{"message": "new login"})
time.Sleep(10 * time.Millisecond)
// Both clients should receive
assert.Equal(t, 1, len(client1.Send))
assert.Equal(t, 1, len(client2.Send))
}
func TestHub_Unsubscribe(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := websocket.NewHubWithConfig(websocket.DefaultHubConfig())
go hub.Run(ctx)
client := &websocket.Client{
Addr: "127.0.0.1:8080",
Send: make(chan []byte, 10),
FirstTime: time.Now().Unix(),
}
hub.Register <- client
hub.Login <- &websocket.LoginEvent{
Client: client,
UserID: "user-123",
Platform: websocket.PlatformIOS,
}
time.Sleep(10 * time.Millisecond)
// Subscribe
result := make(chan []string, 1)
hub.Subscribe <- &websocket.SubscribeEvent{
Client: client,
Topics: []string{"group:123", "room:lobby"},
Result: result,
}
<-result
// Unsubscribe one topic
hub.Unsubscribe <- &websocket.UnsubscribeEvent{
Client: client,
Topics: []string{"group:123"},
}
time.Sleep(10 * time.Millisecond)
assert.Equal(t, 1, hub.TopicCount())
}
func TestHub_TokenExpiration(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cfg := &websocket.HubConfig{
AnonymousTimeout: 10 * time.Second,
AnonymousCleanup: 2 * time.Second,
HeartbeatTimeout: 60 * time.Second,
HeartbeatCleanup: 50 * time.Millisecond, // Fast for testing
PingPeriod: 54 * time.Second,
PongWait: 60 * time.Second,
}
hub := websocket.NewHubWithConfig(cfg)
go hub.Run(ctx)
now := time.Now().Unix()
client := &websocket.Client{Addr: "client1", Send: make(chan []byte, 10), FirstTime: now}
client.Heartbeat(now)
hub.Register <- client
time.Sleep(10 * time.Millisecond)
// Login with token that expires immediately
hub.Login <- &websocket.LoginEvent{
Client: client,
UserID: "user-123",
Platform: websocket.PlatformIOS,
TokenExpiresAt: time.Now().Unix() - 1, // Already expired
}
time.Sleep(150 * time.Millisecond)
// Should receive session.expired notification
select {
case msg := <-client.Send:
assert.Contains(t, string(msg), "session.expired")
default:
t.Error("Should receive session.expired notification")
}
}
func TestHub_UnsubscribeAllOnDisconnect(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := websocket.NewHubWithConfig(websocket.DefaultHubConfig())
go hub.Run(ctx)
time.Sleep(10 * time.Millisecond) // Wait for hub to start
now := time.Now().Unix()
client := &websocket.Client{Addr: "client1", Send: make(chan []byte, 10), FirstTime: now}
client.Heartbeat(now)
hub.Register <- client
time.Sleep(10 * time.Millisecond)
hub.Login <- &websocket.LoginEvent{Client: client, UserID: "user-123", Platform: websocket.PlatformIOS}
time.Sleep(10 * time.Millisecond)
// Subscribe to topics
result := make(chan []string, 1)
hub.Subscribe <- &websocket.SubscribeEvent{Client: client, Topics: []string{"group:123", "room:456"}, Result: result}
<-result
assert.Equal(t, 2, hub.TopicCount())
// Disconnect
hub.Unregister <- client
time.Sleep(50 * time.Millisecond) // Increase wait time
// Topics should be cleaned up
assert.Equal(t, 0, hub.TopicCount())
}
func TestHub_GracefulShutdown(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
hub := websocket.NewHub()
go hub.Run(ctx)
client := &websocket.Client{
Addr: "127.0.0.1:8080",
Send: make(chan []byte, 10),
}
hub.Register <- client
time.Sleep(10 * time.Millisecond)
assert.Equal(t, 1, hub.AnonymousCount())
// Cancel context to trigger shutdown
cancel()
time.Sleep(20 * time.Millisecond)
// Verify client is cleaned up
assert.Equal(t, 0, hub.AnonymousCount())
// Should receive shutdown notification
select {
case msg := <-client.Send:
assert.Contains(t, string(msg), "session.shutdown")
default:
// May have already been drained or not sent
}
// Drain any remaining messages and verify channel is eventually closed
for {
_, ok := <-client.Send
if !ok {
break // Channel closed
}
}
// If we get here, channel was successfully closed
}
func TestHub_GetClient(t *testing.T) {
hub := websocket.NewHub()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go hub.Run(ctx)
// Create and register client
client := &websocket.Client{
ID: "test-client-id",
Send: make(chan []byte, 256),
}
hub.Register <- client
time.Sleep(10 * time.Millisecond)
// Get by ID
found := hub.GetClient("test-client-id")
assert.Equal(t, client, found)
// Not found
notFound := hub.GetClient("unknown")
assert.Nil(t, notFound)
}
func TestHub_GetClientsByUser(t *testing.T) {
hub := websocket.NewHub()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go hub.Run(ctx)
// Create clients for same user on different platforms
client1 := &websocket.Client{
ID: "c1",
Addr: "client1",
Send: make(chan []byte, 256),
}
client2 := &websocket.Client{
ID: "c2",
Addr: "client2",
Send: make(chan []byte, 256),
}
hub.Register <- client1
hub.Register <- client2
time.Sleep(10 * time.Millisecond)
hub.Login <- &websocket.LoginEvent{Client: client1, UserID: "user-123", Platform: websocket.PlatformWeb}
hub.Login <- &websocket.LoginEvent{Client: client2, UserID: "user-123", Platform: websocket.PlatformIOS}
time.Sleep(10 * time.Millisecond)
clients := hub.GetClientsByUser("user-123")
assert.Len(t, clients, 2)
}
func TestHub_Stats(t *testing.T) {
hub := websocket.NewHub()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go hub.Run(ctx)
// Create anonymous client
anonClient := &websocket.Client{
ID: "anon",
Addr: "anon",
Send: make(chan []byte, 256),
}
hub.Register <- anonClient
time.Sleep(10 * time.Millisecond)
// Create authenticated clients
client1 := &websocket.Client{
ID: "c1",
Addr: "client1",
Send: make(chan []byte, 256),
}
client2 := &websocket.Client{
ID: "c2",
Addr: "client2",
Send: make(chan []byte, 256),
}
hub.Register <- client1
hub.Register <- client2
time.Sleep(10 * time.Millisecond)
hub.Login <- &websocket.LoginEvent{Client: client1, UserID: "user1", Platform: websocket.PlatformWeb}
hub.Login <- &websocket.LoginEvent{Client: client2, UserID: "user2", Platform: websocket.PlatformIOS}
time.Sleep(10 * time.Millisecond)
stats := hub.Stats()
assert.Equal(t, int64(1), stats.AnonymousConns)
assert.Equal(t, int64(2), stats.AuthenticatedConns)
assert.Equal(t, int64(3), stats.TotalConnections)
assert.Equal(t, 1, stats.ConnectionsByPlatform[websocket.PlatformWeb])
assert.Equal(t, 1, stats.ConnectionsByPlatform[websocket.PlatformIOS])
}
func TestHub_KickClient(t *testing.T) {
hub := websocket.NewHub()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go hub.Run(ctx)
client := &websocket.Client{
ID: "test-client",
Addr: "client1",
Send: make(chan []byte, 256),
}
hub.Register <- client
time.Sleep(10 * time.Millisecond)
hub.Login <- &websocket.LoginEvent{Client: client, UserID: "user-123", Platform: websocket.PlatformWeb}
time.Sleep(10 * time.Millisecond)
assert.Equal(t, 1, hub.ClientCount())
// Kick client
kicked := hub.KickClient("test-client", "test kick")
assert.True(t, kicked)
// Should receive kick notification
time.Sleep(20 * time.Millisecond)
select {
case msg := <-client.Send:
assert.Contains(t, string(msg), "session.kicked")
default:
t.Error("Should receive kick notification")
}
// Wait for kick to complete
time.Sleep(200 * time.Millisecond)
assert.Equal(t, 0, hub.ClientCount())
}
func TestHub_KickUser(t *testing.T) {
hub := websocket.NewHub()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go hub.Run(ctx)
// User on multiple platforms
client1 := &websocket.Client{
ID: "c1",
Addr: "client1",
Send: make(chan []byte, 256),
}
client2 := &websocket.Client{
ID: "c2",
Addr: "client2",
Send: make(chan []byte, 256),
}
hub.Register <- client1
hub.Register <- client2
time.Sleep(10 * time.Millisecond)
hub.Login <- &websocket.LoginEvent{Client: client1, UserID: "user-123", Platform: websocket.PlatformWeb}
hub.Login <- &websocket.LoginEvent{Client: client2, UserID: "user-123", Platform: websocket.PlatformIOS}
time.Sleep(10 * time.Millisecond)
assert.Equal(t, 2, hub.ClientCount())
// Kick all user's connections
kicked := hub.KickUser("user-123", "account suspended")
assert.Equal(t, 2, kicked)
// Wait for kicks to complete
time.Sleep(200 * time.Millisecond)
assert.Equal(t, 0, hub.ClientCount())
}
// Concurrent tests for race detection
func TestHub_ConcurrentRegisterUnregister(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := websocket.NewHub()
go hub.Run(ctx)
const numClients = 100
clients := make([]*websocket.Client, numClients)
// Create clients
for i := 0; i < numClients; i++ {
clients[i] = &websocket.Client{
ID: string(rune('a' + i%26)) + string(rune(i)),
Addr: "client",
Send: make(chan []byte, 10),
}
}
// Concurrent register
for i := 0; i < numClients; i++ {
go func(c *websocket.Client) {
hub.Register <- c
}(clients[i])
}
time.Sleep(50 * time.Millisecond)
// Concurrent unregister
for i := 0; i < numClients; i++ {
go func(c *websocket.Client) {
hub.Unregister <- c
}(clients[i])
}
time.Sleep(50 * time.Millisecond)
assert.Equal(t, 0, hub.AnonymousCount())
}
func TestHub_ConcurrentLoginAndBroadcast(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := websocket.NewHub()
go hub.Run(ctx)
const numClients = 50
clients := make([]*websocket.Client, numClients)
platforms := []string{websocket.PlatformWeb, websocket.PlatformIOS, websocket.PlatformAndroid}
// Register and login clients concurrently
for i := 0; i < numClients; i++ {
clients[i] = &websocket.Client{
ID: string(rune('a'+i%26)) + string(rune(i)),
Addr: "client",
Send: make(chan []byte, 256),
}
hub.Register <- clients[i]
}
time.Sleep(20 * time.Millisecond)
// Concurrent logins
for i := 0; i < numClients; i++ {
go func(idx int) {
hub.Login <- &websocket.LoginEvent{
Client: clients[idx],
UserID: "user-" + string(rune('0'+idx%10)),
Platform: platforms[idx%3],
}
}(i)
}
time.Sleep(50 * time.Millisecond)
// Concurrent broadcasts while clients are connected
for i := 0; i < 10; i++ {
go func() {
hub.Broadcast <- []byte(`{"jsonrpc":"2.0","method":"test","params":{}}`)
}()
}
time.Sleep(50 * time.Millisecond)
// Drain client send channels
for _, c := range clients {
for len(c.Send) > 0 {
<-c.Send
}
}
assert.True(t, hub.ClientCount() > 0)
}
func TestHub_ConcurrentSubscribeAndPush(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := websocket.NewHub()
go hub.Run(ctx)
const numClients = 30
clients := make([]*websocket.Client, numClients)
topics := []string{"topic1", "topic2", "topic3"}
// Setup clients
for i := 0; i < numClients; i++ {
clients[i] = &websocket.Client{
ID: string(rune('a'+i%26)) + string(rune(i)),
Addr: "client",
Send: make(chan []byte, 256),
}
hub.Register <- clients[i]
}
time.Sleep(20 * time.Millisecond)
for i := 0; i < numClients; i++ {
hub.Login <- &websocket.LoginEvent{
Client: clients[i],
UserID: "user-" + string(rune('0'+i%10)),
Platform: websocket.PlatformWeb,
}
}
time.Sleep(20 * time.Millisecond)
// Concurrent subscriptions
for i := 0; i < numClients; i++ {
go func(idx int) {
hub.Subscribe <- &websocket.SubscribeEvent{
Client: clients[idx],
Topics: []string{topics[idx%3]},
}
}(i)
}
time.Sleep(50 * time.Millisecond)
// Concurrent push to topics while subscriptions may still be processing
for i := 0; i < 20; i++ {
go func(idx int) {
hub.PushToTopic(topics[idx%3], "test.push", map[string]int{"n": idx})
}(i)
}
time.Sleep(50 * time.Millisecond)
// Concurrent unsubscribe
for i := 0; i < numClients; i++ {
go func(idx int) {
hub.Unsubscribe <- &websocket.UnsubscribeEvent{
Client: clients[idx],
Topics: []string{topics[idx%3]},
}
}(i)
}
time.Sleep(50 * time.Millisecond)
assert.Equal(t, 0, hub.TopicCount())
}