true], 200, ['X-Custom' => 'kept']); } private function limiter(int $limit = 3, int $window = 60): RateLimit { return new RateLimit(limit: $limit, windowSeconds: $window, clock: fn(): int => $this->now); } public function testAllowsUpToLimit(): void { $limiter = $this->limiter(3); for ($i = 1; $i <= 3; ++$i) { self::assertSame( 200, $limiter->process(new JsonRequest(), self::passThrough(...))->status(), ); } } public function testExceedingLimitIs429(): void { $limiter = $this->limiter(2); $limiter->process(new JsonRequest(), self::passThrough(...)); $limiter->process(new JsonRequest(), self::passThrough(...)); $response = $limiter->process(new JsonRequest(), self::passThrough(...)); self::assertSame(429, $response->status()); self::assertSame('too_many_requests', $response->body()['code']); self::assertSame('60', $response->headers()['Retry-After']); } public function testHeadersPresentOnSuccess(): void { $response = $this->limiter(10)->process(new JsonRequest(), self::passThrough(...)); self::assertSame('10', $response->headers()['X-RateLimit-Limit']); self::assertSame('9', $response->headers()['X-RateLimit-Remaining']); self::assertSame('1060', $response->headers()['X-RateLimit-Reset']); } public function testKeepsHandlerHeaders(): void { $response = $this->limiter(10)->process(new JsonRequest(), self::passThrough(...)); self::assertSame('kept', $response->headers()['X-Custom']); } public function testWindowResetsAfterExpiry(): void { $limiter = $this->limiter(1); self::assertSame( 200, $limiter->process(new JsonRequest(), self::passThrough(...))->status(), ); self::assertSame( 429, $limiter->process(new JsonRequest(), self::passThrough(...))->status(), ); $this->now += 61; self::assertSame( 200, $limiter->process(new JsonRequest(), self::passThrough(...))->status(), ); } public function testBucketsAreSeparatedByClientAddress(): void { $limiter = $this->limiter(1); $first = new JsonRequest()->withAttribute('client_ip', '10.0.0.1'); $second = new JsonRequest()->withAttribute('client_ip', '10.0.0.2'); self::assertSame(200, $limiter->process($first, self::passThrough(...))->status()); self::assertSame(200, $limiter->process($second, self::passThrough(...))->status()); self::assertSame(429, $limiter->process($first, self::passThrough(...))->status()); } public function testResetInReportsRemainingWindow(): void { $limiter = $this->limiter(1); $request = new JsonRequest(); self::assertSame(0, $limiter->resetIn($request)); $limiter->process($request, self::passThrough(...)); self::assertSame(60, $limiter->resetIn($request)); $this->now += 20; self::assertSame(40, $limiter->resetIn($request)); } }