Debian Codegraph @

ratelimit_test.go

raw ◀ ▶
2 Debian patches touch this file
1 package ratelimit
2
3 import (
4 "sync"
5 "testing"
6 "time"
7
8 "go.uber.org/atomic"
9
10 "github.com/benbjohnson/clock"
11 "github.com/stretchr/testify/assert"
12 )
13
14 type testRunner interface {
15 // createLimiter builds a limiter with given options.
•16 createLimiter(int64, ...Option) Limiter
17 // takeOnceAfter attempts to Take at a specific time.
18 takeOnceAfter(time.Duration, Limiter)
19 // startTaking tries to Take() on passed in limiters in a loop/goroutine.
20 startTaking(rls ...Limiter)
21 // assertCountAt asserts the limiters have Taken() a number of times at the given time.
22 // It's a thin wrapper around afterFunc to reduce boilerplate code.
23 assertCountAt(d time.Duration, count int)
24 // afterFunc executes a func at a given time.
25 // not using clock.AfterFunc because andres-erbsen/clock misses a nap there.
26 afterFunc(d time.Duration, fn func())
27 // some tests want raw access to the clock.
28 getClock() *clock.Mock
29 }
30
31 type runnerImpl struct {
32 t *testing.T
33
34 clock *clock.Mock
•35 constructor func(int64, ...Option) Limiter
36 count atomic.Int32
37 // maxDuration is the time we need to move into the future for a test.
38 // It's populated automatically based on assertCountAt/afterFunc.
39 maxDuration time.Duration
40 doneCh chan struct{}
41 wg sync.WaitGroup
42 }
43
44 func runTest(t *testing.T, fn func(testRunner)) {
45 impls := []struct {
46 name string
•47 constructor func(int64, ...Option) Limiter
48 }{
49 {
50 name: "mutex",
•51 constructor: func(rate int64, opts ...Option) Limiter {
52 return newMutexBased(rate, opts...)
53 },
54 },
55 {
56 name: "atomic",
•57 constructor: func(rate int64, opts ...Option) Limiter {
58 return newAtomicBased(rate, opts...)
59 },
60 },
61 {
62 name: "atomic_int64",
•63 constructor: func(rate int64, opts ...Option) Limiter {
64 return newAtomicInt64Based(rate, opts...)
65 },
66 },
67 }
68
69 for _, tt := range impls {
70 t.Run(tt.name, func(t *testing.T) {
71 // Set a non-default time.Time since some limiters (int64 in particular) use
72 // the default value as "non-initialized" state.
73 clockMock := clock.NewMock()
74 clockMock.Set(time.Now())
75 r := runnerImpl{
76 t: t,
77 clock: clockMock,
78 constructor: tt.constructor,
79 doneCh: make(chan struct{}),
80 }
81 defer close(r.doneCh)
82 defer r.wg.Wait()
83
84 fn(&r)
85 r.clock.Add(r.maxDuration)
86 })
87 }
88 }
89
90 // createLimiter builds a limiter with given options.
•91 func (r *runnerImpl) createLimiter(rate int64, opts ...Option) Limiter {
92 opts = append(opts, WithClock(r.clock))
93 return r.constructor(rate, opts...)
94 }
95
96 func (r *runnerImpl) getClock() *clock.Mock {
97 return r.clock
98 }
99
100 // startTaking tries to Take() on passed in limiters in a loop/goroutine.
101 func (r *runnerImpl) startTaking(rls ...Limiter) {
102 r.goWait(func() {
103 for {
104 for _, rl := range rls {
105 rl.Take()
106 }
107 r.count.Inc()
108 select {
109 case <-r.doneCh:
110 return
111 default:
112 }
113 }
114 })
115 }
116
117 // takeOnceAfter attempts to Take at a specific time.
118 func (r *runnerImpl) takeOnceAfter(d time.Duration, rl Limiter) {
119 r.wg.Add(1)
120 r.afterFunc(d, func() {
121 rl.Take()
122 r.count.Inc()
123 r.wg.Done()
124 })
125 }
126
127 // assertCountAt asserts the limiters have Taken() a number of times at a given time.
128 func (r *runnerImpl) assertCountAt(d time.Duration, count int) {
129 r.wg.Add(1)
130 r.afterFunc(d, func() {
131 assert.Equal(r.t, int32(count), r.count.Load(), "count not as expected")
132 r.wg.Done()
133 })
134 }
135
136 // afterFunc executes a func at a given time.
137 func (r *runnerImpl) afterFunc(d time.Duration, fn func()) {
138 if d > r.maxDuration {
139 r.maxDuration = d
140 }
141
142 r.goWait(func() {
143 select {
144 case <-r.doneCh:
145 return
146 case <-r.clock.After(d):
147 }
148 fn()
149 })
150 }
151
152 // goWait runs a function in a goroutine and makes sure the goroutine was scheduled.
153 func (r *runnerImpl) goWait(fn func()) {
154 wg := sync.WaitGroup{}
155 wg.Add(1)
156 go func() {
157 wg.Done()
158 fn()
159 }()
160 wg.Wait()
161 }
162
163 func TestUnlimited(t *testing.T) {
•164 t.Skip()
165 t.Parallel()
166 now := time.Now()
167 rl := NewUnlimited()
168 for i := 0; i < 1000; i++ {
169 rl.Take()
170 }
171 assert.Condition(t, func() bool { return time.Since(now) < 1*time.Millisecond }, "no artificial delay")
172 }
173
174 func TestRateLimiter(t *testing.T) {
175 t.Parallel()
176 runTest(t, func(r testRunner) {
177 rl := r.createLimiter(100, WithoutSlack)
178
179 // Create copious counts concurrently.
180 r.startTaking(rl)
181 r.startTaking(rl)
182 r.startTaking(rl)
183 r.startTaking(rl)
184
185 r.assertCountAt(1*time.Second, 100)
186 r.assertCountAt(2*time.Second, 200)
187 r.assertCountAt(3*time.Second, 300)
188 })
189 }
190
191 func TestDelayedRateLimiter(t *testing.T) {
192 t.Parallel()
193 runTest(t, func(r testRunner) {
194 slow := r.createLimiter(10, WithoutSlack)
195 fast := r.createLimiter(100, WithoutSlack)
196
197 r.startTaking(slow, fast)
198
199 r.afterFunc(20*time.Second, func() {
200 r.startTaking(fast)
201 r.startTaking(fast)
202 r.startTaking(fast)
203 r.startTaking(fast)
204 })
205
206 r.assertCountAt(30*time.Second, 1200)
207 })
208 }
209
210 func TestPer(t *testing.T) {
211 t.Parallel()
212 runTest(t, func(r testRunner) {
213 rl := r.createLimiter(7, WithoutSlack, Per(time.Minute))
214
215 r.startTaking(rl)
216 r.startTaking(rl)
217
218 r.assertCountAt(1*time.Second, 1)
219 r.assertCountAt(1*time.Minute, 8)
220 r.assertCountAt(2*time.Minute, 15)
221 })
222 }
223
224 // TestInitial verifies that the initial sequence is scheduled as expected.
225 func TestInitial(t *testing.T) {
226 t.Parallel()
227 tests := []struct {
228 msg string
229 opts []Option
230 }{
231 {
232 msg: "With Slack",
233 },
234 {
235 msg: "Without Slack",
236 opts: []Option{WithoutSlack},
237 },
238 }
239
240 for _, tt := range tests {
241 t.Run(tt.msg, func(t *testing.T) {
242 runTest(t, func(r testRunner) {
243 rl := r.createLimiter(10, tt.opts...)
244
245 var (
246 clk = r.getClock()
247 prev = clk.Now()
248
249 results = make(chan time.Time)
250 have []time.Duration
251 startWg sync.WaitGroup
252 )
253 startWg.Add(3)
254
255 for i := 0; i < 3; i++ {
256 go func() {
257 startWg.Done()
258 results <- rl.Take()
259 }()
260 }
261
262 startWg.Wait()
263 clk.Add(time.Second)
264
265 for i := 0; i < 3; i++ {
266 ts := <-results
267 have = append(have, ts.Sub(prev))
268 prev = ts
269 }
270
271 assert.Equal(t,
272 []time.Duration{
273 0,
274 time.Millisecond * 100,
275 time.Millisecond * 100,
276 },
277 have,
278 "bad timestamps for inital takes",
279 )
280 })
281 })
282 }
283 }
284
285 func TestMaxSlack(t *testing.T) {
286 t.Parallel()
287 runTest(t, func(r testRunner) {
288 rl := r.createLimiter(1, WithSlack(1))
289
290 r.takeOnceAfter(time.Nanosecond, rl)
291 r.takeOnceAfter(2*time.Second+1*time.Nanosecond, rl)
292 r.takeOnceAfter(2*time.Second+2*time.Nanosecond, rl)
293 r.takeOnceAfter(2*time.Second+3*time.Nanosecond, rl)
294 r.takeOnceAfter(2*time.Second+4*time.Nanosecond, rl)
295
296 r.assertCountAt(3*time.Second, 3)
297 r.assertCountAt(10*time.Second, 5)
298 })
299 }
300
301 func TestSlack(t *testing.T) {
302 t.Parallel()
303 // To simulate slack, we combine two limiters.
304 // - First, we start a single goroutine with both of them,
305 // during this time the slow limiter will dominate,
306 // and allow the fast limiter to accumulate slack.
307 // - After 2 seconds, we start another goroutine with
308 // only the faster limiter. This will allow it to max out,
309 // and consume all the slack.
310 // - After 3 seconds, we look at the final result, and we expect,
311 // a sum of:
312 // - slower limiter running for 3 seconds
313 // - faster limiter running for 1 second
314 // - slack accumulated by the faster limiter during the two seconds.
315 // it was blocked by slower limiter.
316 tests := []struct {
317 msg string
318 opt []Option
319 want int
320 }{
321 {
322 msg: "no option, defaults to 10",
323 // 2*10 + 1*100 + 1*10 (slack)
324 want: 130,
325 },
326 {
327 msg: "slack of 10, like default",
328 opt: []Option{WithSlack(10)},
329 // 2*10 + 1*100 + 1*10 (slack)
330 want: 130,
331 },
332 {
333 msg: "slack of 20",
334 opt: []Option{WithSlack(20)},
335 // 2*10 + 1*100 + 1*20 (slack)
336 want: 140,
337 },
338 {
339 // Note this is bigger then the rate of the limiter.
340 msg: "slack of 150",
341 opt: []Option{WithSlack(150)},
342 // 2*10 + 1*100 + 1*150 (slack)
343 want: 270,
344 },
345 {
346 msg: "no option, defaults to 10, with per",
347 // 2*(10*2) + 1*(100*2) + 1*10 (slack)
348 opt: []Option{Per(500 * time.Millisecond)},
349 want: 230,
350 },
351 {
352 msg: "slack of 10, like default, with per",
353 opt: []Option{WithSlack(10), Per(500 * time.Millisecond)},
354 // 2*(10*2) + 1*(100*2) + 1*10 (slack)
355 want: 230,
356 },
357 {
358 msg: "slack of 20, with per",
359 opt: []Option{WithSlack(20), Per(500 * time.Millisecond)},
360 // 2*(10*2) + 1*(100*2) + 1*20 (slack)
361 want: 240,
362 },
363 {
364 // Note this is bigger then the rate of the limiter.
365 msg: "slack of 150, with per",
366 opt: []Option{WithSlack(150), Per(500 * time.Millisecond)},
367 // 2*(10*2) + 1*(100*2) + 1*150 (slack)
368 want: 370,
369 },
370 }
371
372 for _, tt := range tests {
373 t.Run(tt.msg, func(t *testing.T) {
374 runTest(t, func(r testRunner) {
375 slow := r.createLimiter(10, WithoutSlack)
376 fast := r.createLimiter(100, tt.opt...)
377
378 r.startTaking(slow, fast)
379
380 r.afterFunc(2*time.Second, func() {
381 r.startTaking(fast)
382 r.startTaking(fast)
383 })
384
385 // limiter with 10hz dominates here - we're always at 10.
386 r.assertCountAt(1*time.Second, 10)
387 r.assertCountAt(3*time.Second, tt.want)
388 })
389 })
390 }
391 }