diff --git a/README.md b/README.md index 292ad8b..876da0a 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ Symfony bundle for managing API endpoint deprecation via standard HTTP headers, | `Deprecation` | [RFC 9745](https://www.rfc-editor.org/rfc/rfc9745.html) | Indicates when the endpoint was deprecated | | `Sunset` | [RFC 8594](https://www.rfc-editor.org/rfc/rfc8594.html) | Indicates when the endpoint will be removed | | `Link` | [RFC 9745 §3](https://www.rfc-editor.org/rfc/rfc9745.html#section-3) | Points to deprecation documentation (`rel="deprecation"`) | +| `Retry-After` | [RFC 7231 §7.1.3](https://www.rfc-editor.org/rfc/rfc7231#section-7.1.3) | Seconds until brownout window ends (brownout 410 responses only) | ## Installation @@ -147,6 +148,7 @@ During the brownout window, the response is: ``` HTTP/1.1 410 Gone +Retry-After: 540 Deprecation: @1717200000 Sunset: Wed, 01 Jan 2025 00:00:00 GMT Link: ; rel="deprecation"; type="text/html" diff --git a/composer.json b/composer.json index 057b25d..ecaf9db 100644 --- a/composer.json +++ b/composer.json @@ -18,6 +18,7 @@ "phpstan/phpstan": "^2.1", "phpstan/phpstan-symfony": "^2.0", "phpunit/phpunit": "^10.0|^11.0", + "psr/clock": "^1.0", "symfony/clock": "^6.4|^7.0|^8.0", "symfony/framework-bundle": "^6.4|^7.0|^8.0" }, diff --git a/src/ApiDeprecationBundle.php b/src/ApiDeprecationBundle.php index 11dd023..fe143a6 100644 --- a/src/ApiDeprecationBundle.php +++ b/src/ApiDeprecationBundle.php @@ -73,6 +73,7 @@ public function loadExtension(array $config, ContainerConfigurator $container, C service('api_deprecation.brownout_checker'), $config['response_on_sunset'], $builder->has('logger') ? service('logger') : null, + $builder->has('clock') ? service('clock') : null, ]) ->tag('kernel.event_subscriber') ; diff --git a/src/Brownout/BrownoutChecker.php b/src/Brownout/BrownoutChecker.php index c6787e5..d1fe5fc 100644 --- a/src/Brownout/BrownoutChecker.php +++ b/src/Brownout/BrownoutChecker.php @@ -19,6 +19,11 @@ public function __construct( } public function isInBrownoutWindow(string $strategyName, \DateTimeImmutable $sunsetDate): bool + { + return $this->getBrownoutWindowEnd($strategyName, $sunsetDate) !== null; + } + + public function getBrownoutWindowEnd(string $strategyName, \DateTimeImmutable $sunsetDate): ?\DateTimeImmutable { if (!isset($this->namedStrategies[$strategyName])) { throw new \InvalidArgumentException(\sprintf('Unknown brownout strategy "%s".', $strategyName)); @@ -28,21 +33,21 @@ public function isInBrownoutWindow(string $strategyName, \DateTimeImmutable $sun $activePhase = $this->resolveActivePhase($strategy, $sunsetDate); if ($activePhase === null) { - return false; + return null; } $now = $this->now(); $cron = new CronExpression($activePhase->cron); - if ($cron->isDue($now)) { - $previousRun = $now; - } else { - $previousRun = \DateTimeImmutable::createFromMutable($cron->getPreviousRunDate($now)); - } + $previousRun = \DateTimeImmutable::createFromMutable($cron->getPreviousRunDate($now, 0, true)); $windowEnd = $previousRun->modify(\sprintf('+%d minutes', $activePhase->durationMinutes)); - return $now >= $previousRun && $now < $windowEnd; + if ($now >= $previousRun && $now < $windowEnd) { + return $windowEnd; + } + + return null; } private function resolveActivePhase(Strategy $strategy, \DateTimeImmutable $sunsetDate): ?Phase diff --git a/src/EventListener/DeprecationHeaderListener.php b/src/EventListener/DeprecationHeaderListener.php index b678a13..b969905 100644 --- a/src/EventListener/DeprecationHeaderListener.php +++ b/src/EventListener/DeprecationHeaderListener.php @@ -9,6 +9,7 @@ use Symfony\Component\HttpKernel\Event\ResponseEvent; use Symfony\Component\HttpKernel\Exception\GoneHttpException; use Symfony\Component\HttpKernel\KernelEvents; +use Psr\Clock\ClockInterface; use Psr\Log\LoggerInterface; use Tiime\ApiDeprecationBundle\Attribute\ApiDeprecated; use Tiime\ApiDeprecationBundle\Attribute\ApiDeprecatedResolver; @@ -22,6 +23,7 @@ public function __construct( private readonly BrownoutChecker $brownoutChecker, private readonly bool $responseOnSunset, private readonly ?LoggerInterface $logger = null, + private readonly ?ClockInterface $clock = null, ) { } @@ -50,7 +52,7 @@ public function onKernelController(ControllerEvent $event): void $this->logger?->info('Deprecated API endpoint called.', ['since' => $attribute->since, 'sunset' => $attribute->sunset]); $headers = $this->buildHeaders($attribute); - $now = new \DateTimeImmutable('now', new \DateTimeZone('UTC')); + $now = $this->now(); $sunsetPassed = $attribute->parsedSunset !== null && $now >= $attribute->parsedSunset; // After sunset: permanent 410, brownouts no longer relevant @@ -71,13 +73,20 @@ public function onKernelController(ControllerEvent $event): void )); } - if ($attribute->brownout !== null && $attribute->parsedSunset !== null && !$sunsetPassed && $this->brownoutChecker->isInBrownoutWindow($attribute->brownout, $attribute->parsedSunset)) { - $this->logger?->warning('Brownout active, returning 410 Gone.', ['brownout' => $attribute->brownout, 'sunset' => $attribute->sunset]); + if ($attribute->brownout !== null && $attribute->parsedSunset !== null && !$sunsetPassed) { + $windowEnd = $this->brownoutChecker->getBrownoutWindowEnd($attribute->brownout, $attribute->parsedSunset); - throw new GoneHttpException( - 'This endpoint is deprecated and currently unavailable (brownout).', - headers: $headers, - ); + if ($windowEnd !== null) { + $retryAfter = $windowEnd->getTimestamp() - $now->getTimestamp(); + $headers['Retry-After'] = (string) max(0, $retryAfter); + + $this->logger?->warning('Brownout active, returning 410 Gone.', ['brownout' => $attribute->brownout, 'sunset' => $attribute->sunset]); + + throw new GoneHttpException( + 'This endpoint is deprecated and currently unavailable (brownout).', + headers: $headers, + ); + } } } @@ -141,4 +150,13 @@ private function buildHeaders(ApiDeprecated $attribute): array return $headers; } + + private function now(): \DateTimeImmutable + { + if ($this->clock !== null) { + return $this->clock->now(); + } + + return new \DateTimeImmutable('now', new \DateTimeZone('UTC')); + } } diff --git a/tests/Brownout/BrownoutCheckerTest.php b/tests/Brownout/BrownoutCheckerTest.php index f9f1ee4..e0afef0 100644 --- a/tests/Brownout/BrownoutCheckerTest.php +++ b/tests/Brownout/BrownoutCheckerTest.php @@ -183,6 +183,75 @@ public function testActivePhaseIsSmallestStartsBeforeStillActive(): void }); } + public function testGetBrownoutWindowEndReturnsDateTimeWhenInWindow(): void + { + // Phase 1: cron "0 10 * * 1" (Monday 10h), duration 15min. + // Clock: 2024-12-02 10:05 (Monday). Window: [10:00, 10:15). + $strategy = $this->createProgressiveStrategy(); + $checker = $this->createChecker(['progressive' => $strategy], '2024-12-02 10:05:00'); + + $windowEnd = $checker->getBrownoutWindowEnd('progressive', $this->sunsetDate()); + + self::assertNotNull($windowEnd); + self::assertInstanceOf(\DateTimeImmutable::class, $windowEnd); + } + + public function testGetBrownoutWindowEndReturnsNullWhenOutsideWindow(): void + { + // Phase 3 active but clock at 15:50 -> outside [15:00, 15:45). + $strategy = $this->createProgressiveStrategy(); + $checker = $this->createChecker(['progressive' => $strategy], '2024-12-26 15:50:00'); + + self::assertNull($checker->getBrownoutWindowEnd('progressive', $this->sunsetDate())); + } + + public function testGetBrownoutWindowEndReturnsCorrectTime(): void + { + $strategy = new Strategy([ + new Phase(\DateInterval::createFromDateString('30 days'), '0 * * * *', 15), + ]); + // Clock: 2024-12-10 10:05. Cron runs at 10:00, duration 15min -> window end = 10:15. + $checker = $this->createChecker(['test' => $strategy], '2024-12-10 10:05:00'); + + $windowEnd = $checker->getBrownoutWindowEnd('test', $this->sunsetDate()); + + self::assertNotNull($windowEnd); + self::assertSame('2024-12-10 10:15:00', $windowEnd->format('Y-m-d H:i:s')); + } + + public function testGetBrownoutWindowEndWithNonZeroSeconds(): void + { + $strategy = new Strategy([ + new Phase(\DateInterval::createFromDateString('30 days'), '0 * * * *', 15), + ]); + // Clock: 2024-12-10 10:00:30 — cron is due at minute granularity, seconds are non-zero. + // Window end should still be 10:15:00, not 10:15:30. + $checker = $this->createChecker(['test' => $strategy], '2024-12-10 10:00:30'); + + $windowEnd = $checker->getBrownoutWindowEnd('test', $this->sunsetDate()); + + self::assertNotNull($windowEnd); + self::assertSame('2024-12-10 10:15:00', $windowEnd->format('Y-m-d H:i:s')); + } + + public function testGetBrownoutWindowEndReturnsNullWhenTooEarly(): void + { + $strategy = $this->createProgressiveStrategy(); + $checker = $this->createChecker(['progressive' => $strategy], '2024-10-01 10:05:00'); + + self::assertNull($checker->getBrownoutWindowEnd('progressive', $this->sunsetDate())); + } + + public function testGetBrownoutWindowEndThrowsForUnknownStrategy(): void + { + $checker = $this->createChecker([], '2024-12-20 10:00:00'); + + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Unknown brownout strategy "nonexistent"'); + + $checker->getBrownoutWindowEnd('nonexistent', $this->sunsetDate()); + } + public function testPhaseActivationAtExactBoundary(): void { // Sunset = 2025-01-01, phase startsBefore = 30 days -> activation = 2024-12-02 00:00:00 diff --git a/tests/EventListener/DeprecationHeaderListenerTest.php b/tests/EventListener/DeprecationHeaderListenerTest.php index 48d6cd6..c5cbf38 100644 --- a/tests/EventListener/DeprecationHeaderListenerTest.php +++ b/tests/EventListener/DeprecationHeaderListenerTest.php @@ -5,6 +5,7 @@ namespace Tiime\ApiDeprecationBundle\Tests\EventListener; use PHPUnit\Framework\TestCase; +use Psr\Clock\ClockInterface; use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -406,13 +407,91 @@ public function __invoke(): void {} $listener->onKernelController($event); } + public function testBrownoutIncludesRetryAfterHeader(): void + { + $checker = $this->createMock(BrownoutChecker::class); + $checker->method('getBrownoutWindowEnd') + ->willReturn(new \DateTimeImmutable('2024-12-20 10:05:00', new \DateTimeZone('UTC'))); + + $clock = $this->createClock('2024-12-20 10:00:00'); + $listener = new DeprecationHeaderListener($this->headerBuilder, $checker, false, null, $clock); + + $controller = new #[ApiDeprecated(since: '2024-06-01', sunset: '2030-01-01', brownout: 'progressive')] class { + public function __invoke(): void {} + }; + + $request = new Request(); + $kernel = $this->createMock(HttpKernelInterface::class); + $event = new ControllerEvent($kernel, $controller, $request, HttpKernelInterface::MAIN_REQUEST); + + try { + $listener->onKernelController($event); + self::fail('Expected GoneHttpException'); + } catch (GoneHttpException $e) { + $headers = $e->getHeaders(); + self::assertArrayHasKey('Retry-After', $headers); + self::assertSame('300', $headers['Retry-After']); + } + } + + public function testBrownoutRetryAfterIsZeroWhenWindowEndsPast(): void + { + $checker = $this->createMock(BrownoutChecker::class); + $checker->method('getBrownoutWindowEnd') + ->willReturn(new \DateTimeImmutable('2024-12-20 09:59:59', new \DateTimeZone('UTC'))); + + $clock = $this->createClock('2024-12-20 10:00:00'); + $listener = new DeprecationHeaderListener($this->headerBuilder, $checker, false, null, $clock); + + $controller = new #[ApiDeprecated(since: '2024-06-01', sunset: '2030-01-01', brownout: 'progressive')] class { + public function __invoke(): void {} + }; + + $request = new Request(); + $kernel = $this->createMock(HttpKernelInterface::class); + $event = new ControllerEvent($kernel, $controller, $request, HttpKernelInterface::MAIN_REQUEST); + + try { + $listener->onKernelController($event); + self::fail('Expected GoneHttpException'); + } catch (GoneHttpException $e) { + $headers = $e->getHeaders(); + self::assertArrayHasKey('Retry-After', $headers); + self::assertSame('0', $headers['Retry-After']); + } + } + private function createBrownoutChecker(bool $inWindow): BrownoutChecker&\PHPUnit\Framework\MockObject\MockObject { $checker = $this->createMock(BrownoutChecker::class); $checker->method('isInBrownoutWindow')->willReturn($inWindow); + if ($inWindow) { + $checker->method('getBrownoutWindowEnd') + ->willReturn(new \DateTimeImmutable('2024-12-20 10:10:00', new \DateTimeZone('UTC'))); + } else { + $checker->method('getBrownoutWindowEnd')->willReturn(null); + } + return $checker; } + + private function createClock(string $datetime): ClockInterface + { + return new class($datetime) implements ClockInterface { + private \DateTimeImmutable $now; + + public function __construct(string $datetime) + { + $this->now = new \DateTimeImmutable($datetime, new \DateTimeZone('UTC')); + } + + public function now(): \DateTimeImmutable + { + return $this->now; + } + }; + } } class ArrayControllerFixture