Skip to content

Commit bcad914

Browse files
committed
feat: add Redis Sentinel support for Cache and Session handlers
1 parent 357b0af commit bcad914

10 files changed

Lines changed: 605 additions & 5 deletions

File tree

‎.github/workflows/reusable-phpunit-test.yml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,15 @@ jobs:
137137
--health-timeout=5s
138138
--health-retries=3
139139
140+
redis-sentinel:
141+
image: bitnami/redis-sentinel:latest
142+
ports:
143+
- 26379:26379
144+
env:
145+
REDIS_MASTER_HOST: redis
146+
REDIS_MASTER_PORT_NUMBER: 6379
147+
REDIS_SENTINEL_QUORUM: 1
148+
140149
memcached:
141150
image: memcached:1.6-alpine
142151
ports:

‎.github/workflows/test-random-execution.yml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,15 @@ jobs:
143143
--health-timeout=5s
144144
--health-retries=3
145145
146+
redis-sentinel:
147+
image: bitnami/redis-sentinel:latest
148+
ports:
149+
- 26379:26379
150+
env:
151+
REDIS_MASTER_HOST: redis
152+
REDIS_MASTER_PORT_NUMBER: 6379
153+
REDIS_SENTINEL_QUORUM: 1
154+
146155
memcached:
147156
image: memcached:1.6-alpine
148157
ports:

‎app/Config/Cache.php‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,9 @@ class Cache extends BaseConfig
120120
* timeout?: int,
121121
* async?: bool,
122122
* persistent?: bool,
123-
* database?: int
123+
* database?: int,
124+
* sentinels?: list<string>,
125+
* service?: string
124126
* }
125127
*/
126128
public array $redis = [

‎app/Config/Session.php‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,4 +125,26 @@ class Session extends BaseConfig
125125
* seconds.
126126
*/
127127
public int $lockMaxRetries = 300;
128+
129+
/**
130+
* --------------------------------------------------------------------------
131+
* Redis Sentinel Hosts
132+
* --------------------------------------------------------------------------
133+
*
134+
* List of Redis Sentinel servers for high availability.
135+
* Used only when $driver is RedisHandler.
136+
*
137+
* @var list<string>|null
138+
*/
139+
public ?array $redisSentinels = null;
140+
141+
/**
142+
* --------------------------------------------------------------------------
143+
* Redis Sentinel Service
144+
* --------------------------------------------------------------------------
145+
*
146+
* The master group name for Redis Sentinel.
147+
* Used only when $driver is RedisHandler.
148+
*/
149+
public ?string $redisSentinelService = null;
128150
}

‎system/Cache/Handlers/PredisHandler.php‎

Lines changed: 98 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,9 @@ class PredisHandler extends BaseHandler
3838
* port: int,
3939
* async: bool,
4040
* persistent: bool,
41-
* timeout: int
41+
* timeout: int,
42+
* sentinels: list<string>,
43+
* service: string,
4244
* }
4345
*/
4446
protected $config = [
@@ -49,6 +51,8 @@ class PredisHandler extends BaseHandler
4951
'async' => false,
5052
'persistent' => false,
5153
'timeout' => 0,
54+
'sentinels' => [],
55+
'service' => '',
5256
];
5357

5458
/**
@@ -68,16 +72,108 @@ public function __construct(Cache $config)
6872
$this->config = array_merge($this->config, $config->redis);
6973
}
7074

75+
/**
76+
* Factory method for creating Predis Client instances.
77+
* Override in tests to mock Client.
78+
*/
79+
protected function createPredisClient(array $connection, array $options = []): Client
80+
{
81+
return new Client($connection, $options);
82+
}
83+
7184
public function initialize(): void
7285
{
7386
try {
74-
$this->redis = new Client($this->config, ['prefix' => $this->prefix]);
87+
$config = $this->config;
88+
89+
if ($config['sentinels'] !== [] && $config['service'] !== '') {
90+
$this->initializeSentinel($config);
91+
92+
return;
93+
}
94+
95+
unset($config['sentinels'], $config['service']);
96+
97+
$this->redis = $this->createPredisClient($config, ['prefix' => $this->prefix]);
7598
$this->redis->time();
7699
} catch (Exception $e) {
77100
throw new CriticalError('Cache: Predis connection refused (' . $e->getMessage() . ').', $e->getCode(), $e);
78101
}
79102
}
80103

104+
/**
105+
* Initializes a connection via Redis Sentinel.
106+
*
107+
* Predis v3.x does not have built-in sentinel support,
108+
* so we manually discover the master via the Sentinel protocol.
109+
*
110+
* @param array{
111+
* sentinels: list<string>,
112+
* service: string,
113+
* timeout: int,
114+
* password?: string|null,
115+
* database?: int,
116+
* prefix?: string,
117+
* } $config
118+
*/
119+
protected function initializeSentinel(array $config): void
120+
{
121+
$sentinels = $config['sentinels'];
122+
$service = $config['service'];
123+
$timeout = $config['timeout'] ?? 0;
124+
125+
$masterHost = null;
126+
$masterPort = null;
127+
128+
foreach ($sentinels as $sentinel) {
129+
$parts = parse_url($sentinel);
130+
$sentinelHost = $parts['host'] ?? '127.0.0.1';
131+
$sentinelPort = $parts['port'] ?? 26379;
132+
$sentinelScheme = $parts['scheme'] ?? 'tcp';
133+
134+
try {
135+
$sentinelClient = $this->createPredisClient([
136+
'scheme' => $sentinelScheme,
137+
'host' => $sentinelHost,
138+
'port' => $sentinelPort,
139+
'timeout' => $timeout,
140+
]);
141+
142+
if (isset($config['password']) && $config['password'] !== null) {
143+
$sentinelClient->auth($config['password']);
144+
}
145+
146+
$addr = $sentinelClient->rawCommand('SENTINEL', 'get-master-addr-by-name', $service);
147+
148+
if (is_array($addr) && count($addr) >= 2) {
149+
$masterHost = $addr[0];
150+
$masterPort = (int) $addr[1];
151+
}
152+
153+
$sentinelClient->disconnect();
154+
unset($sentinelClient);
155+
156+
if ($masterHost !== null) {
157+
break;
158+
}
159+
} catch (Exception) {
160+
continue;
161+
}
162+
}
163+
164+
if ($masterHost === null) {
165+
throw new CriticalError('Cache: Redis Sentinel could not find a master for service "' . $service . '".');
166+
}
167+
168+
$config['scheme'] = 'tcp';
169+
$config['host'] = $masterHost;
170+
$config['port'] = $masterPort;
171+
unset($config['sentinels'], $config['service'], $config['async'], $config['persistent']);
172+
173+
$this->redis = $this->createPredisClient($config, ['prefix' => $this->prefix]);
174+
$this->redis->time();
175+
}
176+
81177
public function get(string $key): mixed
82178
{
83179
$key = static::validateKey($key);

‎system/Cache/Handlers/RedisHandler.php‎

Lines changed: 97 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ class RedisHandler extends BaseHandler
3636
* timeout: int,
3737
* persistent: bool,
3838
* database: int,
39+
* sentinels: list<string>,
40+
* service: string,
3941
* }
4042
*/
4143
protected $config = [
@@ -45,6 +47,8 @@ class RedisHandler extends BaseHandler
4547
'timeout' => 0,
4648
'persistent' => false,
4749
'database' => 0,
50+
'sentinels' => [],
51+
'service' => '',
4852
];
4953

5054
/**
@@ -68,9 +72,15 @@ public function initialize(): void
6872
{
6973
$config = $this->config;
7074

71-
$this->redis = new Redis();
75+
$this->redis = $this->createRedis();
7276

7377
try {
78+
if ($config['sentinels'] !== [] && $config['service'] !== '') {
79+
$this->initializeSentinel($config);
80+
81+
return;
82+
}
83+
7484
$funcConnection = isset($config['persistent']) && $config['persistent'] ? 'pconnect' : 'connect';
7585

7686
// Note:: If Redis is your primary cache choice, and it is "offline", every page load will end up been delayed by the timeout duration.
@@ -98,6 +108,92 @@ public function initialize(): void
98108
}
99109
}
100110

111+
/**
112+
* Initializes a connection via Redis Sentinel.
113+
*
114+
* @param array{
115+
* sentinels: list<string>,
116+
* service: string,
117+
* timeout: int,
118+
* password?: string|null,
119+
* persistent?: bool,
120+
* database?: int,
121+
* } $config
122+
*/
123+
/**
124+
* Factory method for creating Redis connections.
125+
* Override in tests to mock Redis.
126+
*/
127+
protected function createRedis(): Redis
128+
{
129+
return new Redis();
130+
}
131+
132+
protected function initializeSentinel(array $config): void
133+
{
134+
$sentinels = $config['sentinels'];
135+
$service = $config['service'];
136+
$timeout = $config['timeout'] ?? 0;
137+
138+
$masterHost = null;
139+
$masterPort = null;
140+
141+
foreach ($sentinels as $sentinel) {
142+
$parts = parse_url($sentinel);
143+
$sentinelHost = $parts['host'] ?? '127.0.0.1';
144+
$sentinelPort = $parts['port'] ?? 26379;
145+
146+
$sentinelConn = $this->createRedis();
147+
try {
148+
$sentinelConn->connect($sentinelHost, $sentinelPort, $timeout);
149+
150+
if (isset($config['password']) && $config['password'] !== null) {
151+
$sentinelConn->auth($config['password']);
152+
}
153+
154+
$addr = $sentinelConn->rawCommand('SENTINEL', 'get-master-addr-by-name', $service);
155+
156+
if (is_array($addr) && count($addr) >= 2) {
157+
$masterHost = $addr[0];
158+
$masterPort = (int) $addr[1];
159+
}
160+
161+
$sentinelConn->close();
162+
unset($sentinelConn);
163+
164+
if ($masterHost !== null) {
165+
break;
166+
}
167+
} catch (RedisException) {
168+
continue;
169+
}
170+
}
171+
172+
if ($masterHost === null) {
173+
throw new CriticalError('Cache: Redis Sentinel could not find a master for service "' . $service . '".');
174+
}
175+
176+
$funcConnection = isset($config['persistent']) && $config['persistent'] ? 'pconnect' : 'connect';
177+
178+
if (! $this->redis->{$funcConnection}($masterHost, $masterPort, $timeout)) {
179+
log_message('error', 'Cache: Redis connection to Sentinel master failed. Check your configuration.');
180+
181+
throw new CriticalError('Cache: Redis connection to Sentinel master failed. Check your configuration.');
182+
}
183+
184+
if (isset($config['password']) && $config['password'] !== null && ! $this->redis->auth($config['password'])) {
185+
log_message('error', 'Cache: Redis authentication failed.');
186+
187+
throw new CriticalError('Cache: Redis authentication failed.');
188+
}
189+
190+
if (isset($config['database']) && ! $this->redis->select($config['database'])) {
191+
log_message('error', 'Cache: Redis select database failed.');
192+
193+
throw new CriticalError('Cache: Redis select database failed.');
194+
}
195+
}
196+
101197
public function get(string $key): mixed
102198
{
103199
$key = static::validateKey($key, $this->prefix);

0 commit comments

Comments
 (0)