Skip to content

Commit 119a339

Browse files
Merge pull request #618 from components-web-app/fix/buffered-purge-failures
Purge through the purger API Platform's BufferedPurger decorates (#610)
2 parents e15c463 + c99b6db commit 119a339

4 files changed

Lines changed: 118 additions & 6 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ Every change that reaches `main` adds a line under **Unreleased**. When a versio
55
## Unreleased
66

77
### Fixed
8+
- 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))
89
- 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))
910

1011
## [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

‎CLAUDE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ Resources are fetched and cached **individually**. Never embed related data outs
240240
- **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.
241241
- **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.
242242
- **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.
243-
- **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.
243+
- **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.
244244
- **Route write tags (#313):** `<route import prefix>/_/routes` plus `…/_/routes/<path>` (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.
245245
- Response tag headers are unbounded; the limit is the proxy's buffer (a 502 at the proxy, never truncation).
246246

‎src/DependencyInjection/CompilerPass/ApiPlatformCompilerPass.php‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
class ApiPlatformCompilerPass implements CompilerPassInterface
2525
{
2626
private const string HTTP_CACHE_FLUSHER = 'silverback.api_components.http_cache.flusher';
27+
private const string HTTP_CACHE_PURGER = 'silverback.api_components.http_cache.purger';
28+
private const string BUFFERED_PURGER = 'api_platform.http_cache.purger.buffered';
2729
private const string INVALIDATION_CLIENT_PREFIX = 'api_platform.invalidation_http_client.';
2830
private const string EXCEPTION_TO_STATUS = 'api_platform.exception_to_status';
2931

@@ -36,9 +38,11 @@ public function process(ContainerBuilder $container): void
3638
if ($container->hasAlias('api_platform.http_cache.purger')) {
3739
$container->removeDefinition('api_platform.doctrine.listener.http_cache.purge');
3840
} else {
39-
$container->removeDefinition('silverback.api_components.http_cache.purger');
41+
$container->removeDefinition(self::HTTP_CACHE_PURGER);
4042
}
4143

44+
$this->bypassBufferedPurger($container);
45+
4246
$this->configureHttpCacheFlusher($container);
4347

4448
$this->appendApiPlatformDefaultExceptionStatuses($container);
@@ -58,6 +62,28 @@ private function appendApiPlatformDefaultExceptionStatuses(ContainerBuilder $con
5862
$container->setParameter(self::EXCEPTION_TO_STATUS, $container->getParameter(self::EXCEPTION_TO_STATUS) + $defaults);
5963
}
6064

65+
private function bypassBufferedPurger(ContainerBuilder $container): void
66+
{
67+
if (!$container->hasDefinition(self::BUFFERED_PURGER)) {
68+
return;
69+
}
70+
71+
$decoratedService = $container->getDefinition(self::BUFFERED_PURGER)->getDecoratedService();
72+
if (null === $decoratedService) {
73+
return;
74+
}
75+
76+
$innerPurger = new Reference($decoratedService[1] ?? self::BUFFERED_PURGER . '.inner');
77+
78+
if ($container->hasDefinition(self::HTTP_CACHE_PURGER)) {
79+
$container->getDefinition(self::HTTP_CACHE_PURGER)->replaceArgument(2, $innerPurger);
80+
}
81+
82+
if ($container->hasDefinition(self::HTTP_CACHE_FLUSHER)) {
83+
$container->getDefinition(self::HTTP_CACHE_FLUSHER)->replaceArgument(0, $innerPurger);
84+
}
85+
}
86+
6187
private function configureHttpCacheFlusher(ContainerBuilder $container): void
6288
{
6389
if (!$container->hasDefinition(self::HTTP_CACHE_FLUSHER)) {

‎tests/DependencyInjection/CompilerPass/ApiPlatformCompilerPassTest.php‎

Lines changed: 89 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use Silverback\ApiComponentsBundle\Exception\UserDisabledException;
1919
use Silverback\ApiComponentsBundle\Helper\Collection\CollectionPopulator;
2020
use Symfony\Component\DependencyInjection\ContainerBuilder;
21+
use Symfony\Component\DependencyInjection\ContainerInterface;
2122
use Symfony\Component\DependencyInjection\Definition;
2223
use Symfony\Component\DependencyInjection\Reference;
2324
use Symfony\Component\HttpClient\ScopingHttpClient;
@@ -27,6 +28,8 @@
2728
class ApiPlatformCompilerPassTest extends TestCase
2829
{
2930
private const string FLUSHER_ID = 'silverback.api_components.http_cache.flusher';
31+
private const string BUNDLE_PURGER_ID = 'silverback.api_components.http_cache.purger';
32+
private const string BUFFERED_PURGER_ID = 'api_platform.http_cache.purger.buffered';
3033

3134
public function test_the_flusher_receives_each_invalidation_url_with_its_client(): void
3235
{
@@ -64,8 +67,6 @@ public function test_the_collection_listener_receives_the_items_per_page_paramet
6467
public function test_the_api_platform_purge_listener_is_replaced_when_a_purger_is_configured(): void
6568
{
6669
$container = $this->createContainer();
67-
$container->setDefinition('app.purger', new Definition());
68-
$container->setAlias('api_platform.http_cache.purger', 'app.purger');
6970

7071
(new ApiPlatformCompilerPass())->process($container);
7172

@@ -76,6 +77,7 @@ public function test_the_api_platform_purge_listener_is_replaced_when_a_purger_i
7677
public function test_the_bundle_purger_is_removed_when_no_purger_is_configured(): void
7778
{
7879
$container = $this->createContainer();
80+
$container->removeAlias('api_platform.http_cache.purger');
7981

8082
(new ApiPlatformCompilerPass())->process($container);
8183

@@ -125,19 +127,102 @@ public function test_a_configured_status_for_a_default_exception_is_kept(): void
125127
self::assertSame(400, $exceptionToStatus[SerializerExceptionInterface::class]);
126128
}
127129

130+
public function test_the_bundle_purges_through_the_purger_api_platform_buffers_so_a_failure_reaches_it_during_the_request(): void
131+
{
132+
$container = $this->createContainer();
133+
$this->addBufferedPurger($container, null);
134+
135+
(new ApiPlatformCompilerPass())->process($container);
136+
137+
self::assertEquals(new Reference('api_platform.http_cache.purger.buffered.inner'), $container->getDefinition(self::BUNDLE_PURGER_ID)->getArgument(2));
138+
self::assertEquals(new Reference('api_platform.http_cache.purger.buffered.inner'), $container->getDefinition(self::FLUSHER_ID)->getArgument(0));
139+
}
140+
141+
public function test_a_renamed_inner_purger_of_the_buffer_is_the_one_the_bundle_purges_through(): void
142+
{
143+
$container = $this->createContainer();
144+
$this->addBufferedPurger($container, 'app.unbuffered_purger');
145+
146+
(new ApiPlatformCompilerPass())->process($container);
147+
148+
self::assertEquals(new Reference('app.unbuffered_purger'), $container->getDefinition(self::BUNDLE_PURGER_ID)->getArgument(2));
149+
self::assertEquals(new Reference('app.unbuffered_purger'), $container->getDefinition(self::FLUSHER_ID)->getArgument(0));
150+
}
151+
152+
public function test_the_bundle_purges_through_the_configured_purger_when_api_platform_buffers_nothing(): void
153+
{
154+
$container = $this->createContainer();
155+
156+
(new ApiPlatformCompilerPass())->process($container);
157+
158+
self::assertEquals(new Reference('api_platform.http_cache.purger', ContainerInterface::NULL_ON_INVALID_REFERENCE), $container->getDefinition(self::BUNDLE_PURGER_ID)->getArgument(2));
159+
self::assertEquals(new Reference('api_platform.http_cache.purger', ContainerInterface::NULL_ON_INVALID_REFERENCE), $container->getDefinition(self::FLUSHER_ID)->getArgument(0));
160+
}
161+
162+
public function test_a_buffered_purger_service_that_decorates_nothing_is_not_bypassed(): void
163+
{
164+
$container = $this->createContainer();
165+
$container->setDefinition(self::BUFFERED_PURGER_ID, new Definition());
166+
167+
(new ApiPlatformCompilerPass())->process($container);
168+
169+
self::assertEquals(new Reference('api_platform.http_cache.purger', ContainerInterface::NULL_ON_INVALID_REFERENCE), $container->getDefinition(self::BUNDLE_PURGER_ID)->getArgument(2));
170+
self::assertEquals(new Reference('api_platform.http_cache.purger', ContainerInterface::NULL_ON_INVALID_REFERENCE), $container->getDefinition(self::FLUSHER_ID)->getArgument(0));
171+
}
172+
173+
public function test_the_flusher_bypasses_the_buffer_when_the_bundle_purger_was_removed(): void
174+
{
175+
$container = $this->createContainer();
176+
$container->removeAlias('api_platform.http_cache.purger');
177+
$this->addBufferedPurger($container, null);
178+
179+
(new ApiPlatformCompilerPass())->process($container);
180+
181+
self::assertFalse($container->hasDefinition(self::BUNDLE_PURGER_ID));
182+
self::assertEquals(new Reference('api_platform.http_cache.purger.buffered.inner'), $container->getDefinition(self::FLUSHER_ID)->getArgument(0));
183+
}
184+
185+
public function test_a_buffered_purger_is_left_alone_when_the_bundle_http_cache_services_are_not_loaded(): void
186+
{
187+
$container = $this->createContainer();
188+
$container->removeDefinition(self::FLUSHER_ID);
189+
$container->removeDefinition(self::BUNDLE_PURGER_ID);
190+
$this->addBufferedPurger($container, null);
191+
192+
(new ApiPlatformCompilerPass())->process($container);
193+
194+
self::assertFalse($container->hasDefinition(self::FLUSHER_ID));
195+
self::assertFalse($container->hasDefinition(self::BUNDLE_PURGER_ID));
196+
self::assertTrue($container->hasDefinition(self::BUFFERED_PURGER_ID));
197+
}
198+
199+
private function addBufferedPurger(ContainerBuilder $container, ?string $innerId): void
200+
{
201+
$definition = new Definition('ApiPlatform\\HttpCache\\BufferedPurger');
202+
$definition->setDecoratedService('api_platform.http_cache.purger', $innerId);
203+
$container->setDefinition(self::BUFFERED_PURGER_ID, $definition);
204+
}
205+
128206
private function createContainer(): ContainerBuilder
129207
{
130208
$container = new ContainerBuilder();
131209
$container->setParameter('api_platform.collection.pagination.items_per_page_parameter_name', 'perPage');
132210
$container->setParameter('api_platform.exception_to_status', []);
133211
$container->setDefinition(CollectionPopulator::class, new Definition(CollectionPopulator::class));
134-
$container->setDefinition(self::FLUSHER_ID, new Definition());
212+
$container->setDefinition(self::FLUSHER_ID, new Definition(null, [self::purgerReference(), '$invalidationClients' => []]));
135213
$container->setDefinition('api_platform.doctrine.listener.http_cache.purge', new Definition());
136-
$container->setDefinition('silverback.api_components.http_cache.purger', new Definition());
214+
$container->setDefinition(self::BUNDLE_PURGER_ID, new Definition(null, [new Reference('api_platform.iri_converter'), new Reference('api_platform.resource_class_resolver'), self::purgerReference()]));
215+
$container->setDefinition('app.purger', new Definition());
216+
$container->setAlias('api_platform.http_cache.purger', 'app.purger');
137217

138218
return $container;
139219
}
140220

221+
private static function purgerReference(): Reference
222+
{
223+
return new Reference('api_platform.http_cache.purger', ContainerInterface::NULL_ON_INVALID_REFERENCE);
224+
}
225+
141226
private function addInvalidationClient(ContainerBuilder $container, string $id, string $url): void
142227
{
143228
$definition = new Definition(ScopingHttpClient::class, [new Reference('http_client'), $url, ['base_uri' => $url]]);

0 commit comments

Comments
 (0)