Predis.php 44 KB

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