Predis.php 41 KB

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