diff --git a/src/Cache/Adapter/Redis.php b/src/Cache/Adapter/Redis.php index 67dd8ee979..ae14401f98 100644 --- a/src/Cache/Adapter/Redis.php +++ b/src/Cache/Adapter/Redis.php @@ -55,6 +55,20 @@ class Redis implements Adapter, Leasable, Retryable return removed LUA; + /** + * Delete a single $hash field and advance the key's generation in one step, + * so a field-level purge invalidates in-flight leases just like a full purge. + * Returns the number of fields removed, preserving purge()'s deletion-result + * semantics. Single-key. KEYS[1]=key; ARGV[1]=field. + */ + private const LUA_PURGE_FIELD = <<<'LUA' + local removed = redis.call('HDEL', KEYS[1], ARGV[1]) + local current = redis.call('HGET', KEYS[1], '__utopia_gen__') + local next = (tonumber(current) or 0) + 1 + redis.call('HSET', KEYS[1], '__utopia_gen__', next) + return removed + LUA; + /** * @var Client */ @@ -293,7 +307,11 @@ class Redis implements Adapter, Leasable, Retryable return false; } - return (bool) $this->execute(fn () => $this->redis->hdel($key, $hash)); + return (bool) $this->execute(fn () => $this->redis->eval( + self::LUA_PURGE_FIELD, + [$key, $hash], + 1 + )); } // Drop the value fields and advance the in-hash generation in one atomic diff --git a/tests/Cache/E2E/Redis/LeasableTest.php b/tests/Cache/E2E/Redis/LeasableTest.php index 187c352131..e33ac11aae 100644 --- a/tests/Cache/E2E/Redis/LeasableTest.php +++ b/tests/Cache/E2E/Redis/LeasableTest.php @@ -41,6 +41,22 @@ class LeasableTest extends TestCase $this->assertNotSame($before, $this->cache->getGeneration('doc:1')); } + public function testHashPurgeAdvancesGeneration(): void + { + $captured = $this->cache->getGeneration('doc:1'); + $this->assertNotFalse($this->cache->saveWithLease('doc:1', ['v' => 1], 'field-a', $captured)); + + // A field-level purge must advance the per-key generation, just like a + // full purge, or the lease is bypassed for hashed entries. + $this->assertTrue($this->cache->purge('doc:1', 'field-a')); + $this->assertNotSame($captured, $this->cache->getGeneration('doc:1')); + + // A reader holding the pre-purge generation can no longer re-cache a + // stale field via saveWithLease. + $this->assertFalse($this->cache->saveWithLease('doc:1', ['stale' => true], 'field-a', $captured)); + $this->assertFalse($this->cache->load('doc:1', 60, 'field-a')); + } + /** * The core read-after-write guarantee: a reader that captured the generation * BEFORE a concurrent purge must NOT be able to re-cache its now-stale value