Skip to content

Commit 31a746a

Browse files
ddevsrclaude
andcommitted
fix: make Redis Sentinel discovery work across phpredis and Predis
The previous implementation broke against newer clients: - phpredis >= 6.0 changed the RedisSentinel constructor to a single-array signature, so the positional call threw ArgumentCountError. Drop the RedisSentinel class branch entirely and always use the SENTINEL get-master-addr-by-name command via rawCommand, which works on every phpredis version. - Predis' native sentinel replication routes read commands to replicas when any are known, so a cache write/read round-trip against a sentinel setup with a replica returned null. Replace it with the same discovery model as the phpredis handler: query the sentinel nodes for the master address, then connect a plain single-node client to that master. Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 1ffeda1 commit 31a746a

2 files changed

Lines changed: 62 additions & 60 deletions

File tree

‎system/Cache/Handlers/PredisHandler.php‎

Lines changed: 52 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@
2222
use Exception;
2323
use Predis\Client;
2424
use Predis\Collection\Iterator\Keyspace;
25+
use Predis\Command\RawCommand;
2526
use Predis\Response\Status;
27+
use RuntimeException;
2628

2729
/**
2830
* Predis cache handler
@@ -81,43 +83,69 @@ public function __construct(Cache $config)
8183
public function initialize(): void
8284
{
8385
try {
84-
// Predis has native Sentinel support: pass the Sentinel nodes plus a
85-
// replication/service option and it discovers and follows the master.
86+
// When a Sentinel cluster is configured, discover the current master
87+
// address first and connect to it directly (Predis has no built-in
88+
// Sentinel handling on this client). Otherwise connect to the single
89+
// configured host.
8690
if (($this->config['sentinel']['nodes'] ?? []) !== []) {
87-
$nodes = array_map(
88-
static fn (array $node): array => [
89-
'scheme' => $node['scheme'] ?? 'tcp',
90-
'host' => $node['host'],
91-
'port' => $node['port'] ?? 26379,
92-
],
93-
$this->config['sentinel']['nodes'],
94-
);
95-
$options = [
96-
'prefix' => $this->prefix,
97-
'replication' => 'sentinel',
98-
'service' => $this->config['sentinel']['service'],
99-
];
100-
101-
// `parameters` are applied to the connections resolved by Sentinel.
102-
if (isset($this->config['password'])) {
103-
$options['parameters']['password'] = $this->config['password'];
104-
}
105-
if (isset($this->config['database'])) {
106-
$options['parameters']['database'] = $this->config['database'];
107-
}
91+
[$host, $port] = $this->discoverMasterFromSentinel();
10892

109-
$this->redis = new Client($nodes, $options);
93+
$config = $this->config;
94+
$config['host'] = $host;
95+
$config['port'] = $port;
96+
97+
$this->redis = new Client($config, ['prefix' => $this->prefix]);
11098
} else {
11199
$this->redis = new Client($this->config, ['prefix' => $this->prefix]);
112100
}
113101

114102
$this->lockStore = null;
115103
$this->redis->time();
104+
} catch (RuntimeException $e) {
105+
throw new CriticalError('Cache: ' . $e->getMessage(), $e->getCode(), $e);
116106
} catch (Exception $e) {
117107
throw new CriticalError('Cache: Predis connection refused (' . $e->getMessage() . ').', $e->getCode(), $e);
118108
}
119109
}
120110

111+
/**
112+
* Queries the configured Sentinel nodes for the current master address.
113+
*
114+
* Each node is tried in order; the first one that answers wins.
115+
*
116+
* @return array{0: string, 1: int} The master host and port.
117+
*
118+
* @throws RuntimeException When no Sentinel node can discover the master.
119+
*/
120+
private function discoverMasterFromSentinel(): array
121+
{
122+
$service = $this->config['sentinel']['service'];
123+
124+
foreach ($this->config['sentinel']['nodes'] as $node) {
125+
try {
126+
$sentinel = new Client([
127+
'scheme' => $node['scheme'] ?? 'tcp',
128+
'host' => $node['host'],
129+
'port' => $node['port'] ?? 26379,
130+
'timeout' => (float) ($this->config['sentinel']['timeout'] ?? 0),
131+
]);
132+
133+
$result = $sentinel->executeCommand(
134+
RawCommand::create('SENTINEL', 'get-master-addr-by-name', $service),
135+
);
136+
$sentinel->disconnect();
137+
138+
if (is_array($result) && isset($result[0], $result[1]) && is_string($result[0])) {
139+
return [(string) $result[0], (int) $result[1]];
140+
}
141+
} catch (Exception) {
142+
// Node unreachable or command failed; try the next one.
143+
}
144+
}
145+
146+
throw new RuntimeException(sprintf('Redis Sentinel unable to discover master "%s".', $service));
147+
}
148+
121149
public function get(string $key): mixed
122150
{
123151
$key = static::validateKey($key);

‎system/Cache/Handlers/RedisSentinel.php‎

Lines changed: 10 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,10 @@
2222
*
2323
* phpredis has no built-in Sentinel failover handling, so the Redis cache
2424
* and session handlers use this utility to resolve the master address before
25-
* connecting. It prefers the `RedisSentinel` class (phpredis >= 5.3) and
26-
* falls back to a plain `SENTINEL get-master-addr-by-name` command for older
27-
* versions.
25+
* connecting. It sends a plain `SENTINEL get-master-addr-by-name` command to
26+
* each node, which works on every phpredis version without relying on the
27+
* `RedisSentinel` class (whose constructor differs between phpredis 5.x and
28+
* 6.x).
2829
*/
2930
class RedisSentinel
3031
{
@@ -79,24 +80,6 @@ public static function discoverMaster(array $nodes, string $service, float $time
7980
*/
8081
private static function queryNode(string $host, int $port, string $service, float $timeout): ?array
8182
{
82-
// Prefer the dedicated RedisSentinel class (phpredis >= 5.3).
83-
if (class_exists(\RedisSentinel::class)) {
84-
try {
85-
$sentinel = new \RedisSentinel($host, $port, $timeout);
86-
$result = $sentinel->getMasterAddrByName($service);
87-
88-
if ($result === false) {
89-
return null;
90-
}
91-
92-
return self::normalise($result);
93-
} catch (RedisException) {
94-
// Node unreachable or command failed; try the next one.
95-
return null;
96-
}
97-
}
98-
99-
// Fall back to the SENTINEL command on a plain Redis connection.
10083
try {
10184
$redis = new Redis();
10285
$redis->connect($host, $port, $timeout);
@@ -115,34 +98,25 @@ private static function queryNode(string $host, int $port, string $service, floa
11598

11699
return self::normalise($result);
117100
} catch (RedisException) {
101+
// Node unreachable or command failed; try the next one.
118102
return null;
119103
}
120104
}
121105

122106
/**
123-
* Normalises the varied reply shapes into a [host, port] pair.
107+
* Normalises the flat `['host', 'port']` reply into a typed pair.
124108
*
125-
* phpredis returns either a flat `['host', 'port']` list (rawCommand and
126-
* most RedisSentinel builds) or an associative `[['ip' => .., 'port' => ..]]`
127-
* shape on some builds. Both are coerced to `array{0:string, 1:int}`.
109+
* `SENTINEL get-master-addr-by-name` returns a two-element list, e.g.
110+
* `['127.0.0.1', '6379']`.
128111
*
129112
* @param array<array-key, mixed> $result
130113
*
131114
* @return array{0: string, 1: int}|null
132115
*/
133116
private static function normalise(array $result): ?array
134117
{
135-
// Some RedisSentinel builds wrap the entry in an outer array.
136-
$entry = array_is_list($result) && isset($result[0]) && is_array($result[0])
137-
? $result[0]
138-
: $result;
139-
140-
if (isset($entry['ip'], $entry['port'])) {
141-
return [(string) $entry['ip'], (int) $entry['port']];
142-
}
143-
144-
if (isset($entry[0], $entry[1]) && is_string($entry[0]) && (is_string($entry[1]) || is_int($entry[1]))) {
145-
return [(string) $entry[0], (int) $entry[1]];
118+
if (isset($result[0], $result[1]) && is_string($result[0]) && (is_string($result[1]) || is_int($result[1]))) {
119+
return [(string) $result[0], (int) $result[1]];
146120
}
147121

148122
return null;

0 commit comments

Comments
 (0)