Skip to content

Commit ec86761

Browse files
authored
perf(Cache): atomic HMSET and EXPIREAT using Lua script in Redis and Predis handlers (#10707)
1 parent 3cb68b0 commit ec86761

4 files changed

Lines changed: 839 additions & 7 deletions

File tree

‎system/Cache/Handlers/PredisHandler.php‎

Lines changed: 64 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,39 @@
1919
use Exception;
2020
use Predis\Client;
2121
use Predis\Collection\Iterator\Keyspace;
22+
use Predis\Response\ServerException;
2223
use Predis\Response\Status;
2324

2425
/**
2526
* Predis cache handler
2627
*/
2728
class PredisHandler extends BaseHandler
2829
{
30+
/**
31+
* Lua script to execute HMSET and EXPIREAT in a single round trip.
32+
*
33+
* Both commands run through pcall and their error reply is returned as-is,
34+
* so an HMSET error (e.g. WRONGTYPE) stops the script before EXPIREAT and
35+
* every error keeps its original type and message. Predis raises
36+
* ServerException for such a reply, which save() only swallows when it is
37+
* about EVAL itself, so an ACL denial is never retried sequentially.
38+
*
39+
* If HMSET succeeds and EXPIREAT is rejected, the hash is stored without a
40+
* TTL, exactly as with the previous sequential implementation (Redis does
41+
* not roll back script effects).
42+
*/
43+
private const SAVE_SCRIPT = <<<'LUA'
44+
local res = redis.pcall('HMSET', KEYS[1], '__ci_type', ARGV[2], '__ci_value', ARGV[3])
45+
if type(res) == 'table' and res.err then
46+
return res
47+
end
48+
local exp = redis.pcall('EXPIREAT', KEYS[1], ARGV[1])
49+
if type(exp) == 'table' and exp.err then
50+
return exp
51+
end
52+
return 1
53+
LUA;
54+
2955
/**
3056
* Default config
3157
*
@@ -118,17 +144,51 @@ public function save(string $key, mixed $value, int $ttl = 60): bool
118144
return false;
119145
}
120146

121-
if (! $this->redis->hmset($key, ['__ci_type' => $dataType, '__ci_value' => $value]) instanceof Status) {
122-
return false;
147+
$fields = ['__ci_type' => $dataType, '__ci_value' => $value];
148+
149+
if ($ttl === 0) {
150+
return $this->redis->hmset($key, $fields) instanceof Status;
151+
}
152+
153+
$expiresAt = Time::now()->getTimestamp() + $ttl;
154+
155+
try {
156+
return (bool) $this->redis->eval(
157+
self::SAVE_SCRIPT,
158+
1,
159+
$key,
160+
(string) $expiresAt,
161+
$dataType,
162+
(string) $value,
163+
);
164+
} catch (ServerException $e) {
165+
if (! self::isEvalUnavailable($e->getMessage())) {
166+
throw $e;
167+
}
123168
}
124169

125-
if ($ttl !== 0) {
126-
$this->redis->expireat($key, Time::now()->getTimestamp() + $ttl);
170+
// EVAL is unavailable (renamed command or ACL denial): run both commands sequentially.
171+
if (! $this->redis->hmset($key, $fields) instanceof Status) {
172+
return false;
127173
}
128174

175+
$this->redis->expireat($key, $expiresAt);
176+
129177
return true;
130178
}
131179

180+
/**
181+
* Checks whether the exception only means that the EVAL command itself is not
182+
* available to this client, either because it was renamed or because ACL denies it.
183+
*
184+
* Keep the patterns in sync with RedisHandler::isEvalUnavailable().
185+
*/
186+
private static function isEvalUnavailable(string $message): bool
187+
{
188+
return preg_match("/unknown command [`']?eval\\b/i", $message) === 1
189+
|| preg_match("/no permissions to run the [`']eval[`'] command/i", $message) === 1;
190+
}
191+
132192
public function delete(string $key): bool
133193
{
134194
$key = static::validateKey($key);

‎system/Cache/Handlers/RedisHandler.php‎

Lines changed: 104 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,32 @@
2424
*/
2525
class RedisHandler extends BaseHandler
2626
{
27+
/**
28+
* Lua script to execute HMSET and EXPIREAT in a single round trip.
29+
*
30+
* Both commands run through pcall and their error reply is returned as-is,
31+
* so a failing HMSET never runs EXPIREAT and the original error message and
32+
* type are preserved. phpredis exposes the message through
33+
* Redis::getLastError(); save() rethrows a permission error as
34+
* RedisException, as the sequential implementation did, and keeps reporting
35+
* any other error (e.g. WRONGTYPE) as false.
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).
40+
*/
41+
private const SAVE_SCRIPT = <<<'LUA'
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
46+
local exp = redis.pcall('EXPIREAT', KEYS[1], ARGV[1])
47+
if type(exp) == 'table' and exp.err then
48+
return exp
49+
end
50+
return 1
51+
LUA;
52+
2753
/**
2854
* Default config
2955
*
@@ -134,17 +160,92 @@ public function save(string $key, mixed $value, int $ttl = 60): bool
134160
return false;
135161
}
136162

137-
if (! $this->redis->hMset($key, ['__ci_type' => $dataType, '__ci_value' => $value])) {
163+
$fields = ['__ci_type' => $dataType, '__ci_value' => $value];
164+
165+
if ($ttl === 0) {
166+
return (bool) $this->redis->hMset($key, $fields);
167+
}
168+
169+
$expiresAt = Time::now()->getTimestamp() + $ttl;
170+
171+
$shouldFallback = false;
172+
173+
$this->redis->clearLastError();
174+
175+
try {
176+
$result = $this->redis->eval(
177+
self::SAVE_SCRIPT,
178+
[$key, (string) $expiresAt, $dataType, (string) $value],
179+
1,
180+
);
181+
182+
if ($result !== false) {
183+
return (bool) $result;
184+
}
185+
186+
// phpredis reports server errors as false and keeps the message in getLastError().
187+
$error = $this->redis->getLastError();
188+
189+
if (is_string($error)) {
190+
if (self::isEvalUnavailable($error)) {
191+
$shouldFallback = true;
192+
} elseif (self::isDataCommandPermissionError($error)) {
193+
// HMSET or EXPIREAT was denied by an ACL: the script itself ran,
194+
// so keep throwing exactly like the sequential implementation did.
195+
throw new RedisException($error);
196+
}
197+
}
198+
} catch (RedisException $e) {
199+
if (! self::isEvalUnavailable($e->getMessage())) {
200+
throw $e;
201+
}
202+
203+
$shouldFallback = true;
204+
}
205+
206+
if (! $shouldFallback) {
138207
return false;
139208
}
140209

141-
if ($ttl !== 0) {
142-
$this->redis->expireAt($key, Time::now()->getTimestamp() + $ttl);
210+
// EVAL is unavailable (renamed command or ACL denial): run both commands sequentially.
211+
if (! $this->redis->hMset($key, $fields)) {
212+
return false;
143213
}
144214

215+
$this->redis->expireAt($key, $expiresAt);
216+
145217
return true;
146218
}
147219

220+
/**
221+
* Checks whether the message only means that the EVAL command itself is not
222+
* available to this client, either because it was renamed or because ACL denies it.
223+
*
224+
* Keep the patterns in sync with PredisHandler::isEvalUnavailable().
225+
*/
226+
private static function isEvalUnavailable(string $message): bool
227+
{
228+
return preg_match("/unknown command [`']?eval\\b/i", $message) === 1
229+
|| preg_match("/no permissions to run the [`']eval[`'] command/i", $message) === 1;
230+
}
231+
232+
/**
233+
* Checks whether the message means that a data command executed inside the
234+
* save script was denied by an ACL.
235+
*
236+
* EVAL availability was already checked, so the denied command can only be
237+
* HMSET or EXPIREAT. Redis reports it either as a command level denial or as
238+
* an ACL failure while running the script.
239+
*
240+
* Predis throws for every error reply, so this mapping only exists for the
241+
* phpredis false plus getLastError() path.
242+
*/
243+
private static function isDataCommandPermissionError(string $message): bool
244+
{
245+
return preg_match("/no permissions to run the [`']?[a-z]+[`'] command/i", $message) === 1
246+
|| preg_match('/ACL failure in script/i', $message) === 1;
247+
}
248+
148249
public function delete(string $key): bool
149250
{
150251
$key = static::validateKey($key, $this->prefix);

0 commit comments

Comments
 (0)