Skip to content

Commit c259550

Browse files
committed
fix(Cache): preserve client error behaviour in atomic Redis save
Return the pcall error reply from the Lua script instead of 0, so HMSET errors keep their original message and type, and detect an unavailable or denied EVAL via clearLastError()/getLastError() instead of treating every failure as a reason to retry the write. PredisHandler now falls back to sequential writes only when the server reports an unavailable or denied EVAL, and rethrows every other server error without issuing a second HMSET/EXPIREAT. Restore the pre-PR return semantics of the sequential fallback, cover WRONGTYPE, NOPERM (hmset and eval), a stale last error and a prefixed key with regression tests, and document the partial-write behaviour when EXPIREAT is rejected.
1 parent c92b6e0 commit c259550

4 files changed

Lines changed: 482 additions & 72 deletions

File tree

‎system/Cache/Handlers/PredisHandler.php‎

Lines changed: 51 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919
use Exception;
2020
use Predis\Client;
2121
use Predis\Collection\Iterator\Keyspace;
22+
use Predis\Response\ServerException;
2223
use Predis\Response\Status;
23-
use Throwable;
2424

2525
/**
2626
* Predis cache handler
@@ -29,11 +29,20 @@ class PredisHandler extends BaseHandler
2929
{
3030
/**
3131
* Lua script to execute HMSET and EXPIREAT in a single round trip.
32-
* An HMSET error (e.g. WRONGTYPE) aborts the script before EXPIREAT runs and
33-
* is propagated to the client as an exception reply.
32+
*
33+
* The pcall error reply is returned to the client, so an HMSET error (e.g.
34+
* WRONGTYPE) never runs EXPIREAT, keeps its original error type, and is not
35+
* retried by the sequential fallback in save().
36+
*
37+
* If HMSET succeeds and EXPIREAT is rejected, the hash is stored without a
38+
* TTL, exactly as with the previous sequential implementation (Redis does
39+
* not roll back script effects).
3440
*/
3541
private const SAVE_SCRIPT = <<<'LUA'
36-
redis.call('HMSET', KEYS[1], '__ci_type', ARGV[2], '__ci_value', ARGV[3])
42+
local res = redis.pcall('HMSET', KEYS[1], '__ci_type', ARGV[2], '__ci_value', ARGV[3])
43+
if type(res) == 'table' and res.err then
44+
return res
45+
end
3746
redis.call('EXPIREAT', KEYS[1], ARGV[1])
3847
return 1
3948
LUA;
@@ -132,31 +141,47 @@ public function save(string $key, mixed $value, int $ttl = 60): bool
132141

133142
$fields = ['__ci_type' => $dataType, '__ci_value' => $value];
134143

135-
if ($ttl !== 0) {
136-
$expiresAt = Time::now()->getTimestamp() + $ttl;
137-
138-
try {
139-
return (bool) $this->redis->eval(
140-
self::SAVE_SCRIPT,
141-
1,
142-
$key,
143-
(string) $expiresAt,
144-
$dataType,
145-
(string) $value,
146-
);
147-
} catch (Throwable) {
148-
// If EVAL is unsupported or blocked, fallback to sequential execution.
149-
if (! $this->redis->hmset($key, $fields) instanceof Status) {
150-
return false;
151-
}
152-
153-
$this->redis->expireat($key, $expiresAt);
154-
155-
return true;
144+
if ($ttl === 0) {
145+
return $this->redis->hmset($key, $fields) instanceof Status;
146+
}
147+
148+
$expiresAt = Time::now()->getTimestamp() + $ttl;
149+
150+
try {
151+
return (bool) $this->redis->eval(
152+
self::SAVE_SCRIPT,
153+
1,
154+
$key,
155+
(string) $expiresAt,
156+
$dataType,
157+
(string) $value,
158+
);
159+
} catch (ServerException $e) {
160+
if (! self::isEvalUnavailable($e->getMessage())) {
161+
throw $e;
156162
}
157163
}
158164

159-
return $this->redis->hmset($key, $fields) instanceof Status;
165+
// EVAL is unavailable (renamed command or ACL denial): run both commands sequentially.
166+
if (! $this->redis->hmset($key, $fields) instanceof Status) {
167+
return false;
168+
}
169+
170+
$this->redis->expireat($key, $expiresAt);
171+
172+
return true;
173+
}
174+
175+
/**
176+
* Checks whether the exception only means that the EVAL command itself is not
177+
* available to this client, either because it was renamed or because ACL denies it.
178+
*
179+
* Keep the patterns in sync with RedisHandler::isEvalUnavailable().
180+
*/
181+
private static function isEvalUnavailable(string $message): bool
182+
{
183+
return preg_match("/unknown command [`']?eval\\b/i", $message) === 1
184+
|| preg_match("/no permissions to run the [`']eval[`'] command/i", $message) === 1;
160185
}
161186

162187
public function delete(string $key): bool

‎system/Cache/Handlers/RedisHandler.php‎

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

2322
/**
2423
* Redis cache handler
2524
*/
2625
class RedisHandler extends BaseHandler
2726
{
2827
/**
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).
28+
* Lua script to execute HMSET and EXPIREAT in a single round trip.
29+
*
30+
* The pcall error reply is returned to the client, so a failing HMSET never
31+
* runs EXPIREAT and the original error message and type are preserved:
32+
* clients that throw on error replies raise RedisException, phpredis exposes
33+
* the message through Redis::getLastError().
34+
*
35+
* If HMSET succeeds and EXPIREAT is rejected, the hash is stored without a
36+
* TTL, exactly as with the previous sequential implementation (Redis does
37+
* not roll back script effects).
3138
*/
3239
private const SAVE_SCRIPT = <<<'LUA'
3340
local res = redis.pcall('HMSET', KEYS[1], '__ci_type', ARGV[2], '__ci_value', ARGV[3])
3441
if type(res) == 'table' and res.err then
35-
return 0
42+
return res
3643
end
3744
redis.call('EXPIREAT', KEYS[1], ARGV[1])
3845
return 1
@@ -150,34 +157,63 @@ public function save(string $key, mixed $value, int $ttl = 60): bool
150157

151158
$fields = ['__ci_type' => $dataType, '__ci_value' => $value];
152159

153-
if ($ttl !== 0) {
154-
$expiresAt = Time::now()->getTimestamp() + $ttl;
160+
if ($ttl === 0) {
161+
return (bool) $this->redis->hMset($key, $fields);
162+
}
163+
164+
$expiresAt = Time::now()->getTimestamp() + $ttl;
155165

156-
try {
157-
$result = $this->redis->eval(
158-
self::SAVE_SCRIPT,
159-
[$key, $expiresAt, $dataType, (string) $value],
160-
1,
161-
);
162-
163-
// phpredis returns false when EVAL is unavailable (e.g. disabled via
164-
// rename-command). Integer 0 means HMSET failed inside the script and
165-
// must not trigger the fallback.
166-
if ($result !== false) {
167-
return (bool) $result;
168-
}
169-
} catch (Throwable) {
170-
// If EVAL is unsupported or blocked, fallback to sequential execution.
166+
$shouldFallback = false;
167+
168+
$this->redis->clearLastError();
169+
170+
try {
171+
$result = $this->redis->eval(
172+
self::SAVE_SCRIPT,
173+
[$key, (string) $expiresAt, $dataType, (string) $value],
174+
1,
175+
);
176+
177+
if ($result !== false) {
178+
return (bool) $result;
171179
}
172180

173-
if (! $this->redis->hMset($key, $fields)) {
174-
return false;
181+
// phpredis reports server errors as false and keeps the message in getLastError().
182+
$error = $this->redis->getLastError();
183+
184+
$shouldFallback = is_string($error) && self::isEvalUnavailable($error);
185+
} catch (RedisException $e) {
186+
if (! self::isEvalUnavailable($e->getMessage())) {
187+
throw $e;
175188
}
176189

177-
return $this->redis->expireAt($key, $expiresAt);
190+
$shouldFallback = true;
191+
}
192+
193+
if (! $shouldFallback) {
194+
return false;
195+
}
196+
197+
// EVAL is unavailable (renamed command or ACL denial): run both commands sequentially.
198+
if (! $this->redis->hMset($key, $fields)) {
199+
return false;
178200
}
179201

180-
return (bool) $this->redis->hMset($key, $fields);
202+
$this->redis->expireAt($key, $expiresAt);
203+
204+
return true;
205+
}
206+
207+
/**
208+
* Checks whether the message only means that the EVAL command itself is not
209+
* available to this client, either because it was renamed or because ACL denies it.
210+
*
211+
* Keep the patterns in sync with PredisHandler::isEvalUnavailable().
212+
*/
213+
private static function isEvalUnavailable(string $message): bool
214+
{
215+
return preg_match("/unknown command [`']?eval\\b/i", $message) === 1
216+
|| preg_match("/no permissions to run the [`']eval[`'] command/i", $message) === 1;
181217
}
182218

183219
public function delete(string $key): bool

0 commit comments

Comments
 (0)