Skip to content

[RateLimiter] fix incorrect retryAfter of FixedWindow #49070

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public function reserve(int $tokens = 1, float $maxTime = null): Reservation

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

if (null !== $maxTime && $waitDuration > $maxTime) {
// process needs to wait longer than set interval
Expand Down
6 changes: 2 additions & 4 deletions src/Symfony/Component/RateLimiter/Policy/Window.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,13 @@ public function getAvailableTokens(float $now)
return $this->maxSize - $this->hitCount;
}

public function calculateTimeForTokens(int $tokens): int
public function calculateTimeForTokens(int $tokens, float $now): int
{
if (($this->maxSize - $this->hitCount) >= $tokens) {
return 0;
}

$cyclesRequired = ceil($tokens / $this->maxSize);

return $cyclesRequired * $this->intervalInSeconds;
return (int) ceil($this->timer + $this->intervalInSeconds - $now);
}

public function __serialize(): array
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ protected function setUp(): void

public function testConsume()
{
$now = time();
$limiter = $this->createLimiter();

// fill 9 tokens in 45 seconds
Expand All @@ -51,6 +52,9 @@ public function testConsume()
$rateLimit = $limiter->consume();
$this->assertFalse($rateLimit->isAccepted());
$this->assertSame(10, $rateLimit->getLimit());
// Window ends after 1 minute
$retryAfter = \DateTimeImmutable::createFromFormat('U', $now + 60);
$this->assertEquals($retryAfter, $rateLimit->getRetryAfter());
}

/**
Expand Down