Skip to content

Commit 061a1f3

Browse files
committed
fix: make expiration conditional on successful save in Redis and Predis handlers
Execute HMSET and EXPIREAT atomically via a Lua script so that EXPIREAT is never executed when HMSET fails (e.g. WRONGTYPE error on non-hash keys). Falls back to sequential execution if EVAL is unsupported or blocked. Adds regression tests verifying non-hash keys preserve value and TTL.
1 parent ca12cf0 commit 061a1f3

4 files changed

Lines changed: 159 additions & 16 deletions

File tree

‎system/Cache/Handlers/PredisHandler.php‎

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,26 @@
2020
use Predis\Client;
2121
use Predis\Collection\Iterator\Keyspace;
2222
use Predis\Response\Status;
23+
use Throwable;
2324

2425
/**
2526
* Predis cache handler
2627
*/
2728
class PredisHandler extends BaseHandler
2829
{
30+
/**
31+
* Lua script to conditionally execute HMSET and EXPIREAT in a single round trip.
32+
* Prevents EXPIREAT from mutating TTL or expiring keys when HMSET fails (e.g. WRONGTYPE).
33+
*/
34+
private const SAVE_SCRIPT = <<<'LUA'
35+
local res = redis.pcall('HMSET', KEYS[1], '__ci_type', ARGV[2], '__ci_value', ARGV[3])
36+
if type(res) == 'table' and res.err then
37+
return 0
38+
end
39+
redis.call('EXPIREAT', KEYS[1], ARGV[1])
40+
return 1
41+
LUA;
42+
2943
/**
3044
* Default config
3145
*
@@ -121,14 +135,27 @@ public function save(string $key, mixed $value, int $ttl = 60): bool
121135
$fields = ['__ci_type' => $dataType, '__ci_value' => $value];
122136

123137
if ($ttl !== 0) {
124-
// Send HMSET and EXPIREAT in a single round trip.
125138
$expiresAt = Time::now()->getTimestamp() + $ttl;
126-
$results = $this->redis->pipeline(static function ($pipe) use ($key, $fields, $expiresAt): void {
127-
$pipe->hmset($key, $fields);
128-
$pipe->expireat($key, $expiresAt);
129-
});
130139

131-
return is_array($results) && ($results[0] ?? null) instanceof Status;
140+
try {
141+
return (bool) $this->redis->eval(
142+
self::SAVE_SCRIPT,
143+
1,
144+
$key,
145+
(string) $expiresAt,
146+
$dataType,
147+
(string) $value,
148+
);
149+
} catch (Throwable) {
150+
// If EVAL is unsupported or blocked, fallback to sequential execution.
151+
if (! $this->redis->hmset($key, $fields) instanceof Status) {
152+
return false;
153+
}
154+
155+
$this->redis->expireat($key, $expiresAt);
156+
157+
return true;
158+
}
132159
}
133160

134161
return $this->redis->hmset($key, $fields) instanceof Status;

‎system/Cache/Handlers/RedisHandler.php‎

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,26 @@
1818
use Config\Cache;
1919
use Redis;
2020
use RedisException;
21+
use Throwable;
2122

2223
/**
2324
* Redis cache handler
2425
*/
2526
class RedisHandler extends BaseHandler
2627
{
28+
/**
29+
* Lua script to conditionally execute HMSET and EXPIREAT in a single round trip.
30+
* Prevents EXPIREAT from mutating TTL or expiring keys when HMSET fails (e.g. WRONGTYPE).
31+
*/
32+
private const SAVE_SCRIPT = <<<'LUA'
33+
local res = redis.pcall('HMSET', KEYS[1], '__ci_type', ARGV[2], '__ci_value', ARGV[3])
34+
if type(res) == 'table' and res.err then
35+
return 0
36+
end
37+
redis.call('EXPIREAT', KEYS[1], ARGV[1])
38+
return 1
39+
LUA;
40+
2741
/**
2842
* Default config
2943
*
@@ -137,18 +151,22 @@ public function save(string $key, mixed $value, int $ttl = 60): bool
137151
$fields = ['__ci_type' => $dataType, '__ci_value' => $value];
138152

139153
if ($ttl !== 0) {
140-
// Send HMSET and EXPIREAT in a single round trip.
141-
$pipeline = $this->redis->multi(Redis::PIPELINE);
154+
$expiresAt = Time::now()->getTimestamp() + $ttl;
142155

143-
if ($pipeline === false) {
144-
return false;
156+
try {
157+
return (bool) $this->redis->eval(
158+
self::SAVE_SCRIPT,
159+
[$key, $expiresAt, $dataType, (string) $value],
160+
1,
161+
);
162+
} catch (Throwable) {
163+
// If EVAL is unsupported or blocked, fallback to sequential execution.
164+
if (! $this->redis->hMset($key, $fields)) {
165+
return false;
166+
}
167+
168+
return $this->redis->expireAt($key, $expiresAt);
145169
}
146-
147-
$pipeline->hMset($key, $fields);
148-
$pipeline->expireAt($key, Time::now()->getTimestamp() + $ttl);
149-
$results = $pipeline->exec();
150-
151-
return is_array($results) && (bool) ($results[0] ?? false);
152170
}
153171

154172
return (bool) $this->redis->hMset($key, $fields);

‎tests/system/Cache/Handlers/PredisHandlerTest.php‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
use CodeIgniter\I18n\Time;
1919
use Config\Cache;
2020
use PHPUnit\Framework\Attributes\Group;
21+
use Predis\Client;
22+
use RuntimeException;
2123

2224
/**
2325
* @internal
@@ -196,4 +198,52 @@ public function testReconnect(): void
196198

197199
$this->assertSame('value', $this->handler->get(self::$key1));
198200
}
201+
202+
public function testSaveFailsOnNonHashKeyPreservingValueAndTtl(): void
203+
{
204+
/** @var Client $redis */
205+
$redis = $this->getPrivateProperty($this->handler, 'redis');
206+
207+
$prefixedKey = $this->config->prefix . 'non_hash_key';
208+
$redis->set($prefixedKey, 'raw_string_value');
209+
$redis->expire($prefixedKey, 300);
210+
211+
$this->assertFalse($this->handler->save('non_hash_key', 'new_value', 60));
212+
213+
$this->assertSame('raw_string_value', $redis->get($prefixedKey));
214+
$this->assertGreaterThan(250, $redis->ttl($prefixedKey));
215+
216+
// Handler remains usable for subsequent operations
217+
$this->assertTrue($this->handler->save(self::$key1, 'usable_value'));
218+
$this->assertSame('usable_value', $this->handler->get(self::$key1));
219+
220+
$redis->del([$prefixedKey]);
221+
}
222+
223+
public function testSaveFallbackWhenEvalThrowsException(): void
224+
{
225+
/** @var Client $originalClient */
226+
$originalClient = $this->getPrivateProperty($this->handler, 'redis');
227+
228+
$failingClient = new class ($originalClient->getConnection()->getParameters()) extends Client {
229+
/**
230+
* @param string $script
231+
* @param int $numkeys
232+
* @param mixed ...$arguments
233+
*/
234+
public function eval($script, $numkeys, ...$arguments): never
235+
{
236+
throw new RuntimeException('ERR unknown command EVAL');
237+
}
238+
};
239+
240+
try {
241+
$this->setPrivateProperty($this->handler, 'redis', $failingClient);
242+
243+
$this->assertTrue($this->handler->save(self::$key1, 'fallback_value', 120));
244+
$this->assertSame('fallback_value', $this->handler->get(self::$key1));
245+
} finally {
246+
$this->setPrivateProperty($this->handler, 'redis', $originalClient);
247+
}
248+
}
199249
}

‎tests/system/Cache/Handlers/RedisHandlerTest.php‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
use Config\Cache;
2020
use PHPUnit\Framework\Attributes\DataProvider;
2121
use PHPUnit\Framework\Attributes\Group;
22+
use Redis;
23+
use RedisException;
2224

2325
/**
2426
* @internal
@@ -238,4 +240,50 @@ public function testReconnect(): void
238240

239241
$this->assertSame('value', $this->handler->get(self::$key1));
240242
}
243+
244+
public function testSaveFailsOnNonHashKeyPreservingValueAndTtl(): void
245+
{
246+
/** @var Redis $redis */
247+
$redis = $this->getPrivateProperty($this->handler, 'redis');
248+
249+
$prefixedKey = $this->config->prefix . 'non_hash_key';
250+
$redis->set($prefixedKey, 'raw_string_value');
251+
$redis->expire($prefixedKey, 300);
252+
253+
$this->assertFalse($this->handler->save('non_hash_key', 'new_value', 60));
254+
255+
$this->assertSame('raw_string_value', $redis->get($prefixedKey));
256+
$this->assertGreaterThan(250, $redis->ttl($prefixedKey));
257+
258+
// Handler remains usable for subsequent operations
259+
$this->assertTrue($this->handler->save(self::$key1, 'usable_value'));
260+
$this->assertSame('usable_value', $this->handler->get(self::$key1));
261+
262+
$redis->del($prefixedKey);
263+
}
264+
265+
public function testSaveFallbackWhenEvalThrowsException(): void
266+
{
267+
/** @var Redis $originalRedis */
268+
$originalRedis = $this->getPrivateProperty($this->handler, 'redis');
269+
270+
$failingRedis = $this->createMock(Redis::class);
271+
$failingRedis->expects($this->once())
272+
->method('eval')
273+
->willThrowException(new RedisException('ERR unknown command EVAL'));
274+
$failingRedis->expects($this->once())
275+
->method('hMset')
276+
->willReturn(true);
277+
$failingRedis->expects($this->once())
278+
->method('expireAt')
279+
->willReturn(true);
280+
281+
try {
282+
$this->setPrivateProperty($this->handler, 'redis', $failingRedis);
283+
284+
$this->assertTrue($this->handler->save(self::$key1, 'fallback_value', 120));
285+
} finally {
286+
$this->setPrivateProperty($this->handler, 'redis', $originalRedis);
287+
}
288+
}
241289
}

0 commit comments

Comments
 (0)