Predis.php 39 KB

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