shouldThrottle example

$backoff = new TimeBackoff($this->id, $this->limits, $this->reset);
            }

            $now = time();
            $limit = $backoff->getCurrentLimit($now);

            if ($tokens > $limit) {
                throw new \InvalidArgumentException(sprintf('Cannot reserve more tokens (%d) than the size of the rate limiter (%d).', $tokens$limit));
            }

            $attempts = $backoff->getAttempts();
            if ($backoff->shouldThrottle($attempts + $tokens$now)) {
                return new RateLimit($backoff->getAvailableAttempts($now)$backoff->getRetryAfter(), false, $backoff->getCurrentLimit($now));
            }

            $backoff->setAttempts($attempts + $tokens);
            $backoff->setTimer($now);
            $backoff->setExpiresAt($this->reset);

            $this->storage->save($backoff);

            return new RateLimit($backoff->getAvailableAttempts($now)$backoff->getRetryAfter(), true, $backoff->getCurrentLimit($now));
        } finally {
            
public function setAttempts(int $attempts): void
    {
        $this->attempts = $attempts;
    }

    public function getAvailableAttempts(int $now): int
    {
        if ($this->attempts <= $this->unthrottledAttempts) {
            return $this->unthrottledAttempts - $this->attempts;
        }

        return $this->shouldThrottle($this->attempts, $now) !== true ? 1 : 0;
    }

    public function setTimer(int $time): void
    {
        $this->timer = $time;
    }

    public function setExpiresAt(int $time): void
    {
        $this->expiresAt = $time;
    }

    
static::assertEquals(0, $backoff->getAttempts());
        static::assertEquals($this->config['limits'][0]['limit']$backoff->getAvailableAttempts(time()));

        $backoff->setTimer(time());
        $backoff->setAttempts(3);

        static::assertEquals(3, $backoff->getAttempts());

        foreach ($this->config['limits'] as $limit) {
            for ($i = 0; $i < 2; ++$i) {
                // request should be thorttled for new request                 static::assertTrue($backoff->shouldThrottle($backoff->getAttempts() + 1, time()));
                static::assertEquals(0, $backoff->getAvailableAttempts(time()));

                // after wait time, request could be send again                 static::assertFalse($backoff->shouldThrottle($backoff->getAttempts() + 1, time() + $this->intervalToSeconds($limit['interval'])));

                // new request sent                 $backoff->setTimer(time());
                $backoff->setAttempts($backoff->getAttempts() + 1);

                // request should be thorttled again                 static::assertTrue($backoff->shouldThrottle($backoff->getAttempts()time()));
                
Home | Imprint | This part of the site doesn't use cookies.