Repository navigation
Add source-aware context to catalog invalidation events #2559
Replies: 3 comments 2 replies
|
Could be a good idea. Do you have any specific real-world examples you've come across? |
|
Here are 2 possibilities: One for keeping the existing 2.x alpha layout, or refactoring it. Since it's still considered alpha/development, I vote for refactoring. Note: 99% of this was generated using Codex 5.6 SOL with ultra reasoning using the LunarPHP codebase, and using our implementation code for a Redis caching system so that we can invalidate portions of our cache. It found a few hooks to update/create, but this is the most important. It also found the other 2 bugs that I already created tickets for. Current 2.x approachThe current CacheInvalidator (https://github.com/lunarphp/lunar/blob/2.x/packages/core/src/Cache/CacheInvalidator.php) effectively does this: public function record(Model $source, CacheInvalidationReason $reason): void
{
foreach ($source->cacheInvalidationTargets() as $target) {
$key = identityOf($target);
$this->pending[$key] = [
'model' => $target,
'reason' => strongestReason(
$this->pending[$key]['reason'] ?? null,
$reason,
),
];
}
$this->flushAfterCommitOrImmediately();
}When flushed, each target receives only its strongest reason: foreach ($this->pending as $entry) {
event($entry['model']->newCacheInvalidationEvent(
$entry['reason'],
));
}Consequently, a Price, StockLevel, Url, variant, or relationship mutation can all become: ProductInvalidated(
product: $product,
reason: CacheInvalidationReason::RelatedChanged,
);The original cause is no longer available. The relationship wrapper The additive proposal would preserve compatibility by making two recordings: $invalidator->recordMutation($fact);
$invalidator->record($source, $reason);That would work, but it creates two related paths that must remain synchronized. Ordering also matters because record() may flush immediately when no transaction is Refactored approach (breaking changes)If breaking this alpha API is acceptable, I would instead make a catalog mutation the primary input. The names below are illustrative. final readonly class CatalogMutation
{
/**
* @param iterable<Model> $targets
* @param list<string> $changedAttributes
* @param list<string> $changedLocales
*/
public function __construct(
public Model $source,
public iterable $targets,
public CatalogMutationOperation $operation,
public array $changedAttributes = [],
public array $changedLocales = [],
public ?CatalogRelationshipDelta $relationship = null,
) {}
}The lifecycle concern would make one atomic call: $recorder->record(new CatalogMutation(
source: $model,
targets: $model->cacheInvalidationTargets(),
operation: $model->wasRecentlyCreated
? CatalogMutationOperation::Created
: CatalogMutationOperation::Updated,
changedAttributes: array_keys($model->getChanges()),
changedLocales: changedLocaleKeys($model),
));A relationship wrapper could retain its more specific information: $changes = parent::sync($ids);
$recorder->record(new CatalogMutation(
source: $this->parent,
targets: affectedCacheTargets($this->parent, $changes),
operation: CatalogMutationOperation::Related,
relationship: new CatalogRelationshipDelta(
name: $this->relationName ?? $this->getTable(),
operation: 'sync',
attachedKeys: $changes['attached'],
detachedKeys: $changes['detached'],
updatedKeys: $changes['updated'],
),
));The recorder would immediately convert the models into bounded scalar facts and aggregate them per target: public function record(CatalogMutation $mutation): void
{
foreach ($mutation->targets as $target) {
$fact = CatalogMutationFact::capture(
target: $target,
mutation: $mutation,
);
$key = $fact->target->identity();
$entry = $this->pending[$key]
??= new PendingCatalogInvalidation($target);
// Facts are deduplicated and unioned, not replaced.
$entry->add($fact);
}
$this->scheduleFlushAfterCommitOrImmediately();
}CatalogMutationFact would contain scalar metadata only: final readonly class CatalogMutationFact
{
/**
* @param list<string> $changedAttributes
* @param list<string> $changedLocales
*/
public function __construct(
public CatalogEntityReference $target,
public ?CatalogEntityReference $source,
public CatalogMutationOperation $operation,
public array $changedAttributes = [],
public array $changedLocales = [],
public ?CatalogRelationshipDelta $relationship = null,
) {}
}The existing coarse reason could still be derived for compatibility, but the event would also expose every committed fact: public function flush(): void
{
$batch = $this->pending;
$this->pending = [];
foreach ($batch as $entry) {
event($entry->target->newCacheInvalidationEvent(
reason: $entry->strongestReason(),
mutationFacts: $entry->facts(),
));
}
}interface CacheInvalidationEvent {
public function reason(): CacheInvalidationReason;
/** @return list<CatalogMutationFact> */
public function mutationFacts(): array;
// Existing target/tag methods omitted here.
}The mutable recorder should also be container-scoped so its pending state is reset for each HTTP request or queue job: $this->app->scoped(
CatalogMutationRecorder::class,
fn ($app) => new DatabaseCatalogMutationRecorder(
database: $app['db'],
),
);The transaction ledger should remain connection-aware and expose facts only after the outer transaction commits. A full rollback should discard them. Application-side benefitOur listener would receive one normalized payload containing every cause for that product: public function handle(ProductInvalidated $event): void
{
$effects = $this->policy->effectsFor(
$event->mutationFacts(),
);
$this->cacheInvalidator->apply($effects);
}The policy can then map each fact independently: return match (true) {
$fact->source->type === 'price' =>
PricingResultsChanged::forProduct($fact->target->key),
$fact->source->type === 'stock_level' =>
InventoryResultsChanged::forProduct($fact->target->key),
$fact->changedLocales !== [] =>
LocalizedProductContentChanged::forLocales(
$fact->target->key,
$fact->changedLocales,
),
$fact->relationship?->name === 'collections' =>
CollectionMembershipChanged::from($fact->relationship),
default =>
ProductChangedConservatively::forProduct($fact->target->key),
};For example, if a French name and a price change in the same transaction, both facts survive. The application can invalidate the French product/name-order caches and the pricing results without clearing unrelated locales or inventory results. Difference in practical terms
OpinionI think the refactor is worthwhile because it materially simplifies consumer processing and makes it impossible for Lunar’s normal recording path to emit an invalidation without its available source context. |
|
@glennjacobs Hello. Have you had a chance to think about this? I can provide a pull request for either direction. Or do you have any questions or feedback before I create a pull request? |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Current behavior
Lunar's after-commit catalog invalidation events identify the affected target and a broad reason. Before those events are emitted,
CacheInvalidatorreduces each source mutation to the target model and strongestCacheInvalidationReason.This means a consumer cannot tell whether a product was invalidated by a direct save, localized value change, URL change, price change, stock change, or relationship change. The relationship wrappers also know that a pivot mutation occurred, but the operation and affected pivot fields are discarded.
Proposed change
Would the maintainers consider additive, opt-in contextual invalidation contracts such as:
A
CatalogMutationFactcould contain bounded scalar classification metadata:Facts for the same target should be unioned until the surrounding transaction commits. They should not contain Eloquent graphs, translated values, request data, or storage-specific data.
Why it is useful
Storefront caches, search indexes, projections, webhooks, and audit adapters often need to react to the cause of invalidation rather than treating every related change as equivalent. For example, a price update may affect pricing projections, while a localized-name update may affect localized display data and name-based ordering.
Only Lunar's lifecycle concerns and relation wrappers reliably have this context before it is reduced to a coarse target event.
Compatibility and expected behavior
This should be a companion surface rather than a change to
CacheInvalidator::record()orCacheInvalidationEvent. Existing decorators, events, and listeners should continue unchanged.Pull request
If the maintainers agree with this API direction, I can provide a pull request implementing the additive contracts and DTOs, after-commit aggregation, regression tests, and documentation.
Relevant source:
packages/core/src/Cache/CacheInvalidator.php,packages/core/src/Contracts/CacheInvalidator.php, andpackages/core/src/Events/Catalog/.All reactions