-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathratelimiter_test.go
470 lines (432 loc) · 11 KB
/
ratelimiter_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
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
package rate5
import (
"context"
"crypto/rand"
"encoding/binary"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
)
var (
dummyTicker *ticker
)
type randomPatron struct {
key string
Identity
}
const charset = "abcdefghijklmnopqrstuvwxyz1234567890"
func (rp *randomPatron) UniqueKey() string {
return rp.key
}
func randomUint32() uint32 {
b := make([]byte, 8192)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return binary.LittleEndian.Uint32(b)
}
func (rp *randomPatron) GenerateKey() {
var keylen = 10
buf := make([]byte, keylen)
for n := 0; n != keylen; n++ {
buf[n] = charset[randomUint32()%uint32(len(charset))]
}
rp.key = string(buf)
}
var (
forCoverage = &sync.Once{}
watchDebugMutex = &sync.Mutex{}
)
func watchDebug(ctx context.Context, r *Limiter, t *testing.T) {
watchDebugMutex.Lock()
defer watchDebugMutex.Unlock()
rd := r.DebugChannel()
forCoverage.Do(func() {
r.SetDebug(false)
r.SetDebug(true)
rd = r.DebugChannel()
})
for {
select {
case <-ctx.Done():
r = nil
return
case msg := <-rd:
t.Logf("%s \n", msg)
default:
}
}
}
func peekCheckLimited(t *testing.T, limiter *Limiter, shouldbe, stringer bool) {
limited := limiter.Peek(dummyTicker)
if stringer {
limited = limiter.PeekStringer(dummyTicker)
}
switch {
case limited && !shouldbe:
if ct, ok := limiter.Patrons.Get(dummyTicker.UniqueKey()); ok {
t.Errorf("Should not have been limited. Ratelimiter count: %d", ct)
} else {
t.Fatalf("dummyTicker does not exist in ratelimiter at all!")
}
case !limited && shouldbe:
if ct, ok := limiter.Patrons.Get(dummyTicker.UniqueKey()); ok {
t.Errorf("Should have been limited. Ratelimiter count: %d", ct)
} else {
t.Fatalf("dummyTicker does not exist in ratelimiter at all!")
}
case limited && shouldbe:
t.Logf("dummyTicker is limited (pass).")
case !limited && !shouldbe:
t.Logf("dummyTicker is not limited (pass).")
}
}
// this test exists here for coverage, we are simulating the debug channel overflowing and then invoking println().
func Test_debugPrintf(t *testing.T) {
t.Parallel()
limiter := NewLimiter(1, 1)
_ = limiter.DebugChannel()
for n := 0; n < 50; n++ {
limiter.Check(dummyTicker)
}
}
type ticker struct{}
func (tick *ticker) UniqueKey() string {
return "TestItem"
}
func (tick *ticker) String() string {
return "TestItem"
}
func Test_ResetItem(t *testing.T) {
limiter := NewLimiter(500, 1)
ctx, cancel := context.WithCancel(context.Background())
go watchDebug(ctx, limiter, t)
time.Sleep(25 * time.Millisecond)
for n := 0; n < 10; n++ {
limiter.Check(dummyTicker)
}
limiter.ResetItem(dummyTicker)
peekCheckLimited(t, limiter, false, false)
cancel()
}
func Test_NewDefaultLimiter(t *testing.T) {
t.Parallel()
limiter := NewDefaultLimiter()
limiter.Check(dummyTicker)
peekCheckLimited(t, limiter, false, false)
for n := 0; n != DefaultBurst; n++ {
limiter.Check(dummyTicker)
}
peekCheckLimited(t, limiter, true, false)
}
func Test_CheckAndPeekStringer(t *testing.T) {
t.Parallel()
limiter := NewDefaultLimiter()
limiter.CheckStringer(dummyTicker)
peekCheckLimited(t, limiter, false, true)
for n := 0; n != DefaultBurst; n++ {
limiter.CheckStringer(dummyTicker)
}
peekCheckLimited(t, limiter, true, true)
}
func Test_NewLimiter(t *testing.T) {
t.Parallel()
limiter := NewLimiter(5, 1)
limiter.Check(dummyTicker)
peekCheckLimited(t, limiter, false, false)
limiter.Check(dummyTicker)
peekCheckLimited(t, limiter, true, false)
}
func Test_NewDefaultStrictLimiter(t *testing.T) {
t.Parallel()
limiter := NewDefaultStrictLimiter()
// ctx, cancel := context.WithCancel(context.Background())
// go watchDebug(ctx, limiter, t)
time.Sleep(25 * time.Millisecond)
for n := 0; n < 25; n++ {
limiter.Check(dummyTicker)
}
peekCheckLimited(t, limiter, false, false)
limiter.Check(dummyTicker)
peekCheckLimited(t, limiter, true, false)
// cancel()
limiter = nil
}
func Test_NewStrictLimiter(t *testing.T) {
t.Parallel()
limiter := NewStrictLimiter(5, 1)
// ctx, cancel := context.WithCancel(context.Background())
// go watchDebug(ctx, limiter, t)
limiter.Check(dummyTicker)
peekCheckLimited(t, limiter, false, false)
limiter.Check(dummyTicker)
peekCheckLimited(t, limiter, true, false)
limiter.Check(dummyTicker)
// for coverage, first we give the debug messages a couple seconds to be safe,
// then we wait for the cache eviction to trigger a debug message.
time.Sleep(2 * time.Second)
t.Logf(<-limiter.DebugChannel())
peekCheckLimited(t, limiter, false, false)
for n := 0; n != 6; n++ {
limiter.Check(dummyTicker)
}
peekCheckLimited(t, limiter, true, false)
time.Sleep(5 * time.Second)
peekCheckLimited(t, limiter, true, false)
time.Sleep(8 * time.Second)
peekCheckLimited(t, limiter, false, false)
// cancel()
limiter = nil
}
func Test_NewHardcoreLimiter(t *testing.T) {
t.Parallel()
limiter := NewHardcoreLimiter(1, 5)
ctx, cancel := context.WithCancel(context.Background())
go watchDebug(ctx, limiter, t)
for n := 0; n != 4; n++ {
limiter.Check(dummyTicker)
}
peekCheckLimited(t, limiter, false, false)
if !limiter.Check(dummyTicker) {
t.Errorf("Should have been limited")
}
t.Logf("limited once, waiting for cache eviction")
time.Sleep(2 * time.Second)
peekCheckLimited(t, limiter, false, false)
for n := 0; n != 4; n++ {
limiter.Check(dummyTicker)
}
peekCheckLimited(t, limiter, false, false)
if !limiter.Check(dummyTicker) {
t.Errorf("Should have been limited")
}
limiter.Check(dummyTicker)
limiter.Check(dummyTicker)
time.Sleep(3 * time.Second)
peekCheckLimited(t, limiter, true, false)
time.Sleep(5 * time.Second)
peekCheckLimited(t, limiter, false, false)
for n := 0; n != 4; n++ {
limiter.Check(dummyTicker)
}
peekCheckLimited(t, limiter, false, false)
for n := 0; n != 10; n++ {
limiter.Check(dummyTicker)
}
time.Sleep(10 * time.Second)
peekCheckLimited(t, limiter, true, false)
cancel()
// for coverage, triggering the switch statement case for hardcore logic
limiter2 := NewHardcoreLimiter(2, 5)
ctx2, cancel2 := context.WithCancel(context.Background())
go watchDebug(ctx2, limiter2, t)
for n := 0; n != 6; n++ {
limiter2.Check(dummyTicker)
}
peekCheckLimited(t, limiter2, true, false)
time.Sleep(4 * time.Second)
peekCheckLimited(t, limiter2, false, false)
cancel2()
}
func concurrentTest(t *testing.T, jobs int, iterCount int, burst int64, shouldLimit bool) { //nolint:funlen
var randos map[int]*randomPatron
randos = make(map[int]*randomPatron)
limiter := NewCustomLimiter(Policy{
Window: 240,
Burst: burst,
Strict: true,
})
limitNotice := sync.Once{}
limiter.SetDebug(false)
usedkeys := make(map[string]interface{})
for n := 0; n != jobs; n++ {
randos[n] = new(randomPatron)
ok := true
for ok {
randos[n].GenerateKey()
_, ok = usedkeys[randos[n].key]
if ok {
t.Log("collision")
}
}
}
t.Logf("generated %d Patrons with unique keys, running Check() with them %d times concurrently with a burst limit of %d...",
len(randos), iterCount, burst)
finChan := make(chan bool, jobs*iterCount)
var finished = 0
for _, rp := range randos {
go func(randomp *randomPatron) {
for n := 0; n != iterCount; n++ {
limiter.Check(randomp)
if limiter.Peek(randomp) {
limitNotice.Do(func() {
t.Logf("(sync.Once) %s limited", randomp.UniqueKey())
})
}
finChan <- true
}
}(rp)
}
testloop:
for {
select {
// case msg := <-limiter.DebugChannel():
// t.Logf("[debug] %s", msg)
case <-finChan:
finished++
default:
if finished >= (jobs * iterCount) {
break testloop
}
}
}
for _, rp := range randos {
var ok bool
var ci interface{}
if ci, ok = limiter.Patrons.Get(rp.UniqueKey()); !ok {
t.Fatal("randomPatron does not exist in ratelimiter at all!")
}
ct := ci.(*atomic.Int64).Load()
if limiter.Peek(rp) && !shouldLimit {
t.Logf("(%d goroutines running)", runtime.NumGoroutine())
// runtime.Breakpoint()
t.Errorf("FAIL: %s should not have been limited. Ratelimiter count: %d, policy: %d",
rp.UniqueKey(), ct, limiter.Ruleset.Burst)
continue
}
if !limiter.Peek(rp) && shouldLimit {
t.Logf("(%d goroutines running)", runtime.NumGoroutine())
// runtime.Breakpoint()
t.Errorf("FAIL: %s should have been limited. Ratelimiter count: %d, policy: %d",
rp.UniqueKey(), ct, limiter.Ruleset.Burst)
}
}
}
func Test_ConcurrentShouldNotLimit(t *testing.T) {
t.Parallel()
concurrentTest(t, 50, 20, 20, false)
concurrentTest(t, 50, 50, 50, false)
}
func Test_ConcurrentShouldLimit(t *testing.T) {
t.Parallel()
concurrentTest(t, 50, 21, 20, true)
concurrentTest(t, 50, 51, 50, true)
}
func Test_debugChannelOverflow(t *testing.T) {
t.Parallel()
limiter := NewDefaultLimiter()
_ = limiter.DebugChannel()
for n := 0; n != 78; n++ {
limiter.Check(dummyTicker)
if limiter.debugLost > 0 {
t.Fatalf("debug channel overflowed")
}
}
limiter.Check(dummyTicker)
if limiter.debugLost == 0 {
t.Fatalf("debug channel did not overflow")
}
}
func TestDebugPrintfTypeAssertion(t *testing.T) {
t.Parallel()
limiter := NewDefaultLimiter()
limiter.SetDebug(true)
asdf := new(atomic.Int64)
asdf.Store(5)
limiter.debugChannel = make(chan string, 1)
limiter.debugPrintf("test %d %d", 1, asdf)
if <-limiter.debugChannel != "test 1 5" {
t.Fatalf("failed to type assert atomic.Int64")
}
}
func BenchmarkCheck(b *testing.B) {
b.StopTimer()
limiter := NewDefaultLimiter()
b.ReportAllocs()
b.StartTimer()
for n := 0; n < b.N; n++ {
limiter.Check(dummyTicker)
}
}
func BenchmarkCheckHardcore(b *testing.B) {
b.StopTimer()
limiter := NewHardcoreLimiter(25, 25)
b.ReportAllocs()
b.StartTimer()
for n := 0; n < b.N; n++ {
limiter.Check(dummyTicker)
}
}
func BenchmarkCheckStrict(b *testing.B) {
b.StopTimer()
limiter := NewStrictLimiter(25, 25)
b.ReportAllocs()
b.StartTimer()
for n := 0; n < b.N; n++ {
limiter.Check(dummyTicker)
}
}
func BenchmarkCheckStringer(b *testing.B) {
b.StopTimer()
limiter := NewDefaultLimiter()
b.ReportAllocs()
b.StartTimer()
for n := 0; n < b.N; n++ {
limiter.CheckStringer(dummyTicker)
}
}
func BenchmarkPeek(b *testing.B) {
b.StopTimer()
limiter := NewDefaultLimiter()
b.ReportAllocs()
b.StartTimer()
for n := 0; n < b.N; n++ {
limiter.Peek(dummyTicker)
}
}
func BenchmarkConcurrentCheck(b *testing.B) {
b.StopTimer()
limiter := NewDefaultLimiter()
b.ReportAllocs()
b.StartTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
limiter.Check(dummyTicker)
}
})
}
func BenchmarkConcurrentSetAndCheckHardcore(b *testing.B) {
b.StopTimer()
limiter := NewHardcoreLimiter(25, 25)
b.ReportAllocs()
b.StartTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
limiter.Check(dummyTicker)
}
})
}
func BenchmarkConcurrentSetAndCheckStrict(b *testing.B) {
b.StopTimer()
limiter := NewDefaultStrictLimiter()
b.ReportAllocs()
b.StartTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
limiter.Check(dummyTicker)
}
})
}
func BenchmarkConcurrentPeek(b *testing.B) {
b.StopTimer()
limiter := NewDefaultLimiter()
b.ReportAllocs()
b.StartTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
limiter.Peek(dummyTicker)
}
})
}