Predis.php 38 KB

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