Predis.php 44 KB

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