Window example

$this->storage->save(new DummyWindow());
        $limiter = $this->createLimiter();
        $rateLimit = $limiter->consume();
        $this->assertTrue($rateLimit->isAccepted());
        $this->assertEquals(9, $rateLimit->getRemainingTokens());
    }

    public function testWindowResilientToTimeShifting()
    {
        $serverOneClock = microtime(true) - 1;
        $serverTwoClock = microtime(true) + 1;
        $window = new Window('id', 300, 100, $serverTwoClock);
        $this->assertSame(100, $window->getAvailableTokens($serverTwoClock));
        $this->assertSame(100, $window->getAvailableTokens($serverOneClock));

        $window = new Window('id', 300, 100, $serverOneClock);
        $this->assertSame(100, $window->getAvailableTokens($serverTwoClock));
        $this->assertSame(100, $window->getAvailableTokens($serverOneClock));
    }

    public function testPeekConsume()
    {
        $limiter = $this->createLimiter();

        
$this->storage = new CacheStorage($this->pool);
    }

    public function testSave()
    {
        $cacheItem = $this->createMock(CacheItemInterface::class);
        $cacheItem->expects($this->exactly(2))->method('expiresAfter')->with(10);

        $this->pool->expects($this->any())->method('getItem')->with(sha1('test'))->willReturn($cacheItem);
        $this->pool->expects($this->exactly(2))->method('save')->with($cacheItem);

        $window = new Window('test', 10, 20);
        $this->storage->save($window);

        $window = unserialize(serialize($window));
        $this->storage->save($window);
    }

    public function testFetchExistingState()
    {
        $cacheItem = $this->createMock(CacheItemInterface::class);
        $window = new Window('test', 10, 20);
        $cacheItem->expects($this->any())->method('get')->willReturn($window);
        
public function reserve(int $tokens = 1, float $maxTime = null): Reservation
    {
        if ($tokens > $this->limit) {
            throw new \InvalidArgumentException(sprintf('Cannot reserve more tokens (%d) than the size of the rate limiter (%d).', $tokens$this->limit));
        }

        $this->lock?->acquire(true);

        try {
            $window = $this->storage->fetch($this->id);
            if (!$window instanceof Window) {
                $window = new Window($this->id, $this->interval, $this->limit);
            }

            $now = microtime(true);
            $availableTokens = $window->getAvailableTokens($now);

            if ($availableTokens >= max(1, $tokens)) {
                $window->add($tokens$now);

                $reservation = new Reservation($nownew RateLimit($window->getAvailableTokens($now), \DateTimeImmutable::createFromFormat('U', floor($now)), true, $this->limit));
            } else {
                $waitDuration = $window->calculateTimeForTokens(max(1, $tokens)$now);

                
Home | Imprint | This part of the site doesn't use cookies.