diff --git a/.coderabbit.yaml b/.coderabbit.yaml index e640132a..92daf6ce 100644 --- a/.coderabbit.yaml +++ b/.coderabbit.yaml @@ -1,6 +1,9 @@ +# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json # Reviews run on demand: mention @coderabbitai review when a PR needs one. reviews: review_status: false + auto_approvals: + enabled: true pre_merge_checks: docstrings: mode: "off" diff --git a/CHANGELOG.md b/CHANGELOG.md index e8b1be75..f1b59a12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - `ResourceDonut`, `ResourceBodyEvaluator`, `RefreshAnnotatedCommand` and the default log classes `Log\HostRuntime`, `Log\ProcessSession`, `Log\SafeSemanticLogger` and `Log\ShutdownFlush` are `@internal`: depend on the interfaces they implement and the modules that bind them. `RefreshAnnotatedCommand`'s constructor and `ResourceDonut::create()`/`refresh()` take new arguments, so code that builds them with `new` has to take them from the injector instead. +- `ResourceStorageInterface::saveDonut()` now returns `bool` (whether the template entry was saved) instead of `void`; custom `ResourceStorageInterface` implementations must return `bool`. - `HttpCache` and `CliHttpCache` take only the `ConditionalRequest` they answer with, and `UriTag`, `EtagSetter` and `Log\Session` require their dependency. Code that builds them with `new` has to pass it, or take them from the injector. - `#[Cacheable]`'s `expirySecond` is documented as `non-negative-int`, so PHPStan and Psalm report a negative literal; a negative value is stored as no lifetime. - The classes in `src-deprecated/` and `src-annotation-deprecated/` are kept as they were in 1.20.2 and are no longer maintained; `StorageRedisCacheProvider`, `StorageMemcachedCacheProvider`, `NamespacedCacheProvider` and `ResourceStorageCacheableTrait` no longer work, as the qualifiers and classes they use are removed. `RepositoryLoggerInterface` is still bound to `RepositoryLogger` and receives no cache event; read the log from `SemanticLoggerInterface` with `#[CacheLog]`. @@ -49,6 +50,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - The `BaseUriTagInterface` binding: the group tag of an entry is always the one a purge of its bare URI reaches. ### Fixed +- `#[HttpCache]` and `#[NoHttpCache]` on a resource class that inherits `onGet()` from a parent class now apply. +- Direct top-level `DonutRepositoryInterface::putStatic()` and `putDonut()` calls now close their `manual_store` scope with `failed` when the response is unstorable or when saving the view or template is refused by the pool; they previously closed with `stored`. +- `DonutRendererInterface` is now resolved per donut write from DI, so the default transient binding creates a fresh renderer per write instead of retaining rendered hole views across requests in long-running processes; a singleton or `toInstance()` binding remains shared as configured. - A resource stored by `#[Cacheable]`, `#[CacheableResponse]` or `#[DonutCache]` that declares `private` or `no-store`, with `#[HttpCache(isPrivate: true)]`, `#[HttpCache(noStore: true)]` or `#[NoHttpCache]`, throws `UnstorableDeclaration` and stores nothing; it was stored in the shared pool, served to every visitor, and given a CDN lifetime. Remove the cache attribute or the declaration. - A `#[Cacheable(expiryAt: ...)]` response whose time has already passed is not stored and answers `Cache-Control: no-store`, logging `put_skipped` with the reason `expired`; it was stored without expiry and served until a write invalidated it. - A conditional request whose ETag, set by an `EtagSetterInterface` of your own, holds a character PSR-6 reserves in a cache key, such as the `/` of base64, is answered with 304; it was answered in full. diff --git a/docs/schemas/context/manual_store_result.json b/docs/schemas/context/manual_store_result.json index d8250b1d..20511f24 100644 --- a/docs/schemas/context/manual_store_result.json +++ b/docs/schemas/context/manual_store_result.json @@ -7,7 +7,7 @@ "required": ["result"], "properties": { "result": { - "description": "reflects the save_value/save_view outcome. \"failed\" also covers a write this gate refused outright (issue #222: marked unstorable, or a no-store/private Cache-Control; or a #[Cacheable] expiryAt already past) - no save_value/save_view was attempted, and the nested put_skipped{reason} in the same scope names which", + "description": "reflects the save_value/save_view/save_donut/save_donut_view outcome. \"failed\" also covers a write this gate refused outright (issue #222: marked unstorable, or a no-store/private Cache-Control; or a #[Cacheable] expiryAt already past) - no save_value/save_view/save_donut/save_donut_view was attempted, and the nested put_skipped{reason} in the same scope names which", "type": "string", "enum": ["stored", "failed"] } diff --git a/src/CacheableModule.php b/src/CacheableModule.php index 4f734d8c..c018e876 100644 --- a/src/CacheableModule.php +++ b/src/CacheableModule.php @@ -20,6 +20,7 @@ * The following bindings are provided: * * HttpCacheInterface + * DeclaredCacheControl * RefreshTemplateValidator * StorageExpiryModule */ @@ -34,6 +35,7 @@ protected function configure(): void $this->bind(HttpCacheInterface::class)->to(HttpCache::class); $this->bind(ConditionalRequest::class); $this->bind(ConditionalResponseInterface::class)->to(ConditionalResponse::class); + $this->bind(DeclaredCacheControl::class)->in(Scope::SINGLETON); $this->bind(RefreshTemplateValidator::class)->in(Scope::SINGLETON); $this->bind(CacheableClassMatcher::class); $this->install(new StorageExpiryModule(60, 60 * 60, 60 * 60 * 24)); diff --git a/src/DeclaredCacheControl.php b/src/DeclaredCacheControl.php index 0668f318..def95598 100644 --- a/src/DeclaredCacheControl.php +++ b/src/DeclaredCacheControl.php @@ -63,14 +63,7 @@ public function httpCache(ResourceObject $ro): HttpCache|null return $declared instanceof HttpCache ? $declared : null; } - private function forbidsSharing(string $cacheControl): bool - { - $lower = strtolower($cacheControl); - - return str_contains($lower, 'no-store') || str_contains($lower, 'private'); - } - - private function attribute(ResourceObject $ro): HttpCache|NoHttpCache|null + public function attribute(ResourceObject $ro): HttpCache|NoHttpCache|null { if (array_key_exists($ro::class, $this->declared)) { return $this->declared[$ro::class]; @@ -84,4 +77,11 @@ private function attribute(ResourceObject $ro): HttpCache|NoHttpCache|null return $this->declared[$ro::class] = isset($attributes[0]) ? $attributes[0]->newInstance() : null; } + + private function forbidsSharing(string $cacheControl): bool + { + $lower = strtolower($cacheControl); + + return str_contains($lower, 'no-store') || str_contains($lower, 'private'); + } } diff --git a/src/DonutRenderer.php b/src/DonutRenderer.php index 0d26124b..8e28e8c6 100644 --- a/src/DonutRenderer.php +++ b/src/DonutRenderer.php @@ -17,7 +17,7 @@ final class DonutRenderer implements DonutRendererInterface #[Override] public function setView(string $uri, string $view): void { - // One view per placeholder: in a long-running container the latest render of a hole must win. + // Indexed by placeholder so rendering the same hole twice replaces the earlier view $this->views[ResourceDonut::placeholder($uri)] = $view; } diff --git a/src/DonutRepository.php b/src/DonutRepository.php index c30928e7..38d5781e 100644 --- a/src/DonutRepository.php +++ b/src/DonutRepository.php @@ -19,6 +19,8 @@ use BEAR\Resource\ResourceObject; use Koriym\SemanticLogger\SemanticLoggerInterface; use Override; +use Ray\Di\Di\Set; +use Ray\Di\ProviderInterface; use Throwable; use function explode; @@ -27,7 +29,11 @@ /** @internal */ final readonly class DonutRepository implements DonutRepositoryInterface { - /** @SuppressWarnings("PHPMD.ExcessiveParameterList") */ + /** + * @param ProviderInterface $rendererProvider + * + * @SuppressWarnings("PHPMD.ExcessiveParameterList") + */ public function __construct( private QueryRepositoryInterface $queryRepository, private HeaderSetter $headerSetter, @@ -35,7 +41,8 @@ public function __construct( private ResourceInterface $resource, #[CacheLog] private SemanticLoggerInterface $logger, - private DonutRendererInterface $renderer, + #[Set(DonutRendererInterface::class)] + private ProviderInterface $rendererProvider, private DeclaredCacheControl $declaredCacheControl, private ReplacedEntry $replacedEntry, private CacheTags $cacheTags, @@ -115,8 +122,7 @@ private function store(ResourceObject $ro, bool $isPage, int|null $ttl, int|null $openId = $this->logger->open(new ManualStoreContext((string) $ro->uri)); $stored = false; try { - $this->write($ro, $isPage, $ttl, $sMaxAge); - $stored = true; + $stored = $this->write($ro, $isPage, $ttl, $sMaxAge); return $ro; } finally { @@ -130,14 +136,16 @@ private function store(ResourceObject $ro, bool $isPage, int|null $ttl, int|null * The template is tagged with its own URI tag (so `purge($uri)` reaches it, #185) and the material children's tags * ({@see CacheDependencyCollector::materials()}). Holes are left out: their write drops only the view and the page is recomposed. */ - private function write(ResourceObject $ro, bool $isPage, int|null $ttl, int|null $sMaxAge): void + private function write(ResourceObject $ro, bool $isPage, int|null $ttl, int|null $sMaxAge): bool { $keys = $this->dependencyCollector->begin($this->cacheTags->own($ro)); $this->dependencyCollector->materials($ro, $keys); $this->logger->event(new PutDonutContext((string) $ro->uri, $ttl, $sMaxAge)); $templateTags = $this->cacheTags->tags($ro)->toArray(); - $donut = ResourceDonut::create($ro, $this->renderer, $keys, $sMaxAge, $isPage)->withStorageState($ttl, $templateTags); - $donut->render($ro, $this->renderer); + // A per-write renderer from the provider isolates hole views across requests and concurrent coroutines + $renderer = $this->rendererProvider->get(); + $donut = ResourceDonut::create($ro, $renderer, $keys, $sMaxAge, $isPage)->withStorageState($ttl, $templateTags); + $donut->render($ro, $renderer); // Checked on the rendered response before the write adds its own headers $storability = $this->declaredCacheControl->storability($ro); $keys->addTo($ro); @@ -154,16 +162,19 @@ private function write(ResourceObject $ro, bool $isPage, int|null $ttl, int|null $this->logCdnHeaders($ro); if (! $this->replacedEntry->page($ro, $storability)) { - return; + return false; } + $viewSaved = true; if ($viewTags !== null) { - $this->resourceStorage->saveDonutView($ro, $sMaxAge, $viewTags->toArray()); + $viewSaved = $this->resourceStorage->saveDonutView($ro, $sMaxAge, $viewTags->toArray()); // The content state lets a later refresh keep Last-Modified when the recomposed content is unchanged $donut = $donut->withContentState($ro); } - $this->resourceStorage->saveDonut($ro->uri, $donut, $ttl, $templateTags); + $donutSaved = $this->resourceStorage->saveDonut($ro->uri, $donut, $ttl, $templateTags); + + return $viewSaved && $donutSaved; } /** diff --git a/src/HttpCacheInterceptor.php b/src/HttpCacheInterceptor.php index 707ac22c..97841c6a 100644 --- a/src/HttpCacheInterceptor.php +++ b/src/HttpCacheInterceptor.php @@ -4,8 +4,6 @@ namespace BEAR\QueryRepository; -use BEAR\RepositoryModule\Annotation\AbstractCacheControl; -use BEAR\RepositoryModule\Annotation\HttpCache; use BEAR\RepositoryModule\Annotation\NoHttpCache; use BEAR\Resource\ResourceObject; use Override; @@ -25,24 +23,24 @@ * @see https://bearsunday.github.io/manuals/1.0/en/cache.html * @internal */ -final class HttpCacheInterceptor implements MethodInterceptor +final readonly class HttpCacheInterceptor implements MethodInterceptor { + public function __construct( + private DeclaredCacheControl $declaredCacheControl, + ) { + } + /** * {@inheritDoc} */ #[Override] public function invoke(MethodInvocation $invocation) { - $class = $invocation->getMethod()->getDeclaringClass(); - $attributes = $class->getAttributes(HttpCache::class); - if (empty($attributes)) { - $attributes = $class->getAttributes(NoHttpCache::class); - } - - $cacheControl = isset($attributes[0]) ? $attributes[0]->newInstance() : null; + $target = $invocation->getThis(); + $cacheControl = $target instanceof ResourceObject ? $this->declaredCacheControl->attribute($target) : null; $ro = $invocation->proceed(); assert($ro instanceof ResourceObject); - if ($cacheControl instanceof AbstractCacheControl && ($ro->code === 200 || $cacheControl instanceof NoHttpCache)) { + if ($cacheControl !== null && ($ro->code === 200 || $cacheControl instanceof NoHttpCache)) { $ro->headers[Header::findKey($ro->headers, Header::CACHE_CONTROL) ?? Header::CACHE_CONTROL] = (string) $cacheControl; } diff --git a/src/Log/Context/ManualStoreResultContext.php b/src/Log/Context/ManualStoreResultContext.php index 1ef7eea8..81ccecc4 100644 --- a/src/Log/Context/ManualStoreResultContext.php +++ b/src/Log/Context/ManualStoreResultContext.php @@ -12,8 +12,8 @@ * Close of a manual_store scope: whether the resource was stored. * * `false`/"failed" also covers a write refused outright, unstorable or expired: - * no save_value/save_view was even attempted, and the nested put_skipped{reason} in the same - * scope names which. + * no save_value/save_view/save_donut/save_donut_view was even attempted, and the nested + * put_skipped{reason} in the same scope names which. */ final class ManualStoreResultContext extends AbstractContext implements JsonSerializable { diff --git a/src/Log/KeepMutationsAndFailures.php b/src/Log/KeepMutationsAndFailures.php index fbbb55ee..1190eed3 100644 --- a/src/Log/KeepMutationsAndFailures.php +++ b/src/Log/KeepMutationsAndFailures.php @@ -34,12 +34,13 @@ * - a sample, when a rate is configured. * * Deliberately not kept: `cache_error{operation: read}` (availability, monitored elsewhere - - * separating a degraded miss from a cold one is a development-time reading) and every - * `put_skipped`, which records a store that was never attempted because a rule forbade it - a - * response code the path will not cache (`#[Cacheable]` skips any non-200, a donut skips 4xx and - * above), a validator already set, or a page served from its template. Those are decisions, stable - * for as long as the code and the configuration are, and found once in development rather than per - * request in production. + * separating a degraded miss from a cold one is a development-time reading) and `put_skipped` + * on its own, which records a store that was never attempted because a rule forbade it - a + * donut skipping 4xx and above, a validator already set, a page served from its template, or an + * unstorable/expired response. A `#[Cacheable]` non-200 GET emits `put_skipped` and also purges + * its own URI tag, so that session is kept under the real-invalidation rule above. Those skip + * decisions are stable for as long as the code and the configuration are, and found once in + * development rather than per request in production. * `saved: false` is the opposite: the store was attempted and the pool refused it. It can repeat * per write under a capacity problem, and that is the signal, not noise - a host that needs a * ceiling decorates `LogWriterInterface`. diff --git a/src/QueryRepositoryModule.php b/src/QueryRepositoryModule.php index be3e158f..6bb8849a 100644 --- a/src/QueryRepositoryModule.php +++ b/src/QueryRepositoryModule.php @@ -86,7 +86,6 @@ protected function configure(): void $this->bind(UnsafeMethodMatcher::class); // Server context for thread safety (Swoole, RoadRunner, etc.) $this->bind(ServerContextInterface::class)->to(GlobalServerContext::class)->in(Scope::SINGLETON); - $this->bind(DeclaredCacheControl::class)->in(Scope::SINGLETON); $this->bind(ReplacedEntry::class); // #[Cacheable] $this->install(new CacheableModule()); diff --git a/src/ResourceDonut.php b/src/ResourceDonut.php index 96c1a199..c551b805 100644 --- a/src/ResourceDonut.php +++ b/src/ResourceDonut.php @@ -4,6 +4,7 @@ namespace BEAR\QueryRepository; +use ArrayAccess; use BEAR\QueryRepository\Exception\CacheStoreException; use BEAR\Resource\AbstractRequest; use BEAR\Resource\Request; @@ -244,22 +245,15 @@ public static function create(ResourceObject $ro, DonutRendererInterface $storag // an #[Embed] would have made it an array - and a null body holds no embedded request // to wrap. It is composed as an empty one rather than refused. assert(is_iterable($ro->body) || $ro->body === null); - $embeds = []; - if (is_iterable($ro->body)) { - /** - * @var array-key $key - * @var mixed $maybeRequest - */ - foreach ($ro->body as $key => &$maybeRequest) { - if ($maybeRequest instanceof AbstractRequest) { - $maybeRequest = $embeds[$key] = new DonutRequest($maybeRequest, $storage, $etags); - } - } + $embeds = self::wrapEmbeds($ro, $storage, $etags); + try { + $donutTemplate = $ro->toString(); + } catch (Throwable $e) { + self::restoreEmbeds($ro, $embeds); - unset($maybeRequest); + throw $e; } - $donutTemplate = $ro->toString(); foreach ($embeds as $embed) { if ($embed->isEncoded && is_array($ro->body)) { return self::ofBody($ro, $embeds, $etags, $sMaxAge, $isPage); @@ -269,6 +263,43 @@ public static function create(ResourceObject $ro, DonutRendererInterface $storag return new self($donutTemplate, $ro->headers, $sMaxAge, $isPage, code: $ro->code); } + /** @return array */ + private static function wrapEmbeds(ResourceObject $ro, DonutRendererInterface $storage, Dependencies $etags): array + { + if (! is_iterable($ro->body)) { + return []; + } + + $embeds = []; + /** + * @var array-key $key + * @var mixed $maybeRequest + */ + foreach ($ro->body as $key => &$maybeRequest) { + if ($maybeRequest instanceof DonutRequest) { + $maybeRequest = $maybeRequest->request; + } + + if ($maybeRequest instanceof AbstractRequest) { + $maybeRequest = $embeds[$key] = new DonutRequest($maybeRequest, $storage, $etags); + } + } + + unset($maybeRequest); + + return $embeds; + } + + /** @param array $embeds */ + private static function restoreEmbeds(ResourceObject $ro, array $embeds): void + { + if (is_array($ro->body) || $ro->body instanceof ArrayAccess) { + foreach ($embeds as $key => $embed) { + $ro->body[$key] = $embed->request; + } + } + } + /** * A renderer that encodes an embedded request as JSON prints no placeholder for it. The page is stored as the body * it returned and rendered again on each hit with those requests put back, so it shows what it shows without the donut. diff --git a/src/ResourceStorage.php b/src/ResourceStorage.php index 724fd8e2..1f2d2e0e 100644 --- a/src/ResourceStorage.php +++ b/src/ResourceStorage.php @@ -248,7 +248,7 @@ public function saveView(ResourceObject $ro, int $ttl) * {@inheritDoc} */ #[Override] - public function saveDonut(AbstractUri $uri, ResourceDonut $donut, int|null $ttl, array $headerKeys): void + public function saveDonut(AbstractUri $uri, ResourceDonut $donut, int|null $ttl, array $headerKeys): bool { $ttl = $this->nonNegative($ttl); $key = $this->getUriKey($uri, self::KEY_DONUT); @@ -257,6 +257,8 @@ public function saveDonut(AbstractUri $uri, ResourceDonut $donut, int|null $ttl, // saved=false is logged, not asserted: a quiet store failure must stay observable // in the log (an assert here would throw AFTER the event, contradicting it). $this->logger->event(new SaveDonutContext((string) $uri, $headerKeys, $ttl, $saved)); + + return $saved; } #[Override] diff --git a/src/ResourceStorageInterface.php b/src/ResourceStorageInterface.php index 5b964328..3f74cb77 100644 --- a/src/ResourceStorageInterface.php +++ b/src/ResourceStorageInterface.php @@ -47,7 +47,7 @@ public function getDonut(AbstractUri $uri): ResourceDonut|null; * * @param list $headerKeys */ - public function saveDonut(AbstractUri $uri, ResourceDonut $donut, int|null $ttl, array $headerKeys): void; + public function saveDonut(AbstractUri $uri, ResourceDonut $donut, int|null $ttl, array $headerKeys): bool; /** * Save donut-cache state diff --git a/tests/DonutMaterialDependencyTest.php b/tests/DonutMaterialDependencyTest.php index 079c83ee..ae4f36b9 100644 --- a/tests/DonutMaterialDependencyTest.php +++ b/tests/DonutMaterialDependencyTest.php @@ -16,6 +16,7 @@ use PHPUnit\Framework\TestCase; use Ray\Di\Injector; use Ray\Di\InjectorInterface; +use Ray\Di\ProviderInterface; use function array_filter; use function array_values; @@ -287,9 +288,8 @@ public function testAChildTaggedThroughAHeaderDefaultKeepsItsOwnKeyAfterBeingMis } /** - * Pins DonutRenderer: a second full MISS of the same page in one long-running - * container must render the hole's FRESH content, not the first MISS's stale view - * (setView() must overwrite by placeholder, not append). + * A second full MISS of the same page in one long-running container must render the hole's + * FRESH content, not the first MISS's stale view. */ public function testASecondFullMissOfTheSamePageRendersTheFreshHoleContent(): void { @@ -434,7 +434,18 @@ public function fromAssoc(string $uriTemplate, array $assoc): string $storage, $resource, $logger, - $injector->getInstance(DonutRendererInterface::class), + /** @implements ProviderInterface */ + new class ($injector) implements ProviderInterface { + public function __construct(private readonly InjectorInterface $injector) + { + } + + #[Override] + public function get(): DonutRendererInterface + { + return $this->injector->getInstance(DonutRendererInterface::class); + } + }, new DeclaredCacheControl(), new ReplacedEntry($logger, $storage, $uriTag), $cacheTags, diff --git a/tests/DonutRendererTest.php b/tests/DonutRendererTest.php index b750233c..f38f5295 100644 --- a/tests/DonutRendererTest.php +++ b/tests/DonutRendererTest.php @@ -21,10 +21,9 @@ public function testRender(): void } /** - * A long-running container reuses one DonutRenderer across requests: a second MISS of - * the same page must overwrite the hole's view by placeholder, not append behind it - - * str_replace() with a duplicate search entry only ever consumes the FIRST occurrence - * in the template, so an appended, stale second entry would never apply. + * When one DonutRenderer receives the same placeholder twice, the later view must win: + * str_replace() with duplicate search entries consumes the first occurrence, whereas + * strtr() keyed by placeholder replaces it. */ public function testSetViewOverwritesAnEarlierViewForTheSamePlaceholder(): void { diff --git a/tests/DonutRepositoryTest.php b/tests/DonutRepositoryTest.php index 6e88f75c..a1798441 100644 --- a/tests/DonutRepositoryTest.php +++ b/tests/DonutRepositoryTest.php @@ -4,11 +4,17 @@ namespace BEAR\QueryRepository; +use ArrayObject; use BEAR\QueryRepository\Cdn\AkamaiCacheControlHeaderSetter; use BEAR\QueryRepository\Cdn\FastlyCacheControlHeaderSetter; use BEAR\RepositoryModule\Annotation\CacheLog; use BEAR\RepositoryModule\Annotation\ResourceObjectPool; +use BEAR\Resource\AbstractRequest; +use BEAR\Resource\InvokerInterface; +use BEAR\Resource\RenderInterface; +use BEAR\Resource\Request; use BEAR\Resource\ResourceInterface; +use BEAR\Resource\ResourceObject; use BEAR\Resource\Uri; use FakeVendor\HelloWorld\Resource\Page\Html\ClosureBodyDonut; use Koriym\SemanticLogger\SemanticLoggerInterface; @@ -20,6 +26,7 @@ use Ray\Di\Injector; use ReflectionClass; use RuntimeException; +use Stringable; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Cache\Adapter\TagAwareAdapter; use Symfony\Component\Cache\Adapter\TagAwareAdapterInterface; @@ -29,6 +36,7 @@ use function class_exists; use function dirname; use function glob; +use function is_array; use function is_string; use function is_subclass_of; use function time; @@ -682,6 +690,159 @@ public function testDonutCacheRedirectStatusSurvivesTheRefresh(): void $this->assertNotNull(self::eventContextJsonOf($tree, 'refresh_donut'), 'the second request is answered by the template refresh'); } + public function testDonutWriteResolvesFreshRendererPerWrite(): void + { + FakeCountingDonutRenderer::reset(); + $module = ModuleFactory::getInstance('FakeVendor\HelloWorld'); + $module->override(new TwigModule([dirname(__DIR__) . '/tests/Fake/fake-app/var/templates'])); + $module->override(new class extends AbstractModule { + protected function configure(): void + { + $this->bind(DonutRendererInterface::class)->to(FakeCountingDonutRenderer::class); + } + }); + $injector = new Injector($module, __DIR__ . '/tmp'); + $resource = $injector->getInstance(ResourceInterface::class); + $storage = $injector->getInstance(ResourceStorageInterface::class); + + $first = $resource->get('page://self/html/blog-posting'); + $this->assertStringContainsString('comment01', (string) $first->view); + + $storage->invalidateTags([ + (new UriTag(new CacheIdentityFactory(new GlobalServerContext())))(new Uri('page://self/html/blog-posting')), + ]); + $second = $resource->get('page://self/html/blog-posting'); + $this->assertStringContainsString('comment01', (string) $second->view); + + $instances = FakeCountingDonutRenderer::instances(); + $this->assertCount(2, $instances); + $this->assertNotSame($instances[0], $instances[1]); + } + + public function testRetryAfterRenderFailureResolvesHolePlaceholder(): void + { + $injector = $this->getInjector(); + $donutRepository = $injector->getInstance(DonutRepositoryInterface::class); + $attempts = 0; + $invoker = new class ($attempts) implements InvokerInterface { + public function __construct(private int &$attempts) + { + } + + #[Override] + public function invoke(AbstractRequest $request): ResourceObject + { + $this->attempts++; + if ($this->attempts === 1) { + throw new RuntimeException('hole failed once'); + } + + $ro = $request->resourceObject; + $ro->body = ['status' => 'healthy']; + $ro->view = 'healthy'; + + return $ro; + } + }; + $holeRo = new class extends ResourceObject { + }; + $holeRo->uri = new Uri('app://self/flaky-hole'); + + $holeRequest = new Request($invoker, $holeRo); + $page = new class extends ResourceObject { + }; + $page->uri = new Uri('page://self/retry-donut'); + $page->body = ['hole' => $holeRequest]; + $page->setRenderer(new class implements RenderInterface { + #[Override] + public function render(ResourceObject $ro): string + { + assert(is_array($ro->body)); + /** @var Stringable $hole */ + $hole = $ro->body['hole']; + $ro->view = 'page:' . (string) $hole; + + return $ro->view; + } + }); + + $threw = false; + try { + $donutRepository->putDonut($page, null); + } catch (RuntimeException) { + $threw = true; + } + + $this->assertTrue($threw, 'first write fails while rendering the hole'); + $this->assertSame($holeRequest, $page->body['hole'], 'failed render restores the original embedded request'); + + $retried = $donutRepository->putDonut($page, null); + $this->assertSame('page:healthy', $retried->view); + $this->assertStringNotContainsString('[le2:', (string) $retried->view); + } + + public function testRetryAfterRenderFailureRestoresArrayObjectBody(): void + { + $injector = $this->getInjector(); + $donutRepository = $injector->getInstance(DonutRepositoryInterface::class); + $attempts = 0; + $invoker = new class ($attempts) implements InvokerInterface { + public function __construct(private int &$attempts) + { + } + + #[Override] + public function invoke(AbstractRequest $request): ResourceObject + { + $this->attempts++; + if ($this->attempts === 1) { + throw new RuntimeException('hole failed once'); + } + + $ro = $request->resourceObject; + $ro->body = ['status' => 'healthy']; + $ro->view = 'healthy'; + + return $ro; + } + }; + $holeRo = new class extends ResourceObject { + }; + $holeRo->uri = new Uri('app://self/flaky-hole'); + + $holeRequest = new Request($invoker, $holeRo); + $body = new ArrayObject(['hole' => $holeRequest]); + $page = new class extends ResourceObject { + }; + $page->uri = new Uri('page://self/retry-donut-array-object'); + $page->body = $body; + $page->setRenderer(new class implements RenderInterface { + #[Override] + public function render(ResourceObject $ro): string + { + assert($ro->body instanceof ArrayObject); + /** @var Stringable $hole */ + $hole = $ro->body['hole']; + $ro->view = 'page:' . (string) $hole; + + return $ro->view; + } + }); + + $threw = false; + try { + $donutRepository->putDonut($page, null); + } catch (RuntimeException) { + $threw = true; + } + + $this->assertTrue($threw); + $this->assertSame($holeRequest, $body['hole'], 'failed render restores the original request in an ArrayObject body'); + + $retried = $donutRepository->putDonut($page, null); + $this->assertSame('page:healthy', $retried->view); + } + public function testEveryBuiltInCdnHeaderIsInTheRecordedSet(): void { // cdn_headers records the headers named in HeaderSetter::CDN_FACING_HEADERS. Every string diff --git a/tests/Fake/FakeCountingDonutRenderer.php b/tests/Fake/FakeCountingDonutRenderer.php new file mode 100644 index 00000000..dc9c1f6c --- /dev/null +++ b/tests/Fake/FakeCountingDonutRenderer.php @@ -0,0 +1,44 @@ + */ + private static array $instances = []; + + private DonutRenderer $inner; + + public function __construct() + { + $this->inner = new DonutRenderer(); + self::$instances[] = $this; + } + + public static function reset(): void + { + self::$instances = []; + } + + /** @return list */ + public static function instances(): array + { + return self::$instances; + } + + #[Override] + public function setView(string $uri, string $view): void + { + $this->inner->setView($uri, $view); + } + + #[Override] + public function render(string $template): string + { + return $this->inner->render($template); + } +} diff --git a/tests/Fake/fake-app/src/Resource/App/InheritedHttpCacheBase.php b/tests/Fake/fake-app/src/Resource/App/InheritedHttpCacheBase.php new file mode 100644 index 00000000..c59d8e44 --- /dev/null +++ b/tests/Fake/fake-app/src/Resource/App/InheritedHttpCacheBase.php @@ -0,0 +1,17 @@ +body = ['ok' => true]; + + return $this; + } +} diff --git a/tests/Fake/fake-app/src/Resource/App/InheritedHttpCacheChild.php b/tests/Fake/fake-app/src/Resource/App/InheritedHttpCacheChild.php new file mode 100644 index 00000000..8f0b0b8f --- /dev/null +++ b/tests/Fake/fake-app/src/Resource/App/InheritedHttpCacheChild.php @@ -0,0 +1,12 @@ +assertSame(['cache-control' => 'max-age=60'], array_intersect_ukey($ro->headers, ['cache-control' => true], strcasecmp(...))); } + public function testHttpCacheAppliesWhenOnGetIsInherited(): void + { + $ro = $this->resource->get('app://self/inherited-http-cache-child'); + $this->assertSame('max-age=60', $ro->headers['Cache-Control']); + } + + public function testCacheableModuleStandaloneAppliesInheritedHttpCache(): void + { + $resource = (new Injector(new CacheableModule(new ResourceModule('FakeVendor\HelloWorld')), __DIR__ . '/tmp'))->getInstance(ResourceInterface::class); + + $httpCache = $resource->get('app://self/inherited-http-cache-child'); + $this->assertSame('max-age=60', $httpCache->headers['Cache-Control']); + + $noHttpCache = $resource->get('app://self/no-http-cache-control', ['code' => 404]); + $this->assertSame('private, no-store, no-cache, must-revalidate', $noHttpCache->headers['Cache-Control']); + } + public function testHttpCacheEtag(): void { $ro1 = $this->resource->get('app://self/etag'); diff --git a/tests/TopLevelAwareLoggerTest.php b/tests/TopLevelAwareLoggerTest.php index 6fe23244..af288ae9 100644 --- a/tests/TopLevelAwareLoggerTest.php +++ b/tests/TopLevelAwareLoggerTest.php @@ -10,11 +10,15 @@ use BEAR\QueryRepository\Log\Context\ManualStoreContext; use BEAR\QueryRepository\Log\Context\ManualStoreResultContext; use BEAR\RepositoryModule\Annotation\CacheLog; +use BEAR\RepositoryModule\Annotation\ResourceObjectPool; use BEAR\Resource\ResourceInterface; use Koriym\SemanticLogger\SemanticLoggerInterface; use PHPUnit\Framework\TestCase; use Ray\Di\AbstractModule; use Ray\Di\Injector; +use Symfony\Component\Cache\Adapter\ArrayAdapter; +use Symfony\Component\Cache\Adapter\TagAwareAdapter; +use Symfony\Component\Cache\Adapter\TagAwareAdapterInterface; use function array_filter; use function array_values; @@ -31,6 +35,7 @@ class TopLevelAwareLoggerTest extends TestCase { private RecordingTopLevelAwareLogger $logger; private QueryRepositoryInterface $repository; + private DonutRepositoryInterface $donutRepository; private ResourceStorageInterface $storage; private ResourceInterface $resource; @@ -53,6 +58,7 @@ protected function configure(): void }); $injector = new Injector($module, __DIR__ . '/tmp'); $this->repository = $injector->getInstance(QueryRepositoryInterface::class); + $this->donutRepository = $injector->getInstance(DonutRepositoryInterface::class); $this->storage = $injector->getInstance(ResourceStorageInterface::class); $this->resource = $injector->getInstance(ResourceInterface::class); @@ -85,6 +91,73 @@ public function testTopLevelDirectCallsAreRootedInManualScopes(): void $this->assertCount(1, $invalidateOpens); } + public function testTopLevelDonutStoreReportsFailedWhenUnstorable(): void + { + $storable = $this->resource->get('app://self/user', ['id' => 1]); + $this->donutRepository->putStatic($storable); + + $unstorable = clone $storable; + $unstorable->headers[Header::CACHE_CONTROL] = 'private'; + $this->donutRepository->putStatic($unstorable); + + $storeCloses = self::ofType($this->logger->closes, ManualStoreResultContext::class); + $this->assertCount(2, $storeCloses); + $this->assertTrue($storeCloses[0]->stored); + $this->assertFalse($storeCloses[1]->stored); + } + + public function testTopLevelDonutStoreReportsFailedWhenPoolRefusesViewOrTemplate(): void + { + // Refusing only ro- makes saveDonutView() return false while saveDonut() still runs and succeeds + [$viewRefusedLogger, $viewRefusedDonut, $viewRefusedStorage, $viewRefusedResource] = $this->envWithRefusingPool('ro-'); + $ro = $viewRefusedResource->get('app://self/user', ['id' => 1]); + $viewRefusedDonut->putStatic($ro); + $viewCloses = self::ofType($viewRefusedLogger->closes, ManualStoreResultContext::class); + $this->assertCount(1, $viewCloses); + $this->assertFalse($viewCloses[0]->stored); + $this->assertNotNull($viewRefusedStorage->getDonut($ro->uri), 'template save still runs when view save is refused'); + + // Refusing only donut- makes saveDonut() return false for both putStatic() and putDonut() + [$donutRefusedLogger, $donutRefusedDonut, , $donutRefusedResource] = $this->envWithRefusingPool('donut-'); + $page = $donutRefusedResource->get('app://self/user', ['id' => 1]); + $donutRefusedDonut->putStatic($page); + $donutRefusedDonut->putDonut(clone $page, null); + $donutCloses = self::ofType($donutRefusedLogger->closes, ManualStoreResultContext::class); + $this->assertCount(2, $donutCloses); + $this->assertFalse($donutCloses[0]->stored, 'putStatic() reports failed when template save is refused'); + $this->assertFalse($donutCloses[1]->stored, 'putDonut() reports failed when template save is refused'); + } + + /** @return array{RecordingTopLevelAwareLogger, DonutRepositoryInterface, ResourceStorageInterface, ResourceInterface} */ + private function envWithRefusingPool(string $refusedKeyPrefix): array + { + $logger = new RecordingTopLevelAwareLogger(); + $pool = new FakeRefusingPool(new TagAwareAdapter(new ArrayAdapter()), refusedKeyPrefix: $refusedKeyPrefix); + $module = ModuleFactory::getInstance('FakeVendor\HelloWorld'); + $module->override(new class ($logger, $pool) extends AbstractModule { + public function __construct( + private readonly RecordingTopLevelAwareLogger $logger, + private readonly TagAwareAdapterInterface $pool, + ) { + parent::__construct(); + } + + protected function configure(): void + { + $this->bind(SemanticLoggerInterface::class)->annotatedWith(CacheLog::class)->toInstance($this->logger); + $this->bind(TagAwareAdapterInterface::class)->annotatedWith(ResourceObjectPool::class)->toInstance($this->pool); + } + }); + $injector = new Injector($module, __DIR__ . '/tmp'); + + return [ + $logger, + $injector->getInstance(DonutRepositoryInterface::class), + $injector->getInstance(ResourceStorageInterface::class), + $injector->getInstance(ResourceInterface::class), + ]; + } + /** * @param list $contexts * @param class-string $type