forked from gnolang/gno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
throttle_test.go
106 lines (79 loc) · 2.17 KB
/
throttle_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
package main
import (
"context"
"net/netip"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestIPThrottler_RegisterNewRequest(t *testing.T) {
t.Parallel()
t.Run("valid number of requests", func(t *testing.T) {
t.Parallel()
addr, err := netip.ParseAddr("127.0.0.1")
require.NoError(t, err)
// Create the IP throttler
th := newIPThrottler(defaultRateLimitInterval, defaultCleanTimeout)
// Register < max requests
for i := uint64(0); i < maxRequestsPerMinute; i++ {
assert.NoError(t, th.registerNewRequest(addr))
}
})
t.Run("exceeded number of requests", func(t *testing.T) {
t.Parallel()
addr, err := netip.ParseAddr("127.0.0.1")
require.NoError(t, err)
// Create the IP throttler
th := newIPThrottler(defaultRateLimitInterval, defaultCleanTimeout)
// Register max requests
for i := uint64(0); i < maxRequestsPerMinute; i++ {
assert.NoError(t, th.registerNewRequest(addr))
}
// Attempt to register an additional request
assert.ErrorIs(t, th.registerNewRequest(addr), errInvalidNumberOfRequests)
})
}
func TestIPThrottler_RequestsThrottled(t *testing.T) {
t.Parallel()
var (
cleanupInterval = time.Millisecond * 100
requestInterval = 3 * cleanupInterval // requests triggered after ~5 cleans
numRequests = maxRequestsPerMinute * 2 // number of request loops
)
addr, err := netip.ParseAddr("127.0.0.1")
require.NoError(t, err)
// Create the IP throttler
th := newIPThrottler(defaultRateLimitInterval, cleanupInterval)
ctx, cancelFn := context.WithCancel(context.Background())
defer cancelFn()
// Start the throttler (async)
th.start(ctx)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
var (
requestsSent = 0
ticker = time.NewTicker(requestInterval)
)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
// Fill out the request count for the address
for i := uint64(0); i < maxRequestsPerMinute; i++ {
require.NoError(t, th.registerNewRequest(addr))
}
requestsSent += maxRequestsPerMinute
if requestsSent == numRequests {
// Loops done
return
}
}
}
}()
wg.Wait()
}