TimeBackoff example

use PHPUnit\Framework\TestCase;
use Shopware\Core\Framework\RateLimiter\Policy\TimeBackoff;

/** * @internal */
class TimeBackoffTest extends TestCase
{
    public function testThrowsExceptionOnInvalidLimits(): void
    {
        $backoff = new TimeBackoff('test', [
            [
                'limit' => 3,
                'interval' => '10 seconds',
            ],
            [
                'limit' => 5,
                'interval' => '30 seconds',
            ],
        ]);

        $reflection = new \ReflectionClass($backoff);
        

        throw new ReserveNotSupportedException(self::class);
    }

    public function consume(int $tokens = 1): RateLimit
    {
        $this->lock?->acquire(true);

        try {
            $backoff = $this->storage->fetch($this->id);
            if (!$backoff instanceof TimeBackoff) {
                $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)) {
                
$this->limiter->consume($consume);
    }

    public function testReserve(): void
    {
        static::expectException(ReserveNotSupportedException::class);
        $this->limiter->reserve();
    }

    public function testThrottle(): void
    {
        $backoff = new TimeBackoff($this->id, $this->config['limits']);

        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) {
                
Home | Imprint | This part of the site doesn't use cookies.