-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathAbstractRedisClient.php
406 lines (367 loc) · 12.9 KB
/
AbstractRedisClient.php
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
<?php
/**
* This file is part of RedisClient.
* git: https://github.com/cheprasov/php-redis-client
*
* (C) Alexander Cheprasov <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace RedisClient\Client;
use RedisClient\Cluster\ClusterMap;
use RedisClient\Command\Response\ResponseParser;
use RedisClient\Exception\AskResponseException;
use RedisClient\Exception\CommandNotFoundException;
use RedisClient\Exception\ErrorResponseException;
use RedisClient\Exception\InvalidArgumentException;
use RedisClient\Exception\MovedResponseException;
use RedisClient\Exception\TryAgainResponseException;
use RedisClient\Pipeline\Pipeline;
use RedisClient\Pipeline\PipelineInterface;
use RedisClient\Protocol\ProtocolFactory;
use RedisClient\Protocol\ProtocolInterface;
use RedisClient\RedisClient;
abstract class AbstractRedisClient {
const VERSION = '1.10.0';
const CONFIG_SERVER = 'server';
const CONFIG_TIMEOUT = 'timeout';
const CONFIG_DATABASE = 'database';
const CONFIG_PASSWORD = 'password';
const CONFIG_CLUSTER = 'cluster';
const CONFIG_VERSION = 'version';
const CONFIG_CONNECTION = 'connection';
const TRANSACTION_RESPONSE_QUEUED = 'QUEUED';
const TRANSACTION_MODE_NONE = 0;
const TRANSACTION_MODE_STARTED = 1;
const TRANSACTION_MODE_EXECUTED = 2;
/**
* Default configuration
* @var array
*/
protected static $defaultConfig = [
self::CONFIG_SERVER => '127.0.0.1:6379', // or tcp://127.0.0.1:6379 or 'unix:///tmp/redis.sock'
self::CONFIG_TIMEOUT => 1, // in seconds
self::CONFIG_DATABASE => 0, // default db
self::CONFIG_CLUSTER => [
'enabled' => false,
'clusters' => [],
'init_on_start' => false,
'init_on_error_moved' => false,
'timeout_on_error_tryagain' => 0.05,
],
self::CONFIG_CONNECTION => null,
];
/**
* @var ProtocolInterface
*/
protected $Protocol;
/**
* @var array
*/
protected $config;
/**
* @var ClusterMap
*/
protected $ClusterMap;
/**
* @var int
*/
protected $transactionMode = self::TRANSACTION_MODE_NONE;
/**
* @var array[]|null
*/
protected $responseParsers = null;
/**
* @param array|null $config
*/
public function __construct(array $config = null) {
$this->setConfig($config);
}
/**
* @param array|null $config
*/
protected function setConfig(array $config = null) {
$this->config = $config ? array_merge(static::$defaultConfig, $config) : static::$defaultConfig;
if (!empty($this->config[self::CONFIG_CLUSTER]['enabled'])) {
$ClusterMap = new ClusterMap($this, $this->getConfig());
if (!empty($this->config[self::CONFIG_CLUSTER]['clusters'])) {
$ClusterMap->setClusters($this->config[self::CONFIG_CLUSTER]['clusters']);
}
$this->ClusterMap = $ClusterMap;
if (!empty($this->config[self::CONFIG_CLUSTER]['init_on_start'])) {
$this->_syncClusterSlotsFromRedisServer();
}
}
}
/**
* @param string|null $param
* @return mixed|null
*/
protected function getConfig($param = null) {
if (!$param) {
return $this->config;
}
return isset($this->config[$param]) ? $this->config[$param] : null;
}
/**
* @param AbstractRedisClient $RedisClient
* @param $config
* @return \RedisClient\Protocol\ProtocolInterface
*/
protected function createProtocol(AbstractRedisClient $RedisClient, $config)
{
return ProtocolFactory::createRedisProtocol($RedisClient, $config);
}
/**
* @return ProtocolInterface
*/
protected function getProtocol() {
if (!$this->Protocol) {
$this->Protocol = $this->createProtocol($this, $this->getConfig());
if ($this->ClusterMap) {
$this->ClusterMap->addProtocol($this->Protocol);
}
}
return $this->Protocol;
}
/**
*
*/
public function _syncClusterSlotsFromRedisServer() {
/** @var RedisClient $this */
$response = $this->clusterSlots();
$clusters = ResponseParser::parseClusterSlots($response);
$this->ClusterMap->setClusters($clusters);
}
/**
* @inheritdoc
*/
protected function returnCommand(array $command, $keys = null, array $params = null, $parserId = null) {
return $this->executeCommand($command, $keys, $params, $parserId);
}
/**
* @param null|string|string[] $command
* @param array|null $params
* @param int|null $parserId
* @return mixed
* @throws ErrorResponseException
*/
protected function executeCommand(array $command, $keys, array $params = null, $parserId = null) {
$Protocol = $this->getProtocolByKey($keys);
$response = $this->executeProtocolCommand($Protocol, $command, $params);
if ($response instanceof ErrorResponseException) {
throw $response;
}
if ($this->transactionMode === self::TRANSACTION_MODE_NONE) {
if (isset($parserId)) {
return ResponseParser::parse($parserId, $response);
}
} else {
if ($this->transactionMode === self::TRANSACTION_MODE_STARTED) {
if ($response === self::TRANSACTION_RESPONSE_QUEUED) {
$this->responseParsers[] = $parserId;
}
} elseif ($this->transactionMode === self::TRANSACTION_MODE_EXECUTED) {
$this->setTransactionMode(self::TRANSACTION_MODE_NONE);
if (is_array($response) && count($this->responseParsers)
&& count($this->responseParsers) === count($response)) {
return array_map([ResponseParser::class, 'parse'], $this->responseParsers, $response);
}
}
}
return $response;
}
/**
* @param ProtocolInterface $Protocol
* @param array $command
* @param array|null $params
* @return mixed
* @throws ErrorResponseException
*/
protected function executeProtocolCommand(ProtocolInterface $Protocol, array $command, array $params = null) {
$response = $Protocol->send($this->getStructure($command, $params));
if ($response instanceof ErrorResponseException && $this->ClusterMap) {
if ($response instanceof MovedResponseException) {
$conf = $this->getConfig(self::CONFIG_CLUSTER);
if (!empty($conf['init_on_error_moved'])) {
$this->_syncClusterSlotsFromRedisServer();
} else {
$this->ClusterMap->addCluster($response->getSlot(), $response->getServer());
}
$this->Protocol = $this->ClusterMap->getProtocolByServer($response->getServer());
return $this->executeProtocolCommand($this->Protocol, $command, $params);
}
if ($response instanceof AskResponseException) {
$config = $this->getConfig();
$config['server'] = $response->getServer();
$TempRedisProtocol = $this->createProtocol($this, $config);
$TempRedisProtocol->send(['ASKING']);
return $this->executeProtocolCommand($TempRedisProtocol, $command, $params);
}
if ($response instanceof TryAgainResponseException) {
$config = $this->getConfig(self::CONFIG_CLUSTER);
if (isset($config['timeout_on_error_tryagain'])) {
usleep($config['timeout_on_error_tryagain'] * 1000000);
}
return $this->executeProtocolCommand($Protocol, $command, $params);
}
}
return $response;
}
/**
* @param string|string[] $keys
* @return ProtocolInterface
*/
protected function getProtocolByKey($keys) {
if (isset($keys) && $this->ClusterMap) {
$key = is_array($keys) ? $keys[0] : $keys;
if ($Protocol = $this->ClusterMap->getProtocolByKey($key)) {
return $this->Protocol = $Protocol;
}
}
return $this->getProtocol();
}
/**
* @param PipelineInterface $Pipeline
* @return mixed
* @throws ErrorResponseException
*/
protected function executePipeline(PipelineInterface $Pipeline) {
$Protocol = $this->getProtocolByKey($Pipeline->getKeys());
$responses = $Protocol->sendMulti($Pipeline->getStructure());
if (is_object($responses)) {
if ($responses instanceof ErrorResponseException) {
throw $responses;
}
}
return $Pipeline->parseResponse($responses);
}
/**
* @inheritdoc
*/
protected function subscribeCommand(array $subCommand, array $unsubCommand, ?array $params, $callback) {
$Protocol = $this->getProtocol();
$Protocol->subscribe($this->getStructure($subCommand, $params), $callback);
return $this->executeProtocolCommand($Protocol, $unsubCommand, $params);
}
/**
* @param string[] $command
* @param array|null $params
* @return string[]
*/
protected function getStructure(array $command, array $params = null) {
if (!isset($params)) {
return $command;
}
foreach ($params as $param) {
if (is_array($param)) {
foreach($param as $p) {
$command[] = $p;
}
} else {
$command[] = $param;
}
}
return $command;
}
/**
* @param int $transactionMode
*/
protected function setTransactionMode($transactionMode) {
$this->transactionMode = $transactionMode;
}
/**
* @param null|Pipeline|\Closure $Pipeline
* @return mixed|Pipeline
* @throws InvalidArgumentException
*/
public function pipeline($Pipeline = null) {
if (!$Pipeline) {
return $this->createPipeline();
}
if ($Pipeline instanceof \Closure) {
$Pipeline = $this->createPipeline($Pipeline);
}
if ($Pipeline instanceof PipelineInterface) {
return $this->executePipeline($Pipeline);
}
throw new InvalidArgumentException();
}
/**
* @param \Closure|null $Pipeline
* @return PipelineInterface
*/
abstract protected function createPipeline(\Closure $Pipeline = null);
/**
* @param string[] $structure
* @return mixed
* @throws ErrorResponseException
*/
public function executeRaw($structure) {
$response = $this->getProtocol()->send($structure);
if ($response instanceof ErrorResponseException) {
throw $response;
}
return $response;
}
/**
* @deprecated
* Command will parsed by the client, before sent to server
* @param string $command
* @return mixed
*/
public function executeRawString($command) {
return $this->executeRaw($this->parseRawString($command));
}
/**
* @deprecated
* @param string $command
* @return string[]
*/
public function parseRawString($command) {
$structure = [];
$line = ''; $quotes = false;
for ($i = 0, $length = strlen($command); $i <= $length; ++$i) {
if ($i === $length) {
if (isset($line[0])) {
$structure[] = $line;
$line = '';
}
break;
}
if ($command[$i] === '"' && $i && $command[$i - 1] !== '\\') {
$quotes = !$quotes;
if (!$quotes && !isset($line[0]) && $i + 1 === $length) {
$structure[] = $line;
$line = '';
}
} else if ($command[$i] === ' ' && !$quotes) {
if (isset($command[$i + 1]) && trim($command[$i + 1])) {
if (count($structure) || isset($line[0])) {
$structure[] = $line;
$line = '';
}
}
} else {
$line .= $command[$i];
}
}
array_walk($structure, function(&$line) {
$line = str_replace('\\"', '"', $line);
});
return $structure;
}
/**
* @param string $name
* @param array $arguments
* @return mixed
* @throws \Exception
*/
public function __call($name , array $arguments) {
if ($method = $this->getMethodNameForReservedWord($name)) {
return call_user_func_array([$this, $method], $arguments);
}
throw new CommandNotFoundException('Call to undefined method '. static::class. '::'. $name);
}
}