reserve example



        /** @var LimiterInterface $rateLimiter */
        $rateLimiter = $this->rateLimiters[$transportName]->create();
        if ($rateLimiter->consume()->isAccepted()) {
            return;
        }

        $this->logger?->info('Transport {transport} is being rate limited, waiting for token to become available...', ['transport' => $transportName]);

        $this->eventDispatcher?->dispatch(new WorkerRateLimitedEvent($rateLimiter$transportName));
        $rateLimiter->reserve()->wait();
    }

    private function flush(bool $force): bool
    {
        $unacks = $this->unacks;

        if (!$unacks->count()) {
            return false;
        }

        $this->unacks = new \SplObjectStorage();

        

        } finally {
            $this->lock?->release();
        }

        return $reservation;
    }

    public function consume(int $tokens = 1): RateLimit
    {
        try {
            return $this->reserve($tokens, 0)->getRateLimit();
        } catch (MaxWaitDurationExceededException $e) {
            return $e->getRateLimit();
        }
    }
}
        $rateLimit = $limiter->consume(4);

        $start = microtime(true);
        $rateLimit->wait(); // wait 12 seconds         $this->assertEqualsWithDelta($start + 12, microtime(true), 1);
    }

    public function testReserve()
    {
        $this->expectException(ReserveNotSupportedException::class);

        $this->createLimiter()->reserve();
    }

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

        $limiter->consume(9);

        for ($i = 0; $i < 2; ++$i) {
            $rateLimit = $limiter->consume(0);
            $this->assertTrue($rateLimit->isAccepted());
            
static::assertTrue($limit->isAccepted());
        }

        static::expectException(\InvalidArgumentException::class);
        static::expectExceptionMessage(sprintf('Cannot reserve more tokens (%d) than the size of the rate limiter (%d)', $consume$maxLimit));
        $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);

        


    /** * @param array<int, string> $args */
    public function generate(array $config, ?array $args = null, ?bool $preview = false): string
    {
        if ($preview === true) {
            return (string) $this->incrementConnector->preview($config);
        }

        return (string) $this->incrementConnector->reserve($config);
    }

    public function getDecorated(): AbstractValueGenerator
    {
        throw new DecorationPatternException(self::class);
    }
}
        $this->assertTrue($limiter->consume(3)->isAccepted());

        $this->assertEquals(0, $limiter->consume()->getRemainingTokens(), 'Limiter 3 reached the limit');
        sleep(20); // reset limiter3's window         $this->assertTrue($limiter->consume()->isAccepted());
    }

    public function testReserve()
    {
        $this->expectException(ReserveNotSupportedException::class);

        (new CompoundLimiter([$this->createLimiter(4, new \DateInterval('PT1S'))]))->reserve();
    }

    private function createLimiter(int $limit, \DateInterval $interval): FixedWindowLimiter
    {
        return new FixedWindowLimiter('test'.$limit$limit$interval$this->storage);
    }
}
public function testReserveReturnsIncrementIfStartOfPatternIsLowerThenTheIncrement(): void
    {
        $config = [
            'id' => Uuid::randomHex(),
            'start' => 5,
            'pattern' => 'n',
        ];

        $this->storage->set($config['id'], 10);

        static::assertEquals(11, $this->storage->reserve($config));
        static::assertEquals(12, $this->storage->reserve($config));
    }

    public function testReserveReturnsWithoutStart(): void
    {
        $config = [
            'id' => Uuid::randomHex(),
            'start' => null,
            'pattern' => 'n',
        ];

        

        } finally {
            $this->lock?->release();
        }

        return $reservation;
    }

    public function consume(int $tokens = 1): RateLimit
    {
        try {
            return $this->reserve($tokens, 0)->getRateLimit();
        } catch (MaxWaitDurationExceededException $e) {
            return $e->getRateLimit();
        }
    }

    public function getAvailableTokens(int $hitCount): int
    {
        return $this->limit - $hitCount;
    }
}
'pattern' => 'n',
        ];

        $this->lockFactoryMock->expects(static::never())
            ->method('createLock');

        $this->redisMock->expects(static::once())
            ->method('incr')
            ->with($this->getKey($config['id']))
            ->willReturn(10);

        static::assertEquals(10, $this->storage->reserve($config));
    }

    public function testReserveWithoutStart(): void
    {
        $config = [
            'id' => Uuid::randomHex(),
            'start' => null,
            'pattern' => 'n',
        ];

        $this->lockFactoryMock->expects(static::never())
            
ClockMock::register(TokenBucketLimiter::class);
        ClockMock::register(InMemoryStorage::class);
        ClockMock::register(TokenBucket::class);
        ClockMock::register(RateLimit::class);
    }

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

        $this->assertEquals(0, $limiter->reserve(5)->getWaitDuration());
        $this->assertEquals(0, $limiter->reserve(5)->getWaitDuration());
        $this->assertEquals(1, $limiter->reserve(5)->getWaitDuration());
    }

    public function testReserveMoreTokensThanBucketSize()
    {
        $this->expectException(\LogicException::class);
        $this->expectExceptionMessage('Cannot reserve more tokens (15) than the burst size of the rate limiter (10).');

        $limiter = $this->createLimiter();
        $limiter->reserve(15);
    }
class NoLimiterTest extends TestCase
{
    public function testConsume()
    {
        $limiter = new NoLimiter();
        $this->assertInstanceOf(RateLimit::class$limiter->consume());
    }

    public function testReserve()
    {
        $limiter = new NoLimiter();
        $this->assertInstanceOf(Reservation::class$limiter->reserve());
    }
}
Home | Imprint | This part of the site doesn't use cookies.