Debian Codegraph @

testing/e2e/matrix/concurrency_test.go

raw
1 package e2e_test
2
3 import (
4 "fmt"
5 "net/url"
6 "sync"
7 "sync/atomic"
8 "time"
9
10 "github.com/onsi/ginkgo/v2"
11 "github.com/onsi/gomega"
12
13 "github.com/nicholas-fedor/shoutrrr/internal/testutils"
14 "github.com/nicholas-fedor/shoutrrr/pkg/services/chat/matrix"
15 )
16
17 var _ = ginkgo.Describe("Matrix Service E2E Concurrency", func() {
18 // TestE2EConcurrentSends tests that multiple messages can be sent concurrently.
19 ginkgo.Describe("Concurrent Sends", func() {
20 ginkgo.It("should send multiple messages concurrently", func() {
21 // Use shared service if available
22 err := getOrInitSharedService()
23 if err != nil {
24 ginkgo.Skip(fmt.Sprintf("Cannot initialize shared service: %v", err))
25 }
26
27 // Number of concurrent messages to send
28 concurrency := 5
29 errChan := make(chan error, concurrency)
30
31 var wg sync.WaitGroup
32
33 // Send multiple messages concurrently
34 for i := range concurrency {
35 wg.Add(1)
36
37 go func(idx int) {
38 defer wg.Done()
39
40 message := fmt.Sprintf("Concurrent message %d - %d", idx, time.Now().UnixNano())
41
42 err := sharedService.Send(message, nil)
43 errChan <- err
44 }(i)
45 }
46
47 // Wait for all goroutines to complete
48 wg.Wait()
49 close(errChan)
50
51 // Check all sends completed without errors
52 errCount := 0
53
54 for err := range errChan {
55 if err != nil {
56 errCount++
57 }
58 }
59
60 // All sends must succeed
61 gomega.Expect(errCount).To(gomega.Equal(0),
62 "Expected all sends to succeed, but some failed")
63 })
64
65 ginkgo.It("should handle rapid sequential sends without race conditions", func() {
66 err := getOrInitSharedService()
67 if err != nil {
68 ginkgo.Skip(fmt.Sprintf("Cannot initialize shared service: %v", err))
69 }
70
71 // Send messages in quick succession
72 // This tests that the service can handle rapid requests
73 numMessages := 10
74 for range numMessages {
75 err := sharedService.Send("Rapid send test message", nil)
76 // All messages must succeed
77 gomega.Expect(err).NotTo(gomega.HaveOccurred())
78
79 // Small delay between messages
80 time.Sleep(100 * time.Millisecond)
81 }
82 })
83
84 ginkgo.It("should handle concurrent initialization safely", func() {
85 serviceURL := buildServiceURL()
86 if serviceURL == "" {
87 ginkgo.Skip("Matrix server not configured, skipping test")
88 }
89
90 parsedURL, err := url.Parse(serviceURL)
91 gomega.Expect(err).NotTo(gomega.HaveOccurred())
92
93 // Create multiple services concurrently
94 numServices := 3
95
96 var wg sync.WaitGroup
97
98 serviceChan := make(chan *matrix.Service, numServices)
99 errChan := make(chan error, numServices)
100
101 for range numServices {
102 wg.Go(func() {
103 service := &matrix.Service{}
104
105 err := service.Initialize(parsedURL, testutils.TestLogger())
106 serviceChan <- service
107
108 errChan <- err
109 })
110 }
111
112 wg.Wait()
113 close(serviceChan)
114 close(errChan)
115
116 // Collect results
117 var successCount int
118
119 for svc := range serviceChan {
120 if svc != nil {
121 successCount++
122 }
123 }
124
125 // Some may succeed, some may fail due to session conflicts
126 // At least one should succeed
127 gomega.Expect(successCount).To(gomega.BeNumerically(">", 0),
128 "Expected at least one service to initialize successfully")
129 })
130 })
131
132 // TestE2ERaceConditionPrevention tests that transaction IDs prevent duplicate messages.
133 ginkgo.Describe("Race Condition Prevention", func() {
134 ginkgo.It("should generate unique transaction IDs for each message", func() {
135 // Test the transaction ID generation by looking at the internal behavior
136 // We verify that rapid sends don't result in duplicate transaction IDs
137 // which could cause message duplication on the Matrix server
138 err := getOrInitSharedService()
139 if err != nil {
140 ginkgo.Skip(fmt.Sprintf("Cannot initialize shared service: %v", err))
141 }
142
143 // Track transaction IDs indirectly by checking for duplicates in error messages
144 // or by verifying all messages are delivered
145 numMessages := 5
146
147 var successfulSends atomic.Int32
148
149 // Send messages with unique identifiers
150 var wg sync.WaitGroup
151 for i := range numMessages {
152 wg.Add(1)
153
154 go func(idx int) {
155 defer wg.Done()
156 // Each message has a unique identifier in the content
157 uniqueMsg := fmt.Sprintf("Race condition test - unique ID: %d-%d", idx, time.Now().UnixNano())
158
159 err := sharedService.Send(uniqueMsg, nil)
160 if err == nil {
161 successfulSends.Add(1)
162 }
163 }(i)
164 }
165
166 wg.Wait()
167
168 // All messages should succeed
169 gomega.Expect(successfulSends.Load()).To(gomega.Equal(int32(numMessages)),
170 "Expected all messages to be sent successfully")
171 })
172
173 ginkgo.It("should handle multiple goroutines accessing service concurrently", func() {
174 // This is a stress test to ensure thread-safety
175 err := getOrInitSharedService()
176 if err != nil {
177 ginkgo.Skip(fmt.Sprintf("Cannot initialize shared service: %v", err))
178 }
179
180 numGoroutines := 10
181 numIterations := 3
182
183 var wg sync.WaitGroup
184
185 errorCount := &atomic.Int32{}
186
187 for iteration := range numIterations {
188 for i := range numGoroutines {
189 wg.Add(1)
190
191 go func(goroutineID, iterID int) {
192 defer wg.Done()
193
194 message := fmt.Sprintf("Stress test - goroutine %d iteration %d", goroutineID, iterID)
195
196 err := sharedService.Send(message, nil)
197 if err != nil {
198 errorCount.Add(1)
199 }
200 }(i, iteration)
201 }
202 // Small delay between iterations
203 time.Sleep(200 * time.Millisecond)
204 }
205
206 wg.Wait()
207
208 // Calculate success rate
209 totalAttempts := numGoroutines * numIterations
210 successCount := totalAttempts - int(errorCount.Load())
211
212 // At least 50% should succeed (conservative under concurrent load)
213 gomega.Expect(successCount).To(gomega.BeNumerically(">=", totalAttempts/2),
214 "Expected at least 50% success rate under concurrent load")
215 })
216 })
217 })