Predis.php 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  1. <?php
  2. namespace Predis;
  3. class PredisException extends \Exception { }
  4. class ClientException extends PredisException { }
  5. class ServerException extends PredisException { }
  6. class MalformedServerResponse extends ServerException { }
  7. /* ------------------------------------------------------------------------- */
  8. class Client {
  9. // TODO: command arguments should be sanitized or checked for bad arguments
  10. // (e.g. CRLF in keys for inline commands)
  11. private $_connection, $_serverProfile;
  12. public function __construct($host = Connection::DEFAULT_HOST, $port = Connection::DEFAULT_PORT) {
  13. // TODO: for now the server compatibility profile is hardcoded.
  14. $this->_serverProfile = new RedisServer__V1_2();
  15. $this->setConnection($this->createConnection(
  16. func_num_args() === 1 && is_array($host) || @stripos('redis://') === 0
  17. ? $host
  18. : array('host' => $host, 'port' => $port)
  19. ));
  20. }
  21. public function __destruct() {
  22. $this->_connection->disconnect();
  23. }
  24. public static function create(/* arguments */) {
  25. $argv = func_get_args();
  26. $argc = func_num_args();
  27. if ($argc == 1) {
  28. return new Client($argv[0]);
  29. }
  30. else if ($argc > 1) {
  31. $client = new Client();
  32. $cluster = new ConnectionCluster();
  33. foreach ($argv as $parameters) {
  34. // TODO: this is a bit dirty...
  35. $cluster->add($client->createConnection($parameters));
  36. }
  37. $client->setConnection($cluster);
  38. return $client;
  39. }
  40. else {
  41. return new Client();
  42. }
  43. }
  44. private function createConnection($parameters) {
  45. $params = new ConnectionParameters($parameters);
  46. $connection = new Connection($params);
  47. if ($params->password !== null) {
  48. $connection->pushInitCommand($this->createCommandInstance(
  49. 'auth', array($params->password)
  50. ));
  51. }
  52. if ($params->database !== null) {
  53. $connection->pushInitCommand($this->createCommandInstance(
  54. 'select', array($params->database)
  55. ));
  56. }
  57. return $connection;
  58. }
  59. private function setConnection(IConnection $connection) {
  60. $this->_connection = $connection;
  61. }
  62. public function connect() {
  63. $this->_connection->connect();
  64. }
  65. public function disconnect() {
  66. $this->_connection->disconnect();
  67. }
  68. public function isConnected() {
  69. return $this->_connection->isConnected();
  70. }
  71. public function getConnection() {
  72. return $this->_connection;
  73. }
  74. public function __call($method, $arguments) {
  75. $command = $this->createCommandInstance($method, $arguments);
  76. return $this->executeCommand($command);
  77. }
  78. public function createCommandInstance($method, $arguments) {
  79. return $this->_serverProfile->createCommandInstance($method, $arguments);
  80. }
  81. public function executeCommand(Command $command) {
  82. $this->_connection->writeCommand($command);
  83. if ($command->closesConnection()) {
  84. return $this->_connection->disconnect();
  85. }
  86. return $this->_connection->readResponse($command);
  87. }
  88. public function rawCommand($rawCommandData, $closesConnection = false) {
  89. // TODO: rather than check the type of a connection instance, we should
  90. // check if it does respond to the rawCommand method.
  91. if (is_a($this->_connection, '\Predis\ConnectionCluster')) {
  92. throw new ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  93. }
  94. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  95. }
  96. public function pipeline(\Closure $pipelineBlock = null) {
  97. $pipeline = new CommandPipeline($this);
  98. return $pipelineBlock !== null ? $pipeline->execute($pipelineBlock) : $pipeline;
  99. }
  100. public function registerCommands(Array $commands) {
  101. $this->_serverProfile->registerCommands($commands);
  102. }
  103. public function registerCommand($command, $aliases) {
  104. $this->_serverProfile->registerCommand($command, $aliases);
  105. }
  106. }
  107. /* ------------------------------------------------------------------------- */
  108. abstract class Command {
  109. private $_arguments;
  110. public abstract function getCommandId();
  111. public abstract function serializeRequest($command, $arguments);
  112. public function canBeHashed() {
  113. return true;
  114. }
  115. public function closesConnection() {
  116. return false;
  117. }
  118. protected function filterArguments(Array $arguments) {
  119. return $arguments;
  120. }
  121. public function setArguments(/* arguments */) {
  122. $this->_arguments = $this->filterArguments(func_get_args());
  123. }
  124. public function setArgumentsArray(Array $arguments) {
  125. $this->_arguments = $this->filterArguments($arguments);
  126. }
  127. protected function getArguments() {
  128. return $this->_arguments !== null ? $this->_arguments : array();
  129. }
  130. public function getArgument($index = 0) {
  131. return $this->_arguments !== null ? $this->_arguments[$index] : null;
  132. }
  133. public function parseResponse($data) {
  134. return $data;
  135. }
  136. public final function __invoke() {
  137. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  138. }
  139. }
  140. abstract class InlineCommand extends Command {
  141. public function serializeRequest($command, $arguments) {
  142. if (isset($arguments[0]) && is_array($arguments[0])) {
  143. $arguments[0] = implode($arguments[0], ' ');
  144. }
  145. return $command . ' ' . implode($arguments, ' ') . Response::NEWLINE;
  146. }
  147. }
  148. abstract class BulkCommand extends Command {
  149. public function serializeRequest($command, $arguments) {
  150. $data = array_pop($arguments);
  151. if (is_array($data)) {
  152. $data = implode($data, ' ');
  153. }
  154. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  155. Response::NEWLINE . $data . Response::NEWLINE;
  156. }
  157. }
  158. abstract class MultiBulkCommand extends Command {
  159. public function serializeRequest($command, $arguments) {
  160. $buffer = array();
  161. $cmd_args = null;
  162. if (count($arguments) === 1 && is_array($arguments[0])) {
  163. $cmd_args = array();
  164. foreach ($arguments[0] as $k => $v) {
  165. $cmd_args[] = $k;
  166. $cmd_args[] = $v;
  167. }
  168. }
  169. else {
  170. $cmd_args = $arguments;
  171. }
  172. $buffer[] = '*' . ((string) count($cmd_args) + 1) . Response::NEWLINE;
  173. $buffer[] = '$' . strlen($command) . Response::NEWLINE . $command . Response::NEWLINE;
  174. foreach ($cmd_args as $argument) {
  175. $buffer[] = '$' . strlen($argument) . Response::NEWLINE . $argument . Response::NEWLINE;
  176. }
  177. return implode('', $buffer);
  178. }
  179. }
  180. /* ------------------------------------------------------------------------- */
  181. class Response {
  182. const NEWLINE = "\r\n";
  183. const OK = 'OK';
  184. const ERROR = 'ERR';
  185. const NULL = 'nil';
  186. private static $_prefixHandlers;
  187. private static function initializePrefixHandlers() {
  188. return array(
  189. // status
  190. '+' => function($socket) {
  191. $status = rtrim(fgets($socket), Response::NEWLINE);
  192. return $status === Response::OK ? true : $status;
  193. },
  194. // error
  195. '-' => function($socket) {
  196. $errorMessage = rtrim(fgets($socket), Response::NEWLINE);
  197. throw new ServerException(substr($errorMessage, 4));
  198. },
  199. // bulk
  200. '$' => function($socket) {
  201. $dataLength = rtrim(fgets($socket), Response::NEWLINE);
  202. if (!is_numeric($dataLength)) {
  203. throw new ClientException("Cannot parse '$dataLength' as data length");
  204. }
  205. if ($dataLength > 0) {
  206. $value = stream_get_contents($socket, $dataLength);
  207. fread($socket, 2);
  208. return $value;
  209. }
  210. else if ($dataLength == 0) {
  211. // TODO: I just have a doubt here...
  212. fread($socket, 2);
  213. }
  214. return null;
  215. },
  216. // multibulk
  217. '*' => function($socket) {
  218. $rawLength = rtrim(fgets($socket), Response::NEWLINE);
  219. if (!is_numeric($rawLength)) {
  220. throw new ClientException("Cannot parse '$rawLength' as data length");
  221. }
  222. $listLength = (int) $rawLength;
  223. if ($listLength === -1) {
  224. return null;
  225. }
  226. $list = array();
  227. if ($listLength > 0) {
  228. for ($i = 0; $i < $listLength; $i++) {
  229. $handler = Response::getPrefixHandler(fgetc($socket));
  230. $list[] = $handler($socket);
  231. }
  232. }
  233. return $list;
  234. },
  235. // integer
  236. ':' => function($socket) {
  237. $number = rtrim(fgets($socket), Response::NEWLINE);
  238. if (is_numeric($number)) {
  239. return (int) $number;
  240. }
  241. else {
  242. if ($number !== Response::NULL) {
  243. throw new ClientException("Cannot parse '$number' as numeric response");
  244. }
  245. return null;
  246. }
  247. }
  248. );
  249. }
  250. public static function getPrefixHandler($prefix) {
  251. if (self::$_prefixHandlers == null) {
  252. self::$_prefixHandlers = self::initializePrefixHandlers();
  253. }
  254. $handler = self::$_prefixHandlers[$prefix];
  255. if ($handler === null) {
  256. throw new MalformedServerResponse("Unknown prefix '$prefix'");
  257. }
  258. return $handler;
  259. }
  260. }
  261. class CommandPipeline {
  262. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running;
  263. public function __construct(Client $redisClient) {
  264. $this->_redisClient = $redisClient;
  265. $this->_pipelineBuffer = array();
  266. $this->_returnValues = array();
  267. }
  268. public function __call($method, $arguments) {
  269. $command = $this->_redisClient->createCommandInstance($method, $arguments);
  270. $this->recordCommand($command);
  271. }
  272. private function recordCommand(Command $command) {
  273. $this->_pipelineBuffer[] = $command;
  274. }
  275. private function getRecordedCommands() {
  276. return $this->_pipelineBuffer;
  277. }
  278. public function flushPipeline() {
  279. if (count($this->_pipelineBuffer) === 0) {
  280. return;
  281. }
  282. $connection = $this->_redisClient->getConnection();
  283. $commands = &$this->getRecordedCommands();
  284. foreach ($commands as $command) {
  285. $connection->writeCommand($command);
  286. }
  287. foreach ($commands as $command) {
  288. $this->_returnValues[] = $connection->readResponse($command);
  289. }
  290. $this->_pipelineBuffer = array();
  291. }
  292. private function setRunning($bool) {
  293. // TODO: I am honest when I say that I don't like this approach.
  294. if ($bool == true && $this->_running == true) {
  295. throw new ClientException("This pipeline is already opened");
  296. }
  297. $this->_running = $bool;
  298. }
  299. public function execute(\Closure $block = null) {
  300. $this->setRunning(true);
  301. $pipelineBlockException = null;
  302. try {
  303. if ($block !== null) {
  304. $block($this);
  305. }
  306. $this->flushPipeline();
  307. }
  308. catch (\Exception $exception) {
  309. $pipelineBlockException = $exception;
  310. }
  311. $this->setRunning(false);
  312. if ($pipelineBlockException !== null) {
  313. throw $pipelineBlockException;
  314. }
  315. return $this->_returnValues;
  316. }
  317. }
  318. /* ------------------------------------------------------------------------- */
  319. class ConnectionParameters {
  320. private $_parameters;
  321. public function __construct($parameters) {
  322. $this->_parameters = is_array($parameters)
  323. ? self::filterConnectionParams($parameters)
  324. : self::parseURI($parameters);
  325. }
  326. private static function parseURI($uri) {
  327. $parsed = @parse_url($uri);
  328. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  329. throw new ClientException("Invalid URI: $uri");
  330. }
  331. if (array_key_exists('query', $parsed)) {
  332. $details = array();
  333. foreach (explode('&', $parsed['query']) as $kv) {
  334. list($k, $v) = explode('=', $kv);
  335. switch ($k) {
  336. case 'database':
  337. $details['database'] = $v;
  338. break;
  339. case 'password':
  340. $details['password'] = $v;
  341. break;
  342. }
  343. }
  344. $parsed = array_merge($parsed, $details);
  345. }
  346. return self::filterConnectionParams($parsed);
  347. }
  348. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  349. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  350. }
  351. private static function filterConnectionParams($parameters) {
  352. return array(
  353. 'host' => self::getParamOrDefault($parameters, 'host', Connection::DEFAULT_HOST),
  354. 'port' => (int) self::getParamOrDefault($parameters, 'port', Connection::DEFAULT_PORT),
  355. 'database' => self::getParamOrDefault($parameters, 'database'),
  356. 'password' => self::getParamOrDefault($parameters, 'password')
  357. );
  358. }
  359. public function __get($parameter) {
  360. return $this->_parameters[$parameter];
  361. }
  362. }
  363. interface IConnection {
  364. public function connect();
  365. public function disconnect();
  366. public function isConnected();
  367. public function writeCommand(Command $command);
  368. public function readResponse(Command $command);
  369. }
  370. class Connection implements IConnection {
  371. const DEFAULT_HOST = '127.0.0.1';
  372. const DEFAULT_PORT = 6379;
  373. const CONNECTION_TIMEOUT = 2;
  374. const READ_WRITE_TIMEOUT = 5;
  375. private $_params, $_socket, $_initCmds;
  376. public function __construct(ConnectionParameters $parameters) {
  377. $this->_params = $parameters;
  378. $this->_initCmds = array();
  379. }
  380. public function __destruct() {
  381. $this->disconnect();
  382. }
  383. public function isConnected() {
  384. return is_resource($this->_socket);
  385. }
  386. public function connect() {
  387. if ($this->isConnected()) {
  388. throw new ClientException('Connection already estabilished');
  389. }
  390. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  391. $this->_socket = @stream_socket_client($uri, $errno, $errstr, self::CONNECTION_TIMEOUT);
  392. if (!$this->_socket) {
  393. throw new ClientException(trim($errstr), $errno);
  394. }
  395. stream_set_timeout($this->_socket, self::READ_WRITE_TIMEOUT);
  396. if (count($this->_initCmds) > 0){
  397. $this->sendInitializationCommands();
  398. }
  399. }
  400. public function disconnect() {
  401. if ($this->isConnected()) {
  402. fclose($this->_socket);
  403. }
  404. }
  405. public function pushInitCommand(Command $command){
  406. $this->_initCmds[] = $command;
  407. }
  408. private function sendInitializationCommands() {
  409. foreach ($this->_initCmds as $command) {
  410. $this->writeCommand($command);
  411. }
  412. foreach ($this->_initCmds as $command) {
  413. $this->readResponse($command);
  414. }
  415. }
  416. public function writeCommand(Command $command) {
  417. fwrite($this->getSocket(), $command());
  418. }
  419. public function readResponse(Command $command) {
  420. $socket = $this->getSocket();
  421. $handler = Response::getPrefixHandler(fgetc($socket));
  422. $response = $command->parseResponse($handler($socket));
  423. return $response;
  424. }
  425. public function rawCommand($rawCommandData, $closesConnection = false) {
  426. $socket = $this->getSocket();
  427. fwrite($socket, $rawCommandData);
  428. if ($closesConnection) {
  429. return;
  430. }
  431. $handler = Response::getPrefixHandler(fgetc($socket));
  432. return $handler($socket);
  433. }
  434. public function getSocket() {
  435. if (!$this->isConnected()) {
  436. $this->connect();
  437. }
  438. return $this->_socket;
  439. }
  440. public function __toString() {
  441. return sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  442. }
  443. }
  444. class ConnectionCluster implements IConnection {
  445. // TODO: storing a temporary map of commands hashes to hashring items (that
  446. // is, connections) could offer a notable speedup, but I am wondering
  447. // about the increased memory footprint.
  448. // TODO: find a clean way to handle connection failures of single nodes.
  449. private $_pool, $_ring;
  450. public function __construct() {
  451. $this->_pool = array();
  452. $this->_ring = new Utilities\HashRing();
  453. }
  454. public function __destruct() {
  455. $this->disconnect();
  456. }
  457. public function isConnected() {
  458. foreach ($this->_pool as $connection) {
  459. if ($connection->isConnected()) {
  460. return true;
  461. }
  462. }
  463. return false;
  464. }
  465. public function connect() {
  466. foreach ($this->_pool as $connection) {
  467. $connection->connect();
  468. }
  469. }
  470. public function disconnect() {
  471. foreach ($this->_pool as $connection) {
  472. $connection->disconnect();
  473. }
  474. }
  475. public function add(Connection $connection) {
  476. $this->_pool[] = $connection;
  477. $this->_ring->add($connection);
  478. }
  479. private function getConnectionFromRing(Command $command) {
  480. return $this->_ring->get($this->computeHash($command));
  481. }
  482. private function computeHash(Command $command) {
  483. return crc32($command->getArgument(0));
  484. }
  485. private function getConnection(Command $command) {
  486. return $command->canBeHashed()
  487. ? $this->getConnectionFromRing($command)
  488. : $this->getConnectionById(0);
  489. }
  490. public function getConnectionById($id = null) {
  491. return $this->_pool[$id === null ? 0 : $id];
  492. }
  493. public function writeCommand(Command $command) {
  494. $this->getConnection($command)->writeCommand($command);
  495. }
  496. public function readResponse(Command $command) {
  497. return $this->getConnection($command)->readResponse($command);
  498. }
  499. }
  500. /* ------------------------------------------------------------------------- */
  501. abstract class RedisServerProfile {
  502. private $_registeredCommands;
  503. public function __construct() {
  504. $this->_registeredCommands = $this->getSupportedCommands();
  505. }
  506. public abstract function getVersion();
  507. protected abstract function getSupportedCommands();
  508. public function createCommandInstance($method, $arguments) {
  509. $commandClass = $this->_registeredCommands[$method];
  510. if ($commandClass === null) {
  511. throw new ClientException("'$method' is not a registered Redis command");
  512. }
  513. $command = new $commandClass();
  514. $command->setArgumentsArray($arguments);
  515. return $command;
  516. }
  517. public function registerCommands(Array $commands) {
  518. foreach ($commands as $command => $aliases) {
  519. $this->registerCommand($command, $aliases);
  520. }
  521. }
  522. public function registerCommand($command, $aliases) {
  523. $commandReflection = new \ReflectionClass($command);
  524. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  525. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  526. }
  527. if (is_array($aliases)) {
  528. foreach ($aliases as $alias) {
  529. $this->_registeredCommands[$alias] = $command;
  530. }
  531. }
  532. else {
  533. $this->_registeredCommands[$aliases] = $command;
  534. }
  535. }
  536. }
  537. class RedisServer__V1_0 extends RedisServerProfile {
  538. public function getVersion() { return 1.0; }
  539. public function getSupportedCommands() {
  540. return array(
  541. /* miscellaneous commands */
  542. 'ping' => '\Predis\Commands\Ping',
  543. 'echo' => '\Predis\Commands\DoEcho',
  544. 'auth' => '\Predis\Commands\Auth',
  545. /* connection handling */
  546. 'quit' => '\Predis\Commands\Quit',
  547. /* commands operating on string values */
  548. 'set' => '\Predis\Commands\Set',
  549. 'setnx' => '\Predis\Commands\SetPreserve',
  550. 'setPreserve' => '\Predis\Commands\SetPreserve',
  551. 'get' => '\Predis\Commands\Get',
  552. 'mget' => '\Predis\Commands\GetMultiple',
  553. 'getMultiple' => '\Predis\Commands\GetMultiple',
  554. 'getset' => '\Predis\Commands\GetSet',
  555. 'getSet' => '\Predis\Commands\GetSet',
  556. 'incr' => '\Predis\Commands\Increment',
  557. 'increment' => '\Predis\Commands\Increment',
  558. 'incrby' => '\Predis\Commands\IncrementBy',
  559. 'incrementBy' => '\Predis\Commands\IncrementBy',
  560. 'decr' => '\Predis\Commands\Decrement',
  561. 'decrement' => '\Predis\Commands\Decrement',
  562. 'decrby' => '\Predis\Commands\DecrementBy',
  563. 'decrementBy' => '\Predis\Commands\DecrementBy',
  564. 'exists' => '\Predis\Commands\Exists',
  565. 'del' => '\Predis\Commands\Delete',
  566. 'delete' => '\Predis\Commands\Delete',
  567. 'type' => '\Predis\Commands\Type',
  568. /* commands operating on the key space */
  569. 'keys' => '\Predis\Commands\Keys',
  570. 'randomkey' => '\Predis\Commands\RandomKey',
  571. 'randomKey' => '\Predis\Commands\RandomKey',
  572. 'rename' => '\Predis\Commands\Rename',
  573. 'renamenx' => '\Predis\Commands\RenamePreserve',
  574. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  575. 'expire' => '\Predis\Commands\Expire',
  576. 'expireat' => '\Predis\Commands\ExpireAt',
  577. 'expireAt' => '\Predis\Commands\ExpireAt',
  578. 'dbsize' => '\Predis\Commands\DatabaseSize',
  579. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  580. 'ttl' => '\Predis\Commands\TimeToLive',
  581. 'timeToLive' => '\Predis\Commands\TimeToLive',
  582. /* commands operating on lists */
  583. 'rpush' => '\Predis\Commands\ListPushTail',
  584. 'pushTail' => '\Predis\Commands\ListPushTail',
  585. 'lpush' => '\Predis\Commands\ListPushHead',
  586. 'pushHead' => '\Predis\Commands\ListPushHead',
  587. 'llen' => '\Predis\Commands\ListLength',
  588. 'listLength' => '\Predis\Commands\ListLength',
  589. 'lrange' => '\Predis\Commands\ListRange',
  590. 'listRange' => '\Predis\Commands\ListRange',
  591. 'ltrim' => '\Predis\Commands\ListTrim',
  592. 'listTrim' => '\Predis\Commands\ListTrim',
  593. 'lindex' => '\Predis\Commands\ListIndex',
  594. 'listIndex' => '\Predis\Commands\ListIndex',
  595. 'lset' => '\Predis\Commands\ListSet',
  596. 'listSet' => '\Predis\Commands\ListSet',
  597. 'lrem' => '\Predis\Commands\ListRemove',
  598. 'listRemove' => '\Predis\Commands\ListRemove',
  599. 'lpop' => '\Predis\Commands\ListPopFirst',
  600. 'popFirst' => '\Predis\Commands\ListPopFirst',
  601. 'rpop' => '\Predis\Commands\ListPopLast',
  602. 'popLast' => '\Predis\Commands\ListPopLast',
  603. /* commands operating on sets */
  604. 'sadd' => '\Predis\Commands\SetAdd',
  605. 'setAdd' => '\Predis\Commands\SetAdd',
  606. 'srem' => '\Predis\Commands\SetRemove',
  607. 'setRemove' => '\Predis\Commands\SetRemove',
  608. 'spop' => '\Predis\Commands\SetPop',
  609. 'setPop' => '\Predis\Commands\SetPop',
  610. 'smove' => '\Predis\Commands\SetMove',
  611. 'setMove' => '\Predis\Commands\SetMove',
  612. 'scard' => '\Predis\Commands\SetCardinality',
  613. 'setCardinality' => '\Predis\Commands\SetCardinality',
  614. 'sismember' => '\Predis\Commands\SetIsMember',
  615. 'setIsMember' => '\Predis\Commands\SetIsMember',
  616. 'sinter' => '\Predis\Commands\SetIntersection',
  617. 'setIntersection' => '\Predis\Commands\SetIntersection',
  618. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  619. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  620. 'sunion' => '\Predis\Commands\SetUnion',
  621. 'setUnion' => '\Predis\Commands\SetUnion',
  622. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  623. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  624. 'sdiff' => '\Predis\Commands\SetDifference',
  625. 'setDifference' => '\Predis\Commands\SetDifference',
  626. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  627. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  628. 'smembers' => '\Predis\Commands\SetMembers',
  629. 'setMembers' => '\Predis\Commands\SetMembers',
  630. 'srandmember' => '\Predis\Commands\SetRandomMember',
  631. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  632. /* multiple databases handling commands */
  633. 'select' => '\Predis\Commands\SelectDatabase',
  634. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  635. 'move' => '\Predis\Commands\MoveKey',
  636. 'moveKey' => '\Predis\Commands\MoveKey',
  637. 'flushdb' => '\Predis\Commands\FlushDatabase',
  638. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  639. 'flushall' => '\Predis\Commands\FlushAll',
  640. 'flushDatabases' => '\Predis\Commands\FlushAll',
  641. /* sorting */
  642. 'sort' => '\Predis\Commands\Sort',
  643. /* remote server control commands */
  644. 'info' => '\Predis\Commands\Info',
  645. 'slaveof' => '\Predis\Commands\SlaveOf',
  646. 'slaveOf' => '\Predis\Commands\SlaveOf',
  647. /* persistence control commands */
  648. 'save' => '\Predis\Commands\Save',
  649. 'bgsave' => '\Predis\Commands\BackgroundSave',
  650. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  651. 'lastsave' => '\Predis\Commands\LastSave',
  652. 'lastSave' => '\Predis\Commands\LastSave',
  653. 'shutdown' => '\Predis\Commands\Shutdown'
  654. );
  655. }
  656. }
  657. class RedisServer__V1_2 extends RedisServer__V1_0 {
  658. public function getVersion() { return 1.2; }
  659. public function getSupportedCommands() {
  660. return array_merge(parent::getSupportedCommands(), array(
  661. /* commands operating on string values */
  662. 'mset' => '\Predis\Commands\SetMultiple',
  663. 'setMultiple' => '\Predis\Commands\SetMultiple',
  664. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  665. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  666. /* commands operating on lists */
  667. 'rpoplpush' => '\Predis\Commands\ListPushTailPopFirst',
  668. 'listPopLastPushHead' => '\Predis\Commands\ListPopLastPushHead',
  669. /* commands operating on sorted sets */
  670. 'zadd' => '\Predis\Commands\ZSetAdd',
  671. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  672. 'zrem' => '\Predis\Commands\ZSetRemove',
  673. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  674. 'zrange' => '\Predis\Commands\ZSetRange',
  675. 'zsetRange' => '\Predis\Commands\ZSetRange',
  676. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  677. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  678. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  679. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  680. 'zcard' => '\Predis\Commands\ZSetCardinality',
  681. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  682. 'zscore' => '\Predis\Commands\ZSetScore',
  683. 'zsetScore' => '\Predis\Commands\ZSetScore',
  684. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  685. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore'
  686. ));
  687. }
  688. }
  689. /* ------------------------------------------------------------------------- */
  690. namespace Predis\Utilities;
  691. class HashRing {
  692. const DEFAULT_REPLICAS = 128;
  693. private $_ring, $_ringKeys, $_replicas;
  694. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  695. $this->_replicas = $replicas;
  696. $this->_ring = array();
  697. $this->_ringKeys = array();
  698. }
  699. public function add($node) {
  700. $nodeHash = (string) $node;
  701. for ($i = 0; $i < $this->_replicas; $i++) {
  702. $key = crc32($nodeHash . ':' . $i);
  703. $this->_ring[$key] = $node;
  704. }
  705. ksort($this->_ring, SORT_NUMERIC);
  706. $this->_ringKeys = array_keys($this->_ring);
  707. }
  708. public function remove($node) {
  709. $nodeHash = (string) $node;
  710. for ($i = 0; $i < $this->_replicas; $i++) {
  711. $key = crc32($nodeHash . ':' . $i);
  712. unset($this->_ring[$key]);
  713. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  714. return $rk !== $key;
  715. });
  716. }
  717. }
  718. public function get($key) {
  719. return $this->_ring[$this->getNodeKey($key)];
  720. }
  721. private function getNodeKey($key) {
  722. $upper = count($this->_ringKeys) - 1;
  723. $lower = 0;
  724. $index = 0;
  725. while ($lower <= $upper) {
  726. $index = ($lower + $upper) / 2;
  727. $item = $this->_ringKeys[$index];
  728. if ($item === $key) {
  729. return $index;
  730. }
  731. else if ($item > $key) {
  732. $upper = $index - 1;
  733. }
  734. else {
  735. $lower = $index + 1;
  736. }
  737. }
  738. return $this->_ringKeys[$upper];
  739. }
  740. }
  741. /* ------------------------------------------------------------------------- */
  742. namespace Predis\Commands;
  743. /* miscellaneous commands */
  744. class Ping extends \Predis\InlineCommand {
  745. public function canBeHashed() { return false; }
  746. public function getCommandId() { return 'PING'; }
  747. public function parseResponse($data) {
  748. return $data === 'PONG' ? true : false;
  749. }
  750. }
  751. class DoEcho extends \Predis\BulkCommand {
  752. public function canBeHashed() { return false; }
  753. public function getCommandId() { return 'ECHO'; }
  754. }
  755. class Auth extends \Predis\InlineCommand {
  756. public function canBeHashed() { return false; }
  757. public function getCommandId() { return 'AUTH'; }
  758. }
  759. /* connection handling */
  760. class Quit extends \Predis\InlineCommand {
  761. public function canBeHashed() { return false; }
  762. public function getCommandId() { return 'QUIT'; }
  763. public function closesConnection() { return true; }
  764. }
  765. /* commands operating on string values */
  766. class Set extends \Predis\BulkCommand {
  767. public function getCommandId() { return 'SET'; }
  768. }
  769. class SetPreserve extends \Predis\BulkCommand {
  770. public function getCommandId() { return 'SETNX'; }
  771. public function parseResponse($data) { return (bool) $data; }
  772. }
  773. class SetMultiple extends \Predis\MultiBulkCommand {
  774. public function canBeHashed() { return false; }
  775. public function getCommandId() { return 'MSET'; }
  776. }
  777. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  778. public function canBeHashed() { return false; }
  779. public function getCommandId() { return 'MSETNX'; }
  780. public function parseResponse($data) { return (bool) $data; }
  781. }
  782. class Get extends \Predis\InlineCommand {
  783. public function getCommandId() { return 'GET'; }
  784. }
  785. class GetMultiple extends \Predis\InlineCommand {
  786. public function canBeHashed() { return false; }
  787. public function getCommandId() { return 'MGET'; }
  788. }
  789. class GetSet extends \Predis\BulkCommand {
  790. public function getCommandId() { return 'GETSET'; }
  791. }
  792. class Increment extends \Predis\InlineCommand {
  793. public function getCommandId() { return 'INCR'; }
  794. }
  795. class IncrementBy extends \Predis\InlineCommand {
  796. public function getCommandId() { return 'INCRBY'; }
  797. }
  798. class Decrement extends \Predis\InlineCommand {
  799. public function getCommandId() { return 'DECR'; }
  800. }
  801. class DecrementBy extends \Predis\InlineCommand {
  802. public function getCommandId() { return 'DECRBY'; }
  803. }
  804. class Exists extends \Predis\InlineCommand {
  805. public function getCommandId() { return 'EXISTS'; }
  806. public function parseResponse($data) { return (bool) $data; }
  807. }
  808. class Delete extends \Predis\InlineCommand {
  809. public function getCommandId() { return 'DEL'; }
  810. public function parseResponse($data) { return (bool) $data; }
  811. }
  812. class Type extends \Predis\InlineCommand {
  813. public function getCommandId() { return 'TYPE'; }
  814. }
  815. /* commands operating on the key space */
  816. class Keys extends \Predis\InlineCommand {
  817. public function canBeHashed() { return false; }
  818. public function getCommandId() { return 'KEYS'; }
  819. public function parseResponse($data) {
  820. // TODO: is this behaviour correct?
  821. return strlen($data) > 0 ? explode(' ', $data) : array();
  822. }
  823. }
  824. class RandomKey extends \Predis\InlineCommand {
  825. public function canBeHashed() { return false; }
  826. public function getCommandId() { return 'RANDOMKEY'; }
  827. public function parseResponse($data) { return $data !== '' ? $data : null; }
  828. }
  829. class Rename extends \Predis\InlineCommand {
  830. // TODO: doesn't RENAME break the hash-based client-side sharding?
  831. public function canBeHashed() { return false; }
  832. public function getCommandId() { return 'RENAME'; }
  833. }
  834. class RenamePreserve extends \Predis\InlineCommand {
  835. public function canBeHashed() { return false; }
  836. public function getCommandId() { return 'RENAMENX'; }
  837. public function parseResponse($data) { return (bool) $data; }
  838. }
  839. class Expire extends \Predis\InlineCommand {
  840. public function getCommandId() { return 'EXPIRE'; }
  841. public function parseResponse($data) { return (bool) $data; }
  842. }
  843. class ExpireAt extends \Predis\InlineCommand {
  844. public function getCommandId() { return 'EXPIREAT'; }
  845. public function parseResponse($data) { return (bool) $data; }
  846. }
  847. class DatabaseSize extends \Predis\InlineCommand {
  848. public function canBeHashed() { return false; }
  849. public function getCommandId() { return 'DBSIZE'; }
  850. }
  851. class TimeToLive extends \Predis\InlineCommand {
  852. public function getCommandId() { return 'TTL'; }
  853. }
  854. /* commands operating on lists */
  855. class ListPushTail extends \Predis\BulkCommand {
  856. public function getCommandId() { return 'RPUSH'; }
  857. }
  858. class ListPushHead extends \Predis\BulkCommand {
  859. public function getCommandId() { return 'LPUSH'; }
  860. }
  861. class ListLength extends \Predis\InlineCommand {
  862. public function getCommandId() { return 'LLEN'; }
  863. }
  864. class ListRange extends \Predis\InlineCommand {
  865. public function getCommandId() { return 'LRANGE'; }
  866. }
  867. class ListTrim extends \Predis\InlineCommand {
  868. public function getCommandId() { return 'LTRIM'; }
  869. }
  870. class ListIndex extends \Predis\InlineCommand {
  871. public function getCommandId() { return 'LINDEX'; }
  872. }
  873. class ListSet extends \Predis\BulkCommand {
  874. public function getCommandId() { return 'LSET'; }
  875. }
  876. class ListRemove extends \Predis\BulkCommand {
  877. public function getCommandId() { return 'LREM'; }
  878. }
  879. class ListPopLastPushHead extends \Predis\BulkCommand {
  880. public function getCommandId() { return 'RPOPLPUSH'; }
  881. }
  882. class ListPopFirst extends \Predis\InlineCommand {
  883. public function getCommandId() { return 'LPOP'; }
  884. }
  885. class ListPopLast extends \Predis\InlineCommand {
  886. public function getCommandId() { return 'RPOP'; }
  887. }
  888. /* commands operating on sets */
  889. class SetAdd extends \Predis\BulkCommand {
  890. public function getCommandId() { return 'SADD'; }
  891. public function parseResponse($data) { return (bool) $data; }
  892. }
  893. class SetRemove extends \Predis\BulkCommand {
  894. public function getCommandId() { return 'SREM'; }
  895. public function parseResponse($data) { return (bool) $data; }
  896. }
  897. class SetPop extends \Predis\InlineCommand {
  898. public function getCommandId() { return 'SPOP'; }
  899. }
  900. class SetMove extends \Predis\BulkCommand {
  901. public function canBeHashed() { return false; }
  902. public function getCommandId() { return 'SMOVE'; }
  903. public function parseResponse($data) { return (bool) $data; }
  904. }
  905. class SetCardinality extends \Predis\InlineCommand {
  906. public function getCommandId() { return 'SCARD'; }
  907. }
  908. class SetIsMember extends \Predis\BulkCommand {
  909. public function getCommandId() { return 'SISMEMBER'; }
  910. public function parseResponse($data) { return (bool) $data; }
  911. }
  912. class SetIntersection extends \Predis\InlineCommand {
  913. public function getCommandId() { return 'SINTER'; }
  914. }
  915. class SetIntersectionStore extends \Predis\InlineCommand {
  916. public function getCommandId() { return 'SINTERSTORE'; }
  917. }
  918. class SetUnion extends \Predis\InlineCommand {
  919. public function getCommandId() { return 'SUNION'; }
  920. }
  921. class SetUnionStore extends \Predis\InlineCommand {
  922. public function getCommandId() { return 'SUNIONSTORE'; }
  923. }
  924. class SetDifference extends \Predis\InlineCommand {
  925. public function getCommandId() { return 'SDIFF'; }
  926. }
  927. class SetDifferenceStore extends \Predis\InlineCommand {
  928. public function getCommandId() { return 'SDIFFSTORE'; }
  929. }
  930. class SetMembers extends \Predis\InlineCommand {
  931. public function getCommandId() { return 'SMEMBERS'; }
  932. }
  933. class SetRandomMember extends \Predis\InlineCommand {
  934. public function getCommandId() { return 'SRANDMEMBER'; }
  935. }
  936. /* commands operating on sorted sets */
  937. class ZSetAdd extends \Predis\BulkCommand {
  938. public function getCommandId() { return 'ZADD'; }
  939. public function parseResponse($data) { return (bool) $data; }
  940. }
  941. class ZSetRemove extends \Predis\BulkCommand {
  942. public function getCommandId() { return 'ZREM'; }
  943. public function parseResponse($data) { return (bool) $data; }
  944. }
  945. class ZSetRange extends \Predis\InlineCommand {
  946. public function getCommandId() { return 'ZRANGE'; }
  947. }
  948. class ZSetReverseRange extends \Predis\InlineCommand {
  949. public function getCommandId() { return 'ZREVRANGE'; }
  950. }
  951. class ZSetRangeByScore extends \Predis\InlineCommand {
  952. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  953. }
  954. class ZSetCardinality extends \Predis\InlineCommand {
  955. public function getCommandId() { return 'ZCARD'; }
  956. }
  957. class ZSetScore extends \Predis\BulkCommand {
  958. public function getCommandId() { return 'ZSCORE'; }
  959. }
  960. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  961. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  962. }
  963. /* multiple databases handling commands */
  964. class SelectDatabase extends \Predis\InlineCommand {
  965. public function canBeHashed() { return false; }
  966. public function getCommandId() { return 'SELECT'; }
  967. }
  968. class MoveKey extends \Predis\InlineCommand {
  969. public function canBeHashed() { return false; }
  970. public function getCommandId() { return 'MOVE'; }
  971. public function parseResponse($data) { return (bool) $data; }
  972. }
  973. class FlushDatabase extends \Predis\InlineCommand {
  974. public function canBeHashed() { return false; }
  975. public function getCommandId() { return 'FLUSHDB'; }
  976. }
  977. class FlushAll extends \Predis\InlineCommand {
  978. public function canBeHashed() { return false; }
  979. public function getCommandId() { return 'FLUSHALL'; }
  980. }
  981. /* sorting */
  982. class Sort extends \Predis\InlineCommand {
  983. public function getCommandId() { return 'SORT'; }
  984. public function filterArguments($arguments) {
  985. if (count($arguments) === 1) {
  986. return $arguments;
  987. }
  988. // TODO: add more parameters checks
  989. $query = array($arguments[0]);
  990. $sortParams = $arguments[1];
  991. if (isset($sortParams['by'])) {
  992. $query[] = 'BY ' . $sortParams['by'];
  993. }
  994. if (isset($sortParams['get'])) {
  995. $query[] = 'GET ' . $sortParams['get'];
  996. }
  997. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  998. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  999. }
  1000. if (isset($sortParams['sort'])) {
  1001. $query[] = strtoupper($sortParams['sort']);
  1002. }
  1003. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1004. $query[] = 'ALPHA';
  1005. }
  1006. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1007. $query[] = 'STORE ' . $sortParams['store'];
  1008. }
  1009. return $query;
  1010. }
  1011. }
  1012. /* persistence control commands */
  1013. class Save extends \Predis\InlineCommand {
  1014. public function canBeHashed() { return false; }
  1015. public function getCommandId() { return 'SAVE'; }
  1016. }
  1017. class BackgroundSave extends \Predis\InlineCommand {
  1018. public function canBeHashed() { return false; }
  1019. public function getCommandId() { return 'BGSAVE'; }
  1020. }
  1021. class LastSave extends \Predis\InlineCommand {
  1022. public function canBeHashed() { return false; }
  1023. public function getCommandId() { return 'LASTSAVE'; }
  1024. }
  1025. class Shutdown extends \Predis\InlineCommand {
  1026. public function canBeHashed() { return false; }
  1027. public function getCommandId() { return 'SHUTDOWN'; }
  1028. public function closesConnection() { return true; }
  1029. }
  1030. /* remote server control commands */
  1031. class Info extends \Predis\InlineCommand {
  1032. public function canBeHashed() { return false; }
  1033. public function getCommandId() { return 'INFO'; }
  1034. public function parseResponse($data) {
  1035. $info = array();
  1036. $infoLines = explode("\r\n", $data, -1);
  1037. foreach ($infoLines as $row) {
  1038. list($k, $v) = explode(':', $row);
  1039. if (!preg_match('/^db\d+$/', $k)) {
  1040. $info[$k] = $v;
  1041. }
  1042. else {
  1043. $db = array();
  1044. foreach (explode(',', $v) as $dbvar) {
  1045. list($dbvk, $dbvv) = explode('=', $dbvar);
  1046. $db[trim($dbvk)] = $dbvv;
  1047. }
  1048. $info[$k] = $db;
  1049. }
  1050. }
  1051. return $info;
  1052. }
  1053. }
  1054. class SlaveOf extends \Predis\InlineCommand {
  1055. public function canBeHashed() { return false; }
  1056. public function getCommandId() { return 'SLAVEOF'; }
  1057. public function filterArguments($arguments) {
  1058. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1059. }
  1060. }
  1061. ?>