Debian Codegraph @

ratelimit_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
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(int, ...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(int, ...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(int, ...Option) Limiter
48 }{
49 {
50 name: "mutex",
51 constructor: func(rate int, opts ...Option) Limiter {
52 return newMutexBased(rate, opts...)
53 },
54 },
55 {
56 name: "atomic",
57 constructor: func(rate int, opts ...Option) Limiter {
58 return newAtomicBased(rate, opts...)
59 },
60 },
61 {
62 name: "atomic_int64",
63 constructor: func(rate int, 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 int, 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.Parallel()
165 now := time.Now()
166 rl := NewUnlimited()
167 for i := 0; i < 1000; i++ {
168 rl.Take()
169 }
170 assert.Condition(t, func() bool { return time.Since(now) < 1*time.Millisecond }, "no artificial delay")
171 }
172
173 func TestRateLimiter(t *testing.T) {
174 t.Parallel()
175 runTest(t, func(r testRunner) {
176 rl := r.createLimiter(100, WithoutSlack)
177
178 // Create copious counts concurrently.
179 r.startTaking(rl)
180 r.startTaking(rl)
181 r.startTaking(rl)
182 r.startTaking(rl)
183
184 r.assertCountAt(1*time.Second, 100)
185 r.assertCountAt(2*time.Second, 200)
186 r.assertCountAt(3*time.Second, 300)
187 })
188 }
189
190 func TestDelayedRateLimiter(t *testing.T) {
191 t.Parallel()
192 runTest(t, func(r testRunner) {
193 slow := r.createLimiter(10, WithoutSlack)
194 fast := r.createLimiter(100, WithoutSlack)
195
196 r.startTaking(slow, fast)
197
198 r.afterFunc(20*time.Second, func() {
199 r.startTaking(fast)
200 r.startTaking(fast)
201 r.startTaking(fast)
202 r.startTaking(fast)
203 })
204
205 r.assertCountAt(30*time.Second, 1200)
206 })
207 }
208
209 func TestPer(t *testing.T) {
210 t.Parallel()
211 runTest(t, func(r testRunner) {
212 rl := r.createLimiter(7, WithoutSlack, Per(time.Minute))
213
214 r.startTaking(rl)
215 r.startTaking(rl)
216
217 r.assertCountAt(1*time.Second, 1)
218 r.assertCountAt(1*time.Minute, 8)
219 r.assertCountAt(2*time.Minute, 15)
220 })
221 }
222
223 // TestInitial verifies that the initial sequence is scheduled as expected.
224 func TestInitial(t *testing.T) {
225 t.Parallel()
226 tests := []struct {
227 msg string
228 opts []Option
229 }{
230 {
231 msg: "With Slack",
232 },
233 {
234 msg: "Without Slack",
235 opts: []Option{WithoutSlack},
236 },
237 }
238
239 for _, tt := range tests {
240 t.Run(tt.msg, func(t *testing.T) {
241 runTest(t, func(r testRunner) {
242 rl := r.createLimiter(10, tt.opts...)
243
244 var (
245 clk = r.getClock()
246 prev = clk.Now()
247
248 results = make(chan time.Time)
249 have []time.Duration
250 startWg sync.WaitGroup
251 )
252 startWg.Add(3)
253
254 for i := 0; i < 3; i++ {
255 go func() {
256 startWg.Done()
257 results <- rl.Take()
258 }()
259 }
260
261 startWg.Wait()
262 clk.Add(time.Second)
263
264 for i := 0; i < 3; i++ {
265 ts := <-results
266 have = append(have, ts.Sub(prev))
267 prev = ts
268 }
269
270 assert.Equal(t,
271 []time.Duration{
272 0,
273 time.Millisecond * 100,
274 time.Millisecond * 100,
275 },
276 have,
277 "bad timestamps for inital takes",
278 )
279 })
280 })
281 }
282 }
283
284 func TestMaxSlack(t *testing.T) {
285 t.Parallel()
286 runTest(t, func(r testRunner) {
287 rl := r.createLimiter(1, WithSlack(1))
288
289 r.takeOnceAfter(time.Nanosecond, rl)
290 r.takeOnceAfter(2*time.Second+1*time.Nanosecond, rl)
291 r.takeOnceAfter(2*time.Second+2*time.Nanosecond, rl)
292 r.takeOnceAfter(2*time.Second+3*time.Nanosecond, rl)
293 r.takeOnceAfter(2*time.Second+4*time.Nanosecond, rl)
294
295 r.assertCountAt(3*time.Second, 3)
296 r.assertCountAt(10*time.Second, 5)
297 })
298 }
299
300 func TestSlack(t *testing.T) {
301 t.Parallel()
302 // To simulate slack, we combine two limiters.
303 // - First, we start a single goroutine with both of them,
304 // during this time the slow limiter will dominate,
305 // and allow the fast limiter to accumulate slack.
306 // - After 2 seconds, we start another goroutine with
307 // only the faster limiter. This will allow it to max out,
308 // and consume all the slack.
309 // - After 3 seconds, we look at the final result, and we expect,
310 // a sum of:
311 // - slower limiter running for 3 seconds
312 // - faster limiter running for 1 second
313 // - slack accumulated by the faster limiter during the two seconds.
314 // it was blocked by slower limiter.
315 tests := []struct {
316 msg string
317 opt []Option
318 want int
319 }{
320 {
321 msg: "no option, defaults to 10",
322 // 2*10 + 1*100 + 1*10 (slack)
323 want: 130,
324 },
325 {
326 msg: "slack of 10, like default",
327 opt: []Option{WithSlack(10)},
328 // 2*10 + 1*100 + 1*10 (slack)
329 want: 130,
330 },
331 {
332 msg: "slack of 20",
333 opt: []Option{WithSlack(20)},
334 // 2*10 + 1*100 + 1*20 (slack)
335 want: 140,
336 },
337 {
338 // Note this is bigger then the rate of the limiter.
339 msg: "slack of 150",
340 opt: []Option{WithSlack(150)},
341 // 2*10 + 1*100 + 1*150 (slack)
342 want: 270,
343 },
344 {
345 msg: "no option, defaults to 10, with per",
346 // 2*(10*2) + 1*(100*2) + 1*10 (slack)
347 opt: []Option{Per(500 * time.Millisecond)},
348 want: 230,
349 },
350 {
351 msg: "slack of 10, like default, with per",
352 opt: []Option{WithSlack(10), Per(500 * time.Millisecond)},
353 // 2*(10*2) + 1*(100*2) + 1*10 (slack)
354 want: 230,
355 },
356 {
357 msg: "slack of 20, with per",
358 opt: []Option{WithSlack(20), Per(500 * time.Millisecond)},
359 // 2*(10*2) + 1*(100*2) + 1*20 (slack)
360 want: 240,
361 },
362 {
363 // Note this is bigger then the rate of the limiter.
364 msg: "slack of 150, with per",
365 opt: []Option{WithSlack(150), Per(500 * time.Millisecond)},
366 // 2*(10*2) + 1*(100*2) + 1*150 (slack)
367 want: 370,
368 },
369 }
370
371 for _, tt := range tests {
372 t.Run(tt.msg, func(t *testing.T) {
373 runTest(t, func(r testRunner) {
374 slow := r.createLimiter(10, WithoutSlack)
375 fast := r.createLimiter(100, tt.opt...)
376
377 r.startTaking(slow, fast)
378
379 r.afterFunc(2*time.Second, func() {
380 r.startTaking(fast)
381 r.startTaking(fast)
382 })
383
384 // limiter with 10hz dominates here - we're always at 10.
385 r.assertCountAt(1*time.Second, 10)
386 r.assertCountAt(3*time.Second, tt.want)
387 })
388 })
389 }
390 }