github.com/unionj-cloud/go-doudou@v1.3.8-0.20221011095552-0088008e5b31/framework/ratelimit/memrate/rate_test.go (about) 1 // Copyright 2015 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 //go:build go1.7 6 // +build go1.7 7 8 package memrate 9 10 import ( 11 "context" 12 . "github.com/smartystreets/goconvey/convey" 13 "github.com/unionj-cloud/go-doudou/framework/ratelimit" 14 "log" 15 "math" 16 "runtime" 17 "sync" 18 "sync/atomic" 19 "testing" 20 "time" 21 ) 22 23 func TestLimit(t *testing.T) { 24 if Limit(10) == Inf { 25 t.Errorf("Limit(10) == Inf should be false") 26 } 27 } 28 29 func closeEnough(a, b Limit) bool { 30 return (math.Abs(float64(a)/float64(b)) - 1.0) < 1e-9 31 } 32 33 func TestEvery(t *testing.T) { 34 cases := []struct { 35 interval time.Duration 36 lim Limit 37 }{ 38 {0, Inf}, 39 {-1, Inf}, 40 {1 * time.Nanosecond, Limit(1e9)}, 41 {1 * time.Microsecond, Limit(1e6)}, 42 {1 * time.Millisecond, Limit(1e3)}, 43 {10 * time.Millisecond, Limit(100)}, 44 {100 * time.Millisecond, Limit(10)}, 45 {1 * time.Second, Limit(1)}, 46 {2 * time.Second, Limit(0.5)}, 47 {time.Duration(2.5 * float64(time.Second)), Limit(0.4)}, 48 {4 * time.Second, Limit(0.25)}, 49 {10 * time.Second, Limit(0.1)}, 50 {time.Duration(math.MaxInt64), Limit(1e9 / float64(math.MaxInt64))}, 51 } 52 for _, tc := range cases { 53 lim := Every(tc.interval) 54 if !closeEnough(lim, tc.lim) { 55 t.Errorf("Every(%v) = %v want %v", tc.interval, lim, tc.lim) 56 } 57 } 58 } 59 60 const ( 61 d = 100 * time.Millisecond 62 ) 63 64 var ( 65 t0 = time.Now() 66 t1 = t0.Add(time.Duration(1) * d) 67 t2 = t0.Add(time.Duration(2) * d) 68 t3 = t0.Add(time.Duration(3) * d) 69 t4 = t0.Add(time.Duration(4) * d) 70 t5 = t0.Add(time.Duration(5) * d) 71 t9 = t0.Add(time.Duration(9) * d) 72 ) 73 74 type allow struct { 75 t time.Time 76 n int 77 ok bool 78 } 79 80 func run(t *testing.T, lim *Limiter, allows []allow) { 81 t.Helper() 82 for i, allow := range allows { 83 ok := lim.AllowN(allow.t, allow.n) 84 if ok != allow.ok { 85 t.Errorf("step %d: lim.AllowN(%v, %v) = %v want %v", 86 i, allow.t, allow.n, ok, allow.ok) 87 } 88 } 89 } 90 91 func TestLimiterBurst1(t *testing.T) { 92 run(t, NewLimiter(10, 1), []allow{ 93 {t0, 1, true}, 94 {t0, 1, false}, 95 {t0, 1, false}, 96 {t1, 1, true}, 97 {t1, 1, false}, 98 {t1, 1, false}, 99 {t2, 2, false}, // burst size is 1, so n=2 always fails 100 {t2, 1, true}, 101 {t2, 1, false}, 102 }) 103 } 104 105 func TestLimiterBurst3(t *testing.T) { 106 run(t, NewLimiter(10, 3), []allow{ 107 {t0, 2, true}, 108 {t0, 2, false}, 109 {t0, 1, true}, 110 {t0, 1, false}, 111 {t1, 4, false}, 112 {t2, 1, true}, 113 {t3, 1, true}, 114 {t4, 1, true}, 115 {t4, 1, true}, 116 {t4, 1, false}, 117 {t4, 1, false}, 118 {t9, 3, true}, 119 {t9, 0, true}, 120 }) 121 } 122 123 func TestLimiterJumpBackwards(t *testing.T) { 124 run(t, NewLimiter(10, 3), []allow{ 125 {t1, 1, true}, // start at t1 126 {t0, 1, true}, // jump back to t0, two tokens remain 127 {t0, 1, true}, 128 {t0, 1, false}, 129 {t0, 1, false}, 130 {t1, 1, true}, // got a token 131 {t1, 1, false}, 132 {t1, 1, false}, 133 {t2, 1, true}, // got another token 134 {t2, 1, false}, 135 {t2, 1, false}, 136 }) 137 } 138 139 // Ensure that tokensFromDuration doesn't produce 140 // rounding errors by truncating nanoseconds. 141 // See golang.org/issues/34861. 142 func TestLimiter_noTruncationErrors(t *testing.T) { 143 if !NewLimiter(0.7692307692307693, 1).Allow() { 144 t.Fatal("expected true") 145 } 146 } 147 148 func TestSimultaneousRequests(t *testing.T) { 149 const ( 150 limit = 1 151 burst = 5 152 numRequests = 15 153 ) 154 var ( 155 wg sync.WaitGroup 156 numOK = uint32(0) 157 ) 158 159 // Very slow replenishing bucket. 160 lim := NewLimiter(limit, burst) 161 162 // Tries to take a token, atomically updates the counter and decreases the wait 163 // group counter. 164 f := func() { 165 defer wg.Done() 166 if ok := lim.Allow(); ok { 167 atomic.AddUint32(&numOK, 1) 168 } 169 } 170 171 wg.Add(numRequests) 172 for i := 0; i < numRequests; i++ { 173 go f() 174 } 175 wg.Wait() 176 if numOK != burst { 177 t.Errorf("numOK = %d, want %d", numOK, burst) 178 } 179 } 180 181 func TestLongRunningQPS(t *testing.T) { 182 if testing.Short() { 183 t.Skip("skipping in short mode") 184 } 185 if runtime.GOOS == "openbsd" { 186 t.Skip("low resolution time.Sleep invalidates test (golang.org/issue/14183)") 187 return 188 } 189 190 // The test runs for a few seconds executing many requests and then checks 191 // that overall number of requests is reasonable. 192 const ( 193 limit = 100 194 burst = 100 195 ) 196 var numOK = int32(0) 197 198 lim := NewLimiter(limit, burst) 199 200 var wg sync.WaitGroup 201 f := func() { 202 if ok := lim.Allow(); ok { 203 atomic.AddInt32(&numOK, 1) 204 } 205 wg.Done() 206 } 207 208 start := time.Now() 209 end := start.Add(5 * time.Second) 210 for time.Now().Before(end) { 211 wg.Add(1) 212 go f() 213 214 // This will still offer ~500 requests per second, but won't consume 215 // outrageous amount of CPU. 216 time.Sleep(2 * time.Millisecond) 217 } 218 wg.Wait() 219 elapsed := time.Since(start) 220 ideal := burst + (limit * float64(elapsed) / float64(time.Second)) 221 222 // We should never get more requests than allowed. 223 if want := int32(ideal + 1); numOK > want { 224 t.Errorf("numOK = %d, want %d (ideal %f)", numOK, want, ideal) 225 } 226 // We should get very close to the number of requests allowed. 227 if want := int32(0.999 * ideal); numOK < want { 228 t.Errorf("numOK = %d, want %d (ideal %f)", numOK, want, ideal) 229 } 230 } 231 232 type request struct { 233 t time.Time 234 n int 235 act time.Time 236 ok bool 237 } 238 239 // dFromDuration converts a duration to a multiple of the global constant d 240 func dFromDuration(dur time.Duration) int { 241 // Adding a millisecond to be swallowed by the integer division 242 // because we don't care about small inaccuracies 243 return int((dur + time.Millisecond) / d) 244 } 245 246 // dSince returns multiples of d since t0 247 func dSince(t time.Time) int { 248 return dFromDuration(t.Sub(t0)) 249 } 250 251 func runReserve(t *testing.T, lim *Limiter, req request) *Reservation { 252 t.Helper() 253 return runReserveMax(t, lim, req, InfDuration) 254 } 255 256 func runReserveMax(t *testing.T, lim *Limiter, req request, maxReserve time.Duration) *Reservation { 257 t.Helper() 258 r := lim.reserveN(req.t, req.n, maxReserve) 259 if r.ok && (dSince(r.timeToAct) != dSince(req.act)) || r.ok != req.ok { 260 t.Errorf("lim.reserveN(t%d, %v, %v) = (t%d, %v) want (t%d, %v)", 261 dSince(req.t), req.n, maxReserve, dSince(r.timeToAct), r.ok, dSince(req.act), req.ok) 262 } 263 return &r 264 } 265 266 func TestSimpleReserve(t *testing.T) { 267 lim := NewLimiter(10, 2) 268 269 runReserve(t, lim, request{t0, 2, t0, true}) 270 runReserve(t, lim, request{t0, 2, t2, true}) 271 runReserve(t, lim, request{t3, 2, t4, true}) 272 } 273 274 func TestMix(t *testing.T) { 275 lim := NewLimiter(10, 2) 276 277 runReserve(t, lim, request{t0, 3, t1, false}) // should return false because n > Burst 278 runReserve(t, lim, request{t0, 2, t0, true}) 279 run(t, lim, []allow{{t1, 2, false}}) // not enough tokens - don't allow 280 runReserve(t, lim, request{t1, 2, t2, true}) 281 run(t, lim, []allow{{t1, 1, false}}) // negative tokens - don't allow 282 run(t, lim, []allow{{t3, 1, true}}) 283 } 284 285 func TestCancelInvalid(t *testing.T) { 286 lim := NewLimiter(10, 2) 287 288 runReserve(t, lim, request{t0, 2, t0, true}) 289 r := runReserve(t, lim, request{t0, 3, t3, false}) 290 r.CancelAt(t0) // should have no effect 291 runReserve(t, lim, request{t0, 2, t2, true}) // did not get extra tokens 292 } 293 294 func TestCancelLast(t *testing.T) { 295 lim := NewLimiter(10, 2) 296 297 runReserve(t, lim, request{t0, 2, t0, true}) 298 r := runReserve(t, lim, request{t0, 2, t2, true}) 299 r.CancelAt(t1) // got 2 tokens back 300 runReserve(t, lim, request{t1, 2, t2, true}) 301 } 302 303 func TestCancelTooLate(t *testing.T) { 304 lim := NewLimiter(10, 2) 305 306 runReserve(t, lim, request{t0, 2, t0, true}) 307 r := runReserve(t, lim, request{t0, 2, t2, true}) 308 r.CancelAt(t3) // too late to cancel - should have no effect 309 runReserve(t, lim, request{t3, 2, t4, true}) 310 } 311 312 func TestCancel0Tokens(t *testing.T) { 313 lim := NewLimiter(10, 2) 314 315 runReserve(t, lim, request{t0, 2, t0, true}) 316 r := runReserve(t, lim, request{t0, 1, t1, true}) 317 runReserve(t, lim, request{t0, 1, t2, true}) 318 r.CancelAt(t0) // got 0 tokens back 319 runReserve(t, lim, request{t0, 1, t3, true}) 320 } 321 322 func TestCancel1Token(t *testing.T) { 323 lim := NewLimiter(10, 2) 324 325 runReserve(t, lim, request{t0, 2, t0, true}) 326 r := runReserve(t, lim, request{t0, 2, t2, true}) 327 runReserve(t, lim, request{t0, 1, t3, true}) 328 r.CancelAt(t2) // got 1 token back 329 runReserve(t, lim, request{t2, 2, t4, true}) 330 } 331 332 func TestCancelMulti(t *testing.T) { 333 lim := NewLimiter(10, 4) 334 335 runReserve(t, lim, request{t0, 4, t0, true}) 336 rA := runReserve(t, lim, request{t0, 3, t3, true}) 337 runReserve(t, lim, request{t0, 1, t4, true}) 338 rC := runReserve(t, lim, request{t0, 1, t5, true}) 339 rC.CancelAt(t1) // get 1 token back 340 rA.CancelAt(t1) // get 2 tokens back, as if C was never reserved 341 runReserve(t, lim, request{t1, 3, t5, true}) 342 } 343 344 func TestReserveJumpBack(t *testing.T) { 345 lim := NewLimiter(10, 2) 346 347 runReserve(t, lim, request{t1, 2, t1, true}) // start at t1 348 runReserve(t, lim, request{t0, 1, t1, true}) // should violate Limit,Burst 349 runReserve(t, lim, request{t2, 2, t3, true}) 350 } 351 352 func TestReserveJumpBackCancel(t *testing.T) { 353 lim := NewLimiter(10, 2) 354 355 runReserve(t, lim, request{t1, 2, t1, true}) // start at t1 356 r := runReserve(t, lim, request{t1, 2, t3, true}) 357 runReserve(t, lim, request{t1, 1, t4, true}) 358 r.CancelAt(t0) // cancel at t0, get 1 token back 359 runReserve(t, lim, request{t1, 2, t4, true}) // should violate Limit,Burst 360 } 361 362 func TestReserveSetLimit(t *testing.T) { 363 lim := NewLimiter(5, 2) 364 365 runReserve(t, lim, request{t0, 2, t0, true}) 366 runReserve(t, lim, request{t0, 2, t4, true}) 367 lim.SetLimitAt(t2, 10) 368 runReserve(t, lim, request{t2, 1, t4, true}) // violates Limit and Burst 369 } 370 371 func TestReserveSetBurst(t *testing.T) { 372 lim := NewLimiter(5, 2) 373 374 runReserve(t, lim, request{t0, 2, t0, true}) 375 runReserve(t, lim, request{t0, 2, t4, true}) 376 lim.SetBurstAt(t3, 4) 377 runReserve(t, lim, request{t0, 4, t9, true}) // violates Limit and Burst 378 } 379 380 func TestReserveSetLimitCancel(t *testing.T) { 381 lim := NewLimiter(5, 2) 382 383 runReserve(t, lim, request{t0, 2, t0, true}) 384 r := runReserve(t, lim, request{t0, 2, t4, true}) 385 lim.SetLimitAt(t2, 10) 386 r.CancelAt(t2) // 2 tokens back 387 runReserve(t, lim, request{t2, 2, t3, true}) 388 } 389 390 func TestReserveMax(t *testing.T) { 391 lim := NewLimiter(10, 2) 392 maxT := d 393 394 runReserveMax(t, lim, request{t0, 2, t0, true}, maxT) 395 runReserveMax(t, lim, request{t0, 1, t1, true}, maxT) // reserve for close future 396 runReserveMax(t, lim, request{t0, 1, t2, false}, maxT) // time to act too far in the future 397 } 398 399 type wait struct { 400 name string 401 ctx context.Context 402 n int 403 delay int // in multiples of d 404 nilErr bool 405 } 406 407 func runWait(t *testing.T, lim *Limiter, w wait) { 408 t.Helper() 409 start := time.Now() 410 err := lim.WaitN(w.ctx, w.n) 411 delay := time.Since(start) 412 if (w.nilErr && err != nil) || (!w.nilErr && err == nil) || w.delay != dFromDuration(delay) { 413 errString := "<nil>" 414 if !w.nilErr { 415 errString = "<non-nil error>" 416 } 417 t.Errorf("lim.WaitN(%v, lim, %v) = %v with delay %v ; want %v with delay %v", 418 w.name, w.n, err, delay, errString, d*time.Duration(w.delay)) 419 } 420 } 421 422 func TestWaitSimple(t *testing.T) { 423 lim := NewLimiter(10, 3) 424 425 ctx, cancel := context.WithCancel(context.Background()) 426 cancel() 427 runWait(t, lim, wait{"already-cancelled", ctx, 1, 0, false}) 428 429 runWait(t, lim, wait{"exceed-burst-error", context.Background(), 4, 0, false}) 430 431 runWait(t, lim, wait{"act-now", context.Background(), 2, 0, true}) 432 runWait(t, lim, wait{"act-later", context.Background(), 3, 2, true}) 433 } 434 435 func TestWaitCancel(t *testing.T) { 436 lim := NewLimiter(10, 3) 437 438 ctx, cancel := context.WithCancel(context.Background()) 439 runWait(t, lim, wait{"act-now", ctx, 2, 0, true}) // after this lim.tokens = 1 440 go func() { 441 time.Sleep(d) 442 cancel() 443 }() 444 runWait(t, lim, wait{"will-cancel", ctx, 3, 1, false}) 445 // should get 3 tokens back, and have lim.tokens = 2 446 t.Logf("tokens:%v last:%v lastEvent:%v", lim.tokens, lim.last, lim.lastEvent) 447 runWait(t, lim, wait{"act-now-after-cancel", context.Background(), 2, 0, true}) 448 } 449 450 func TestWaitTimeout(t *testing.T) { 451 lim := NewLimiter(10, 3) 452 453 ctx, cancel := context.WithTimeout(context.Background(), d) 454 defer cancel() 455 runWait(t, lim, wait{"act-now", ctx, 2, 0, true}) 456 runWait(t, lim, wait{"w-timeout-err", ctx, 3, 0, false}) 457 } 458 459 func TestWaitInf(t *testing.T) { 460 lim := NewLimiter(Inf, 0) 461 462 runWait(t, lim, wait{"exceed-burst-no-error", context.Background(), 3, 0, true}) 463 } 464 465 func BenchmarkAllowN(b *testing.B) { 466 lim := NewLimiter(Every(1*time.Second), 1) 467 now := time.Now() 468 b.ReportAllocs() 469 b.ResetTimer() 470 b.RunParallel(func(pb *testing.PB) { 471 for pb.Next() { 472 lim.AllowN(now, 1) 473 } 474 }) 475 } 476 477 func BenchmarkWaitNNoDelay(b *testing.B) { 478 lim := NewLimiter(Limit(b.N), b.N) 479 ctx := context.Background() 480 b.ReportAllocs() 481 b.ResetTimer() 482 for i := 0; i < b.N; i++ { 483 lim.WaitN(ctx, 1) 484 } 485 } 486 487 func TestZeroLimit(t *testing.T) { 488 r := NewLimiter(0, 1) 489 if !r.Allow() { 490 t.Errorf("Limit(0, 1) want true when first used") 491 } 492 if r.Allow() { 493 t.Errorf("Limit(0, 1) want false when already used") 494 } 495 } 496 497 func TestNewLimiter(t *testing.T) { 498 type args struct { 499 r Limit 500 b int 501 opts []LimiterOption 502 } 503 store := NewMemoryStore(nil) 504 tests := []struct { 505 name string 506 args args 507 }{ 508 { 509 name: "", 510 args: args{ 511 r: 1, 512 b: 3, 513 opts: []LimiterOption{ 514 WithTimer(10*time.Second, func() { 515 store.DeleteKey("any") 516 }), 517 }, 518 }, 519 }, 520 } 521 for _, tt := range tests { 522 t.Run(tt.name, func(t *testing.T) { 523 if got := NewLimiter(tt.args.r, tt.args.b, tt.args.opts...); got == nil { 524 t.Error("got should not be nil") 525 } 526 }) 527 } 528 } 529 530 func TestTokenLimiter_Allow(t *testing.T) { 531 tl := NewLimiter(1, 3) 532 if got := tl.Allow(); got != true { 533 t.Errorf("Allow() should return true") 534 } 535 if got := tl.Allow(); got != true { 536 t.Errorf("Allow() should return true") 537 } 538 if got := tl.Allow(); got != true { 539 t.Errorf("Allow() should return true") 540 } 541 if got := tl.Allow(); got != false { 542 t.Errorf("Allow() should return false") 543 } 544 } 545 546 func TestTokenLimiter_Reserve(t *testing.T) { 547 tl := NewLimiter(1, 3) 548 if d, ok, _ := tl.ReserveE(); ok != true && d != 0 { 549 t.Errorf("Reserve() should return true and d should equal to 0") 550 } 551 if d, ok, _ := tl.ReserveE(); ok != true && d != 0 { 552 t.Errorf("Reserve() should return true and d should equal to 0") 553 } 554 if d, ok, _ := tl.ReserveE(); ok != true && d != 0 { 555 t.Errorf("Reserve() should return true and d should equal to 0") 556 } 557 if d, ok, _ := tl.ReserveE(); ok != true && d <= 0 { 558 t.Errorf("Reserve() should return true and d should greater than 0") 559 } 560 tl = NewLimiter(1, 0) 561 if _, ok, _ := tl.ReserveE(); ok != false { 562 t.Errorf("Reserve() should return false") 563 } 564 } 565 566 func TestTokenLimiter_Wait(t *testing.T) { 567 tl := NewLimiter(1, 3) 568 ctx := context.Background() 569 if err := tl.Wait(ctx); err != nil { 570 t.Errorf("Wait() shouldn't return error") 571 } 572 if err := tl.Wait(ctx); err != nil { 573 t.Errorf("Wait() shouldn't return error") 574 } 575 if err := tl.Wait(ctx); err != nil { 576 t.Errorf("Wait() shouldn't return error") 577 } 578 ctx, cancel := context.WithTimeout(ctx, 1*time.Millisecond) 579 defer cancel() 580 if err := tl.Wait(ctx); err.Error() != "rate: Wait(n=1) would exceed context deadline" { 581 t.Errorf("Wait() should return error: rate: Wait(n=1) would exceed context deadline, but actual error: %s", err.Error()) 582 } 583 } 584 585 func TestLimiter_Limit(t *testing.T) { 586 Convey("Test limiter", t, func() { 587 tl := NewLimiter(1, 3) 588 Convey("Limit should equal to 1", func() { 589 So(tl.Limit(), ShouldEqual, 1) 590 }) 591 Convey("Burst should equal to 3", func() { 592 So(tl.Burst(), ShouldEqual, 3) 593 }) 594 }) 595 } 596 597 func TestNewLimiterLimit(t *testing.T) { 598 Convey("Test limiter", t, func() { 599 tl := NewLimiterLimit(ratelimit.PerSecondBurst(1, 3), WithTimer(10*time.Second, func() { 600 log.Println("do nothing") 601 })) 602 Convey("Limit should equal to 1", func() { 603 So(tl.Limit(), ShouldEqual, 1) 604 }) 605 Convey("Burst should equal to 3", func() { 606 So(tl.Burst(), ShouldEqual, 3) 607 }) 608 609 tl.SetLimit(10) 610 Convey("Limit should equal to 10", func() { 611 So(tl.Limit(), ShouldEqual, 10) 612 }) 613 614 tl.SetBurst(100) 615 Convey("Burst should equal to 100", func() { 616 So(tl.Burst(), ShouldEqual, 100) 617 }) 618 619 tl.resetTimer() 620 621 ok := tl.AllowCtx(context.Background()) 622 So(ok, ShouldBeTrue) 623 ok, err := tl.AllowECtx(context.Background()) 624 So(err, ShouldBeNil) 625 So(ok, ShouldBeTrue) 626 dur, ok, err := tl.ReserveECtx(context.Background()) 627 So(err, ShouldBeNil) 628 So(ok, ShouldBeTrue) 629 So(dur, ShouldEqual, 0) 630 631 ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) 632 defer cancel() 633 time.Sleep(600 * time.Millisecond) 634 ok = tl.AllowCtx(ctx) 635 So(ok, ShouldBeFalse) 636 ok, err = tl.AllowECtx(ctx) 637 So(err, ShouldResemble, context.DeadlineExceeded) 638 So(ok, ShouldBeFalse) 639 dur, ok, err = tl.ReserveECtx(ctx) 640 So(err, ShouldResemble, context.DeadlineExceeded) 641 So(ok, ShouldBeFalse) 642 So(dur, ShouldEqual, 0) 643 }) 644 }