Predis.php 44 KB

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