From faee3bb785dd89bd1b3f83f48d4f4968021d79ae Mon Sep 17 00:00:00 2001 From: Manuk Date: Fri, 6 Nov 2026 19:49:08 +0400 Subject: [PATCH 1/3] fix: cache the entity registry per filament panel Discovery builds the registry from the current panel's resources, but the cache key was shared, so a multi-panel app served every panel the registry of whichever panel built it first. The key now carries the panel id, and the configured ttl reaches the cache. --- src/EntitySystem/EntityManager.php | 28 ++++++++-- src/Providers/EntityServiceProvider.php | 3 +- tests/Feature/EntityRegistryCacheTest.php | 65 +++++++++++++++++++++++ 3 files changed, 90 insertions(+), 6 deletions(-) create mode 100644 tests/Feature/EntityRegistryCacheTest.php diff --git a/src/EntitySystem/EntityManager.php b/src/EntitySystem/EntityManager.php index 8f874a14..96e677ae 100644 --- a/src/EntitySystem/EntityManager.php +++ b/src/EntitySystem/EntityManager.php @@ -8,6 +8,8 @@ namespace Relaticle\CustomFields\EntitySystem; use Closure; +use Filament\Exceptions\NoDefaultPanelSetException; +use Filament\Facades\Filament; use Filament\Resources\Resource; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Traits\Macroable; @@ -21,7 +23,7 @@ final class EntityManager implements EntityManagerInterface private const string CACHE_KEY = 'custom_fields_entities'; - private const int CACHE_TTL = 3600; // 1 hour + private const string NO_PANEL = 'no-panel'; private array $entities = []; @@ -34,7 +36,8 @@ final class EntityManager implements EntityManagerInterface private array $resolvingCallbacks = []; public function __construct( - private readonly bool $cacheEnabled = true + private readonly bool $cacheEnabled = true, + private readonly int $cacheTtl = 3600, ) {} /** @@ -55,7 +58,7 @@ public function getEntities(): EntityCollection { if ($this->cachedEntities === null) { $this->cachedEntities = $this->cacheEnabled - ? Cache::remember(self::CACHE_KEY, self::CACHE_TTL, fn (): array => $this->buildEntityCache()) + ? Cache::remember($this->cacheKey($this->currentPanelId()), $this->cacheTtl, fn (): array => $this->buildEntityCache()) : $this->buildEntityCache(); } @@ -117,13 +120,28 @@ public function clearCache(): static { $this->invalidateCache(); - if ($this->cacheEnabled) { - Cache::forget(self::CACHE_KEY); + foreach ([...array_keys(Filament::getPanels()), self::NO_PANEL] as $panelId) { + Cache::forget($this->cacheKey($panelId)); } return $this; } + // Discovery reads the current panel's resources, so each panel caches its own registry. + private function cacheKey(string $panelId): string + { + return self::CACHE_KEY.':'.$panelId; + } + + private function currentPanelId(): string + { + try { + return Filament::getCurrentOrDefaultPanel()?->getId() ?? self::NO_PANEL; + } catch (NoDefaultPanelSetException) { + return self::NO_PANEL; + } + } + /** * Get entities for a specific feature */ diff --git a/src/Providers/EntityServiceProvider.php b/src/Providers/EntityServiceProvider.php index d0674a4b..7eca2fb9 100644 --- a/src/Providers/EntityServiceProvider.php +++ b/src/Providers/EntityServiceProvider.php @@ -24,7 +24,8 @@ public function register(): void $config = $this->getEntityConfig(); return new EntityManager( - cacheEnabled: $config['cache_entities'] ?? true + cacheEnabled: $config['cache_entities'] ?? true, + cacheTtl: $config['cache_ttl'] ?? 3600, ); }); diff --git a/tests/Feature/EntityRegistryCacheTest.php b/tests/Feature/EntityRegistryCacheTest.php new file mode 100644 index 00000000..5e6722cb --- /dev/null +++ b/tests/Feature/EntityRegistryCacheTest.php @@ -0,0 +1,65 @@ +register(Panel::make()->id('portal')); + + useCachedResourceDiscovery(ttl: 600); +}); + +function useCachedResourceDiscovery(int $ttl): void +{ + config()->set('custom-fields.entity_configuration', + EntityConfigurator::configure() + ->discover([]) + ->cache(true, $ttl) + ); + + rebuildEntityManager(); +} + +function rebuildEntityManager(): EntityManager +{ + app()->forgetInstance(EntityManager::class); + app()->forgetInstance(EntityManagerInterface::class); + + return app(EntityManager::class); +} + +function entitiesSeenInPanel(string $panelId): EntityManager +{ + Filament::setCurrentPanel($panelId); + + return rebuildEntityManager(); +} + +it('serves each panel the registry built from its own resources', function (): void { + expect(entitiesSeenInPanel('portal')->hasEntity(Post::class))->toBeFalse(); + + expect(entitiesSeenInPanel('admin')->getEntity(Post::class)?->getResourceClass())->toBe(PostResource::class); + + expect(entitiesSeenInPanel('portal')->hasEntity(Post::class))->toBeFalse(); +}); + +it('stores the registry for the configured ttl', function (): void { + useCachedResourceDiscovery(ttl: 120); + + entitiesSeenInPanel('admin')->getEntities(); + + $this->travel(119)->seconds(); + expect(Cache::has('custom_fields_entities:admin'))->toBeTrue(); + + $this->travel(2)->seconds(); + expect(Cache::has('custom_fields_entities:admin'))->toBeFalse(); +}); From c79cf7707f69a96b80cb3a5ecd7f15ccbd8d55ee Mon Sep 17 00:00:00 2001 From: Manuk Date: Fri, 6 Nov 2026 19:49:08 +0400 Subject: [PATCH 2/3] feat: add custom-fields:clear-cache command Clears the cached entity registry of every panel, so a deploy can drop a registry built from the previous configuration. --- docs/content/2.essentials/1.configuration.md | 8 +++++- src/Console/Commands/ClearCacheCommand.php | 26 ++++++++++++++++++++ src/CustomFieldsServiceProvider.php | 2 ++ tests/Feature/EntityRegistryCacheTest.php | 12 +++++++++ 4 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 src/Console/Commands/ClearCacheCommand.php diff --git a/docs/content/2.essentials/1.configuration.md b/docs/content/2.essentials/1.configuration.md index ebc2d53c..bf3b6278 100644 --- a/docs/content/2.essentials/1.configuration.md +++ b/docs/content/2.essentials/1.configuration.md @@ -297,12 +297,18 @@ Optimize for production: ```php 'entity_configuration' => EntityConfigurator::configure() ->discover(app_path('Models')) - ->cache(env('CUSTOM_FIELDS_CACHE', true)), // Enable caching + ->cache(env('CUSTOM_FIELDS_CACHE', true), ttl: 3600), // Cache the entity registry for an hour 'field_type_configuration' => FieldTypeConfigurator::configure() ->cache(enabled: true, ttl: 3600), // Cache field types ``` +The entity registry is cached once per Filament panel, because discovery reads each panel's own resources. Clear it on every deploy so a changed `entity_configuration` takes effect at once: + +```bash +php artisan custom-fields:clear-cache +``` + ### Multi-Tenancy Setup Enable tenant isolation: diff --git a/src/Console/Commands/ClearCacheCommand.php b/src/Console/Commands/ClearCacheCommand.php new file mode 100644 index 00000000..8ef9a16a --- /dev/null +++ b/src/Console/Commands/ClearCacheCommand.php @@ -0,0 +1,26 @@ +clearCache(); + + $this->components->info('Custom fields entity cache cleared.'); + + return self::SUCCESS; + } +} diff --git a/src/CustomFieldsServiceProvider.php b/src/CustomFieldsServiceProvider.php index df9c83d1..7eabb42e 100644 --- a/src/CustomFieldsServiceProvider.php +++ b/src/CustomFieldsServiceProvider.php @@ -14,6 +14,7 @@ use Illuminate\Filesystem\Filesystem; use Livewire\Livewire; use Relaticle\CustomFields\Console\Commands\CleanupOrphanedValuesCommand; +use Relaticle\CustomFields\Console\Commands\ClearCacheCommand; use Relaticle\CustomFields\Console\Commands\MakeCustomFieldsMigrationCommand; use Relaticle\CustomFields\Console\Commands\MakeFieldTypeCommand; use Relaticle\CustomFields\Console\Commands\UpgradeCommand; @@ -177,6 +178,7 @@ private function getCommands(): array { return [ CleanupOrphanedValuesCommand::class, + ClearCacheCommand::class, MakeCustomFieldsMigrationCommand::class, MakeFieldTypeCommand::class, UpgradeCommand::class, diff --git a/tests/Feature/EntityRegistryCacheTest.php b/tests/Feature/EntityRegistryCacheTest.php index 5e6722cb..e24024d3 100644 --- a/tests/Feature/EntityRegistryCacheTest.php +++ b/tests/Feature/EntityRegistryCacheTest.php @@ -63,3 +63,15 @@ function entitiesSeenInPanel(string $panelId): EntityManager $this->travel(2)->seconds(); expect(Cache::has('custom_fields_entities:admin'))->toBeFalse(); }); + +it('clears the cached registry of every panel', function (): void { + entitiesSeenInPanel('admin')->getEntities(); + entitiesSeenInPanel('portal')->getEntities(); + + $this->artisan('custom-fields:clear-cache') + ->expectsOutputToContain('Custom fields entity cache cleared.') + ->assertSuccessful(); + + expect(Cache::has('custom_fields_entities:admin'))->toBeFalse() + ->and(Cache::has('custom_fields_entities:portal'))->toBeFalse(); +}); From cb7422ace077387ff3f9fe5a8544a09db632e06c Mon Sep 17 00:00:00 2001 From: Manuk Date: Fri, 6 Nov 2026 19:53:55 +0400 Subject: [PATCH 3/3] fix: keep the in-memory entity registry per panel A long-lived manager, such as a queue worker running import jobs for several panels, kept serving the first panel's registry and could write it under another panel's cache key. The manager's memo is now keyed by panel id, and discovery no longer keeps its own memo. --- docs/content/2.essentials/1.configuration.md | 2 +- src/EntitySystem/EntityDiscovery.php | 10 +--------- src/EntitySystem/EntityManager.php | 21 ++++++++++++-------- tests/Feature/EntityRegistryCacheTest.php | 20 +++++++++++++++++++ 4 files changed, 35 insertions(+), 18 deletions(-) diff --git a/docs/content/2.essentials/1.configuration.md b/docs/content/2.essentials/1.configuration.md index bf3b6278..8e03b05c 100644 --- a/docs/content/2.essentials/1.configuration.md +++ b/docs/content/2.essentials/1.configuration.md @@ -303,7 +303,7 @@ Optimize for production: ->cache(enabled: true, ttl: 3600), // Cache field types ``` -The entity registry is cached once per Filament panel, because discovery reads each panel's own resources. Clear it on every deploy so a changed `entity_configuration` takes effect at once: +The entity registry is cached once per Filament panel, because discovery reads each panel's own resources. Clear it on every deploy so a changed `entity_configuration` takes effect at once. The command clears the entity registry only: ```bash php artisan custom-fields:clear-cache diff --git a/src/EntitySystem/EntityDiscovery.php b/src/EntitySystem/EntityDiscovery.php index 8f799987..592da778 100644 --- a/src/EntitySystem/EntityDiscovery.php +++ b/src/EntitySystem/EntityDiscovery.php @@ -21,8 +21,6 @@ final class EntityDiscovery { - private array $discoveredCache = []; - public function __construct( private array $paths = [], private array $namespaces = [] @@ -43,10 +41,6 @@ public function __construct( */ public function discover(): array { - if ($this->discoveredCache !== []) { - return $this->discoveredCache; - } - $entities = []; // 1. Discover from Filament Resources (highest priority) @@ -73,9 +67,7 @@ public function discover(): array } } - $this->discoveredCache = array_values($entities); - - return $this->discoveredCache; + return array_values($entities); } /** diff --git a/src/EntitySystem/EntityManager.php b/src/EntitySystem/EntityManager.php index 96e677ae..353662d8 100644 --- a/src/EntitySystem/EntityManager.php +++ b/src/EntitySystem/EntityManager.php @@ -27,7 +27,8 @@ final class EntityManager implements EntityManagerInterface private array $entities = []; - private ?array $cachedEntities = null; + /** @var array> */ + private array $cachedEntities = []; private ?EntityDiscovery $discovery = null; @@ -56,13 +57,13 @@ public function register(array|Closure $entities): static */ public function getEntities(): EntityCollection { - if ($this->cachedEntities === null) { - $this->cachedEntities = $this->cacheEnabled - ? Cache::remember($this->cacheKey($this->currentPanelId()), $this->cacheTtl, fn (): array => $this->buildEntityCache()) - : $this->buildEntityCache(); - } + $panelId = $this->currentPanelId(); + + $this->cachedEntities[$panelId] ??= $this->cacheEnabled + ? Cache::remember($this->cacheKey($panelId), $this->cacheTtl, fn (): array => $this->buildEntityCache()) + : $this->buildEntityCache(); - return new EntityCollection($this->cachedEntities); + return new EntityCollection($this->cachedEntities[$panelId]); } /** @@ -110,7 +111,7 @@ public function disableDiscovery(): static */ private function invalidateCache(): void { - $this->cachedEntities = null; + $this->cachedEntities = []; } /** @@ -120,6 +121,10 @@ public function clearCache(): static { $this->invalidateCache(); + if (! $this->cacheEnabled) { + return $this; + } + foreach ([...array_keys(Filament::getPanels()), self::NO_PANEL] as $panelId) { Cache::forget($this->cacheKey($panelId)); } diff --git a/tests/Feature/EntityRegistryCacheTest.php b/tests/Feature/EntityRegistryCacheTest.php index e24024d3..e882cfea 100644 --- a/tests/Feature/EntityRegistryCacheTest.php +++ b/tests/Feature/EntityRegistryCacheTest.php @@ -52,6 +52,23 @@ function entitiesSeenInPanel(string $panelId): EntityManager expect(entitiesSeenInPanel('portal')->hasEntity(Post::class))->toBeFalse(); }); +it('keeps panels apart within one long-lived manager', function (): void { + $manager = entitiesSeenInPanel('admin'); + $postAlias = $manager->getEntity(Post::class)?->getAlias(); + + expect($postAlias)->not->toBeNull(); + + $manager->clearCache(); + Filament::setCurrentPanel('portal'); + + expect($manager->hasEntity(Post::class))->toBeFalse() + ->and(Cache::get('custom_fields_entities:portal'))->not->toHaveKey($postAlias); + + Filament::setCurrentPanel('admin'); + + expect($manager->getEntity(Post::class)?->getResourceClass())->toBe(PostResource::class); +}); + it('stores the registry for the configured ttl', function (): void { useCachedResourceDiscovery(ttl: 120); @@ -68,6 +85,9 @@ function entitiesSeenInPanel(string $panelId): EntityManager entitiesSeenInPanel('admin')->getEntities(); entitiesSeenInPanel('portal')->getEntities(); + expect(Cache::has('custom_fields_entities:admin'))->toBeTrue() + ->and(Cache::has('custom_fields_entities:portal'))->toBeTrue(); + $this->artisan('custom-fields:clear-cache') ->expectsOutputToContain('Custom fields entity cache cleared.') ->assertSuccessful();