diff --git a/ProcessMaker/Cache/Settings/SettingCacheManager.php b/ProcessMaker/Cache/Settings/SettingCacheManager.php index 3285fe1a67..aea1dfc1b1 100644 --- a/ProcessMaker/Cache/Settings/SettingCacheManager.php +++ b/ProcessMaker/Cache/Settings/SettingCacheManager.php @@ -15,6 +15,11 @@ class SettingCacheManager extends CacheManagerBase implements CacheInterface const DEFAULT_CACHE_PREFIX = 'settings:'; + /** + * Envelope marker so cached null is distinguishable from a Laravel cache miss. + */ + private const ENVELOPE_FLAG = '__pm_setting'; + protected CacheManager $manager; protected Repository $cacheManager; @@ -28,8 +33,6 @@ public function __construct(CacheManager $cacheManager) /** * Determine and set the cache driver to use. * - * @param CacheManager $cacheManager - * * @return void */ private function setCacheDriver(): void @@ -44,14 +47,10 @@ private function setCacheDriver(): void } /** - * Create a cache key for a screen + * Create a cache key for a setting. * - * @param int $processId Process ID - * @param int $processVersionId Process Version ID - * @param string $language Language code - * @param int $screenId Screen ID - * @param int $screenVersionId Screen Version ID - * @return string The generated cache key + * @param array $params + * @return string */ public function createKey(array $params): string { @@ -88,7 +87,80 @@ public function __call($method, $arguments): mixed */ public function get(string $key, mixed $default = null): mixed { - return $this->cacheManager->get($key, $default); + SettingMemoryCache::syncEpoch(); + + if (SettingMemoryCache::isEpochUnreliable()) { + return $default; + } + + if (SettingMemoryCache::exists($key)) { + return SettingMemoryCache::get($key); + } + + $entry = $this->readStoreEntry($key); + if (!$entry['hit']) { + return $default; + } + + SettingMemoryCache::put($key, $entry['value']); + + return $entry['value']; + } + + /** + * Resolve a setting from L1, then Redis, then the loader (typically DB). + * + * @param string $key + * @param callable $loader + * + * @return mixed + */ + public function resolve(string $key, callable $loader): mixed + { + SettingMemoryCache::syncEpoch(); + + // Freshness oracle unavailable: fail closed to DB, do not trust L1/L2. + if (SettingMemoryCache::isEpochUnreliable()) { + return $loader(); + } + + if (SettingMemoryCache::exists($key)) { + return SettingMemoryCache::get($key); + } + + $epochAtStart = SettingMemoryCache::localEpoch(); + $entry = $this->readStoreEntry($key); + + if ($entry['hit']) { + SettingMemoryCache::put($key, $entry['value']); + + return $entry['value']; + } + + $value = $loader(); + + // If another worker published a committed value while we loaded, do not + // overwrite Redis with a possibly pre-commit row. + SettingMemoryCache::forceResyncEpoch(); + if (SettingMemoryCache::isEpochUnreliable()) { + return $value; + } + + if (SettingMemoryCache::localEpoch() !== $epochAtStart) { + $entry = $this->readStoreEntry($key); + if ($entry['hit']) { + $value = $entry['value']; + } else { + $value = $loader(); + $this->writeStoreEntry($key, $value); + } + } else { + $this->writeStoreEntry($key, $value); + } + + SettingMemoryCache::put($key, $value); + + return $value; } /** @@ -125,7 +197,7 @@ public function getOrCache(string $key, callable $callback): mixed } /** - * Store a value in the settings cache. + * Store a committed setting value, then publish a new epoch so other workers refresh L1. * * @param string $key * @param mixed $value @@ -135,7 +207,14 @@ public function getOrCache(string $key, callable $callback): mixed */ public function set(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool { - return $this->cacheManager->put($key, $value, $ttl); + $result = $this->writeStoreEntry($key, $value, $ttl); + + if ($result) { + SettingMemoryCache::bumpEpoch(); + SettingMemoryCache::put($key, $value); + } + + return $result; } /** @@ -147,7 +226,11 @@ public function set(string $key, mixed $value, null|int|\DateInterval $ttl = nul */ public function delete(string $key): bool { - return $this->cacheManager->forget($key); + $result = $this->cacheManager->forget($key); + SettingMemoryCache::forget($key); + SettingMemoryCache::bumpEpoch(); + + return $result; } /** @@ -157,7 +240,10 @@ public function delete(string $key): bool */ public function clear(): bool { - return $this->cacheManager->clear(); + $result = $this->cacheManager->clear(); + SettingMemoryCache::bumpEpochAfterStoreCleared(); + + return $result; } /** @@ -181,6 +267,8 @@ public function clearBy(string $pattern): void if (!empty($matchedKeys)) { Redis::connection($defaultDriver)->del($matchedKeys); } + + SettingMemoryCache::bumpEpoch(); } catch (\Exception $e) { Log::error('SettingCacheException' . $e->getMessage()); @@ -197,6 +285,16 @@ public function clearBy(string $pattern): void */ public function has(string $key): bool { + SettingMemoryCache::syncEpoch(); + + if (SettingMemoryCache::isEpochUnreliable()) { + return false; + } + + if (SettingMemoryCache::exists($key)) { + return true; + } + return $this->keyExists($key); } @@ -213,22 +311,78 @@ public function missing(string $key): bool } /** - * Invalidate a value in the settings cache. + * Drop a settings cache key from Redis/L1. * - * @param string $key + * By default does NOT bump the shared epoch — that must happen after the + * committed value is published via set()/saved()/delete. Pass + * bump_epoch=true for hard invalidations (e.g. deleted settings). + * + * @param array $params * * @return void */ public function invalidate($params): void { try { - //extract the params from the array $key = $params['key']; + $bumpEpoch = (bool) ($params['bump_epoch'] ?? false); + $this->cacheManager->forget($key); + SettingMemoryCache::forget($key); + + if ($bumpEpoch) { + SettingMemoryCache::bumpEpoch(); + } } catch (\Exception $e) { Log::error($e->getMessage()); throw new SettingCacheException('Failed to invalidate cache KEY:' . $key); } } + + /** + * Publish a new shared epoch without changing Redis setting payloads. + */ + public function publishEpoch(): void + { + SettingMemoryCache::bumpEpoch(); + } + + /** + * Expose the underlying cache store (used for tests). + */ + public function store(): Repository + { + return $this->cacheManager; + } + + /** + * @return array{hit: bool, value: mixed} + */ + private function readStoreEntry(string $key): array + { + $sentinel = SettingMemoryCache::sentinel(); + $stored = $this->cacheManager->get($key, $sentinel); + + if ($stored === $sentinel) { + return ['hit' => false, 'value' => null]; + } + + if (is_array($stored) && ($stored[self::ENVELOPE_FLAG] ?? false) === true) { + return ['hit' => true, 'value' => $stored['v']]; + } + + // Legacy unwrapped values written before envelopes. + return ['hit' => true, 'value' => $stored]; + } + + private function writeStoreEntry(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool + { + $envelope = [ + self::ENVELOPE_FLAG => true, + 'v' => $value, + ]; + + return $this->cacheManager->put($key, $envelope, $ttl); + } } diff --git a/ProcessMaker/Cache/Settings/SettingMemoryCache.php b/ProcessMaker/Cache/Settings/SettingMemoryCache.php new file mode 100644 index 0000000000..f903518328 --- /dev/null +++ b/ProcessMaker/Cache/Settings/SettingMemoryCache.php @@ -0,0 +1,310 @@ +> + */ + private static array $items = []; + + /** + * Last known epoch per tenant scope. + * + * @var array + */ + private static array $localEpochs = []; + + /** + * Whether the Redis epoch was synced for the current request per tenant. + * + * @var array + */ + private static array $syncedThisRequest = []; + + /** + * When true, Redis epoch could not be read — skip L1/L2 and use DB. + * + * @var array + */ + private static array $epochUnreliable = []; + + /** + * Identifies the HTTP/console/job scope that last opened an L1 sync scope. + */ + private static int|string|null $activeRequestToken = null; + + private static ?object $sentinel = null; + + /** + * Mark the start of a request/job so the epoch is checked once (lazy) per tenant. + */ + public static function beginRequest(): void + { + self::$syncedThisRequest = []; + self::$epochUnreliable = []; + self::$activeRequestToken = self::currentRequestToken(); + } + + /** + * Sentinel object used to distinguish a cache miss from a cached null. + */ + public static function sentinel(): object + { + return self::$sentinel ??= new class + { + }; + } + + public static function currentTenantKey(): string + { + $tenant = app()->bound('currentTenant') ? app('currentTenant') : null; + + if ($tenant && isset($tenant->id)) { + return (string) $tenant->id; + } + + return 'landlord'; + } + + /** + * Sync local epoch with Redis once per request/tenant; clear L1 on mismatch. + */ + public static function syncEpoch(): void + { + self::ensureRequestScope(); + + $tenantKey = self::currentTenantKey(); + + if (!empty(self::$syncedThisRequest[$tenantKey])) { + return; + } + + $remote = self::fetchRemoteEpoch(); + + if ($remote['unreliable']) { + self::$items[$tenantKey] = []; + self::$epochUnreliable[$tenantKey] = true; + self::$syncedThisRequest[$tenantKey] = true; + + return; + } + + self::$epochUnreliable[$tenantKey] = false; + $remoteEpoch = $remote['epoch']; + $localEpoch = self::$localEpochs[$tenantKey] ?? null; + + if ($localEpoch !== $remoteEpoch) { + self::$items[$tenantKey] = []; + self::$localEpochs[$tenantKey] = $remoteEpoch; + } + + self::$syncedThisRequest[$tenantKey] = true; + } + + /** + * Force a fresh Redis epoch read (used to avoid publishing stale resolve fills). + */ + public static function forceResyncEpoch(): void + { + $tenantKey = self::currentTenantKey(); + unset(self::$syncedThisRequest[$tenantKey]); + self::syncEpoch(); + } + + public static function isEpochUnreliable(): bool + { + self::ensureRequestScope(); + + return !empty(self::$epochUnreliable[self::currentTenantKey()]); + } + + /** + * Open a new sync scope when the HTTP request or job token changes. + */ + private static function ensureRequestScope(): void + { + $token = self::currentRequestToken(); + + if ($token === self::$activeRequestToken) { + return; + } + + self::$syncedThisRequest = []; + self::$epochUnreliable = []; + self::$activeRequestToken = $token; + } + + private static function currentRequestToken(): int|string + { + if (app()->bound('request')) { + $request = app('request'); + if (is_object($request)) { + return spl_object_id($request); + } + } + + return 'console'; + } + + public static function exists(string $key): bool + { + $tenantKey = self::currentTenantKey(); + + return array_key_exists($key, self::$items[$tenantKey] ?? []); + } + + public static function get(string $key): mixed + { + $tenantKey = self::currentTenantKey(); + + return self::$items[$tenantKey][$key] ?? null; + } + + public static function put(string $key, mixed $value): void + { + $tenantKey = self::currentTenantKey(); + self::$items[$tenantKey][$key] = $value; + } + + public static function forget(string $key): void + { + $tenantKey = self::currentTenantKey(); + unset(self::$items[$tenantKey][$key]); + } + + public static function clearLocal(): void + { + $tenantKey = self::currentTenantKey(); + self::$items[$tenantKey] = []; + } + + public static function clearAllLocal(): void + { + self::$items = []; + self::$localEpochs = []; + self::$syncedThisRequest = []; + self::$epochUnreliable = []; + self::$activeRequestToken = null; + } + + /** + * Increment the shared epoch and reset local L1 for the current tenant. + */ + public static function bumpEpoch(): void + { + self::ensureRequestScope(); + + $tenantKey = self::currentTenantKey(); + $newEpoch = self::incrementRemoteEpoch(); + + self::$items[$tenantKey] = []; + self::$localEpochs[$tenantKey] = $newEpoch; + self::$epochUnreliable[$tenantKey] = false; + self::$syncedThisRequest[$tenantKey] = true; + } + + /** + * After the Redis settings store was fully cleared, re-seed a raw epoch + * strictly ahead of any plausible worker-local value. + */ + public static function bumpEpochAfterStoreCleared(): void + { + self::ensureRequestScope(); + + $tenantKey = self::currentTenantKey(); + $local = self::$localEpochs[$tenantKey] ?? 0; + $newEpoch = max($local + 1, (int) (microtime(true) * 1000)); + + try { + self::redis()->set(self::epochRedisKey(), (string) $newEpoch); + } catch (Throwable $e) { + Log::info('SettingMemoryCache: failed to seed epoch after clear: ' . $e->getMessage()); + } + + self::$items[$tenantKey] = []; + self::$localEpochs[$tenantKey] = $newEpoch; + self::$epochUnreliable[$tenantKey] = false; + self::$syncedThisRequest[$tenantKey] = true; + } + + public static function localEpoch(): ?int + { + $tenantKey = self::currentTenantKey(); + + return self::$localEpochs[$tenantKey] ?? null; + } + + /** + * @return array{unreliable: bool, epoch: int} + */ + private static function fetchRemoteEpoch(): array + { + try { + $value = self::redis()->get(self::epochRedisKey()); + + return [ + 'unreliable' => false, + 'epoch' => $value === null || $value === false ? 0 : (int) $value, + ]; + } catch (Throwable $e) { + Log::info('SettingMemoryCache: failed to read epoch: ' . $e->getMessage()); + + return [ + 'unreliable' => true, + 'epoch' => 0, + ]; + } + } + + private static function incrementRemoteEpoch(): int + { + try { + return (int) self::redis()->incr(self::epochRedisKey()); + } catch (Throwable $e) { + Log::info('SettingMemoryCache: failed to increment epoch: ' . $e->getMessage()); + $value = (self::$localEpochs[self::currentTenantKey()] ?? 0) + 1; + + try { + self::redis()->set(self::epochRedisKey(), (string) $value); + } catch (Throwable $inner) { + Log::info('SettingMemoryCache: failed to write epoch: ' . $inner->getMessage()); + } + + return $value; + } + } + + private static function epochRedisKey(): string + { + $prefix = config('cache.stores.cache_settings.prefix', 'settings:'); + + return $prefix . self::EPOCH_KEY; + } + + private static function redis() + { + $connection = config('cache.stores.cache_settings.connection', 'cache_settings'); + + return Redis::connection($connection); + } +} diff --git a/ProcessMaker/Models/Setting.php b/ProcessMaker/Models/Setting.php index 87395b44d8..7625f8ff9a 100644 --- a/ProcessMaker/Models/Setting.php +++ b/ProcessMaker/Models/Setting.php @@ -10,6 +10,7 @@ use Illuminate\Validation\Rule; use Log; use ProcessMaker\Cache\Settings\SettingCacheFactory; +use ProcessMaker\Cache\Settings\SettingCacheManager; use ProcessMaker\Contracts\PrometheusMetricInterface; use ProcessMaker\Traits\ExtendedPMQL; use ProcessMaker\Traits\SerializeToIso8601; @@ -166,16 +167,23 @@ public static function byKey(string $key) $settingKey = $settingCache->createKey([ 'key' => $key, ]); - $exists = $settingCache->has($settingKey); - // if the setting is not in the cache, get it from the database and store it in the cache + // L1 (worker memory) then a single Redis GET, then DB on miss. + if ($settingCache instanceof SettingCacheManager) { + return $settingCache->resolve($settingKey, function () use ($key) { + return (new self)->where('key', $key)->first(); + }); + } + + // Fallback for mocks/decorators that do not expose resolve(). + $exists = $settingCache->has($settingKey); if ($exists) { - $setting = $settingCache->get($settingKey); - } else { - $setting = (new self)->where('key', $key)->first(); - $settingCache->set($settingKey, $setting); + return $settingCache->get($settingKey); } + $setting = (new self)->where('key', $key)->first(); + $settingCache->set($settingKey, $setting); + return $setting; } diff --git a/ProcessMaker/Observers/SettingObserver.php b/ProcessMaker/Observers/SettingObserver.php index e4144ab3fb..187fda1914 100644 --- a/ProcessMaker/Observers/SettingObserver.php +++ b/ProcessMaker/Observers/SettingObserver.php @@ -75,6 +75,30 @@ public function saving(Setting $setting) $this->invalidateSettingCache($setting); } + /** + * After the row is committed, publish a new L1 epoch so other workers refresh. + * + * Epoch is intentionally not bumped in saving() — that races with concurrent + * byKey() loaders that can refill Redis/L1 with the pre-commit value. + * + * @param Setting $setting + * @return void + */ + public function saved(Setting $setting): void + { + $settingCache = SettingCacheFactory::getSettingsCache(); + $key = $settingCache->createKey(['key' => $setting->key]); + // Drop any concurrent resolve() fill that raced before commit, then + // publish epoch so other workers discard L1 and reload committed data. + $settingCache->invalidate([ + 'key' => $key, + 'bump_epoch' => false, + ]); + if (method_exists($settingCache, 'publishEpoch')) { + $settingCache->publishEpoch(); + } + } + /** * Handle the setting "deleted" event. * @@ -83,15 +107,18 @@ public function saving(Setting $setting) */ public function deleted(Setting $setting): void { - $this->invalidateSettingCache($setting); + $this->invalidateSettingCache($setting, true); } - private function invalidateSettingCache(Setting $setting) + private function invalidateSettingCache(Setting $setting, bool $bumpEpoch = false) { $settingCache = SettingCacheFactory::getSettingsCache(); - // Invalidate the setting cache + // Drop Redis/L1 for this key. Epoch publish waits for saved()/set()/delete. $key = $settingCache->createKey(['key' => $setting->key]); - $settingCache->invalidate(['key' => $key]); + $settingCache->invalidate([ + 'key' => $key, + 'bump_epoch' => $bumpEpoch, + ]); // Check to see if we already added the refresh to the app's terminating queue. // This is important for install commands when multiple settings are being created/updated. diff --git a/ProcessMaker/Octane/ResetRequestState.php b/ProcessMaker/Octane/ResetRequestState.php index 45071e97ad..9b61f28d14 100644 --- a/ProcessMaker/Octane/ResetRequestState.php +++ b/ProcessMaker/Octane/ResetRequestState.php @@ -4,6 +4,7 @@ namespace ProcessMaker\Octane; +use ProcessMaker\Cache\Settings\SettingMemoryCache; use ProcessMaker\Listeners\HandleRedirectListener; use ProcessMaker\Providers\ProcessMakerServiceProvider; @@ -13,5 +14,8 @@ public function handle(): void { ProcessMakerServiceProvider::beginRequestTiming(); HandleRedirectListener::reset(); + // Allow the settings L1 epoch to be re-checked once per request without + // dropping the in-memory map when the epoch is unchanged. + SettingMemoryCache::beginRequest(); } } diff --git a/ProcessMaker/Providers/ProcessMakerServiceProvider.php b/ProcessMaker/Providers/ProcessMakerServiceProvider.php index aa62d8e7e9..70731f814f 100644 --- a/ProcessMaker/Providers/ProcessMakerServiceProvider.php +++ b/ProcessMaker/Providers/ProcessMakerServiceProvider.php @@ -19,6 +19,7 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\URL; use Illuminate\Support\Facades\Vite; @@ -32,6 +33,7 @@ use OpenApi\Analysers\DocBlockAnnotationFactory; use OpenApi\Analysers\ReflectionAnalyser; use ProcessMaker\Cache\Settings\SettingCacheManager; +use ProcessMaker\Cache\Settings\SettingMemoryCache; use ProcessMaker\Console\Commands\HorizonListen; use ProcessMaker\Console\Migration\ExtendedMigrateCommand; use ProcessMaker\Contracts\ConditionalRedirectServiceInterface; @@ -118,6 +120,9 @@ public function boot(): void // Register Octane listeners if Octane is enabled $this->registerOctaneListeners(); + // Re-check settings L1 epoch at the start of each queued job + $this->registerSettingsCacheJobListeners(); + // Hook after service providers boot self::$bootTime = (microtime(true) - self::$bootStart) * 1000; // Convert to milliseconds } @@ -604,6 +609,17 @@ private function registerOctaneListeners(): void Event::listen(RequestTerminated::class, ResetRequestState::class); } + /** + * Reset settings L1 epoch sync scope at the start of each queued job so + * Horizon/queue:work workers re-check Redis instead of serving a sticky map. + */ + private function registerSettingsCacheJobListeners(): void + { + Queue::before(function () { + SettingMemoryCache::beginRequest(); + }); + } + /** * Find the tenant based on the environment variable */ diff --git a/tests/Feature/Cache/SettingCacheTest.php b/tests/Feature/Cache/SettingCacheTest.php index 7b9afb9d6b..2e5c78fa70 100644 --- a/tests/Feature/Cache/SettingCacheTest.php +++ b/tests/Feature/Cache/SettingCacheTest.php @@ -7,6 +7,7 @@ use Illuminate\Support\Facades\Redis; use ProcessMaker\Cache\Settings\SettingCacheException; use ProcessMaker\Cache\Settings\SettingCacheFactory; +use ProcessMaker\Cache\Settings\SettingMemoryCache; use ProcessMaker\Models\Setting; use ProcessMaker\Models\User; use Tests\Feature\Shared\RequestHelper; @@ -20,6 +21,9 @@ protected function setUp(): void { parent::setUp(); + SettingMemoryCache::clearAllLocal(); + SettingMemoryCache::beginRequest(); + $this->user = User::factory()->create([ 'is_administrator' => true, ]); diff --git a/tests/Feature/Cache/SettingMemoryCacheTest.php b/tests/Feature/Cache/SettingMemoryCacheTest.php new file mode 100644 index 0000000000..7182d4201f --- /dev/null +++ b/tests/Feature/Cache/SettingMemoryCacheTest.php @@ -0,0 +1,309 @@ +seedEpoch(0); + } + + protected function tearDown(): void + { + SettingMemoryCache::clearAllLocal(); + parent::tearDown(); + } + + private function seedEpoch(int $epoch): void + { + $prefix = config('cache.stores.cache_settings.prefix', 'settings:'); + $connection = config('cache.stores.cache_settings.connection', 'cache_settings'); + Redis::connection($connection)->set($prefix . SettingMemoryCache::EPOCH_KEY, (string) $epoch); + } + + private function remoteEpoch(): int + { + $prefix = config('cache.stores.cache_settings.prefix', 'settings:'); + $connection = config('cache.stores.cache_settings.connection', 'cache_settings'); + + return (int) Redis::connection($connection)->get($prefix . SettingMemoryCache::EPOCH_KEY); + } + + public function testL1HitAvoidsSecondRedisReadForSameKey(): void + { + $setting = Setting::factory()->create([ + 'key' => 'l1.hit.test', + 'config' => true, + 'format' => 'boolean', + ]); + + /** @var SettingCacheManager $cache */ + $cache = SettingCacheFactory::getSettingsCache(); + $cacheKey = $cache->createKey(['key' => $setting->key]); + + $first = Setting::byKey($setting->key); + $this->assertNotNull($first); + $this->assertTrue(SettingMemoryCache::exists($cacheKey)); + + Cache::store('cache_settings')->forget($cacheKey); + + $second = Setting::byKey($setting->key); + $this->assertNotNull($second); + $this->assertEquals($setting->key, $second->key); + $this->assertEquals($first->config, $second->config); + } + + public function testIntraRequestMemoizationForRepeatedByKeyCalls(): void + { + $setting = Setting::factory()->create([ + 'key' => 'l1.memo.test', + 'config' => ['value' => 1], + 'format' => 'object', + ]); + + $cacheKey = SettingCacheFactory::getSettingsCache()->createKey(['key' => $setting->key]); + + Setting::byKey($setting->key); + $this->assertTrue(SettingMemoryCache::exists($cacheKey)); + + for ($i = 0; $i < 10; $i++) { + $resolved = Setting::byKey($setting->key); + $this->assertNotNull($resolved); + $this->assertEquals($setting->key, $resolved->key); + } + } + + public function testEpochBumpClearsL1ForSubsequentRequest(): void + { + $setting = Setting::factory()->create([ + 'key' => 'l1.epoch.test', + 'config' => 1, + 'format' => 'boolean', + ]); + + /** @var SettingCacheManager $cache */ + $cache = SettingCacheFactory::getSettingsCache(); + $cacheKey = $cache->createKey(['key' => $setting->key]); + + Setting::byKey($setting->key); + $this->assertTrue(SettingMemoryCache::exists($cacheKey)); + + $cache->set($cacheKey, $setting); + $this->assertTrue(SettingMemoryCache::exists($cacheKey)); + + SettingMemoryCache::clearAllLocal(); + Cache::store('cache_settings')->put($cacheKey, [ + '__pm_setting' => true, + 'v' => $setting, + ]); + SettingMemoryCache::put($cacheKey, $setting); + + $reflected = new \ReflectionClass(SettingMemoryCache::class); + $localEpochs = $reflected->getProperty('localEpochs'); + $localEpochs->setAccessible(true); + $localEpochs->setValue(null, [SettingMemoryCache::currentTenantKey() => 0]); + + SettingMemoryCache::beginRequest(); + Setting::byKey($setting->key); + + $this->assertTrue(SettingMemoryCache::exists($cacheKey)); + $this->assertSame($this->remoteEpoch(), SettingMemoryCache::localEpoch()); + } + + public function testSetIncrementsSharedEpoch(): void + { + /** @var SettingCacheManager $cache */ + $cache = SettingCacheFactory::getSettingsCache(); + $this->seedEpoch(5); + SettingMemoryCache::beginRequest(); + SettingMemoryCache::syncEpoch(); + $this->assertSame(5, SettingMemoryCache::localEpoch()); + + $cache->set('setting_any.key', 'value'); + + $this->assertSame(6, $this->remoteEpoch()); + $this->assertSame(6, SettingMemoryCache::localEpoch()); + } + + public function testInvalidateWithoutBumpDoesNotAdvanceEpoch(): void + { + /** @var SettingCacheManager $cache */ + $cache = SettingCacheFactory::getSettingsCache(); + $this->seedEpoch(5); + SettingMemoryCache::beginRequest(); + SettingMemoryCache::syncEpoch(); + + $cache->invalidate(['key' => 'setting_any.key']); + + $this->assertSame(5, $this->remoteEpoch()); + } + + public function testClearSeedsNewEpochAndClearsL1(): void + { + /** @var SettingCacheManager $cache */ + $cache = SettingCacheFactory::getSettingsCache(); + $cache->set('setting_clear.test', 'value'); + $this->assertTrue(SettingMemoryCache::exists('setting_clear.test')); + + $cache->clear(); + + $this->assertFalse(SettingMemoryCache::exists('setting_clear.test')); + $this->assertNull($cache->get('setting_clear.test')); + $this->assertGreaterThan(0, $this->remoteEpoch()); + } + + public function testTenantScopesAreIsolatedInL1(): void + { + $cacheKey = 'setting_tenant.isolation'; + + app()->instance('currentTenant', (object) ['id' => 1]); + SettingMemoryCache::beginRequest(); + SettingMemoryCache::put($cacheKey, 'tenant-1-value'); + + app()->instance('currentTenant', (object) ['id' => 2]); + SettingMemoryCache::beginRequest(); + $this->assertFalse(SettingMemoryCache::exists($cacheKey)); + SettingMemoryCache::put($cacheKey, 'tenant-2-value'); + + app()->instance('currentTenant', (object) ['id' => 1]); + SettingMemoryCache::beginRequest(); + $this->assertTrue(SettingMemoryCache::exists($cacheKey)); + $this->assertSame('tenant-1-value', SettingMemoryCache::get($cacheKey)); + + app()->instance('currentTenant', (object) ['id' => 2]); + SettingMemoryCache::beginRequest(); + $this->assertSame('tenant-2-value', SettingMemoryCache::get($cacheKey)); + + app()->forgetInstance('currentTenant'); + } + + public function testResetRequestStateAllowsEpochRecheckWithoutDroppingHotL1(): void + { + /** @var SettingCacheManager $cache */ + $cache = SettingCacheFactory::getSettingsCache(); + $this->seedEpoch(1); + SettingMemoryCache::syncEpoch(); + SettingMemoryCache::put('setting_hot', 'hot-value'); + + (new ResetRequestState())->handle(); + + SettingMemoryCache::syncEpoch(); + $this->assertTrue(SettingMemoryCache::exists('setting_hot')); + $this->assertSame('hot-value', SettingMemoryCache::get('setting_hot')); + } + + public function testNewHttpRequestResyncsEpochWithoutResetRequestState(): void + { + $setting = Setting::factory()->create([ + 'key' => 'l1.fpm.stale', + 'config' => 'old-color', + 'format' => 'text', + ]); + + /** @var SettingCacheManager $cache */ + $cache = SettingCacheFactory::getSettingsCache(); + $cacheKey = $cache->createKey(['key' => $setting->key]); + + $requestOne = Request::create('/login', 'GET'); + app()->instance('request', $requestOne); + Setting::byKey($setting->key); + $this->assertTrue(SettingMemoryCache::exists($cacheKey)); + $this->assertSame('old-color', SettingMemoryCache::get($cacheKey)->config); + + $setting->config = 'new-color'; + $setting->saveQuietly(); + $cache->set($cacheKey, $setting->fresh()); + + $requestTwo = Request::create('/login', 'GET'); + $this->assertNotSame(spl_object_id($requestOne), spl_object_id($requestTwo)); + app()->instance('request', $requestTwo); + + $resolved = Setting::byKey($setting->key); + + $this->assertNotNull($resolved); + $this->assertSame('new-color', $resolved->config); + $this->assertSame('new-color', SettingMemoryCache::get($cacheKey)->config); + } + + public function testCachedNullDoesNotHitDatabaseAcrossEpochFlush(): void + { + $key = 'l1.null.cached'; + $cacheKey = 'setting_' . $key; + + /** @var SettingCacheManager $cache */ + $cache = SettingCacheFactory::getSettingsCache(); + $cache->set($cacheKey, null); + + // New request scope + matching epoch still serves null from Redis envelope (no DB). + SettingMemoryCache::clearAllLocal(); + SettingMemoryCache::beginRequest(); + + DB::enableQueryLog(); + DB::flushQueryLog(); + + $setting = Setting::byKey($key); + + $this->assertNull($setting); + $this->assertCount(0, DB::getQueryLog()); + } + + public function testSavedPublishesEpochAfterCommitNotDuringSaving(): void + { + $setting = Setting::factory()->create([ + 'key' => 'l1.race.setting', + 'config' => 'old', + 'format' => 'text', + ]); + + /** @var SettingCacheManager $cache */ + $cache = SettingCacheFactory::getSettingsCache(); + $cacheKey = $cache->createKey(['key' => $setting->key]); + $cache->set($cacheKey, $setting); + $epochAfterSet = $this->remoteEpoch(); + + $setting->config = 'new'; + $setting->save(); + + // saved() publishes epoch after commit + $this->assertGreaterThan($epochAfterSet, $this->remoteEpoch()); + + // Redis key dropped by saved(); committed value comes from DB until set(). + SettingMemoryCache::clearAllLocal(); + SettingMemoryCache::beginRequest(); + $resolved = Setting::byKey($setting->key); + $this->assertSame('new', $resolved->config); + } + + public function testJobBeginRequestResyncsEpoch(): void + { + /** @var SettingCacheManager $cache */ + $cache = SettingCacheFactory::getSettingsCache(); + $this->seedEpoch(1); + SettingMemoryCache::syncEpoch(); + SettingMemoryCache::put('setting_job', 'stale'); + + // Simulate Horizon starting another job (Queue::before → beginRequest). + SettingMemoryCache::beginRequest(); + $this->seedEpoch(2); + + SettingMemoryCache::syncEpoch(); + $this->assertFalse(SettingMemoryCache::exists('setting_job')); + $this->assertSame(2, SettingMemoryCache::localEpoch()); + } +}