forked from agntcy/dir
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouting_test.go
More file actions
618 lines (497 loc) · 14.9 KB
/
routing_test.go
File metadata and controls
618 lines (497 loc) · 14.9 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
// Copyright AGNTCY Contributors (https://github.com/agntcy)
// SPDX-License-Identifier: Apache-2.0
package client
import (
"context"
"io"
"runtime"
"testing"
"time"
corev1 "github.com/agntcy/dir/api/core/v1"
routingv1 "github.com/agntcy/dir/api/routing/v1"
"google.golang.org/grpc"
)
const (
// Test data constants.
testRecordCID = "test-cid"
// Test size constants.
testResponseCountSmall = 10
testResponseCountMedium = 100
testResponseCountLarge = 1000
// Test timeout constants.
testSlowServerDelay = 10 * time.Millisecond
testFastServerDelay = 1 * time.Millisecond
testMediumServerDelay = 50 * time.Millisecond
testResponseTimeout = 1 * time.Second
testDrainTimeout = 500 * time.Millisecond
testCleanupDelay = 50 * time.Millisecond
testLongCleanupDelay = 200 * time.Millisecond
testBenchmarkCleanupDelay = 100 * time.Millisecond
// Goroutine leak tolerance.
testGoroutineLeakTolerance = 2
testBenchmarkGoroutineLeakTolerance = 10
// Test read counts.
testPartialReadCount = 5
testSmallReadCount = 10
)
// ============================================================================
// Issue 5: Blocked Goroutine Leaks Tests
// ============================================================================
// mockListStream simulates a gRPC List stream.
type mockListStream struct {
responses []*routingv1.ListResponse
index int
delay time.Duration // Delay between sends to simulate slow server
grpc.ClientStream
}
func (m *mockListStream) Recv() (*routingv1.ListResponse, error) {
if m.delay > 0 {
time.Sleep(m.delay)
}
if m.index >= len(m.responses) {
return nil, io.EOF
}
resp := m.responses[m.index]
m.index++
return resp, nil
}
// mockSearchStream simulates a gRPC Search stream.
type mockSearchStream struct {
responses []*routingv1.SearchResponse
index int
delay time.Duration
grpc.ClientStream
}
func (m *mockSearchStream) Recv() (*routingv1.SearchResponse, error) {
if m.delay > 0 {
time.Sleep(m.delay)
}
if m.index >= len(m.responses) {
return nil, io.EOF
}
resp := m.responses[m.index]
m.index++
return resp, nil
}
// mockRoutingServiceClient is a mock for testing routing methods.
type mockRoutingServiceClient struct {
listResponses []*routingv1.ListResponse
searchResponses []*routingv1.SearchResponse
listDelay time.Duration
searchDelay time.Duration
routingv1.RoutingServiceClient
}
func (m *mockRoutingServiceClient) List(ctx context.Context, req *routingv1.ListRequest, opts ...grpc.CallOption) (routingv1.RoutingService_ListClient, error) {
return &mockListStream{
responses: m.listResponses,
delay: m.listDelay,
}, nil
}
func (m *mockRoutingServiceClient) Search(ctx context.Context, req *routingv1.SearchRequest, opts ...grpc.CallOption) (routingv1.RoutingService_SearchClient, error) {
return &mockSearchStream{
responses: m.searchResponses,
delay: m.searchDelay,
}, nil
}
// countGoroutines returns the current number of goroutines.
func countGoroutines() int {
return runtime.NumGoroutine()
}
// testContextCancellation is a helper that tests context cancellation for streaming methods.
func testContextCancellation(t *testing.T, startStream func(context.Context) (<-chan any, error), name string) {
t.Helper()
initialGoroutines := countGoroutines()
t.Logf("Initial goroutines: %d", initialGoroutines)
ctx, cancel := context.WithCancel(context.Background())
resCh, err := startStream(ctx)
if err != nil {
t.Fatalf("%s failed: %v", name, err)
}
// Read a few responses
readCount := 0
for range testPartialReadCount {
select {
case _, ok := <-resCh:
if !ok {
t.Fatal("Channel closed unexpectedly")
}
readCount++
case <-time.After(testResponseTimeout):
t.Fatal("Timeout waiting for response")
}
}
t.Logf("Read %d responses", readCount)
// Cancel context (consumer stops reading)
cancel()
// Drain remaining responses to allow goroutine to exit
drained := 0
drainTimeout := time.After(testDrainTimeout)
drainLoop:
for {
select {
case _, ok := <-resCh:
if !ok {
// Channel closed, good!
break drainLoop
}
drained++
case <-drainTimeout:
t.Log("Timeout while draining channel")
break drainLoop
}
}
t.Logf("Drained %d additional responses", drained)
// Wait for goroutine to clean up
time.Sleep(testCleanupDelay)
// Count goroutines after
finalGoroutines := countGoroutines()
t.Logf("Final goroutines: %d", finalGoroutines)
// Verify no goroutine leak (allow some tolerance for test framework goroutines)
if finalGoroutines > initialGoroutines+testGoroutineLeakTolerance {
t.Errorf("Goroutine leak detected: initial=%d, final=%d, leaked=%d",
initialGoroutines, finalGoroutines, finalGoroutines-initialGoroutines)
}
}
// testConsumerStopsReading is a helper that tests consumer stopping reading for streaming methods.
func testConsumerStopsReading(t *testing.T, startStream func(context.Context) (<-chan any, error), name string) {
t.Helper()
initialGoroutines := countGoroutines()
t.Logf("Initial goroutines: %d", initialGoroutines)
ctx, cancel := context.WithTimeout(context.Background(), testContextTimeout)
defer cancel()
resCh, err := startStream(ctx)
if err != nil {
t.Fatalf("%s failed: %v", name, err)
}
// Read only a few responses and stop (consumer stops reading)
readCount := 0
for range testSmallReadCount {
<-resCh
readCount++
}
t.Logf("Read %d responses, then stopped", readCount)
// Cancel context to signal we're done
cancel()
// Wait for cleanup
time.Sleep(testLongCleanupDelay)
finalGoroutines := countGoroutines()
t.Logf("Final goroutines: %d", finalGoroutines)
// Verify no significant goroutine leak
if finalGoroutines > initialGoroutines+testGoroutineLeakTolerance {
t.Errorf("Goroutine leak detected: initial=%d, final=%d, leaked=%d",
initialGoroutines, finalGoroutines, finalGoroutines-initialGoroutines)
}
}
// TestList_ContextCancellation tests that List() properly handles context cancellation.
func TestList_ContextCancellation(t *testing.T) {
// Create mock responses
responses := make([]*routingv1.ListResponse, testResponseCountMedium)
for i := range testResponseCountMedium {
responses[i] = &routingv1.ListResponse{
RecordRef: &corev1.RecordRef{
Cid: testRecordCID,
},
}
}
mockClient := &mockRoutingServiceClient{
listResponses: responses,
listDelay: testSlowServerDelay,
}
client := &Client{
RoutingServiceClient: mockClient,
}
// Use helper to test context cancellation
testContextCancellation(t, func(ctx context.Context) (<-chan any, error) {
ch, err := client.List(ctx, &routingv1.ListRequest{})
if err != nil {
return nil, err
}
// Convert typed channel to any channel
outCh := make(chan any)
go func() {
defer close(outCh)
for v := range ch {
outCh <- v
}
}()
return outCh, nil
}, "List()")
}
// TestList_ConsumerStopsReading tests that List() handles consumer stopping reading.
func TestList_ConsumerStopsReading(t *testing.T) {
// Create many mock responses
responses := make([]*routingv1.ListResponse, testResponseCountLarge)
for i := range testResponseCountLarge {
responses[i] = &routingv1.ListResponse{
RecordRef: &corev1.RecordRef{
Cid: testRecordCID,
},
}
}
mockClient := &mockRoutingServiceClient{
listResponses: responses,
listDelay: testFastServerDelay,
}
client := &Client{
RoutingServiceClient: mockClient,
}
// Use helper to test consumer stops reading
testConsumerStopsReading(t, func(ctx context.Context) (<-chan any, error) {
ch, err := client.List(ctx, &routingv1.ListRequest{})
if err != nil {
return nil, err
}
// Convert typed channel to any channel
outCh := make(chan any)
go func() {
defer close(outCh)
for v := range ch {
outCh <- v
}
}()
return outCh, nil
}, "List()")
}
// TestList_FullConsumption tests that List() works correctly when consumer reads everything.
func TestList_FullConsumption(t *testing.T) {
responses := make([]*routingv1.ListResponse, testResponseCountSmall)
for i := range testResponseCountSmall {
responses[i] = &routingv1.ListResponse{
RecordRef: &corev1.RecordRef{
Cid: testRecordCID,
},
}
}
mockClient := &mockRoutingServiceClient{
listResponses: responses,
}
client := &Client{
RoutingServiceClient: mockClient,
}
ctx := context.Background()
resCh, err := client.List(ctx, &routingv1.ListRequest{})
if err != nil {
t.Fatalf("List() failed: %v", err)
}
// Read all responses
count := 0
for range resCh {
count++
}
if count != len(responses) {
t.Errorf("Expected to receive %d responses, got %d", len(responses), count)
}
}
// TestSearchRouting_ContextCancellation tests that SearchRouting() properly handles context cancellation.
func TestSearchRouting_ContextCancellation(t *testing.T) {
responses := make([]*routingv1.SearchResponse, testResponseCountMedium)
for i := range testResponseCountMedium {
responses[i] = &routingv1.SearchResponse{
RecordRef: &corev1.RecordRef{
Cid: testRecordCID,
},
}
}
mockClient := &mockRoutingServiceClient{
searchResponses: responses,
searchDelay: testSlowServerDelay,
}
client := &Client{
RoutingServiceClient: mockClient,
}
// Use helper to test context cancellation
testContextCancellation(t, func(ctx context.Context) (<-chan any, error) {
ch, err := client.SearchRouting(ctx, &routingv1.SearchRequest{})
if err != nil {
return nil, err
}
// Convert typed channel to any channel
outCh := make(chan any)
go func() {
defer close(outCh)
for v := range ch {
outCh <- v
}
}()
return outCh, nil
}, "SearchRouting()")
}
// TestSearchRouting_ConsumerStopsReading tests that SearchRouting() handles consumer stopping reading.
func TestSearchRouting_ConsumerStopsReading(t *testing.T) {
responses := make([]*routingv1.SearchResponse, testResponseCountLarge)
for i := range testResponseCountLarge {
responses[i] = &routingv1.SearchResponse{
RecordRef: &corev1.RecordRef{
Cid: testRecordCID,
},
}
}
mockClient := &mockRoutingServiceClient{
searchResponses: responses,
searchDelay: testFastServerDelay,
}
client := &Client{
RoutingServiceClient: mockClient,
}
// Use helper to test consumer stops reading
testConsumerStopsReading(t, func(ctx context.Context) (<-chan any, error) {
ch, err := client.SearchRouting(ctx, &routingv1.SearchRequest{})
if err != nil {
return nil, err
}
// Convert typed channel to any channel
outCh := make(chan any)
go func() {
defer close(outCh)
for v := range ch {
outCh <- v
}
}()
return outCh, nil
}, "SearchRouting()")
}
// TestSearchRouting_FullConsumption tests that SearchRouting() works correctly when consumer reads everything.
func TestSearchRouting_FullConsumption(t *testing.T) {
responses := make([]*routingv1.SearchResponse, testResponseCountSmall)
for i := range testResponseCountSmall {
responses[i] = &routingv1.SearchResponse{
RecordRef: &corev1.RecordRef{
Cid: testRecordCID,
},
}
}
mockClient := &mockRoutingServiceClient{
searchResponses: responses,
}
client := &Client{
RoutingServiceClient: mockClient,
}
ctx := context.Background()
resCh, err := client.SearchRouting(ctx, &routingv1.SearchRequest{})
if err != nil {
t.Fatalf("SearchRouting() failed: %v", err)
}
// Read all responses
count := 0
for range resCh {
count++
}
if count != len(responses) {
t.Errorf("Expected to receive %d responses, got %d", len(responses), count)
}
}
// TestList_ImmediateCancellation tests List() with immediate context cancellation.
func TestList_ImmediateCancellation(t *testing.T) {
responses := make([]*routingv1.ListResponse, testResponseCountMedium)
for i := range testResponseCountMedium {
responses[i] = &routingv1.ListResponse{
RecordRef: &corev1.RecordRef{
Cid: testRecordCID,
},
}
}
mockClient := &mockRoutingServiceClient{
listResponses: responses,
listDelay: testMediumServerDelay,
}
client := &Client{
RoutingServiceClient: mockClient,
}
// Create already-cancelled context
ctx, cancel := context.WithCancel(context.Background())
cancel() // Cancel immediately
resCh, err := client.List(ctx, &routingv1.ListRequest{})
if err != nil {
t.Fatalf("List() failed: %v", err)
}
// Channel should close quickly due to cancelled context
select {
case _, ok := <-resCh:
if ok {
// If we got a response, that's OK - might have sent before cancel was processed
t.Logf("Got response before cancellation was processed")
}
case <-time.After(testDrainTimeout):
t.Error("Channel should close when context is already cancelled")
}
// Wait for cleanup
time.Sleep(testBenchmarkCleanupDelay)
}
// TestSearchRouting_ImmediateCancellation tests SearchRouting() with immediate context cancellation.
func TestSearchRouting_ImmediateCancellation(t *testing.T) {
responses := make([]*routingv1.SearchResponse, testResponseCountMedium)
for i := range testResponseCountMedium {
responses[i] = &routingv1.SearchResponse{
RecordRef: &corev1.RecordRef{
Cid: testRecordCID,
},
}
}
mockClient := &mockRoutingServiceClient{
searchResponses: responses,
searchDelay: testMediumServerDelay,
}
client := &Client{
RoutingServiceClient: mockClient,
}
// Create already-cancelled context
ctx, cancel := context.WithCancel(context.Background())
cancel()
resCh, err := client.SearchRouting(ctx, &routingv1.SearchRequest{})
if err != nil {
t.Fatalf("SearchRouting() failed: %v", err)
}
// Channel should close quickly
select {
case _, ok := <-resCh:
if ok {
t.Logf("Got response before cancellation was processed")
}
case <-time.After(testDrainTimeout):
t.Error("Channel should close when context is already cancelled")
}
// Wait for cleanup
time.Sleep(testBenchmarkCleanupDelay)
}
// BenchmarkList_NoLeak benchmarks List() to detect goroutine leaks under load.
func BenchmarkList_NoLeak(b *testing.B) {
responses := make([]*routingv1.ListResponse, testResponseCountSmall)
for i := range testResponseCountSmall {
responses[i] = &routingv1.ListResponse{
RecordRef: &corev1.RecordRef{
Cid: testRecordCID,
},
}
}
mockClient := &mockRoutingServiceClient{
listResponses: responses,
}
client := &Client{
RoutingServiceClient: mockClient,
}
initialGoroutines := countGoroutines()
for b.Loop() {
ctx, cancel := context.WithCancel(context.Background())
resCh, err := client.List(ctx, &routingv1.ListRequest{})
if err != nil {
b.Fatalf("List() failed: %v", err)
}
// Read a few then cancel
for range testPartialReadCount - 2 {
<-resCh
}
cancel()
// Drain channel
for range resCh {
}
}
b.StopTimer()
// Check for goroutine leaks
runtime.GC()
time.Sleep(testBenchmarkCleanupDelay)
finalGoroutines := countGoroutines()
if finalGoroutines > initialGoroutines+testBenchmarkGoroutineLeakTolerance {
b.Errorf("Potential goroutine leak: initial=%d, final=%d, leaked=%d",
initialGoroutines, finalGoroutines, finalGoroutines-initialGoroutines)
}
}