Debian Codegraph @

internal/recovery/sync_test.go

raw
1 package recovery
2
3 import (
4 "strconv"
5 "sync"
6 "testing"
7 "time"
8
9 "github.com/centrifugal/protocol"
10 "github.com/stretchr/testify/require"
11 )
12
13 func TestPubSubSync(t *testing.T) {
14 psSync := NewPubSubSync()
15 require.Empty(t, psSync.subSync)
16
17 channels := []string{"ch1", "ch2", "ch3"}
18
19 var wg sync.WaitGroup
20 wg.Add(len(channels))
21 for _, channel := range channels {
22 go func(channel string) {
23 defer wg.Done()
24 done := make(chan struct{}, 1)
25 wait := make(chan struct{}, 1)
26
27 psSync.StartBuffering(channel)
28 go func() {
29 for i := 0; i < 10; i++ {
30 psSync.SyncPublication(channel, &protocol.Publication{}, func() {})
31 }
32 close(wait)
33 }()
34 go func() {
35 <-wait
36 psSync.LockBuffer(channel)
37 pubs := psSync.ReadBuffered(channel)
38 require.Equal(t, 10, len(pubs))
39 psSync.StopBuffering(channel)
40 close(done)
41 }()
42 select {
43 case <-done:
44 case <-time.After(time.Second):
45 require.Fail(t, "timeout")
46 }
47 }(channel)
48 }
49 wg.Wait()
50
51 require.Empty(t, psSync.subSync)
52 }
53
54 func BenchmarkPubSubSync(b *testing.B) {
55 psSync := NewPubSubSync()
56 var channels []string
57 for i := 0; i < 1; i++ {
58 channels = append(channels, "server-side-"+strconv.Itoa(i))
59 }
60 b.ResetTimer()
61 for i := 0; i < b.N; i++ {
62 var wg sync.WaitGroup
63 wg.Add(len(channels))
64 for _, channel := range channels {
65 go func(channel string) {
66 defer wg.Done()
67 wait := make(chan struct{}, 1)
68 psSync.StartBuffering(channel)
69 go func() {
70 psSync.SyncPublication(channel, &protocol.Publication{}, func() {})
71 close(wait)
72 }()
73 <-wait
74 psSync.LockBuffer(channel)
75 _ = psSync.ReadBuffered(channel)
76 psSync.StopBuffering(channel)
77 }(channel)
78 }
79 wg.Wait()
80 }
81 b.StopTimer()
82 b.ReportAllocs()
83 }