-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathlimiter_test.go
357 lines (287 loc) · 8.17 KB
/
limiter_test.go
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
package ratelimiter
import (
"fmt"
"sync"
"testing"
"time"
)
func TestInvalidLimiterConfiguration(t *testing.T) {
limiter := NewDefaultLimiter(10, time.Microsecond*800)
if _, err := limiter.ShouldAllow(3); err == nil {
t.Fatalf("ShouldAllow() failed, did not throw error when window size <= 1 millisecond")
}
limiter1 := NewSyncLimiter(0, 10*time.Second)
if _, err := limiter1.ShouldAllow(10); err == nil {
t.Fatalf("ShouldAllow() failed, did not throw error when limit == 0")
}
}
func TestLimiterAccuracy(t *testing.T) {
nRuns := 10
var count uint64 = 0
// Time duration of the window.
duration := time.Second * 1
// 100 tasks must be allowed to execute
// for every `duration` interval.
var limit uint64 = 100
// test with accuracy +/- 3, modify this variable to
// test accuracy for various error offsets, 0 is the most
// ideal case.
var allowanceRange uint64 = 20
// will be set to true once the go routine completes all `nRuns`
limiter := NewDefaultLimiter(limit, duration)
defer limiter.Kill()
for i := 0; i < nRuns; i++ {
count = 0
nTicks := 0
for range time.Tick(time.Millisecond * 2) {
canAllow, err := limiter.ShouldAllow(1)
if err != nil {
t.Fatalf("%v", err)
}
if canAllow {
count++
}
nTicks++
if nTicks%500 == 0 {
break
}
}
if (limit-allowanceRange) <= count && count <= (limit+allowanceRange) {
fmt.Printf(
"Iteration %d, Allowed tasks: %d, passed rate limiting accuracy test.\n",
i+1, count,
)
count = 0
} else {
t.Fatalf(
"Accuracy test failed, expected results to be in +/- %d error range, but got %d",
allowanceRange, count,
)
}
}
}
func TestConcurrentLimiterAccuracy(t *testing.T) {
nRuns := 10
duration := time.Second * 1
// 100 tasks must be allowed to execute
// for every `duration` interval.
var limit uint64 = 100
// create a limiter, that is shared across go routines:
sharedLimiter := NewDefaultLimiter(limit, duration)
defer sharedLimiter.Kill()
// launch N go-routines:
nRoutines := 4
// test with accuracy +/- 3, modify this variable to
// test accuracy for various error offsets, 0 is the most
// ideal case.
var allowanceRange uint64 = 20
counterSlice := make([]uint64, nRoutines)
routine := func(idx int, wg *sync.WaitGroup) {
defer wg.Done()
// no need of mutex locking the counterSlice
// because each goroutine has access to only a
// unique index `idx` of the slice.
counterSlice[idx] = 0
j := 0
// Use of time.Tick in production is discouraged.
// time.Tick cannot be stopped, we are using it because
// this is a test code.
for range time.Tick(2 * time.Millisecond) {
canAllow, err := sharedLimiter.ShouldAllow(1)
if err != nil {
break
}
if canAllow {
counterSlice[idx]++
}
j++
if j%500 == 0 {
break
}
}
}
for i := 0; i < nRuns; i++ {
// create a wait group and
wg := sync.WaitGroup{}
for j := 0; j < nRoutines; j++ {
wg.Add(1)
go routine(j, &wg)
}
wg.Wait()
// sum over the counterSlice and check accuracy:
var count uint64 = 0
for _, partialCount := range counterSlice {
count += partialCount
}
// check accuracy of counter
if (limit-allowanceRange) <= count && count <= (limit+allowanceRange) {
fmt.Printf(
"Iteration %d, Allowed tasks: %d, passed rate limiting accuracy test.\n",
i+1, count,
)
} else {
t.Fatalf(
"Accuracy test failed, expected results to be in +/- %d error range, but got %d",
allowanceRange, count,
)
}
}
}
func TestConcurrentSyncLimiter(t *testing.T) {
nRuns := 10
duration := time.Second * 1
// 100 tasks must be allowed to execute
// for every `duration` interval.
var limit uint64 = 100
// create a limiter, that is shared across go routines:
sharedLimiter := NewSyncLimiter(limit, duration)
defer sharedLimiter.Kill()
// launch N go-routines:
nRoutines := 4
// dry run, this will allow rate-limiter to stabilize:
isDry := true
// test with accuracy +/- 3, modify this variable to
// test accuracy for various error offsets, 0 is the most
// ideal case.
var allowanceRange uint64 = 20
counterSlice := make([]uint64, nRoutines)
routine := func(idx int, wg *sync.WaitGroup) {
defer wg.Done()
// no need of mutex locking the counterSlice
// because each goroutine has access to only a
// unique index `idx` of the slice.
counterSlice[idx] = 0
j := 0
// Use of time.Tick in production is discouraged.
// time.Tick cannot be stopped, we are using it because
// this is a test code.
for range time.Tick(2 * time.Millisecond) {
canAllow, err := sharedLimiter.ShouldAllow(1)
if err != nil {
break
}
if canAllow {
counterSlice[idx]++
}
j++
if j%500 == 0 {
break
}
}
}
for i := 0; i < nRuns; i++ {
// create a wait group and
wg := sync.WaitGroup{}
for j := 0; j < nRoutines; j++ {
wg.Add(1)
go routine(j, &wg)
}
wg.Wait()
// sum over the counterSlice and check accuracy:
var count uint64 = 0
for _, partialCount := range counterSlice {
count += partialCount
}
// check accuracy of counter
if !isDry {
if (limit-allowanceRange) <= count && count <= (limit+allowanceRange) {
fmt.Printf(
"Iteration %d, Allowed tasks: %d, passed rate limiting accuracy test.\n",
i, count,
)
} else {
t.Fatalf(
"Accuracy test failed, expected results to be in +/- %d error range, but got %d",
allowanceRange, count,
)
}
}
isDry = false
}
}
func TestLimiterCleanup(t *testing.T) {
var limit uint64 = 10
var size time.Duration = 5 * time.Second
limiter := NewDefaultLimiter(limit, size)
// call allow check on limiter:
_, err := limiter.ShouldAllow(1)
if err != nil {
t.Fatalf("Error when calling ShouldAllow() on active limiter, Error: %v", err)
}
// kill the limiter:
if err = limiter.Kill(); err != nil {
t.Fatalf("Failed to kill an active limiter, Error: %v", err)
}
// try to call kill again on already killed limiter:
if err = limiter.Kill(); err == nil {
t.Fatalf("Failed to throw error when Kill() was called on the same limiter twice.")
}
// call ShouldAllow() on inactive limiter, this should throw an error
_, err = limiter.ShouldAllow(4)
if err == nil {
t.Fatalf("Calling ShouldAllow() on inactive limiter did not throw any errors.")
}
}
func TestSyncLimiterCleanup(t *testing.T) {
var limit uint64 = 10
var size time.Duration = 5 * time.Second
limiter := NewSyncLimiter(limit, size)
// call allow check on limiter:
_, err := limiter.ShouldAllow(1)
if err != nil {
t.Fatalf("Error when calling ShouldAllow() on active limiter, Error: %v", err)
}
// kill the limiter:
if err = limiter.Kill(); err != nil {
t.Fatalf("Failed to kill an active limiter, Error: %v", err)
}
// try to call kill again on already killed limiter:
if err = limiter.Kill(); err == nil {
t.Fatalf("Failed to throw error when Kill() was called on the same limiter twice.")
}
// call ShouldAllow() on inactive limiter, this should throw an error
_, err = limiter.ShouldAllow(4)
if err == nil {
t.Fatalf("Calling ShouldAllow() on inactive limiter did not throw any errors.")
}
}
func BenchmarkDefaultLimiter(b *testing.B) {
limiter := NewDefaultLimiter(100, 1*time.Second)
for i := 0; i < b.N; i++ {
_, err := limiter.ShouldAllow(1)
if err != nil {
b.Fatalf("Error when calling ShouldAllow() on active limiter, Error: %v", err)
}
}
}
func BenchmarkSyncLimiter(b *testing.B) {
limiter := NewSyncLimiter(100, 1*time.Second)
for i := 0; i < b.N; i++ {
_, err := limiter.ShouldAllow(1)
if err != nil {
b.Fatalf("Error when calling ShouldAllow() on active limiter, Error: %v", err)
}
}
}
func BenchmarkConcurrentDefaultLimiter(b *testing.B) {
limiter := NewDefaultLimiter(100, 1*time.Second)
b.RunParallel(func(p *testing.PB) {
for p.Next() {
_, err := limiter.ShouldAllow(1)
if err != nil {
b.Fatalf("Error when calling ShouldAllow() on active limiter, Error: %v", err)
}
}
})
}
func BenchmarkConcurrentSyncLimiter(b *testing.B) {
limiter := NewSyncLimiter(100, 1*time.Second)
b.RunParallel(func(p *testing.PB) {
for p.Next() {
_, err := limiter.ShouldAllow(1)
if err != nil {
b.Fatalf("Error when calling ShouldAllow() on active limiter, Error: %v", err)
}
}
})
}