8000 bug #58601 [RateLimiter] Fix bucket size reduced when previously crea… · symfony/symfony@c15a195 · GitHub
[go: up one dir, main page]

Skip to content

Commit c15a195

Browse files
committed
bug #58601 [RateLimiter] Fix bucket size reduced when previously created with bigger size (Orkin)
This PR was merged into the 6.4 branch. Discussion ---------- [RateLimiter] Fix bucket size reduced when previously created with bigger size | Q | A | ------------- | --- | Branch? | 6.4 | Bug fix? | yes | New feature? | no | Deprecations? | no | Issues | Fix # | License | MIT ```yaml foo: policy: 'token_bucket' limit: 1000 rate: { interval: '15 minutes', amount: 5 } cache_pool: rate_limiter.cache_pool lock_factory: 'lock.rate_limiter.factory' ``` `rate_limiter.cache_pool` => it's a persistent cache pool like redis When using previously this configuration and consume the token bucket with 1 token it was save on the storage with 999 tokens available. If you update the configuration with a lower token limit ```yaml foo: policy: 'token_bucket' limit: 10 rate: { interval: '15 minutes', amount: 5 } cache_pool: rate_limiter.cache_pool lock_factory: 'lock.rate_limiter.factory' ``` You can consume 999 tokens before triggering the bucket limit without flushing the cache. The purpose of this PR is to update and use the new configuration limit. Commits ------- 6c34c58 Fix bucket size reduce when previously created with bigger size
2 parents d9cecb7 + 6c34c58 commit c15a195

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

src/Symfony/Component/RateLimiter/Policy/TokenBucketLimiter.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,10 @@ public function reserve(int $tokens = 1, ?float $maxTime = null): Reservation
6767
$now = microtime(true);
6868
$availableTokens = $bucket->getAvailableTokens($now);
6969

70+
if ($availableTokens > $this->maxBurst) {
71+
$availableTokens = $this->maxBurst;
72+
}
73+
7074
if ($availableTokens >= $tokens) {
7175
// tokens are now available, update bucket
7276
$bucket->setTokens($availableTokens - $tokens);

src/Symfony/Component/RateLimiter/Tests/Policy/TokenBucketLimiterTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,18 @@ public function testReserveMoreTokensThanBucketSize()
5656
$limiter->reserve(15);
5757
}
5858

59+
public function testReduceBucketSizeWhenAlreadyExistInStorageWithBiggerBucketSize()
60+
{
61+
$limiter = $this->createLimiter(100);
62+
63+
$limiter->consume();
64+
65+
$limiter2 = $this->createLimiter(1);
66+
$limiter2->consume();
67+
68+
$this->assertFalse($limiter2->consume()->isAccepted());
69+
}
70+
5971
public function testReserveMaxWaitingTime()
6072
{
6173
$this->expectException(MaxWaitDurationExceededException::class);

0 commit comments

Comments
 (0)
0