From d42da0c2a21ada942fd9e6c1119afc3b3c4ecd72 Mon Sep 17 00:00:00 2001 From: silverbackdan Date: Thu, 26 Nov 2026 16:13:50 +0000 Subject: [PATCH 1/2] Purge through the purger API Platform's BufferedPurger decorates API Platform dev-main (api-platform/core#8869) buffers purges during a main request and flushes them on kernel.response, where a failure is a 500 the bundle cannot catch. Give HttpCachePurger and HttpCacheFlusher the buffer's inner purger so #311 holds: a failed purge after a write is logged, and an explicit purge is a 502. --- CHANGELOG.md | 1 + CLAUDE.md | 2 +- .../CompilerPass/ApiPlatformCompilerPass.php | 28 +++++- .../ApiPlatformCompilerPassTest.php | 93 ++++++++++++++++++- 4 files changed, 118 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bff4b074..fd4ee206 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ Every change that reaches `main` adds a line under **Unreleased**. When a versio ## Unreleased ### Fixed +- On API Platform versions that buffer HTTP cache purges until the response (`BufferedPurger`, api-platform/core#8869), the bundle purges through the unbuffered purger, so a failed purge after a write is still logged rather than a 500 and an explicit purge is still a 502 ([#PR](https://github.com/components-web-app/api-components-bundle/pull/PR)) - A page data class's to-many associations, and associations to a class that is not an API resource, are no longer page data properties, so writing an entity such an association holds no longer 500s ("SingleValuedAssociationField expected" on flush) and the page data metadata no longer lists them ([#617](https://github.com/components-web-app/api-components-bundle/pull/617)) ## [2.0.0-alpha.47](https://github.com/components-web-app/api-components-bundle/compare/2.0.0-alpha.46...2.0.0-alpha.47) - 2026-11-25 diff --git a/CLAUDE.md b/CLAUDE.md index 0ee832f4..e73c0bea 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -240,7 +240,7 @@ Resources are fetched and cached **individually**. Never embed related data outs - **Scoped purge endpoint (#484):** `POST /_/http_cache/purge` flushes only when the request has **no body at all** (empty content). Any body is a scoped purge or a 422, never a flush: `{}`, `null`, `[]`, malformed JSON, an unknown key, an empty or non-list `paths`/`tags`, or a bad item are violations on `paths`/`tags`/`paths[i]`/`tags[i]` (the root for a body that is not an object or names neither key). `paths` and `tags` may both be sent; the union is purged once. `ScopedPurgeRequest` is the one parser and applies the command's rules: a path starts with `/` and resolves through `getRouteTag()` only (no expansion), a tag (given or resolved) with whitespace or a comma is refused. The operation keeps `input: false` and reads `$context['request']`'s content itself, because a deserialized body could not tell no body from `{}` nor make malformed JSON a 422. Scoped with no purger is 501, unlike the command's exit 0, because the endpoint's flush is 501 when unsupported. - **Warm after a full flush (#484):** `http_cache.warm_after_flush` (off by default) makes `HttpCacheFlusher::flush()`, after every invalidation URL succeeded, call `HttpCacheWarmDispatcher`, which dispatches one `WarmHttpCacheMessage` per encoding (`gzip` for SSR, `br` for browsers and the CDN) on `messenger.default_bus`; `WarmHttpCacheHandler` runs `HttpCacheWarmer` over `PublicRoutePaths` (shortest first) with the configured `base_url`, `max_time` (per encoding), `concurrency`, `timeout` and `limit`. So the endpoint, `purge-http-cache` with no options and the fixture load flush all warm, and a scoped purge never does. **Never run the warm without a bus or in the flusher itself:** with no bus it logs a warning and warms nothing (unlike the orphan scan, which runs its handler inline), because a warm inside a php worker request holds the worker for up to `2 × (max_time + timeout)`. A site that enables it routes the message to an async transport; a synchronous route still runs it inline, which is the site's choice. A failed dispatch (Messenger's `ExceptionInterface` only) is logged at error and never fails the flush or the other encoding. It changes no response. - **Cache warm (#442):** `silverback:api-components:warm-http-cache` (`HttpCache\Warm\HttpCacheWarmer`) requests through the cache what SSR requests: the route, then its manifest, then every manifest IRI, a redirect only its route. **A warm request is useful only under the exact key SSR uses, and a wrong key still returns 200**, so the headers are pinned request by request in `HttpCacheWarmerTest`. The key is the template's Souin `key` template plus the response's `Vary`: `Accept` (`/_api` only), the host (any dotless or `.local` host maps to `BROWSER_SERVER_NAME`), the normalised `Accept-Encoding` (Node 26's fetch sends `gzip, deflate`, so `gzip`), `path` (`Vary: path` on a page data position) and `preload`: Vulcain runs inside the cache and adds `Vary: Preload` whenever it answers with `Link` headers, which over SSR's plain HTTP is always. **`ModuleRequestHeaders` is a cross-repo contract** with the module's `cwa-fetch.ts` (`Accept`), `preload-headers.ts` and `manifestDepthPath()`/`createRequestHeaders()` (`path`: the route path at the IRI's deepest manifest depth, else that depth's page data IRI, else the route path); change both together. Routes come from `PublicRoutePaths`, which applies `RouteExtension` as an anonymous caller would see `GET /_/routes`, shortest first. Requests are anonymous. Follow-ups jump the queue of routes so each route is warmed whole before a `--max-time` stops it. **At `--max-time` it starts no new request and never cancels one in flight**: each finishes, bounded by `--timeout`, and counts as completed or failed by its real outcome, because a cancelled request is logged by Caddy as a 500. So a warm can run up to `max_time + timeout`, and it is reported as stopped only when something was left unstarted. `WarmHttpCacheHandler` runs the same warmer. After the command starts, nothing fails it: invalid options exit 2, and everything else exits 0. **A warm that cannot decode what it asks for never runs** (#488): `HttpCacheWarmer::canDecode()` is false when the `Accept-Encoding` lists `br` and `brotli_uncompress` is not callable (the function name is a constructor argument, so tests pass `base64_decode` or a missing name, never the machine's extension), and then the command refuses with exit 2 and `WarmHttpCacheHandler` logs at error and requests nothing; the check is in the handler, not the dispatcher, because the handler's process is the one that decodes. **A route or manifest body it cannot decode counts as failed, with the reason as the request's error**, so a skipped follow-up never reads as a normal request in the summary. **Spreading a warm across pods is `--requests-per-connection=N` (`warm_after_flush.requests_per_connection`), off by default** (#553): a Kubernetes Service balances per TCP connection and the client keeps connections alive, so every Nth request started carries `Connection: close`, the only header it may add (hop-by-hop, never part of a cache key), and 1 closes every connection. It is a request header, not a client reset or a curl option: `reset()` closes no connection on any Symfony client, it works on every HTTP/1.1 client, and curl closes the connection itself even when the server ignores it. Over HTTP/2 it does nothing, so it is for a plain-HTTP Service URL. `HttpCacheWarmerConnectionTest` counts real connections on curl against `tests/HttpCache/Warm/assets/keep-alive-server.php`, a keep-alive server the test starts (`php -S` closes every connection, so it cannot tell). `KernelHttpClient` sends a functional test's warm into its kernel. -- **Purge failures (#311):** after a write, a failed purge is logged at error and swallowed, and later propagators (Mercure) still run. `reset()` runs in a `finally`. An explicit purge fails loudly: exit 1, or 502. Catch only HttpClient's `ExceptionInterface` and AP's `RuntimeException` (tag too long), never `\Throwable`. On API Platform 5.0.7+ a failure is a `PurgeFailedException`, which is both, thrown after every chunk × invalidation URL was attempted; its message is only "N of M HTTP cache purge requests failed." with the first failure as `previous`, so a test asserts the cause on the exception chain, never on the message or the exception's class. Before that, `SurrogateKeysPurger` throws the first failure inside `purge()` itself, because the discarded response's destructor runs there. +- **Purge failures (#311):** after a write, a failed purge is logged at error and swallowed, and later propagators (Mercure) still run. `reset()` runs in a `finally`. An explicit purge fails loudly: exit 1, or 502. Catch only HttpClient's `ExceptionInterface` and AP's `RuntimeException` (tag too long), never `\Throwable`. On API Platform 5.0.7+ a failure is a `PurgeFailedException`, which is both, thrown after every chunk × invalidation URL was attempted; its message is only "N of M HTTP cache purge requests failed." with the first failure as `previous`, so a test asserts the cause on the exception chain, never on the message or the exception's class. Before that, `SurrogateKeysPurger` throws the first failure inside `purge()` itself, because the discarded response's destructor runs there. **The bundle never purges through API Platform's `BufferedPurger`** (`api_platform.http_cache.purger.buffered`, api-platform/core#8869, which decorates `api_platform.http_cache.purger` and, during a main request, holds every purge until its `kernel.response` listener, where a failure is a 500 no bundle code can catch): `ApiPlatformCompilerPass` gives `HttpCachePurger` and `HttpCacheFlusher` the buffer's inner purger whenever that service decorates something, so each purge fails inside the bundle's own call. The bundle already purges once per flush, so the buffer adds nothing to it; an `instanceof SouinPurger` on the buffered purger would also be false. - **Route write tags (#313):** `/_/routes` plus `…/_/routes/` (e.g. `/_api/_/routes//my-route`), and the old path's IRI on a path change. The tags are identical from HTTP and CLI. A sub-directory deployment needs `framework.router.default_uri` for CLI purges to match. - Response tag headers are unbounded; the limit is the proxy's buffer (a 502 at the proxy, never truncation). diff --git a/src/DependencyInjection/CompilerPass/ApiPlatformCompilerPass.php b/src/DependencyInjection/CompilerPass/ApiPlatformCompilerPass.php index 8c462bd7..768a4809 100644 --- a/src/DependencyInjection/CompilerPass/ApiPlatformCompilerPass.php +++ b/src/DependencyInjection/CompilerPass/ApiPlatformCompilerPass.php @@ -24,6 +24,8 @@ class ApiPlatformCompilerPass implements CompilerPassInterface { private const string HTTP_CACHE_FLUSHER = 'silverback.api_components.http_cache.flusher'; + private const string HTTP_CACHE_PURGER = 'silverback.api_components.http_cache.purger'; + private const string BUFFERED_PURGER = 'api_platform.http_cache.purger.buffered'; private const string INVALIDATION_CLIENT_PREFIX = 'api_platform.invalidation_http_client.'; private const string EXCEPTION_TO_STATUS = 'api_platform.exception_to_status'; @@ -36,9 +38,11 @@ public function process(ContainerBuilder $container): void if ($container->hasAlias('api_platform.http_cache.purger')) { $container->removeDefinition('api_platform.doctrine.listener.http_cache.purge'); } else { - $container->removeDefinition('silverback.api_components.http_cache.purger'); + $container->removeDefinition(self::HTTP_CACHE_PURGER); } + $this->bypassBufferedPurger($container); + $this->configureHttpCacheFlusher($container); $this->appendApiPlatformDefaultExceptionStatuses($container); @@ -58,6 +62,28 @@ private function appendApiPlatformDefaultExceptionStatuses(ContainerBuilder $con $container->setParameter(self::EXCEPTION_TO_STATUS, $container->getParameter(self::EXCEPTION_TO_STATUS) + $defaults); } + private function bypassBufferedPurger(ContainerBuilder $container): void + { + if (!$container->hasDefinition(self::BUFFERED_PURGER)) { + return; + } + + $decoratedService = $container->getDefinition(self::BUFFERED_PURGER)->getDecoratedService(); + if (null === $decoratedService) { + return; + } + + $innerPurger = new Reference($decoratedService[1] ?? self::BUFFERED_PURGER . '.inner'); + + if ($container->hasDefinition(self::HTTP_CACHE_PURGER)) { + $container->getDefinition(self::HTTP_CACHE_PURGER)->replaceArgument(2, $innerPurger); + } + + if ($container->hasDefinition(self::HTTP_CACHE_FLUSHER)) { + $container->getDefinition(self::HTTP_CACHE_FLUSHER)->replaceArgument(0, $innerPurger); + } + } + private function configureHttpCacheFlusher(ContainerBuilder $container): void { if (!$container->hasDefinition(self::HTTP_CACHE_FLUSHER)) { diff --git a/tests/DependencyInjection/CompilerPass/ApiPlatformCompilerPassTest.php b/tests/DependencyInjection/CompilerPass/ApiPlatformCompilerPassTest.php index 9616c163..1657c6f9 100644 --- a/tests/DependencyInjection/CompilerPass/ApiPlatformCompilerPassTest.php +++ b/tests/DependencyInjection/CompilerPass/ApiPlatformCompilerPassTest.php @@ -18,6 +18,7 @@ use Silverback\ApiComponentsBundle\Exception\UserDisabledException; use Silverback\ApiComponentsBundle\Helper\Collection\CollectionPopulator; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\HttpClient\ScopingHttpClient; @@ -27,6 +28,8 @@ class ApiPlatformCompilerPassTest extends TestCase { private const string FLUSHER_ID = 'silverback.api_components.http_cache.flusher'; + private const string BUNDLE_PURGER_ID = 'silverback.api_components.http_cache.purger'; + private const string BUFFERED_PURGER_ID = 'api_platform.http_cache.purger.buffered'; public function test_the_flusher_receives_each_invalidation_url_with_its_client(): void { @@ -64,8 +67,6 @@ public function test_the_collection_listener_receives_the_items_per_page_paramet public function test_the_api_platform_purge_listener_is_replaced_when_a_purger_is_configured(): void { $container = $this->createContainer(); - $container->setDefinition('app.purger', new Definition()); - $container->setAlias('api_platform.http_cache.purger', 'app.purger'); (new ApiPlatformCompilerPass())->process($container); @@ -76,6 +77,7 @@ public function test_the_api_platform_purge_listener_is_replaced_when_a_purger_i public function test_the_bundle_purger_is_removed_when_no_purger_is_configured(): void { $container = $this->createContainer(); + $container->removeAlias('api_platform.http_cache.purger'); (new ApiPlatformCompilerPass())->process($container); @@ -125,19 +127,102 @@ public function test_a_configured_status_for_a_default_exception_is_kept(): void self::assertSame(400, $exceptionToStatus[SerializerExceptionInterface::class]); } + public function test_the_bundle_purges_through_the_purger_api_platform_buffers_so_a_failure_reaches_it_during_the_request(): void + { + $container = $this->createContainer(); + $this->addBufferedPurger($container, null); + + (new ApiPlatformCompilerPass())->process($container); + + self::assertEquals(new Reference('api_platform.http_cache.purger.buffered.inner'), $container->getDefinition(self::BUNDLE_PURGER_ID)->getArgument(2)); + self::assertEquals(new Reference('api_platform.http_cache.purger.buffered.inner'), $container->getDefinition(self::FLUSHER_ID)->getArgument(0)); + } + + public function test_a_renamed_inner_purger_of_the_buffer_is_the_one_the_bundle_purges_through(): void + { + $container = $this->createContainer(); + $this->addBufferedPurger($container, 'app.unbuffered_purger'); + + (new ApiPlatformCompilerPass())->process($container); + + self::assertEquals(new Reference('app.unbuffered_purger'), $container->getDefinition(self::BUNDLE_PURGER_ID)->getArgument(2)); + self::assertEquals(new Reference('app.unbuffered_purger'), $container->getDefinition(self::FLUSHER_ID)->getArgument(0)); + } + + public function test_the_bundle_purges_through_the_configured_purger_when_api_platform_buffers_nothing(): void + { + $container = $this->createContainer(); + + (new ApiPlatformCompilerPass())->process($container); + + self::assertEquals(new Reference('api_platform.http_cache.purger', ContainerInterface::NULL_ON_INVALID_REFERENCE), $container->getDefinition(self::BUNDLE_PURGER_ID)->getArgument(2)); + self::assertEquals(new Reference('api_platform.http_cache.purger', ContainerInterface::NULL_ON_INVALID_REFERENCE), $container->getDefinition(self::FLUSHER_ID)->getArgument(0)); + } + + public function test_a_buffered_purger_service_that_decorates_nothing_is_not_bypassed(): void + { + $container = $this->createContainer(); + $container->setDefinition(self::BUFFERED_PURGER_ID, new Definition()); + + (new ApiPlatformCompilerPass())->process($container); + + self::assertEquals(new Reference('api_platform.http_cache.purger', ContainerInterface::NULL_ON_INVALID_REFERENCE), $container->getDefinition(self::BUNDLE_PURGER_ID)->getArgument(2)); + self::assertEquals(new Reference('api_platform.http_cache.purger', ContainerInterface::NULL_ON_INVALID_REFERENCE), $container->getDefinition(self::FLUSHER_ID)->getArgument(0)); + } + + public function test_the_flusher_bypasses_the_buffer_when_the_bundle_purger_was_removed(): void + { + $container = $this->createContainer(); + $container->removeAlias('api_platform.http_cache.purger'); + $this->addBufferedPurger($container, null); + + (new ApiPlatformCompilerPass())->process($container); + + self::assertFalse($container->hasDefinition(self::BUNDLE_PURGER_ID)); + self::assertEquals(new Reference('api_platform.http_cache.purger.buffered.inner'), $container->getDefinition(self::FLUSHER_ID)->getArgument(0)); + } + + public function test_a_buffered_purger_is_left_alone_when_the_bundle_http_cache_services_are_not_loaded(): void + { + $container = $this->createContainer(); + $container->removeDefinition(self::FLUSHER_ID); + $container->removeDefinition(self::BUNDLE_PURGER_ID); + $this->addBufferedPurger($container, null); + + (new ApiPlatformCompilerPass())->process($container); + + self::assertFalse($container->hasDefinition(self::FLUSHER_ID)); + self::assertFalse($container->hasDefinition(self::BUNDLE_PURGER_ID)); + self::assertTrue($container->hasDefinition(self::BUFFERED_PURGER_ID)); + } + + private function addBufferedPurger(ContainerBuilder $container, ?string $innerId): void + { + $definition = new Definition('ApiPlatform\\HttpCache\\BufferedPurger'); + $definition->setDecoratedService('api_platform.http_cache.purger', $innerId); + $container->setDefinition(self::BUFFERED_PURGER_ID, $definition); + } + private function createContainer(): ContainerBuilder { $container = new ContainerBuilder(); $container->setParameter('api_platform.collection.pagination.items_per_page_parameter_name', 'perPage'); $container->setParameter('api_platform.exception_to_status', []); $container->setDefinition(CollectionPopulator::class, new Definition(CollectionPopulator::class)); - $container->setDefinition(self::FLUSHER_ID, new Definition()); + $container->setDefinition(self::FLUSHER_ID, new Definition(null, [self::purgerReference(), '$invalidationClients' => []])); $container->setDefinition('api_platform.doctrine.listener.http_cache.purge', new Definition()); - $container->setDefinition('silverback.api_components.http_cache.purger', new Definition()); + $container->setDefinition(self::BUNDLE_PURGER_ID, new Definition(null, [new Reference('api_platform.iri_converter'), new Reference('api_platform.resource_class_resolver'), self::purgerReference()])); + $container->setDefinition('app.purger', new Definition()); + $container->setAlias('api_platform.http_cache.purger', 'app.purger'); return $container; } + private static function purgerReference(): Reference + { + return new Reference('api_platform.http_cache.purger', ContainerInterface::NULL_ON_INVALID_REFERENCE); + } + private function addInvalidationClient(ContainerBuilder $container, string $id, string $url): void { $definition = new Definition(ScopingHttpClient::class, [new Reference('http_client'), $url, ['base_uri' => $url]]); From c99b6dbda259ea1e30f66d47d04e912573cec8cc Mon Sep 17 00:00:00 2001 From: silverbackdan Date: Thu, 26 Nov 2026 16:14:30 +0000 Subject: [PATCH 2/2] Link the changelog line to #618 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd4ee206..dcffdabd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ Every change that reaches `main` adds a line under **Unreleased**. When a versio ## Unreleased ### Fixed -- On API Platform versions that buffer HTTP cache purges until the response (`BufferedPurger`, api-platform/core#8869), the bundle purges through the unbuffered purger, so a failed purge after a write is still logged rather than a 500 and an explicit purge is still a 502 ([#PR](https://github.com/components-web-app/api-components-bundle/pull/PR)) +- On API Platform versions that buffer HTTP cache purges until the response (`BufferedPurger`, api-platform/core#8869), the bundle purges through the unbuffered purger, so a failed purge after a write is still logged rather than a 500 and an explicit purge is still a 502 ([#618](https://github.com/components-web-app/api-components-bundle/pull/618)) - A page data class's to-many associations, and associations to a class that is not an API resource, are no longer page data properties, so writing an entity such an association holds no longer 500s ("SingleValuedAssociationField expected" on flush) and the page data metadata no longer lists them ([#617](https://github.com/components-web-app/api-components-bundle/pull/617)) ## [2.0.0-alpha.47](https://github.com/components-web-app/api-components-bundle/compare/2.0.0-alpha.46...2.0.0-alpha.47) - 2026-11-25