Predis.php 44 KB

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