Debian Codegraph @

server/ipqueue_test.go

raw
1 // Copyright 2021-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "sync"
18 "sync/atomic"
19 "testing"
20 "time"
21 )
22
23 func TestIPQueueBasic(t *testing.T) {
24 s := &Server{}
25 q := newIPQueue[int](s, "test")
26 // Check that pool has been created
27 if q.pool == nil {
28 t.Fatal("Expected pool to have been created")
29 }
30 // Check for the default mrs
31 if q.mrs != ipQueueDefaultMaxRecycleSize {
32 t.Fatalf("Expected default max recycle size to be %v, got %v",
33 ipQueueDefaultMaxRecycleSize, q.mrs)
34 }
35 select {
36 case <-q.ch:
37 t.Fatalf("Should not have been notified")
38 default:
39 // OK!
40 }
41 if l := q.len(); l != 0 {
42 t.Fatalf("Expected len to be 0, got %v", l)
43 }
44
45 // Try to change the max recycle size
46 q2 := newIPQueue[int](s, "test2", ipqMaxRecycleSize[int](10))
47 if q2.mrs != 10 {
48 t.Fatalf("Expected max recycle size to be 10, got %v", q2.mrs)
49 }
50
51 // Check that those 2 queues are registered
52 var gotFirst bool
53 var gotSecond bool
54 s.ipQueues.Range(func(k, v any) bool {
55 switch k.(string) {
56 case "test":
57 gotFirst = true
58 case "test2":
59 gotSecond = true
60 default:
61 t.Fatalf("Unknown queue: %q", k.(string))
62 }
63 return true
64 })
65 if !gotFirst {
66 t.Fatalf("Did not find queue %q", "test")
67 }
68 if !gotSecond {
69 t.Fatalf("Did not find queue %q", "test2")
70 }
71 // Unregister them
72 q.unregister()
73 q2.unregister()
74 // They should have been removed from the map
75 s.ipQueues.Range(func(k, v any) bool {
76 t.Fatalf("Got queue %q", k.(string))
77 return false
78 })
79 // But verify that we can still push/pop
80 q.push(1)
81 elts := q.pop()
82 if len(elts) != 1 {
83 t.Fatalf("Should have gotten 1 element, got %v", len(elts))
84 }
85 q2.push(2)
86 if e, ok := q2.popOne(); !ok || e != 2 {
87 t.Fatalf("popOne failed: %+v", e)
88 }
89 }
90
91 func TestIPQueuePush(t *testing.T) {
92 s := &Server{}
93 q := newIPQueue[int](s, "test")
94 q.push(1)
95 if l := q.len(); l != 1 {
96 t.Fatalf("Expected len to be 1, got %v", l)
97 }
98 select {
99 case <-q.ch:
100 // OK
101 default:
102 t.Fatalf("Should have been notified of addition")
103 }
104 // Push a new element, we should not be notified.
105 q.push(2)
106 if l := q.len(); l != 2 {
107 t.Fatalf("Expected len to be 2, got %v", l)
108 }
109 select {
110 case <-q.ch:
111 t.Fatalf("Should not have been notified of addition")
112 default:
113 // OK
114 }
115 }
116
117 func TestIPQueuePop(t *testing.T) {
118 s := &Server{}
119 q := newIPQueue[int](s, "test")
120 q.push(1)
121 <-q.ch
122 elts := q.pop()
123 if l := len(elts); l != 1 {
124 t.Fatalf("Expected 1 elt, got %v", l)
125 }
126 if l := q.len(); l != 0 {
127 t.Fatalf("Expected len to be 0, got %v", l)
128 }
129 // The channel notification should be empty
130 select {
131 case <-q.ch:
132 t.Fatalf("Should not have been notified of addition")
133 default:
134 // OK
135 }
136 // Since pop() brings the number of pending to 0, we keep track of the
137 // number of "in progress" elements. Check that the value is 1 here.
138 if n := q.inProgress(); n != 1 {
139 t.Fatalf("Expected count to be 1, got %v", n)
140 }
141 // Recycling will bring it down to 0.
142 q.recycle(&elts)
143 if n := q.inProgress(); n != 0 {
144 t.Fatalf("Expected count to be 0, got %v", n)
145 }
146 // If we call pop() now, we should get nil.
147 if elts = q.pop(); elts != nil {
148 t.Fatalf("Expected nil, got %v", elts)
149 }
150 // The in progress count should still be 0
151 if n := q.inProgress(); n != 0 {
152 t.Fatalf("Expected count to be 0, got %v", n)
153 }
154 // Calling pop() on an unitialized queue will return nil
155 var q2 *ipQueue[int]
156 elts = q2.pop()
157 require_True(t, elts == nil)
158 }
159
160 func TestIPQueuePopOne(t *testing.T) {
161 s := &Server{}
162 q := newIPQueue[int](s, "test")
163 q.push(1)
164 <-q.ch
165 e, ok := q.popOne()
166 if !ok {
167 t.Fatal("Got nil")
168 }
169 if i := e; i != 1 {
170 t.Fatalf("Expected 1, got %v", i)
171 }
172 if l := q.len(); l != 0 {
173 t.Fatalf("Expected len to be 0, got %v", l)
174 }
175 // That does not affect the number of notProcessed
176 if n := q.inProgress(); n != 0 {
177 t.Fatalf("Expected count to be 0, got %v", n)
178 }
179 select {
180 case <-q.ch:
181 t.Fatalf("Should not have been notified of addition")
182 default:
183 // OK
184 }
185 q.push(2)
186 q.push(3)
187 e, ok = q.popOne()
188 if !ok {
189 t.Fatal("Got nil")
190 }
191 if i := e; i != 2 {
192 t.Fatalf("Expected 2, got %v", i)
193 }
194 if l := q.len(); l != 1 {
195 t.Fatalf("Expected len to be 1, got %v", l)
196 }
197 select {
198 case <-q.ch:
199 // OK
200 default:
201 t.Fatalf("Should have been notified that there is more")
202 }
203 e, ok = q.popOne()
204 if !ok {
205 t.Fatal("Got nil")
206 }
207 if i := e; i != 3 {
208 t.Fatalf("Expected 3, got %v", i)
209 }
210 if l := q.len(); l != 0 {
211 t.Fatalf("Expected len to be 0, got %v", l)
212 }
213 select {
214 case <-q.ch:
215 t.Fatalf("Should not have been notified that there is more")
216 default:
217 // OK
218 }
219 // Calling it again now that we know there is nothing, we
220 // should get nil.
221 if e, ok = q.popOne(); ok {
222 t.Fatalf("Expected nil, got %v", e)
223 }
224
225 q = newIPQueue[int](s, "test2")
226 q.push(1)
227 q.push(2)
228 // Capture current capacity
229 q.Lock()
230 c := cap(q.elts)
231 q.Unlock()
232 e, ok = q.popOne()
233 if !ok || e != 1 {
234 t.Fatalf("Invalid value: %v", e)
235 }
236 if l := q.len(); l != 1 {
237 t.Fatalf("Expected len to be 1, got %v", l)
238 }
239 values := q.pop()
240 if len(values) != 1 || values[0] != 2 {
241 t.Fatalf("Unexpected values: %v", values)
242 }
243 if cap(values) != c-1 {
244 t.Fatalf("Unexpected capacity: %v vs %v", cap(values), c-1)
245 }
246 if l := q.len(); l != 0 {
247 t.Fatalf("Expected len to be 0, got %v", l)
248 }
249 // Just make sure that this is ok...
250 q.recycle(&values)
251 }
252
253 func TestIPQueueMultiProducers(t *testing.T) {
254 s := &Server{}
255 q := newIPQueue[int](s, "test")
256
257 wg := sync.WaitGroup{}
258 wg.Add(3)
259 send := func(start, end int) {
260 defer wg.Done()
261
262 for i := start; i <= end; i++ {
263 q.push(i)
264 }
265 }
266 go send(1, 100)
267 go send(101, 200)
268 go send(201, 300)
269
270 tm := time.NewTimer(2 * time.Second)
271 m := make(map[int]struct{})
272 for done := false; !done; {
273 select {
274 case <-q.ch:
275 values := q.pop()
276 for _, v := range values {
277 m[v] = struct{}{}
278 }
279 q.recycle(&values)
280 if n := q.inProgress(); n != 0 {
281 t.Fatalf("Expected count to be 0, got %v", n)
282 }
283 done = len(m) == 300
284 case <-tm.C:
285 t.Fatalf("Did not receive all elements: %v", m)
286 }
287 }
288 wg.Wait()
289 }
290
291 func TestIPQueueRecycle(t *testing.T) {
292 s := &Server{}
293 q := newIPQueue[int](s, "test")
294 total := 1000
295 for iter := 0; iter < 5; iter++ {
296 var sz int
297 for i := 0; i < total; i++ {
298 sz, _ = q.push(i)
299 }
300 if sz != total {
301 t.Fatalf("Expected size to be %v, got %v", total, sz)
302 }
303 values := q.pop()
304 preRecycleCap := cap(values)
305 q.recycle(&values)
306 sz, _ = q.push(1001)
307 if sz != 1 {
308 t.Fatalf("Expected size to be %v, got %v", 1, sz)
309 }
310 values = q.pop()
311 if l := len(values); l != 1 {
312 t.Fatalf("Len should be 1, got %v", l)
313 }
314 if c := cap(values); c == preRecycleCap {
315 break
316 } else if iter == 4 {
317 // We can't fail the test since there is no guarantee that the slice
318 // is still present in the pool when we do a Get(), but let's log that
319 // recycling did not occur even after all iterations..
320 t.Logf("Seem like the previous slice was not recycled, old cap=%v new cap=%v",
321 preRecycleCap, c)
322 }
323 }
324
325 q = newIPQueue[int](s, "test2", ipqMaxRecycleSize[int](10))
326 for i := 0; i < 100; i++ {
327 q.push(i)
328 }
329 values := q.pop()
330 preRecycleCap := cap(values)
331 q.recycle(&values)
332 q.push(1001)
333 values = q.pop()
334 if l := len(values); l != 1 {
335 t.Fatalf("Len should be 1, got %v", l)
336 }
337 // This time, we should not have recycled it, so the new cap should be whatever
338 // the default is, but less than the preRecycleCap.
339 if c := cap(values); c >= preRecycleCap {
340 t.Fatalf("The slice should not have been put back in the pool, got cap of %v", c)
341 }
342 q.recycle(&values)
343
344 // Check that we don't crash when recycling a nil or empty slice
345 values = q.pop()
346 q.recycle(&values)
347 q.recycle(nil)
348 }
349
350 func TestIPQueueDrain(t *testing.T) {
351 s := &Server{}
352 q := newIPQueue[int](s, "test")
353 for iter, recycled := 0, false; iter < 5 && !recycled; iter++ {
354 for i := 0; i < 100; i++ {
355 q.push(i + 1)
356 }
357 q.drain()
358 // Try to get something from the pool right away
359 s := q.pool.Get()
360 recycled := s != nil
361 if !recycled {
362 // We can't fail the test, since we have no guarantee it will be recycled
363 // especially when running with `-race` flag...
364 if iter == 4 {
365 t.Log("nothing was recycled")
366 }
367 }
368 // Check that we have consumed the signal...
369 select {
370 case <-q.ch:
371 t.Fatal("Signal should have been consumed by drain")
372 default:
373 // OK!
374 }
375 // Check len
376 if l := q.len(); l != 0 {
377 t.Fatalf("Expected len to be 0, got %v", l)
378 }
379 if recycled {
380 break
381 }
382 }
383 }
384
385 func TestIPQueueSizeCalculation(t *testing.T) {
386 type testType = [16]byte
387 var testValue testType
388
389 calc := ipqSizeCalculation[testType](func(e testType) uint64 {
390 return uint64(len(e))
391 })
392 s := &Server{}
393 q := newIPQueue[testType](s, "test", calc)
394
395 for i := 0; i < 10; i++ {
396 q.push(testValue)
397 require_Equal(t, q.len(), i+1)
398 require_Equal(t, q.size(), uint64(i+1)*uint64(len(testValue)))
399 }
400
401 for i := 10; i > 5; i-- {
402 q.popOne()
403 require_Equal(t, q.len(), i-1)
404 require_Equal(t, q.size(), uint64(i-1)*uint64(len(testValue)))
405 }
406
407 q.pop()
408 require_Equal(t, q.len(), 0)
409 require_Equal(t, q.size(), 0)
410 }
411
412 func TestIPQueueSizeCalculationWithLimits(t *testing.T) {
413 type testType = [16]byte
414 var testValue testType
415
416 calc := ipqSizeCalculation[testType](func(e testType) uint64 {
417 return uint64(len(e))
418 })
419 s := &Server{}
420
421 t.Run("LimitByLen", func(t *testing.T) {
422 q := newIPQueue[testType](s, "test", calc, ipqLimitByLen[testType](5))
423 for i := 0; i < 10; i++ {
424 n, err := q.push(testValue)
425 if i >= 5 {
426 require_Error(t, err, errIPQLenLimitReached)
427 } else {
428 require_NoError(t, err)
429 }
430 require_LessThan(t, n, 6)
431 }
432 })
433
434 t.Run("LimitBySize", func(t *testing.T) {
435 q := newIPQueue[testType](s, "test", calc, ipqLimitBySize[testType](16*5))
436 for i := 0; i < 10; i++ {
437 n, err := q.push(testValue)
438 if i >= 5 {
439 require_Error(t, err, errIPQSizeLimitReached)
440 } else {
441 require_NoError(t, err)
442 }
443 require_LessThan(t, n, 6)
444 }
445 })
446 }
447
448 func Benchmark_IPQueueSizeCalculation(b *testing.B) {
449 type testType = [16]byte
450 var testValue testType
451
452 s := &Server{}
453
454 runPopOne := func(b *testing.B, q *ipQueue[testType]) {
455 b.SetBytes(16)
456 for i := 0; i < b.N; i++ {
457 q.push(testValue)
458 }
459 for i := b.N; i > 0; i-- {
460 q.popOne()
461 }
462 }
463 runPopAll := func(b *testing.B, q *ipQueue[testType]) {
464 b.SetBytes(16)
465 for i := 0; i < b.N; i++ {
466 q.push(testValue)
467 }
468 elts := q.pop()
469 for _, v := range elts {
470 _ = v
471 }
472 q.recycle(&elts)
473 }
474 for _, test := range []struct {
475 name string
476 run func(b *testing.B, q *ipQueue[testType])
477 }{
478 {"pop one", runPopOne},
479 {"pop all", runPopAll},
480 } {
481 b.Run(test.name, func(b *testing.B) {
482 // Measures without calculation function overheads.
483 b.Run("WithoutCalc", func(b *testing.B) {
484 test.run(b, newIPQueue[testType](s, "test"))
485 })
486
487 // Measures the raw overhead of having a calculation function.
488 b.Run("WithEmptyCalc", func(b *testing.B) {
489 calc := ipqSizeCalculation[testType](func(e testType) uint64 {
490 return 0
491 })
492 test.run(b, newIPQueue[testType](s, "test", calc))
493 })
494
495 // Measures the overhead of having a calculation function that
496 // actually measures something useful.
497 b.Run("WithLenCalc", func(b *testing.B) {
498 calc := ipqSizeCalculation[testType](func(e testType) uint64 {
499 return uint64(len(e))
500 })
501 test.run(b, newIPQueue[testType](s, "test", calc))
502 })
503 })
504 }
505 }
506
507 func Benchmark_IPQueue1Prod1ConsPopOne(b *testing.B) {
508 benchIPQueue(b, 1, 1, true, false)
509 }
510
511 func Benchmark_IPQueue5Prod1ConsPopOne(b *testing.B) {
512 benchIPQueue(b, 5, 1, true, false)
513 }
514
515 func Benchmark_IPQueue1Prod5ConsPopOne(b *testing.B) {
516 benchIPQueue(b, 1, 5, true, false)
517 }
518
519 func Benchmark_IPQueue5Prod5ConsPopOne(b *testing.B) {
520 benchIPQueue(b, 5, 5, true, false)
521 }
522
523 func Benchmark_IPQueue1Prod1ConsPopAll(b *testing.B) {
524 benchIPQueue(b, 1, 1, false, false)
525 }
526
527 func Benchmark_IPQueue5Prod1ConsPopAll(b *testing.B) {
528 benchIPQueue(b, 5, 1, false, false)
529 }
530
531 func Benchmark_IPQueue1Prod5ConsPopAll(b *testing.B) {
532 benchIPQueue(b, 1, 5, false, false)
533 }
534
535 func Benchmark_IPQueue5Prod5ConsPopAll(b *testing.B) {
536 benchIPQueue(b, 5, 5, false, false)
537 }
538
539 func Benchmark_IPQueueWithLim1Prod1ConsPopOne(b *testing.B) {
540 benchIPQueue(b, 1, 1, true, true)
541 }
542
543 func Benchmark_IPQueueWithLim5Prod1ConsPopOne(b *testing.B) {
544 benchIPQueue(b, 5, 1, true, true)
545 }
546
547 func Benchmark_IPQueueWithLim1Prod5ConsPopOne(b *testing.B) {
548 benchIPQueue(b, 1, 5, true, true)
549 }
550
551 func Benchmark_IPQueueWithLim5Prod5ConsPopOne(b *testing.B) {
552 benchIPQueue(b, 5, 5, true, true)
553 }
554
555 func Benchmark_IPQueueWithLim1Prod1ConsPopAll(b *testing.B) {
556 benchIPQueue(b, 1, 1, false, true)
557 }
558
559 func Benchmark_IPQueueWithLim5Prod1ConsPopAll(b *testing.B) {
560 benchIPQueue(b, 5, 1, false, true)
561 }
562
563 func Benchmark_IPQueueWithLim1Prod5ConsPopAll(b *testing.B) {
564 benchIPQueue(b, 1, 5, false, true)
565 }
566
567 func Benchmark_IPQueueWithLim5Prod5ConsPopAll(b *testing.B) {
568 benchIPQueue(b, 5, 5, false, true)
569 }
570
571 func benchIPQueue(b *testing.B, numProd, numCons int, popOne, withLimits bool) {
572 var count atomic.Int64
573 var sum atomic.Int64
574
575 perProd := (b.N / numProd) + 1
576 total := int64(perProd * numProd)
577
578 var opts []ipQueueOpt[int]
579 if withLimits {
580 // Add len/size options but make sure they are big enough that we don't fail push() calls.
581 // What we want is to activate code that is checking for limits.
582 opts = append(opts, ipqLimitByLen[int](int(total+100)))
583 opts = append(opts, ipqLimitBySize[int](uint64((total+100)*5)))
584 opts = append(opts, ipqSizeCalculation[int](func(e int) uint64 { return uint64(5) }))
585 }
586 queue := newIPQueue[int](&Server{}, "bench", opts...)
587
588 cdone := make(chan struct{}, numCons)
589 for i := 0; i < numCons; i++ {
590 go func() {
591 for range queue.ch {
592 if popOne {
593 v, ok := queue.popOne()
594 if !ok {
595 continue
596 }
597 sum.Add(int64(v))
598 if count.Add(1) >= total {
599 cdone <- struct{}{}
600 return
601 }
602 } else {
603 elts := queue.pop()
604 for _, v := range elts {
605 sum.Add(int64(v))
606 if count.Add(1) >= total {
607 queue.recycle(&elts)
608 cdone <- struct{}{}
609 return
610 }
611 }
612 queue.recycle(&elts)
613 }
614 }
615 }()
616 }
617
618 pwg := sync.WaitGroup{}
619 pwg.Add(numProd)
620 var expected atomic.Int64
621 for i := 0; i < numProd; i++ {
622 go func() {
623 defer pwg.Done()
624 for i := 0; i < perProd; i++ {
625 expected.Add(int64(i + 1))
626 queue.push(i + 1)
627 }
628 }()
629 }
630
631 pwg.Wait()
632 <-cdone
633 b.StopTimer()
634
635 for i := 1; i < numCons; i++ {
636 queue.push(0)
637 <-cdone
638 }
639 if sum.Load() != expected.Load() {
640 b.Fatalf("Invalid sum, expected %v, got %v", expected.Load(), sum.Load())
641 }
642 }
643
644 func Benchmark_IPQueuePushAndPopOne(b *testing.B) {
645 s := &Server{}
646 q := newIPQueue[int](s, "test")
647 for i := 0; i < b.N; i++ {
648 q.push(i + 1)
649 }
650 require_Equal[int](b, q.len(), b.N)
651 for i := 0; i < b.N; i++ {
652 v, ok := q.popOne()
653 require_True(b, ok)
654 require_Equal[int](b, v, i+1)
655 }
656 require_Equal[int](b, q.len(), 0)
657 require_Equal(b, q.inProgress(), 0)
658 }
659
660 func Benchmark_IPQueuePushAndPopAll(b *testing.B) {
661 s := &Server{}
662 q := newIPQueue[int](s, "test")
663 expected := 0
664 for i := 0; i < b.N; i++ {
665 q.push(i + 1)
666 expected += i + 1
667 }
668 require_Equal(b, q.len(), b.N)
669 <-q.ch
670
671 elts := q.pop()
672 require_Equal(b, len(elts), b.N)
673 require_Equal(b, q.len(), 0)
674 require_Equal(b, q.inProgress(), int64(b.N))
675 sum := 0
676 for _, v := range elts {
677 sum += v
678 }
679 q.recycle(&elts)
680 require_Equal(b, expected, sum)
681 require_Equal(b, q.len(), 0)
682 require_Equal(b, q.inProgress(), 0)
683 }