Skip to content

Commit 9738b1d

Browse files
committed
bug symfony#44941 [RateLimiter] Resolve crash on near-round timestamps (xesxen)
This PR was merged into the 5.4 branch. Discussion ---------- [RateLimiter] Resolve crash on near-round timestamps | Q | A | ------------- | --- | Branch? | 5.4 | Bug fix? | yes | New feature? | no | Deprecations? | no | Tickets | - | License | MIT | Doc PR | - Occasionally timestamps will be fully round (eg. 1234567890.000000) or close to it (eg. 1234567890.000031). When converting those specific float timestamps to string in SlidingWindow (due to `DateTimeImmutable::createFromFormat`), the number is formatted by PHP without any digits. This causes the resulting value of SlidingWindow::getRetryAfter() to be violated with the boolean value `false`. This patch formats the float to include the decimal digits. ``` Return value of Symfony\Component\RateLimiter\Policy\SlidingWindow::getRetryAfter() must be an instance of DateTimeImmutable, bool returned #0 .../vendor/symfony/rate-limiter/Policy/SlidingWindowLimiter.php(84): Symfony\Component\RateLimiter\Policy\SlidingWindow->getRetryAfter() #1 .../usercode.php(123): Symfony\Component\RateLimiter\Policy\SlidingWindowLimiter->consume(1) ``` Commits ------- 4965952 [RateLimiter] Resolve crash on near-round timestamps
2 parents 9ab920d + 4965952 commit 9738b1d

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,6 @@ public function getHitCount(): int
122122

123123
public function getRetryAfter(): \DateTimeImmutable
124124
{
125-
return \DateTimeImmutable::createFromFormat('U.u', $this->windowEndAt);
125+
return \DateTimeImmutable::createFromFormat('U.u', sprintf('%.6F', $this->windowEndAt));
126126
}
127127
}

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,4 +102,13 @@ public function testGetRetryAfterUsesMicrotime()
102102
// should be 500ms left (10 - 9.5)
103103
$this->assertEqualsWithDelta(0.5, $window->getRetryAfter()->format('U.u') - microtime(true), 0.2);
104104
}
105+
106+
public function testCreateAtExactTime()
107+
{
108+
ClockMock::register(SlidingWindow::class);
109+
ClockMock::withClockMock(1234567890.000000);
110+
$window = new SlidingWindow('foo', 10);
111+
$window->getRetryAfter();
112+
$this->assertEquals('1234567900.000000', $window->getRetryAfter()->format('U.u'));
113+
}
105114
}

0 commit comments

Comments
 (0)