Predis.php 44 KB

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