-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrequest_coalescing_test.go
More file actions
407 lines (322 loc) · 9.67 KB
/
Copy pathrequest_coalescing_test.go
File metadata and controls
407 lines (322 loc) · 9.67 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
package main
import (
"errors"
"sync"
"sync/atomic"
"testing"
"time"
libpack_logger "github.com/lukaszraczylo/graphql-monitoring-proxy/logging"
libpack_monitoring "github.com/lukaszraczylo/graphql-monitoring-proxy/monitoring"
"github.com/stretchr/testify/assert"
)
func TestNewRequestCoalescer(t *testing.T) {
tests := []struct {
name string
enabled bool
}{
{
name: "enabled coalescer",
enabled: true,
},
{
name: "disabled coalescer",
enabled: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
logger := libpack_logger.New()
monitoring := libpack_monitoring.NewMonitoring(&libpack_monitoring.InitConfig{})
rc := NewRequestCoalescer(tt.enabled, logger, monitoring)
assert.NotNil(t, rc)
assert.Equal(t, tt.enabled, rc.enabled)
})
}
}
func TestRequestCoalescer_Do_SingleRequest(t *testing.T) {
rc := NewRequestCoalescer(true, libpack_logger.New(), nil)
executed := false
response := &CoalescedResponse{
Body: []byte("test response"),
StatusCode: 200,
}
fn := func() (*CoalescedResponse, error) {
executed = true
return response, nil
}
result, err := rc.Do("test-key", fn)
assert.NoError(t, err)
assert.True(t, executed)
assert.Equal(t, response, result)
stats := rc.GetStats()
assert.Equal(t, int64(1), stats["total_requests"])
assert.Equal(t, int64(1), stats["primary_requests"])
assert.Equal(t, int64(0), stats["coalesced_requests"])
}
func TestRequestCoalescer_Do_ConcurrentRequests(t *testing.T) {
rc := NewRequestCoalescer(true, libpack_logger.New(), nil)
var executionCount atomic.Int32
response := &CoalescedResponse{
Body: []byte("test response"),
StatusCode: 200,
}
fn := func() (*CoalescedResponse, error) {
executionCount.Add(1)
time.Sleep(50 * time.Millisecond) // Simulate work
return response, nil
}
// Launch concurrent requests with the same key
concurrentRequests := 10
var wg sync.WaitGroup
wg.Add(concurrentRequests)
results := make([]*CoalescedResponse, concurrentRequests)
errs := make([]error, concurrentRequests)
for i := 0; i < concurrentRequests; i++ {
go func(index int) {
defer wg.Done()
results[index], errs[index] = rc.Do("same-key", fn)
}(i)
}
wg.Wait()
// Function should only execute once
assert.Equal(t, int32(1), executionCount.Load())
// All requests should get the same response
for i := 0; i < concurrentRequests; i++ {
assert.NoError(t, errs[i])
assert.Equal(t, response, results[i])
}
stats := rc.GetStats()
assert.Equal(t, int64(concurrentRequests), stats["total_requests"])
assert.Equal(t, int64(1), stats["primary_requests"])
assert.Equal(t, int64(concurrentRequests-1), stats["coalesced_requests"])
// Check backend savings
backendSavings := stats["backend_savings_pct"].(float64)
assert.Greater(t, backendSavings, 0.0)
}
func TestRequestCoalescer_Do_DifferentKeys(t *testing.T) {
rc := NewRequestCoalescer(true, libpack_logger.New(), nil)
var executionCount atomic.Int32
fn := func() (*CoalescedResponse, error) {
executionCount.Add(1)
return &CoalescedResponse{Body: []byte("response")}, nil
}
// Concurrent requests with different keys
var wg sync.WaitGroup
keys := []string{"key1", "key2", "key3"}
for _, key := range keys {
wg.Add(1)
go func(k string) {
defer wg.Done()
rc.Do(k, fn)
}(key)
}
wg.Wait()
// Function should execute for each unique key
assert.Equal(t, int32(len(keys)), executionCount.Load())
stats := rc.GetStats()
assert.Equal(t, int64(3), stats["primary_requests"])
assert.Equal(t, int64(0), stats["coalesced_requests"])
}
func TestRequestCoalescer_Do_Error(t *testing.T) {
rc := NewRequestCoalescer(true, libpack_logger.New(), nil)
expectedErr := errors.New("test error")
fn := func() (*CoalescedResponse, error) {
return nil, expectedErr
}
result, err := rc.Do("error-key", fn)
assert.NoError(t, err)
assert.NotNil(t, result)
assert.Error(t, result.Err)
assert.Equal(t, expectedErr, result.Err)
}
func TestRequestCoalescer_Do_ConcurrentWithError(t *testing.T) {
rc := NewRequestCoalescer(true, libpack_logger.New(), nil)
expectedErr := errors.New("test error")
var executionCount atomic.Int32
fn := func() (*CoalescedResponse, error) {
executionCount.Add(1)
time.Sleep(50 * time.Millisecond)
return nil, expectedErr
}
// Launch concurrent requests
concurrentRequests := 5
var wg sync.WaitGroup
wg.Add(concurrentRequests)
results := make([]*CoalescedResponse, concurrentRequests)
for i := 0; i < concurrentRequests; i++ {
go func(index int) {
defer wg.Done()
results[index], _ = rc.Do("error-key", fn)
}(i)
}
wg.Wait()
// Function should only execute once
assert.Equal(t, int32(1), executionCount.Load())
// All requests should get the same error in response
for i := 0; i < concurrentRequests; i++ {
assert.NotNil(t, results[i])
assert.Error(t, results[i].Err)
assert.Equal(t, expectedErr, results[i].Err)
}
}
func TestRequestCoalescer_Do_Disabled(t *testing.T) {
rc := NewRequestCoalescer(false, libpack_logger.New(), nil)
var executionCount atomic.Int32
fn := func() (*CoalescedResponse, error) {
executionCount.Add(1)
return &CoalescedResponse{Body: []byte("response")}, nil
}
// Launch concurrent requests with the same key
concurrentRequests := 5
var wg sync.WaitGroup
wg.Add(concurrentRequests)
for i := 0; i < concurrentRequests; i++ {
go func() {
defer wg.Done()
rc.Do("same-key", fn)
}()
}
wg.Wait()
// When disabled, function should execute for each request
assert.Equal(t, int32(concurrentRequests), executionCount.Load())
stats := rc.GetStats()
assert.Equal(t, false, stats["enabled"])
}
func TestRequestCoalescer_GetStats(t *testing.T) {
rc := NewRequestCoalescer(true, libpack_logger.New(), nil)
fn := func() (*CoalescedResponse, error) {
time.Sleep(10 * time.Millisecond)
return &CoalescedResponse{Body: []byte("response")}, nil
}
// Simulate some coalesced requests
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
rc.Do("key1", fn)
}()
}
wg.Wait()
// Add some non-coalesced requests
rc.Do("key2", fn)
rc.Do("key3", fn)
stats := rc.GetStats()
assert.Equal(t, true, stats["enabled"])
assert.Equal(t, int64(12), stats["total_requests"])
assert.Equal(t, int64(3), stats["primary_requests"])
assert.Equal(t, int64(9), stats["coalesced_requests"])
assert.Equal(t, int64(0), stats["inflight_count"])
coalescingRate := stats["coalescing_rate_pct"].(float64)
assert.Greater(t, coalescingRate, 0.0)
assert.LessOrEqual(t, coalescingRate, 100.0)
backendSavings := stats["backend_savings_pct"].(float64)
assert.Greater(t, backendSavings, 0.0)
}
func TestRequestCoalescer_Reset(t *testing.T) {
rc := NewRequestCoalescer(true, libpack_logger.New(), nil)
fn := func() (*CoalescedResponse, error) {
return &CoalescedResponse{Body: []byte("response")}, nil
}
// Generate some activity
rc.Do("key1", fn)
rc.Do("key2", fn)
statsBefore := rc.GetStats()
assert.Greater(t, statsBefore["total_requests"].(int64), int64(0))
// Reset
rc.Reset()
statsAfter := rc.GetStats()
assert.Equal(t, int64(0), statsAfter["total_requests"])
assert.Equal(t, int64(0), statsAfter["primary_requests"])
assert.Equal(t, int64(0), statsAfter["coalesced_requests"])
}
func TestRequestCoalescer_RaceCondition(t *testing.T) {
rc := NewRequestCoalescer(true, libpack_logger.New(), nil)
var executionCount atomic.Int32
fn := func() (*CoalescedResponse, error) {
executionCount.Add(1)
time.Sleep(5 * time.Millisecond)
return &CoalescedResponse{Body: []byte("response")}, nil
}
// Launch many concurrent requests in waves
waves := 5
requestsPerWave := 20
for wave := 0; wave < waves; wave++ {
var wg sync.WaitGroup
wg.Add(requestsPerWave)
for i := 0; i < requestsPerWave; i++ {
go func() {
defer wg.Done()
rc.Do("race-key", fn)
}()
}
wg.Wait()
time.Sleep(10 * time.Millisecond) // Small delay between waves
}
// Execution count should be much less than total requests
totalRequests := waves * requestsPerWave
assert.Less(t, int(executionCount.Load()), totalRequests)
stats := rc.GetStats()
assert.Equal(t, int64(totalRequests), stats["total_requests"])
}
func TestRequestCoalescer_BackendSavingsCalculation(t *testing.T) {
tests := []struct {
name string
totalRequests int64
coalescedRequests int64
expectedSavings float64
}{
{
name: "50% savings",
totalRequests: 100,
coalescedRequests: 50,
expectedSavings: 100.0, // 50 coalesced / 50 primary = 100%
},
{
name: "90% savings",
totalRequests: 100,
coalescedRequests: 90,
expectedSavings: 900.0, // 90 coalesced / 10 primary = 900%
},
{
name: "no savings",
totalRequests: 100,
coalescedRequests: 0,
expectedSavings: 0.0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rc := NewRequestCoalescer(true, libpack_logger.New(), nil)
rc.totalRequests.Store(tt.totalRequests)
rc.coalescedRequests.Store(tt.coalescedRequests)
stats := rc.GetStats()
savings := stats["backend_savings_pct"].(float64)
assert.InDelta(t, tt.expectedSavings, savings, 0.1)
})
}
}
func TestRequestCoalescer_GlobalInstance(t *testing.T) {
rc := InitializeRequestCoalescer(true, libpack_logger.New(), nil)
assert.NotNil(t, rc)
// Should return the same instance
rc2 := GetRequestCoalescer()
assert.Equal(t, rc, rc2)
}
func TestMin(t *testing.T) {
tests := []struct {
a int
b int
expected int
}{
{a: 5, b: 10, expected: 5},
{a: 10, b: 5, expected: 5},
{a: 5, b: 5, expected: 5},
{a: 0, b: 10, expected: 0},
{a: -5, b: 5, expected: -5},
}
for _, tt := range tests {
result := min(tt.a, tt.b)
assert.Equal(t, tt.expected, result)
}
}