From ea820ea7cca7768942d2040c2a10e8ec9deec514 Mon Sep 17 00:00:00 2001 From: rflavien Date: Fri, 13 Mar 2026 12:52:27 +0100 Subject: [PATCH 1/4] Add Retry-After header during brownout windows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refactor BrownoutChecker to expose getBrownoutWindowEnd() returning the window end time, and use it in DeprecationHeaderListener to include a Retry-After header (RFC 7231 §7.1.3) in 410 responses during brownouts. This lets clients know when to retry after a brownout window closes. Co-Authored-By: Claude Opus 4.6 --- src/Brownout/BrownoutChecker.php | 13 +++- .../DeprecationHeaderListener.php | 19 ++++-- tests/Brownout/BrownoutCheckerTest.php | 54 ++++++++++++++++ .../DeprecationHeaderListenerTest.php | 62 +++++++++++++++++++ 4 files changed, 140 insertions(+), 8 deletions(-) diff --git a/src/Brownout/BrownoutChecker.php b/src/Brownout/BrownoutChecker.php index c6787e5..79c33f9 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,7 +33,7 @@ public function isInBrownoutWindow(string $strategyName, \DateTimeImmutable $sun $activePhase = $this->resolveActivePhase($strategy, $sunsetDate); if ($activePhase === null) { - return false; + return null; } $now = $this->now(); @@ -42,7 +47,11 @@ public function isInBrownoutWindow(string $strategyName, \DateTimeImmutable $sun $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..64acad2 100644 --- a/src/EventListener/DeprecationHeaderListener.php +++ b/src/EventListener/DeprecationHeaderListener.php @@ -71,13 +71,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() - (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->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, + ); + } } } diff --git a/tests/Brownout/BrownoutCheckerTest.php b/tests/Brownout/BrownoutCheckerTest.php index f9f1ee4..4063daa 100644 --- a/tests/Brownout/BrownoutCheckerTest.php +++ b/tests/Brownout/BrownoutCheckerTest.php @@ -183,6 +183,60 @@ 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 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..703eec1 100644 --- a/tests/EventListener/DeprecationHeaderListenerTest.php +++ b/tests/EventListener/DeprecationHeaderListenerTest.php @@ -406,11 +406,73 @@ public function __invoke(): void {} $listener->onKernelController($event); } + public function testBrownoutIncludesRetryAfterHeader(): void + { + $checker = $this->createMock(BrownoutChecker::class); + $checker->method('getBrownoutWindowEnd') + ->willReturn(new \DateTimeImmutable('+5 minutes', new \DateTimeZone('UTC'))); + + $listener = new DeprecationHeaderListener($this->headerBuilder, $checker, false); + + $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); + $retryAfter = (int) $headers['Retry-After']; + // Should be approximately 300 seconds (5 minutes), allow some tolerance + self::assertGreaterThan(250, $retryAfter); + self::assertLessThanOrEqual(300, $retryAfter); + } + } + + public function testBrownoutRetryAfterIsZeroWhenWindowEndsPast(): void + { + $checker = $this->createMock(BrownoutChecker::class); + $checker->method('getBrownoutWindowEnd') + ->willReturn(new \DateTimeImmutable('-1 second', new \DateTimeZone('UTC'))); + + $listener = new DeprecationHeaderListener($this->headerBuilder, $checker, false); + + $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('+10 minutes', new \DateTimeZone('UTC'))); + } else { + $checker->method('getBrownoutWindowEnd')->willReturn(null); + } + return $checker; } } From 8312861f51cdcded125290f94297b95d4d3373b6 Mon Sep 17 00:00:00 2001 From: rflavien Date: Fri, 13 Mar 2026 14:32:26 +0100 Subject: [PATCH 2/4] review --- src/ApiDeprecationBundle.php | 1 + src/Brownout/BrownoutChecker.php | 6 +--- .../DeprecationHeaderListener.php | 15 ++++++-- tests/Brownout/BrownoutCheckerTest.php | 15 ++++++++ .../DeprecationHeaderListenerTest.php | 35 ++++++++++++++----- 5 files changed, 56 insertions(+), 16 deletions(-) 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 79c33f9..d1fe5fc 100644 --- a/src/Brownout/BrownoutChecker.php +++ b/src/Brownout/BrownoutChecker.php @@ -39,11 +39,7 @@ public function getBrownoutWindowEnd(string $strategyName, \DateTimeImmutable $s $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)); diff --git a/src/EventListener/DeprecationHeaderListener.php b/src/EventListener/DeprecationHeaderListener.php index 64acad2..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 @@ -75,7 +77,7 @@ public function onKernelController(ControllerEvent $event): void $windowEnd = $this->brownoutChecker->getBrownoutWindowEnd($attribute->brownout, $attribute->parsedSunset); if ($windowEnd !== null) { - $retryAfter = $windowEnd->getTimestamp() - (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->getTimestamp(); + $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]); @@ -148,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 4063daa..e0afef0 100644 --- a/tests/Brownout/BrownoutCheckerTest.php +++ b/tests/Brownout/BrownoutCheckerTest.php @@ -219,6 +219,21 @@ public function testGetBrownoutWindowEndReturnsCorrectTime(): void 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(); diff --git a/tests/EventListener/DeprecationHeaderListenerTest.php b/tests/EventListener/DeprecationHeaderListenerTest.php index 703eec1..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; @@ -410,9 +411,10 @@ public function testBrownoutIncludesRetryAfterHeader(): void { $checker = $this->createMock(BrownoutChecker::class); $checker->method('getBrownoutWindowEnd') - ->willReturn(new \DateTimeImmutable('+5 minutes', new \DateTimeZone('UTC'))); + ->willReturn(new \DateTimeImmutable('2024-12-20 10:05:00', new \DateTimeZone('UTC'))); - $listener = new DeprecationHeaderListener($this->headerBuilder, $checker, false); + $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 {} @@ -428,10 +430,7 @@ public function __invoke(): void {} } catch (GoneHttpException $e) { $headers = $e->getHeaders(); self::assertArrayHasKey('Retry-After', $headers); - $retryAfter = (int) $headers['Retry-After']; - // Should be approximately 300 seconds (5 minutes), allow some tolerance - self::assertGreaterThan(250, $retryAfter); - self::assertLessThanOrEqual(300, $retryAfter); + self::assertSame('300', $headers['Retry-After']); } } @@ -439,9 +438,10 @@ public function testBrownoutRetryAfterIsZeroWhenWindowEndsPast(): void { $checker = $this->createMock(BrownoutChecker::class); $checker->method('getBrownoutWindowEnd') - ->willReturn(new \DateTimeImmutable('-1 second', new \DateTimeZone('UTC'))); + ->willReturn(new \DateTimeImmutable('2024-12-20 09:59:59', new \DateTimeZone('UTC'))); - $listener = new DeprecationHeaderListener($this->headerBuilder, $checker, false); + $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 {} @@ -468,13 +468,30 @@ private function createBrownoutChecker(bool $inWindow): BrownoutChecker&\PHPUnit if ($inWindow) { $checker->method('getBrownoutWindowEnd') - ->willReturn(new \DateTimeImmutable('+10 minutes', new \DateTimeZone('UTC'))); + ->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 From 36052106ff2bacb02c13c99ecfa4e44b173ced3d Mon Sep 17 00:00:00 2001 From: rflavien Date: Fri, 13 Mar 2026 14:38:22 +0100 Subject: [PATCH 3/4] update readme --- README.md | 2 ++ 1 file changed, 2 insertions(+) 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" From eff1eaca616b3af1a30b081fa802fd70f7be4a31 Mon Sep 17 00:00:00 2001 From: rflavien Date: Fri, 13 Mar 2026 14:41:43 +0100 Subject: [PATCH 4/4] add psr --- composer.json | 1 + 1 file changed, 1 insertion(+) 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" },