File size: 1,924 Bytes
b110593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//                           _       _
// __      _____  __ ___   ___  __ _| |_ ___
// \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
//  \ V  V /  __/ (_| |\ V /| | (_| | ||  __/
//   \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
//
//  Copyright © 2016 - 2024 Weaviate B.V. All rights reserved.
//
//  CONTACT: [email protected]
//

package ratelimiter

import (
	"math/rand"
	"sync"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func TestLimiter(t *testing.T) {
	l := New(3)

	// add 3 requests, should all work
	assert.True(t, l.TryInc())
	assert.True(t, l.TryInc())
	assert.True(t, l.TryInc())

	// try to add one more, should fail
	assert.False(t, l.TryInc())

	// decrease and try again
	l.Dec()
	l.Dec()
	assert.True(t, l.TryInc())
	assert.True(t, l.TryInc())
	assert.False(t, l.TryInc())
}

func TestLimiterConcurrently(t *testing.T) {
	var count int
	lock := &sync.Mutex{}

	l := New(30)

	request := func() {
		lock.Lock()
		count++
		if count > 30 {
			t.Fail()
		}
		lock.Unlock()

		time.Sleep(30 * time.Millisecond)

		lock.Lock()
		count--
		lock.Unlock()
	}

	wg := sync.WaitGroup{}
	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			time.Sleep(time.Duration(rand.Intn(200)) * time.Millisecond)
			if l.TryInc() {
				request()
				l.Dec()
			}
		}()
	}

	wg.Wait()
}

func TestLimiterUnlimited(t *testing.T) {
	l := New(-1)

	for i := 0; i < 1000; i++ {
		assert.True(t, l.TryInc())
	}

	for i := 0; i < 1000; i++ {
		l.Dec()
	}

	assert.True(t, l.TryInc())
}

func TestLimiterCantGoNegative(t *testing.T) {
	l := New(3)

	for i := 0; i < 10; i++ {
		l.Dec()
	}

	for i := 0; i < 3; i++ {
		assert.True(t, l.TryInc())
	}
	assert.False(t, l.TryInc())
}

func BenchmarkLimiter(b *testing.B) {
	l := New(-1)
	for i := 0; i < b.N; i++ {
		l.TryInc()
		l.Dec()
	}
}