Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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: <https://docs.example.com/api/v1/users-deprecation>; rel="deprecation"; type="text/html"
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down
1 change: 1 addition & 0 deletions src/ApiDeprecationBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -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')
;
Expand Down
19 changes: 12 additions & 7 deletions src/Brownout/BrownoutChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@
}

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));
Expand All @@ -28,21 +33,21 @@
$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));

Check warning on line 42 in src/Brownout/BrownoutChecker.php

View workflow job for this annotation

GitHub Actions / Mutation Testing

Escaped Mutant for Mutator "DecrementInteger": @@ @@ $now = $this->now(); $cron = new CronExpression($activePhase->cron); - $previousRun = \DateTimeImmutable::createFromMutable($cron->getPreviousRunDate($now, 0, true)); + $previousRun = \DateTimeImmutable::createFromMutable($cron->getPreviousRunDate($now, -1, true)); $windowEnd = $previousRun->modify(\sprintf('+%d minutes', $activePhase->durationMinutes));

$windowEnd = $previousRun->modify(\sprintf('+%d minutes', $activePhase->durationMinutes));

return $now >= $previousRun && $now < $windowEnd;
if ($now >= $previousRun && $now < $windowEnd) {
return $windowEnd;
}
Comment thread
rflavien marked this conversation as resolved.
Resolved

return null;
}

private function resolveActivePhase(Strategy $strategy, \DateTimeImmutable $sunsetDate): ?Phase
Expand Down
32 changes: 25 additions & 7 deletions src/EventListener/DeprecationHeaderListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Comment thread
rflavien marked this conversation as resolved.
Resolved
use Tiime\ApiDeprecationBundle\Attribute\ApiDeprecated;
use Tiime\ApiDeprecationBundle\Attribute\ApiDeprecatedResolver;
Expand All @@ -22,6 +23,7 @@
private readonly BrownoutChecker $brownoutChecker,
private readonly bool $responseOnSunset,
private readonly ?LoggerInterface $logger = null,
private readonly ?ClockInterface $clock = null,
) {
}

Expand Down Expand Up @@ -50,8 +52,8 @@
$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;

Check warning on line 56 in src/EventListener/DeprecationHeaderListener.php

View workflow job for this annotation

GitHub Actions / Mutation Testing

Escaped Mutant for Mutator "GreaterThanOrEqualTo": @@ @@ $headers = $this->buildHeaders($attribute); $now = $this->now(); - $sunsetPassed = $attribute->parsedSunset !== null && $now >= $attribute->parsedSunset; + $sunsetPassed = $attribute->parsedSunset !== null && $now > $attribute->parsedSunset; // After sunset: permanent 410, brownouts no longer relevant if ($this->responseOnSunset && $sunsetPassed) {

// After sunset: permanent 410, brownouts no longer relevant
if ($this->responseOnSunset && $sunsetPassed) {
Expand All @@ -71,13 +73,20 @@
));
}

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,
);
}
}
}

Expand Down Expand Up @@ -109,9 +118,9 @@
{
$controller = $event->getController();

if (\is_array($controller) && isset($controller[0], $controller[1]) && \is_object($controller[0]) && \is_string($controller[1])) {

Check warning on line 121 in src/EventListener/DeprecationHeaderListener.php

View workflow job for this annotation

GitHub Actions / Mutation Testing

Escaped Mutant for Mutator "DecrementInteger": @@ @@ { $controller = $event->getController(); - if (\is_array($controller) && isset($controller[0], $controller[1]) && \is_object($controller[0]) && \is_string($controller[1])) { + if (\is_array($controller) && isset($controller[0], $controller[0]) && \is_object($controller[0]) && \is_string($controller[1])) { $reflection = new \ReflectionMethod($controller[0], $controller[1]); } elseif (\is_object($controller) && method_exists($controller, '__invoke')) { $reflection = new \ReflectionMethod($controller, '__invoke');

Check warning on line 121 in src/EventListener/DeprecationHeaderListener.php

View workflow job for this annotation

GitHub Actions / Mutation Testing

Escaped Mutant for Mutator "IncrementInteger": @@ @@ { $controller = $event->getController(); - if (\is_array($controller) && isset($controller[0], $controller[1]) && \is_object($controller[0]) && \is_string($controller[1])) { + if (\is_array($controller) && isset($controller[1], $controller[1]) && \is_object($controller[0]) && \is_string($controller[1])) { $reflection = new \ReflectionMethod($controller[0], $controller[1]); } elseif (\is_object($controller) && method_exists($controller, '__invoke')) { $reflection = new \ReflectionMethod($controller, '__invoke');
$reflection = new \ReflectionMethod($controller[0], $controller[1]);
} elseif (\is_object($controller) && method_exists($controller, '__invoke')) {

Check warning on line 123 in src/EventListener/DeprecationHeaderListener.php

View workflow job for this annotation

GitHub Actions / Mutation Testing

Escaped Mutant for Mutator "LogicalAnd": @@ @@ if (\is_array($controller) && isset($controller[0], $controller[1]) && \is_object($controller[0]) && \is_string($controller[1])) { $reflection = new \ReflectionMethod($controller[0], $controller[1]); - } elseif (\is_object($controller) && method_exists($controller, '__invoke')) { + } elseif (\is_object($controller) || method_exists($controller, '__invoke')) { $reflection = new \ReflectionMethod($controller, '__invoke'); } else { return null;
$reflection = new \ReflectionMethod($controller, '__invoke');
} else {
return null;
Expand Down Expand Up @@ -141,4 +150,13 @@

return $headers;
}

private function now(): \DateTimeImmutable
{
if ($this->clock !== null) {
return $this->clock->now();
}

return new \DateTimeImmutable('now', new \DateTimeZone('UTC'));
}
}
69 changes: 69 additions & 0 deletions tests/Brownout/BrownoutCheckerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'));
}

Comment thread
rflavien marked this conversation as resolved.
Resolved
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
Expand Down
79 changes: 79 additions & 0 deletions tests/EventListener/DeprecationHeaderListenerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
Loading