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
3 changes: 3 additions & 0 deletions .coderabbit.yaml
Original file line number Diff line number Diff line change
@@ -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"
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]`.
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/schemas/context/manual_store_result.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
}
Expand Down
2 changes: 2 additions & 0 deletions src/CacheableModule.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
* The following bindings are provided:
*
* HttpCacheInterface
* DeclaredCacheControl
* RefreshTemplateValidator
* StorageExpiryModule
*/
Expand All @@ -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));
Expand Down
16 changes: 8 additions & 8 deletions src/DeclaredCacheControl.php
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand All @@ -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');
}
}
2 changes: 1 addition & 1 deletion src/DonutRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
31 changes: 21 additions & 10 deletions src/DonutRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -27,15 +29,20 @@
/** @internal */
final readonly class DonutRepository implements DonutRepositoryInterface
{
/** @SuppressWarnings("PHPMD.ExcessiveParameterList") */
/**
* @param ProviderInterface<DonutRendererInterface> $rendererProvider
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
*/
public function __construct(
private QueryRepositoryInterface $queryRepository,
private HeaderSetter $headerSetter,
private ResourceStorageInterface $resourceStorage,
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,
Expand Down Expand Up @@ -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 {
Expand All @@ -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);
Expand All @@ -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;
}

/**
Expand Down
20 changes: 9 additions & 11 deletions src/HttpCacheInterceptor.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
}

Expand Down
4 changes: 2 additions & 2 deletions src/Log/Context/ManualStoreResultContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
13 changes: 7 additions & 6 deletions src/Log/KeepMutationsAndFailures.php
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
1 change: 0 additions & 1 deletion src/QueryRepositoryModule.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
57 changes: 44 additions & 13 deletions src/ResourceDonut.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace BEAR\QueryRepository;

use ArrayAccess;
use BEAR\QueryRepository\Exception\CacheStoreException;
use BEAR\Resource\AbstractRequest;
use BEAR\Resource\Request;
Expand Down Expand Up @@ -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);
Expand All @@ -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<array-key, DonutRequest> */
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<array-key, DonutRequest> $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.
Expand Down
4 changes: 3 additions & 1 deletion src/ResourceStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion src/ResourceStorageInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public function getDonut(AbstractUri $uri): ResourceDonut|null;
*
* @param list<string> $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
Expand Down
Loading
Loading