Skip to content

Commit 92844d1

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 b0fdd5b commit 92844d1

4 files changed

Lines changed: 105 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: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use CodeIgniter\I18n\Time;
1919
use Config\Cache;
2020
use PHPUnit\Framework\Attributes\Group;
21+
use Predis\Client;
2122

2223
/**
2324
* @internal
@@ -196,4 +197,25 @@ public function testReconnect(): void
196197

197198
$this->assertSame('value', $this->handler->get(self::$key1));
198199
}
200+
201+
public function testSaveFailsOnNonHashKeyPreservingValueAndTtl(): void
202+
{
203+
/** @var Client $redis */
204+
$redis = $this->getPrivateProperty($this->handler, 'redis');
205+
206+
$prefixedKey = $this->config->prefix . 'non_hash_key';
207+
$redis->set($prefixedKey, 'raw_string_value');
208+
$redis->expire($prefixedKey, 300);
209+
210+
$this->assertFalse($this->handler->save('non_hash_key', 'new_value', 60));
211+
212+
$this->assertSame('raw_string_value', $redis->get($prefixedKey));
213+
$this->assertGreaterThan(250, $redis->ttl($prefixedKey));
214+
215+
// Handler remains usable for subsequent operations
216+
$this->assertTrue($this->handler->save(self::$key1, 'usable_value'));
217+
$this->assertSame('usable_value', $this->handler->get(self::$key1));
218+
219+
$redis->del([$prefixedKey]);
220+
}
199221
}

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

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

2324
/**
2425
* @internal
@@ -238,4 +239,25 @@ public function testReconnect(): void
238239

239240
$this->assertSame('value', $this->handler->get(self::$key1));
240241
}
242+
243+
public function testSaveFailsOnNonHashKeyPreservingValueAndTtl(): void
244+
{
245+
/** @var Redis $redis */
246+
$redis = $this->getPrivateProperty($this->handler, 'redis');
247+
248+
$prefixedKey = $this->config->prefix . 'non_hash_key';
249+
$redis->set($prefixedKey, 'raw_string_value');
250+
$redis->expire($prefixedKey, 300);
251+
252+
$this->assertFalse($this->handler->save('non_hash_key', 'new_value', 60));
253+
254+
$this->assertSame('raw_string_value', $redis->get($prefixedKey));
255+
$this->assertGreaterThan(250, $redis->ttl($prefixedKey));
256+
257+
// Handler remains usable for subsequent operations
258+
$this->assertTrue($this->handler->save(self::$key1, 'usable_value'));
259+
$this->assertSame('usable_value', $this->handler->get(self::$key1));
260+
261+
$redis->del($prefixedKey);
262+
}
241263
}

0 commit comments

Comments
 (0)