-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathRedisHandler.php
More file actions
283 lines (268 loc) · 8.26 KB
/
Copy pathRedisHandler.php
File metadata and controls
283 lines (268 loc) · 8.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
<?php declare(strict_types=1);
/*
* This file is part of Aplus Framework Session Library.
*
* (c) Natan Felles <natanfelles@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Framework\Session\SaveHandlers;
use Framework\Log\LogLevel;
use Framework\Session\SaveHandler;
use Redis;
use RedisException;
use SensitiveParameter;
/**
* Class RedisHandler.
*
* @package session
*/
class RedisHandler extends SaveHandler
{
protected ?Redis $redis;
/**
* Prepare configurations to be used by the RedisHandler.
*
* @param array<string,mixed> $config Custom configs
*
* The custom configs are:
*
* ```php
* $configs = [
* // A custom prefix prepended in the keys
* 'prefix' => '',
* // The Redis host
* 'host' => '127.0.0.1',
* // The Redis host port
* 'port' => 6379,
* // The connection timeout
* 'timeout' => 0.0,
* // Optional auth password
* 'password' => null,
* // Optional database to select
* 'database' => null,
* // Maximum attempts to try lock a session id
* 'lock_attempts' => 60,
* // Interval between the lock attempts in microseconds
* 'lock_sleep' => 1_000_000,
* // TTL to the lock (valid for the current session only)
* 'lock_ttl' => 600,
* // The maxlifetime (TTL) used for cache item expiration
* 'maxlifetime' => null, // Null to use the ini value of session.gc_maxlifetime
* // Match IP?
* 'match_ip' => false,
* // Match User-Agent?
* 'match_ua' => false,
* ];
* ```
*/
protected function prepareConfig(#[SensitiveParameter] array $config) : void
{
$this->config = \array_replace([
'prefix' => '',
'host' => '127.0.0.1',
'port' => 6379,
'timeout' => 0.0,
'password' => null,
'database' => null,
'lock_attempts' => 60,
'lock_sleep' => 1_000_000,
'lock_ttl' => 600,
'maxlifetime' => null,
'match_ip' => false,
'match_ua' => false,
], $config);
}
public function setRedis(Redis $redis) : static
{
$this->setByExternal = true;
$this->redis = $redis;
return $this;
}
public function getRedis() : ?Redis
{
return $this->redis ?? null;
}
/**
* Get a key for Redis, using the optional
* prefix, match IP and match User-Agent configs.
*
* @param string $id The session id
*
* @return string The final key
*/
protected function getKey(string $id) : string
{
return $this->config['prefix'] . $id . $this->getKeySuffix();
}
public function open($path, $name) : bool
{
if (isset($this->redis)) {
return true;
}
$this->redis = new Redis();
try {
@$this->redis->connect(
$this->config['host'],
$this->config['port'],
$this->config['timeout']
);
} catch (RedisException) {
$this->log(
'Session (redis): Could not connect to server '
. $this->config['host'] . ':' . $this->config['port']
);
return false;
}
if (isset($this->config['password'])) {
try {
$this->redis->auth($this->config['password']);
} catch (RedisException) {
$this->log('Session (redis): Authentication failed');
return false;
}
}
if (isset($this->config['database'])
&& !$this->redis->select($this->config['database'])
) {
$this->log(
"Session (redis): Could not select the database '{$this->config['database']}'"
);
return false;
}
return true;
}
public function read($id) : string
{
if (!isset($this->redis) || !$this->lock($id)) {
return '';
}
if (!isset($this->sessionId)) {
$this->sessionId = $id;
}
$data = $this->redis->get($this->getKey($id));
\is_string($data) ? $this->sessionExists = true : $data = '';
$this->setFingerprint($data);
return $data;
}
public function write($id, $data) : bool
{
if (!isset($this->redis)) {
return false;
}
if ($id !== $this->sessionId) {
if (!$this->unlock() || !$this->lock($id)) {
return false;
}
$this->sessionExists = false;
$this->sessionId = $id;
}
if ($this->lockId === false) {
return false;
}
$maxlifetime = $this->getMaxlifetime();
$this->redis->expire($this->lockId, $this->config['lock_ttl']);
if ($this->sessionExists === false || !$this->hasSameFingerprint($data)) {
if ($this->redis->set($this->getKey($id), $data, $maxlifetime)) {
$this->setFingerprint($data);
$this->sessionExists = true;
return true;
}
return false;
}
return $this->redis->expire($this->getKey($id), $maxlifetime);
}
public function updateTimestamp($id, $data) : bool
{
return $this->redis->setex($this->getKey($id), $this->getMaxlifetime(), $data);
}
public function close() : bool
{
if (!isset($this->redis)) {
return true;
}
if ($this->setByExternal === false) {
try {
if ($this->redis->ping()) {
if ($this->lockId) {
$this->redis->del($this->lockId);
}
if (!$this->redis->close()) {
return false;
}
}
} catch (RedisException $e) {
$this->log('Session (redis): Got RedisException on close: ' . $e->getMessage());
}
$this->redis = null;
}
return true;
}
public function destroy($id) : bool
{
if (!$this->lockId) {
return false;
}
$result = $this->redis->del($this->getKey($id));
if ($result !== 1) {
$this->log(
'Session (redis): Expected to delete 1 key, deleted ' . $result,
LogLevel::DEBUG
);
}
return true;
}
public function gc($max_lifetime) : false | int
{
return 0;
}
protected function lock(string $id) : bool
{
$ttl = $this->config['lock_ttl'];
if ($this->lockId && $this->redis->get($this->lockId)) {
return $this->redis->expire($this->lockId, $ttl);
}
$lockId = $this->getKey($id) . ':lock';
$attempt = 0;
while ($attempt < $this->config['lock_attempts']) {
$attempt++;
$oldTtl = $this->redis->ttl($lockId);
if (\is_int($oldTtl) && $oldTtl > 0) {
\usleep($this->config['lock_sleep']);
continue;
}
if (!$this->redis->setex($lockId, $ttl, (string) \time())) {
$this->log('Session (redis): Error while trying to lock ' . $lockId);
return false;
}
$this->lockId = $lockId;
break;
}
if ($attempt === $this->config['lock_attempts']) {
$this->log(
"Session (redis): Unable to lock {$lockId} after {$attempt} attempts"
);
return false;
}
if (isset($oldTtl) && $oldTtl === -1) {
$this->log(
'Session (redis): Lock for ' . $this->getKey($id) . ' had not TTL',
LogLevel::DEBUG
);
}
return true;
}
protected function unlock() : bool
{
if ($this->lockId === false) {
return true;
}
if (!$this->redis->del($this->lockId)) {
$this->log('Session (redis): Error while trying to unlock ' . $this->lockId);
return false;
}
$this->lockId = false;
return true;
}
}