Predis.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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 = null) {
  78. $pipeline = new CommandPipeline($this);
  79. return $pipelineBlock !== null ? $pipeline->execute($pipelineBlock) : $pipeline;
  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 = null) {
  433. $this->setRunning(true);
  434. $pipelineBlockException = null;
  435. try {
  436. if ($block !== null) {
  437. $block($this);
  438. }
  439. $this->flushPipeline();
  440. }
  441. catch (\Exception $exception) {
  442. $pipelineBlockException = $exception;
  443. }
  444. $this->setRunning(false);
  445. if ($pipelineBlockException !== null) {
  446. throw $pipelineBlockException;
  447. }
  448. return $this->_returnValues;
  449. }
  450. }
  451. /* ------------------------------------------------------------------------- */
  452. interface IConnection {
  453. public function connect();
  454. public function disconnect();
  455. public function isConnected();
  456. public function writeCommand(Command $command);
  457. public function readResponse(Command $command);
  458. }
  459. class Connection implements IConnection {
  460. const DEFAULT_HOST = '127.0.0.1';
  461. const DEFAULT_PORT = 6379;
  462. const CONNECTION_TIMEOUT = 2;
  463. const READ_WRITE_TIMEOUT = 5;
  464. private $_host, $_port, $_socket;
  465. public function __construct($host = self::DEFAULT_HOST, $port = self::DEFAULT_PORT) {
  466. $this->_host = $host;
  467. $this->_port = $port;
  468. }
  469. public function __destruct() {
  470. $this->disconnect();
  471. }
  472. public function isConnected() {
  473. return is_resource($this->_socket);
  474. }
  475. public function connect() {
  476. if ($this->isConnected()) {
  477. throw new ClientException('Connection already estabilished');
  478. }
  479. $uri = sprintf('tcp://%s:%d/', $this->_host, $this->_port);
  480. $this->_socket = @stream_socket_client($uri, $errno, $errstr, self::CONNECTION_TIMEOUT);
  481. if (!$this->_socket) {
  482. throw new ClientException(trim($errstr), $errno);
  483. }
  484. stream_set_timeout($this->_socket, self::READ_WRITE_TIMEOUT);
  485. }
  486. public function disconnect() {
  487. if ($this->isConnected()) {
  488. fclose($this->_socket);
  489. }
  490. }
  491. public function writeCommand(Command $command) {
  492. fwrite($this->getSocket(), $command());
  493. }
  494. public function readResponse(Command $command) {
  495. $socket = $this->getSocket();
  496. $handler = Response::getPrefixHandler(fgetc($socket));
  497. $response = $command->parseResponse($handler($socket));
  498. return $response;
  499. }
  500. public function rawCommand($rawCommandData, $closesConnection = false) {
  501. $socket = $this->getSocket();
  502. fwrite($socket, $rawCommandData);
  503. if ($closesConnection) {
  504. return;
  505. }
  506. $handler = Response::getPrefixHandler(fgetc($socket));
  507. return $handler($socket);
  508. }
  509. public function getSocket() {
  510. if (!$this->isConnected()) {
  511. $this->connect();
  512. }
  513. return $this->_socket;
  514. }
  515. public function __toString() {
  516. return sprintf('tcp://%s:%d/', $this->_host, $this->_port);
  517. }
  518. }
  519. class ConnectionCluster implements IConnection {
  520. // TODO: storing a temporary map of commands hashes to hashring items (that
  521. // is, connections) could offer a notable speedup, but I am wondering
  522. // about the increased memory footprint.
  523. // TODO: find a clean way to handle connection failures of single nodes.
  524. private $_pool, $_ring;
  525. public function __construct() {
  526. $this->_pool = array();
  527. $this->_ring = new Utilities\HashRing();
  528. }
  529. public function __destruct() {
  530. $this->disconnect();
  531. }
  532. public function isConnected() {
  533. foreach ($this->_pool as $connection) {
  534. if ($connection->isConnected()) {
  535. return true;
  536. }
  537. }
  538. return false;
  539. }
  540. public function connect() {
  541. foreach ($this->_pool as $connection) {
  542. $connection->connect();
  543. }
  544. }
  545. public function disconnect() {
  546. foreach ($this->_pool as $connection) {
  547. $connection->disconnect();
  548. }
  549. }
  550. public function add(Connection $connection) {
  551. $this->_pool[] = $connection;
  552. $this->_ring->add($connection);
  553. }
  554. private function getConnectionFromRing(Command $command) {
  555. return $this->_ring->get($this->computeHash($command));
  556. }
  557. private function computeHash(Command $command) {
  558. return crc32($command->getArgument(0));
  559. }
  560. private function getConnection(Command $command) {
  561. return $command->canBeHashed()
  562. ? $this->getConnectionFromRing($command)
  563. : $this->getConnectionById(0);
  564. }
  565. public function getConnectionById($id = null) {
  566. return $this->_pool[$id === null ? 0 : $id];
  567. }
  568. public function writeCommand(Command $command) {
  569. $this->getConnection($command)->writeCommand($command);
  570. }
  571. public function readResponse(Command $command) {
  572. return $this->getConnection($command)->readResponse($command);
  573. }
  574. }
  575. /* ------------------------------------------------------------------------- */
  576. namespace Predis\Utilities;
  577. class HashRing {
  578. const NUMBER_OF_REPLICAS = 64;
  579. private $_ring, $_ringKeys;
  580. public function __construct() {
  581. $this->_ring = array();
  582. $this->_ringKeys = array();
  583. }
  584. public function add($node) {
  585. for ($i = 0; $i < self::NUMBER_OF_REPLICAS; $i++) {
  586. $key = crc32((string)$node . ':' . $i);
  587. $this->_ring[$key] = $node;
  588. }
  589. ksort($this->_ring, SORT_NUMERIC);
  590. $this->_ringKeys = array_keys($this->_ring);
  591. }
  592. public function remove($node) {
  593. for ($i = 0; $i < self::NUMBER_OF_REPLICAS; $i++) {
  594. $key = crc32((string)$node . '_' . $i);
  595. unset($this->_ring[$key]);
  596. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  597. return $rk !== $key;
  598. });
  599. }
  600. }
  601. public function get($key) {
  602. return $this->_ring[$this->getNodeKey($key)];
  603. }
  604. private function getNodeKey($key) {
  605. $upper = count($this->_ringKeys) - 1;
  606. $lower = 0;
  607. $index = 0;
  608. while ($lower <= $upper) {
  609. $index = ($lower + $upper) / 2;
  610. $item = $this->_ringKeys[$index];
  611. if ($item === $key) {
  612. return $index;
  613. }
  614. else if ($item > $key) {
  615. $upper = $index - 1;
  616. }
  617. else {
  618. $lower = $index + 1;
  619. }
  620. }
  621. return $this->_ringKeys[$upper];
  622. }
  623. }
  624. /* ------------------------------------------------------------------------- */
  625. namespace Predis\Commands;
  626. /* miscellaneous commands */
  627. class Ping extends \Predis\InlineCommand {
  628. public function canBeHashed() { return false; }
  629. public function getCommandId() { return 'PING'; }
  630. public function parseResponse($data) {
  631. return $data === 'PONG' ? true : false;
  632. }
  633. }
  634. class DoEcho extends \Predis\BulkCommand {
  635. public function canBeHashed() { return false; }
  636. public function getCommandId() { return 'ECHO'; }
  637. }
  638. class Auth extends \Predis\InlineCommand {
  639. public function canBeHashed() { return false; }
  640. public function getCommandId() { return 'AUTH'; }
  641. }
  642. /* connection handling */
  643. class Quit extends \Predis\InlineCommand {
  644. public function canBeHashed() { return false; }
  645. public function getCommandId() { return 'QUIT'; }
  646. public function closesConnection() { return true; }
  647. }
  648. /* commands operating on string values */
  649. class Set extends \Predis\BulkCommand {
  650. public function getCommandId() { return 'SET'; }
  651. }
  652. class SetPreserve extends \Predis\BulkCommand {
  653. public function getCommandId() { return 'SETNX'; }
  654. public function parseResponse($data) { return (bool) $data; }
  655. }
  656. class SetMultiple extends \Predis\MultiBulkCommand {
  657. public function canBeHashed() { return false; }
  658. public function getCommandId() { return 'MSET'; }
  659. }
  660. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  661. public function canBeHashed() { return false; }
  662. public function getCommandId() { return 'MSETNX'; }
  663. public function parseResponse($data) { return (bool) $data; }
  664. }
  665. class Get extends \Predis\InlineCommand {
  666. public function getCommandId() { return 'GET'; }
  667. }
  668. class GetMultiple extends \Predis\InlineCommand {
  669. public function canBeHashed() { return false; }
  670. public function getCommandId() { return 'MGET'; }
  671. }
  672. class GetSet extends \Predis\BulkCommand {
  673. public function getCommandId() { return 'GETSET'; }
  674. }
  675. class Increment extends \Predis\InlineCommand {
  676. public function getCommandId() { return 'INCR'; }
  677. }
  678. class IncrementBy extends \Predis\InlineCommand {
  679. public function getCommandId() { return 'INCRBY'; }
  680. }
  681. class Decrement extends \Predis\InlineCommand {
  682. public function getCommandId() { return 'DECR'; }
  683. }
  684. class DecrementBy extends \Predis\InlineCommand {
  685. public function getCommandId() { return 'DECRBY'; }
  686. }
  687. class Exists extends \Predis\InlineCommand {
  688. public function getCommandId() { return 'EXISTS'; }
  689. public function parseResponse($data) { return (bool) $data; }
  690. }
  691. class Delete extends \Predis\InlineCommand {
  692. public function getCommandId() { return 'DEL'; }
  693. public function parseResponse($data) { return (bool) $data; }
  694. }
  695. class Type extends \Predis\InlineCommand {
  696. public function getCommandId() { return 'TYPE'; }
  697. }
  698. /* commands operating on the key space */
  699. class Keys extends \Predis\InlineCommand {
  700. public function canBeHashed() { return false; }
  701. public function getCommandId() { return 'KEYS'; }
  702. public function parseResponse($data) {
  703. // TODO: is this behaviour correct?
  704. return strlen($data) > 0 ? explode(' ', $data) : array();
  705. }
  706. }
  707. class RandomKey extends \Predis\InlineCommand {
  708. public function canBeHashed() { return false; }
  709. public function getCommandId() { return 'RANDOMKEY'; }
  710. public function parseResponse($data) { return $data !== '' ? $data : null; }
  711. }
  712. class Rename extends \Predis\InlineCommand {
  713. // TODO: doesn't RENAME break the hash-based client-side sharding?
  714. public function canBeHashed() { return false; }
  715. public function getCommandId() { return 'RENAME'; }
  716. }
  717. class RenamePreserve extends \Predis\InlineCommand {
  718. public function canBeHashed() { return false; }
  719. public function getCommandId() { return 'RENAMENX'; }
  720. public function parseResponse($data) { return (bool) $data; }
  721. }
  722. class Expire extends \Predis\InlineCommand {
  723. public function getCommandId() { return 'EXPIRE'; }
  724. public function parseResponse($data) { return (bool) $data; }
  725. }
  726. class ExpireAt extends \Predis\InlineCommand {
  727. public function getCommandId() { return 'EXPIREAT'; }
  728. public function parseResponse($data) { return (bool) $data; }
  729. }
  730. class DatabaseSize extends \Predis\InlineCommand {
  731. public function canBeHashed() { return false; }
  732. public function getCommandId() { return 'DBSIZE'; }
  733. }
  734. class TimeToLive extends \Predis\InlineCommand {
  735. public function getCommandId() { return 'TTL'; }
  736. }
  737. /* commands operating on lists */
  738. class ListPushTail extends \Predis\BulkCommand {
  739. public function getCommandId() { return 'RPUSH'; }
  740. }
  741. class ListPushHead extends \Predis\BulkCommand {
  742. public function getCommandId() { return 'LPUSH'; }
  743. }
  744. class ListLength extends \Predis\InlineCommand {
  745. public function getCommandId() { return 'LLEN'; }
  746. }
  747. class ListRange extends \Predis\InlineCommand {
  748. public function getCommandId() { return 'LRANGE'; }
  749. }
  750. class ListTrim extends \Predis\InlineCommand {
  751. public function getCommandId() { return 'LTRIM'; }
  752. }
  753. class ListIndex extends \Predis\InlineCommand {
  754. public function getCommandId() { return 'LINDEX'; }
  755. }
  756. class ListSet extends \Predis\BulkCommand {
  757. public function getCommandId() { return 'LSET'; }
  758. }
  759. class ListRemove extends \Predis\BulkCommand {
  760. public function getCommandId() { return 'LREM'; }
  761. }
  762. class ListPopFirst extends \Predis\InlineCommand {
  763. public function getCommandId() { return 'LPOP'; }
  764. }
  765. class ListPopLast extends \Predis\InlineCommand {
  766. public function getCommandId() { return 'RPOP'; }
  767. }
  768. /* commands operating on sets */
  769. class SetAdd extends \Predis\BulkCommand {
  770. public function getCommandId() { return 'SADD'; }
  771. public function parseResponse($data) { return (bool) $data; }
  772. }
  773. class SetRemove extends \Predis\BulkCommand {
  774. public function getCommandId() { return 'SREM'; }
  775. public function parseResponse($data) { return (bool) $data; }
  776. }
  777. class SetPop extends \Predis\InlineCommand {
  778. public function getCommandId() { return 'SPOP'; }
  779. }
  780. class SetMove extends \Predis\BulkCommand {
  781. public function canBeHashed() { return false; }
  782. public function getCommandId() { return 'SMOVE'; }
  783. public function parseResponse($data) { return (bool) $data; }
  784. }
  785. class SetCardinality extends \Predis\InlineCommand {
  786. public function getCommandId() { return 'SCARD'; }
  787. }
  788. class SetIsMember extends \Predis\BulkCommand {
  789. public function getCommandId() { return 'SISMEMBER'; }
  790. public function parseResponse($data) { return (bool) $data; }
  791. }
  792. class SetIntersection extends \Predis\InlineCommand {
  793. public function getCommandId() { return 'SINTER'; }
  794. }
  795. class SetIntersectionStore extends \Predis\InlineCommand {
  796. public function getCommandId() { return 'SINTERSTORE'; }
  797. }
  798. class SetUnion extends \Predis\InlineCommand {
  799. public function getCommandId() { return 'SUNION'; }
  800. }
  801. class SetUnionStore extends \Predis\InlineCommand {
  802. public function getCommandId() { return 'SUNIONSTORE'; }
  803. }
  804. class SetDifference extends \Predis\InlineCommand {
  805. public function getCommandId() { return 'SDIFF'; }
  806. }
  807. class SetDifferenceStore extends \Predis\InlineCommand {
  808. public function getCommandId() { return 'SDIFFSTORE'; }
  809. }
  810. class SetMembers extends \Predis\InlineCommand {
  811. public function getCommandId() { return 'SMEMBERS'; }
  812. }
  813. class SetRandomMember extends \Predis\InlineCommand {
  814. public function getCommandId() { return 'SRANDMEMBER'; }
  815. }
  816. /* commands operating on sorted sets */
  817. class ZSetAdd extends \Predis\BulkCommand {
  818. public function getCommandId() { return 'ZADD'; }
  819. public function parseResponse($data) { return (bool) $data; }
  820. }
  821. class ZSetRemove extends \Predis\BulkCommand {
  822. public function getCommandId() { return 'ZREM'; }
  823. public function parseResponse($data) { return (bool) $data; }
  824. }
  825. class ZSetRange extends \Predis\InlineCommand {
  826. public function getCommandId() { return 'ZRANGE'; }
  827. }
  828. class ZSetReverseRange extends \Predis\InlineCommand {
  829. public function getCommandId() { return 'ZREVRANGE'; }
  830. }
  831. class ZSetRangeByScore extends \Predis\InlineCommand {
  832. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  833. }
  834. class ZSetCardinality extends \Predis\InlineCommand {
  835. public function getCommandId() { return 'ZCARD'; }
  836. }
  837. class ZSetScore extends \Predis\BulkCommand {
  838. public function getCommandId() { return 'ZSCORE'; }
  839. }
  840. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  841. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  842. }
  843. /* multiple databases handling commands */
  844. class SelectDatabase extends \Predis\InlineCommand {
  845. public function canBeHashed() { return false; }
  846. public function getCommandId() { return 'SELECT'; }
  847. }
  848. class MoveKey extends \Predis\InlineCommand {
  849. public function canBeHashed() { return false; }
  850. public function getCommandId() { return 'MOVE'; }
  851. public function parseResponse($data) { return (bool) $data; }
  852. }
  853. class FlushDatabase extends \Predis\InlineCommand {
  854. public function canBeHashed() { return false; }
  855. public function getCommandId() { return 'FLUSHDB'; }
  856. }
  857. class FlushAll extends \Predis\InlineCommand {
  858. public function canBeHashed() { return false; }
  859. public function getCommandId() { return 'FLUSHALL'; }
  860. }
  861. /* sorting */
  862. class Sort extends \Predis\InlineCommand {
  863. public function getCommandId() { return 'SORT'; }
  864. public function filterArguments($arguments) {
  865. if (count($arguments) === 1) {
  866. return $arguments;
  867. }
  868. // TODO: add more parameters checks
  869. $query = array($arguments[0]);
  870. $sortParams = $arguments[1];
  871. if (isset($sortParams['by'])) {
  872. $query[] = 'BY ' . $sortParams['by'];
  873. }
  874. if (isset($sortParams['get'])) {
  875. $query[] = 'GET ' . $sortParams['get'];
  876. }
  877. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  878. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  879. }
  880. if (isset($sortParams['sort'])) {
  881. $query[] = strtoupper($sortParams['sort']);
  882. }
  883. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  884. $query[] = 'ALPHA';
  885. }
  886. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  887. $query[] = 'STORE ' . $sortParams['store'];
  888. }
  889. return $query;
  890. }
  891. }
  892. /* persistence control commands */
  893. class Save extends \Predis\InlineCommand {
  894. public function canBeHashed() { return false; }
  895. public function getCommandId() { return 'SAVE'; }
  896. }
  897. class BackgroundSave extends \Predis\InlineCommand {
  898. public function canBeHashed() { return false; }
  899. public function getCommandId() { return 'BGSAVE'; }
  900. }
  901. class LastSave extends \Predis\InlineCommand {
  902. public function canBeHashed() { return false; }
  903. public function getCommandId() { return 'LASTSAVE'; }
  904. }
  905. class Shutdown extends \Predis\InlineCommand {
  906. public function canBeHashed() { return false; }
  907. public function getCommandId() { return 'SHUTDOWN'; }
  908. public function closesConnection() { return true; }
  909. }
  910. /* remote server control commands */
  911. class Info extends \Predis\InlineCommand {
  912. public function canBeHashed() { return false; }
  913. public function getCommandId() { return 'INFO'; }
  914. public function parseResponse($data) {
  915. $info = array();
  916. $infoLines = explode("\r\n", $data, -1);
  917. foreach ($infoLines as $row) {
  918. list($k, $v) = explode(':', $row);
  919. $info[$k] = $v;
  920. }
  921. return $info;
  922. }
  923. }
  924. class SlaveOf extends \Predis\InlineCommand {
  925. public function canBeHashed() { return false; }
  926. public function getCommandId() { return 'SLAVEOF'; }
  927. public function filterArguments($arguments) {
  928. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  929. }
  930. }
  931. ?>