Example #1
0
    public void ReserveTellsYouHowLongToWait()
    {
        var clock   = new FakeSystemClock();
        var limiter = new Limiter(new Limit(10), 50, clock);

        var initiallyAllowed = limiter.AllowN(clock.UtcNow, 50);
        var thenNotAllowed1  = limiter.Allow();

        var reserveOne = limiter.Reserve();
        var delayOne   = reserveOne.Delay();

        var reserveTwoMore = limiter.Reserve(clock.UtcNow, 2);
        var delayTwoMore   = reserveTwoMore.Delay();

        clock.Advance(TimeSpan.FromMilliseconds(450));

        var reserveAlreadyAvailable = limiter.Reserve();
        var delayAlreadyAvailable   = reserveAlreadyAvailable.Delay();

        var reserveHalfAvailable = limiter.Reserve();
        var delayHalfAvailable   = reserveHalfAvailable.Delay();

        Assert.True(initiallyAllowed);
        Assert.False(thenNotAllowed1);
        Assert.True(reserveOne.Ok);
        Assert.Equal(TimeSpan.FromMilliseconds(100), delayOne);
        Assert.True(reserveTwoMore.Ok);
        Assert.Equal(TimeSpan.FromMilliseconds(300), delayTwoMore);
        Assert.True(reserveAlreadyAvailable.Ok);
        Assert.Equal(TimeSpan.Zero, delayAlreadyAvailable);
        Assert.True(reserveHalfAvailable.Ok);
        Assert.Equal(TimeSpan.FromMilliseconds(50), delayHalfAvailable);
    }
Example #2
0
    public void TokensBecomeAvailableAtLimitPerSecondRate()
    {
        var clock   = new FakeSystemClock();
        var limiter = new Limiter(new Limit(10), 50, clock);

        var initiallyAllowed = limiter.AllowN(clock.UtcNow, 50);
        var thenNotAllowed1  = limiter.Allow();

        clock.Advance(TimeSpan.FromMilliseconds(100));
        var oneTokenAvailable = limiter.Allow();
        var thenNotAllowed2   = limiter.Allow();

        clock.Advance(TimeSpan.FromMilliseconds(200));
        var twoTokensAvailable1 = limiter.Allow();
        var twoTokensAvailable2 = limiter.Allow();
        var thenNotAllowed3     = limiter.Allow();

        Assert.True(initiallyAllowed);
        Assert.False(thenNotAllowed1);
        Assert.True(oneTokenAvailable);
        Assert.False(thenNotAllowed2);
        Assert.True(twoTokensAvailable1);
        Assert.True(twoTokensAvailable2);
        Assert.False(thenNotAllowed3);
    }