Skip to content

Commit 65e8614

Browse files
committed
Make RateLimiter resilient to timeShifting
1 parent e9a7026 commit 65e8614

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

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

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,6 @@ public function getHitCount(): int
6868

6969
public function getAvailableTokens(float $now)
7070
{
71-
// if timer is in future, there are no tokens available anymore
72-
if ($this->timer > $now) {
73-
return 0;
74-
}
75-
7671
// if now is more than the window interval in the past, all tokens are available
7772
if (($now - $this->timer) > $this->intervalInSeconds) {
7873
return $this->maxSize;

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use PHPUnit\Framework\TestCase;
1515
use Symfony\Bridge\PhpUnit\ClockMock;
1616
use Symfony\Component\RateLimiter\Policy\FixedWindowLimiter;
17+
use Symfony\Component\RateLimiter\Policy\Window;
1718
use Symfony\Component\RateLimiter\RateLimit;
1819
use Symfony\Component\RateLimiter\Storage\InMemoryStorage;
1920
use Symfony\Component\RateLimiter\Tests\Resources\DummyWindow;
@@ -90,6 +91,19 @@ public function testWrongWindowFromCache()
9091
$this->assertEquals(9, $rateLimit->getRemainingTokens());
9192
}
9293

94+
public function testWindowResilientToTimeShifting()
95+
{
96+
$serverOneClock = microtime(true) - 1;
97+
$serverTwoClock = microtime(true) + 1;
98+
$window = new Window('id', 300, 100, $serverTwoClock);
99+
$this->assertSame(100, $window->getAvailableTokens($serverTwoClock));
100+
$this->assertSame(100, $window->getAvailableTokens($serverOneClock));
101+
102+
$window = new Window('id', 300, 100, $serverOneClock);
103+
$this->assertSame(100, $window->getAvailableTokens($serverTwoClock));
104+
$this->assertSame(100, $window->getAvailableTokens($serverOneClock));
105+
}
106+
93107
private function createLimiter(): FixedWindowLimiter
94108
{
95109
return new FixedWindowLimiter('test', 10, new \DateInterval('PT1M'), $this->storage);

0 commit comments

Comments
 (0)