Predis.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  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;
  12. public function __construct($host = Connection::DEFAULT_HOST, $port = Connection::DEFAULT_PORT) {
  13. $this->_registeredCommands = self::initializeDefaultCommands();
  14. $this->setConnection($this->createConnection(
  15. func_num_args() === 1 && is_array($host) || @stripos('redis://') === 0
  16. ? $host
  17. : array('host' => $host, 'port' => $port)
  18. ));
  19. }
  20. public function __destruct() {
  21. $this->_connection->disconnect();
  22. }
  23. public static function create(/* arguments */) {
  24. $argv = func_get_args();
  25. $argc = func_num_args();
  26. if ($argc == 1) {
  27. return new Client($argv[0]);
  28. }
  29. else if ($argc > 1) {
  30. $client = new Client();
  31. $cluster = new ConnectionCluster();
  32. foreach ($argv as $parameters) {
  33. // TODO: this is a bit dirty...
  34. $cluster->add($client->createConnection($parameters));
  35. }
  36. $client->setConnection($cluster);
  37. return $client;
  38. }
  39. else {
  40. return new Client();
  41. }
  42. }
  43. private function createConnection($parameters) {
  44. $params = new ConnectionParameters($parameters);
  45. $connection = new Connection($params);
  46. if ($params->password !== null) {
  47. $connection->pushInitCommand($this->createCommandInstance(
  48. 'auth', array($params->password)
  49. ));
  50. }
  51. if ($params->database !== null) {
  52. $connection->pushInitCommand($this->createCommandInstance(
  53. 'select', array($params->database)
  54. ));
  55. }
  56. return $connection;
  57. }
  58. private function setConnection(IConnection $connection) {
  59. $this->_connection = $connection;
  60. }
  61. public function connect() {
  62. $this->_connection->connect();
  63. }
  64. public function disconnect() {
  65. $this->_connection->disconnect();
  66. }
  67. public function isConnected() {
  68. return $this->_connection->isConnected();
  69. }
  70. public function getConnection() {
  71. return $this->_connection;
  72. }
  73. public function __call($method, $arguments) {
  74. $command = $this->createCommandInstance($method, $arguments);
  75. return $this->executeCommand($command);
  76. }
  77. public function createCommandInstance($method, $arguments) {
  78. $commandClass = $this->_registeredCommands[$method];
  79. if ($commandClass === null) {
  80. throw new ClientException("'$method' is not a registered Redis command");
  81. }
  82. $command = new $commandClass();
  83. $command->setArgumentsArray($arguments);
  84. return $command;
  85. }
  86. public function executeCommand(Command $command) {
  87. $this->_connection->writeCommand($command);
  88. if ($command->closesConnection()) {
  89. return $this->_connection->disconnect();
  90. }
  91. return $this->_connection->readResponse($command);
  92. }
  93. public function rawCommand($rawCommandData, $closesConnection = false) {
  94. // TODO: rather than check the type of a connection instance, we should
  95. // check if it does respond to the rawCommand method.
  96. if (is_a($this->_connection, '\Predis\ConnectionCluster')) {
  97. throw new ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  98. }
  99. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  100. }
  101. public function pipeline(\Closure $pipelineBlock = null) {
  102. $pipeline = new CommandPipeline($this);
  103. return $pipelineBlock !== null ? $pipeline->execute($pipelineBlock) : $pipeline;
  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. 'decr' => '\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, $_returnValues, $_running;
  422. public function __construct(Client $redisClient) {
  423. $this->_redisClient = $redisClient;
  424. $this->_pipelineBuffer = array();
  425. $this->_returnValues = array();
  426. }
  427. public function __call($method, $arguments) {
  428. $command = $this->_redisClient->createCommandInstance($method, $arguments);
  429. $this->recordCommand($command);
  430. }
  431. private function recordCommand(Command $command) {
  432. $this->_pipelineBuffer[] = $command;
  433. }
  434. private function getRecordedCommands() {
  435. return $this->_pipelineBuffer;
  436. }
  437. public function flushPipeline() {
  438. if (count($this->_pipelineBuffer) === 0) {
  439. return;
  440. }
  441. $connection = $this->_redisClient->getConnection();
  442. $commands = &$this->getRecordedCommands();
  443. foreach ($commands as $command) {
  444. $connection->writeCommand($command);
  445. }
  446. foreach ($commands as $command) {
  447. $this->_returnValues[] = $connection->readResponse($command);
  448. }
  449. $this->_pipelineBuffer = array();
  450. }
  451. private function setRunning($bool) {
  452. // TODO: I am honest when I say that I don't like this approach.
  453. if ($bool == true && $this->_running == true) {
  454. throw new ClientException("This pipeline is already opened");
  455. }
  456. $this->_running = $bool;
  457. }
  458. public function execute(\Closure $block = null) {
  459. $this->setRunning(true);
  460. $pipelineBlockException = null;
  461. try {
  462. if ($block !== null) {
  463. $block($this);
  464. }
  465. $this->flushPipeline();
  466. }
  467. catch (\Exception $exception) {
  468. $pipelineBlockException = $exception;
  469. }
  470. $this->setRunning(false);
  471. if ($pipelineBlockException !== null) {
  472. throw $pipelineBlockException;
  473. }
  474. return $this->_returnValues;
  475. }
  476. }
  477. /* ------------------------------------------------------------------------- */
  478. class ConnectionParameters {
  479. private $_parameters;
  480. public function __construct($parameters) {
  481. $this->_parameters = is_array($parameters)
  482. ? self::filterConnectionParams($parameters)
  483. : self::parseURI($parameters);
  484. }
  485. private static function parseURI($uri) {
  486. $parsed = @parse_url($uri);
  487. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  488. throw new ClientException("Invalid URI: $uri");
  489. }
  490. if (array_key_exists('query', $parsed)) {
  491. $details = array();
  492. foreach (explode('&', $parsed['query']) as $kv) {
  493. list($k, $v) = explode('=', $kv);
  494. switch ($k) {
  495. case 'database':
  496. $details['database'] = $v;
  497. break;
  498. case 'password':
  499. $details['password'] = $v;
  500. break;
  501. }
  502. }
  503. $parsed = array_merge($parsed, $details);
  504. }
  505. return self::filterConnectionParams($parsed);
  506. }
  507. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  508. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  509. }
  510. private static function filterConnectionParams($parameters) {
  511. return array(
  512. 'host' => self::getParamOrDefault($parameters, 'host', Connection::DEFAULT_HOST),
  513. 'port' => (int) self::getParamOrDefault($parameters, 'port', Connection::DEFAULT_PORT),
  514. 'database' => self::getParamOrDefault($parameters, 'database'),
  515. 'password' => self::getParamOrDefault($parameters, 'password')
  516. );
  517. }
  518. public function __get($parameter) {
  519. return $this->_parameters[$parameter];
  520. }
  521. }
  522. interface IConnection {
  523. public function connect();
  524. public function disconnect();
  525. public function isConnected();
  526. public function writeCommand(Command $command);
  527. public function readResponse(Command $command);
  528. }
  529. class Connection implements IConnection {
  530. const DEFAULT_HOST = '127.0.0.1';
  531. const DEFAULT_PORT = 6379;
  532. const CONNECTION_TIMEOUT = 2;
  533. const READ_WRITE_TIMEOUT = 5;
  534. private $_params, $_socket, $_initCmds;
  535. public function __construct(ConnectionParameters $parameters) {
  536. $this->_params = $parameters;
  537. $this->_initCmds = array();
  538. }
  539. public function __destruct() {
  540. $this->disconnect();
  541. }
  542. public function isConnected() {
  543. return is_resource($this->_socket);
  544. }
  545. public function connect() {
  546. if ($this->isConnected()) {
  547. throw new ClientException('Connection already estabilished');
  548. }
  549. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  550. $this->_socket = @stream_socket_client($uri, $errno, $errstr, self::CONNECTION_TIMEOUT);
  551. if (!$this->_socket) {
  552. throw new ClientException(trim($errstr), $errno);
  553. }
  554. stream_set_timeout($this->_socket, self::READ_WRITE_TIMEOUT);
  555. if (count($this->_initCmds) > 0){
  556. $this->sendInitializationCommands();
  557. }
  558. }
  559. public function disconnect() {
  560. if ($this->isConnected()) {
  561. fclose($this->_socket);
  562. }
  563. }
  564. public function pushInitCommand(Command $command){
  565. $this->_initCmds[] = $command;
  566. }
  567. private function sendInitializationCommands() {
  568. foreach ($this->_initCmds as $command) {
  569. $this->writeCommand($command);
  570. }
  571. foreach ($this->_initCmds as $command) {
  572. $this->readResponse($command);
  573. }
  574. }
  575. public function writeCommand(Command $command) {
  576. fwrite($this->getSocket(), $command());
  577. }
  578. public function readResponse(Command $command) {
  579. $socket = $this->getSocket();
  580. $handler = Response::getPrefixHandler(fgetc($socket));
  581. $response = $command->parseResponse($handler($socket));
  582. return $response;
  583. }
  584. public function rawCommand($rawCommandData, $closesConnection = false) {
  585. $socket = $this->getSocket();
  586. fwrite($socket, $rawCommandData);
  587. if ($closesConnection) {
  588. return;
  589. }
  590. $handler = Response::getPrefixHandler(fgetc($socket));
  591. return $handler($socket);
  592. }
  593. public function getSocket() {
  594. if (!$this->isConnected()) {
  595. $this->connect();
  596. }
  597. return $this->_socket;
  598. }
  599. public function __toString() {
  600. return sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  601. }
  602. }
  603. class ConnectionCluster implements IConnection, \IteratorAggregate {
  604. // TODO: storing a temporary map of commands hashes to hashring items (that
  605. // is, connections) could offer a notable speedup, but I am wondering
  606. // about the increased memory footprint.
  607. // TODO: find a clean way to handle connection failures of single nodes.
  608. private $_pool, $_ring;
  609. public function __construct() {
  610. $this->_pool = array();
  611. $this->_ring = new Utilities\HashRing();
  612. }
  613. public function __destruct() {
  614. $this->disconnect();
  615. }
  616. public function isConnected() {
  617. foreach ($this->_pool as $connection) {
  618. if ($connection->isConnected()) {
  619. return true;
  620. }
  621. }
  622. return false;
  623. }
  624. public function connect() {
  625. foreach ($this->_pool as $connection) {
  626. $connection->connect();
  627. }
  628. }
  629. public function disconnect() {
  630. foreach ($this->_pool as $connection) {
  631. $connection->disconnect();
  632. }
  633. }
  634. public function add(Connection $connection) {
  635. $this->_pool[] = $connection;
  636. $this->_ring->add($connection);
  637. }
  638. private function getConnectionFromRing(Command $command) {
  639. return $this->_ring->get($this->computeHash($command));
  640. }
  641. private function computeHash(Command $command) {
  642. return crc32($command->getArgument(0));
  643. }
  644. private function getConnection(Command $command) {
  645. return $command->canBeHashed()
  646. ? $this->getConnectionFromRing($command)
  647. : $this->getConnectionById(0);
  648. }
  649. public function getConnectionById($id = null) {
  650. return $this->_pool[$id === null ? 0 : $id];
  651. }
  652. public function getIterator() {
  653. return new \ArrayIterator($this->_pool);
  654. }
  655. public function writeCommand(Command $command) {
  656. $this->getConnection($command)->writeCommand($command);
  657. }
  658. public function readResponse(Command $command) {
  659. return $this->getConnection($command)->readResponse($command);
  660. }
  661. }
  662. /* ------------------------------------------------------------------------- */
  663. namespace Predis\Utilities;
  664. class HashRing {
  665. const DEFAULT_REPLICAS = 128;
  666. private $_ring, $_ringKeys, $_replicas;
  667. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  668. $this->_replicas = $replicas;
  669. $this->_ring = array();
  670. $this->_ringKeys = array();
  671. }
  672. public function add($node) {
  673. $nodeHash = (string) $node;
  674. for ($i = 0; $i < $this->_replicas; $i++) {
  675. $key = crc32($nodeHash . ':' . $i);
  676. $this->_ring[$key] = $node;
  677. }
  678. ksort($this->_ring, SORT_NUMERIC);
  679. $this->_ringKeys = array_keys($this->_ring);
  680. }
  681. public function remove($node) {
  682. $nodeHash = (string) $node;
  683. for ($i = 0; $i < $this->_replicas; $i++) {
  684. $key = crc32($nodeHash . ':' . $i);
  685. unset($this->_ring[$key]);
  686. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  687. return $rk !== $key;
  688. });
  689. }
  690. }
  691. public function get($key) {
  692. return $this->_ring[$this->getNodeKey($key)];
  693. }
  694. private function getNodeKey($key) {
  695. $upper = count($this->_ringKeys) - 1;
  696. $lower = 0;
  697. $index = 0;
  698. while ($lower <= $upper) {
  699. $index = ($lower + $upper) / 2;
  700. $item = $this->_ringKeys[$index];
  701. if ($item === $key) {
  702. return $index;
  703. }
  704. else if ($item > $key) {
  705. $upper = $index - 1;
  706. }
  707. else {
  708. $lower = $index + 1;
  709. }
  710. }
  711. return $this->_ringKeys[$upper];
  712. }
  713. }
  714. /* ------------------------------------------------------------------------- */
  715. namespace Predis\Commands;
  716. /* miscellaneous commands */
  717. class Ping extends \Predis\InlineCommand {
  718. public function canBeHashed() { return false; }
  719. public function getCommandId() { return 'PING'; }
  720. public function parseResponse($data) {
  721. return $data === 'PONG' ? true : false;
  722. }
  723. }
  724. class DoEcho extends \Predis\BulkCommand {
  725. public function canBeHashed() { return false; }
  726. public function getCommandId() { return 'ECHO'; }
  727. }
  728. class Auth extends \Predis\InlineCommand {
  729. public function canBeHashed() { return false; }
  730. public function getCommandId() { return 'AUTH'; }
  731. }
  732. /* connection handling */
  733. class Quit extends \Predis\InlineCommand {
  734. public function canBeHashed() { return false; }
  735. public function getCommandId() { return 'QUIT'; }
  736. public function closesConnection() { return true; }
  737. }
  738. /* commands operating on string values */
  739. class Set extends \Predis\BulkCommand {
  740. public function getCommandId() { return 'SET'; }
  741. }
  742. class SetPreserve extends \Predis\BulkCommand {
  743. public function getCommandId() { return 'SETNX'; }
  744. public function parseResponse($data) { return (bool) $data; }
  745. }
  746. class SetMultiple extends \Predis\MultiBulkCommand {
  747. public function canBeHashed() { return false; }
  748. public function getCommandId() { return 'MSET'; }
  749. }
  750. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  751. public function canBeHashed() { return false; }
  752. public function getCommandId() { return 'MSETNX'; }
  753. public function parseResponse($data) { return (bool) $data; }
  754. }
  755. class Get extends \Predis\InlineCommand {
  756. public function getCommandId() { return 'GET'; }
  757. }
  758. class GetMultiple extends \Predis\InlineCommand {
  759. public function canBeHashed() { return false; }
  760. public function getCommandId() { return 'MGET'; }
  761. }
  762. class GetSet extends \Predis\BulkCommand {
  763. public function getCommandId() { return 'GETSET'; }
  764. }
  765. class Increment extends \Predis\InlineCommand {
  766. public function getCommandId() { return 'INCR'; }
  767. }
  768. class IncrementBy extends \Predis\InlineCommand {
  769. public function getCommandId() { return 'INCRBY'; }
  770. }
  771. class Decrement extends \Predis\InlineCommand {
  772. public function getCommandId() { return 'DECR'; }
  773. }
  774. class DecrementBy extends \Predis\InlineCommand {
  775. public function getCommandId() { return 'DECRBY'; }
  776. }
  777. class Exists extends \Predis\InlineCommand {
  778. public function getCommandId() { return 'EXISTS'; }
  779. public function parseResponse($data) { return (bool) $data; }
  780. }
  781. class Delete extends \Predis\InlineCommand {
  782. public function getCommandId() { return 'DEL'; }
  783. public function parseResponse($data) { return (bool) $data; }
  784. }
  785. class Type extends \Predis\InlineCommand {
  786. public function getCommandId() { return 'TYPE'; }
  787. }
  788. /* commands operating on the key space */
  789. class Keys extends \Predis\InlineCommand {
  790. public function canBeHashed() { return false; }
  791. public function getCommandId() { return 'KEYS'; }
  792. public function parseResponse($data) {
  793. // TODO: is this behaviour correct?
  794. return strlen($data) > 0 ? explode(' ', $data) : array();
  795. }
  796. }
  797. class RandomKey extends \Predis\InlineCommand {
  798. public function canBeHashed() { return false; }
  799. public function getCommandId() { return 'RANDOMKEY'; }
  800. public function parseResponse($data) { return $data !== '' ? $data : null; }
  801. }
  802. class Rename extends \Predis\InlineCommand {
  803. // TODO: doesn't RENAME break the hash-based client-side sharding?
  804. public function canBeHashed() { return false; }
  805. public function getCommandId() { return 'RENAME'; }
  806. }
  807. class RenamePreserve extends \Predis\InlineCommand {
  808. public function canBeHashed() { return false; }
  809. public function getCommandId() { return 'RENAMENX'; }
  810. public function parseResponse($data) { return (bool) $data; }
  811. }
  812. class Expire extends \Predis\InlineCommand {
  813. public function getCommandId() { return 'EXPIRE'; }
  814. public function parseResponse($data) { return (bool) $data; }
  815. }
  816. class ExpireAt extends \Predis\InlineCommand {
  817. public function getCommandId() { return 'EXPIREAT'; }
  818. public function parseResponse($data) { return (bool) $data; }
  819. }
  820. class DatabaseSize extends \Predis\InlineCommand {
  821. public function canBeHashed() { return false; }
  822. public function getCommandId() { return 'DBSIZE'; }
  823. }
  824. class TimeToLive extends \Predis\InlineCommand {
  825. public function getCommandId() { return 'TTL'; }
  826. }
  827. /* commands operating on lists */
  828. class ListPushTail extends \Predis\BulkCommand {
  829. public function getCommandId() { return 'RPUSH'; }
  830. }
  831. class ListPushHead extends \Predis\BulkCommand {
  832. public function getCommandId() { return 'LPUSH'; }
  833. }
  834. class ListLength extends \Predis\InlineCommand {
  835. public function getCommandId() { return 'LLEN'; }
  836. }
  837. class ListRange extends \Predis\InlineCommand {
  838. public function getCommandId() { return 'LRANGE'; }
  839. }
  840. class ListTrim extends \Predis\InlineCommand {
  841. public function getCommandId() { return 'LTRIM'; }
  842. }
  843. class ListIndex extends \Predis\InlineCommand {
  844. public function getCommandId() { return 'LINDEX'; }
  845. }
  846. class ListSet extends \Predis\BulkCommand {
  847. public function getCommandId() { return 'LSET'; }
  848. }
  849. class ListRemove extends \Predis\BulkCommand {
  850. public function getCommandId() { return 'LREM'; }
  851. }
  852. class ListPopLastPushHead extends \Predis\BulkCommand {
  853. public function getCommandId() { return 'RPOPLPUSH'; }
  854. }
  855. class ListPopFirst extends \Predis\InlineCommand {
  856. public function getCommandId() { return 'LPOP'; }
  857. }
  858. class ListPopLast extends \Predis\InlineCommand {
  859. public function getCommandId() { return 'RPOP'; }
  860. }
  861. /* commands operating on sets */
  862. class SetAdd extends \Predis\BulkCommand {
  863. public function getCommandId() { return 'SADD'; }
  864. public function parseResponse($data) { return (bool) $data; }
  865. }
  866. class SetRemove extends \Predis\BulkCommand {
  867. public function getCommandId() { return 'SREM'; }
  868. public function parseResponse($data) { return (bool) $data; }
  869. }
  870. class SetPop extends \Predis\InlineCommand {
  871. public function getCommandId() { return 'SPOP'; }
  872. }
  873. class SetMove extends \Predis\BulkCommand {
  874. public function canBeHashed() { return false; }
  875. public function getCommandId() { return 'SMOVE'; }
  876. public function parseResponse($data) { return (bool) $data; }
  877. }
  878. class SetCardinality extends \Predis\InlineCommand {
  879. public function getCommandId() { return 'SCARD'; }
  880. }
  881. class SetIsMember extends \Predis\BulkCommand {
  882. public function getCommandId() { return 'SISMEMBER'; }
  883. public function parseResponse($data) { return (bool) $data; }
  884. }
  885. class SetIntersection extends \Predis\InlineCommand {
  886. public function getCommandId() { return 'SINTER'; }
  887. }
  888. class SetIntersectionStore extends \Predis\InlineCommand {
  889. public function getCommandId() { return 'SINTERSTORE'; }
  890. }
  891. class SetUnion extends \Predis\InlineCommand {
  892. public function getCommandId() { return 'SUNION'; }
  893. }
  894. class SetUnionStore extends \Predis\InlineCommand {
  895. public function getCommandId() { return 'SUNIONSTORE'; }
  896. }
  897. class SetDifference extends \Predis\InlineCommand {
  898. public function getCommandId() { return 'SDIFF'; }
  899. }
  900. class SetDifferenceStore extends \Predis\InlineCommand {
  901. public function getCommandId() { return 'SDIFFSTORE'; }
  902. }
  903. class SetMembers extends \Predis\InlineCommand {
  904. public function getCommandId() { return 'SMEMBERS'; }
  905. }
  906. class SetRandomMember extends \Predis\InlineCommand {
  907. public function getCommandId() { return 'SRANDMEMBER'; }
  908. }
  909. /* commands operating on sorted sets */
  910. class ZSetAdd extends \Predis\BulkCommand {
  911. public function getCommandId() { return 'ZADD'; }
  912. public function parseResponse($data) { return (bool) $data; }
  913. }
  914. class ZSetRemove extends \Predis\BulkCommand {
  915. public function getCommandId() { return 'ZREM'; }
  916. public function parseResponse($data) { return (bool) $data; }
  917. }
  918. class ZSetRange extends \Predis\InlineCommand {
  919. public function getCommandId() { return 'ZRANGE'; }
  920. }
  921. class ZSetReverseRange extends \Predis\InlineCommand {
  922. public function getCommandId() { return 'ZREVRANGE'; }
  923. }
  924. class ZSetRangeByScore extends \Predis\InlineCommand {
  925. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  926. }
  927. class ZSetCardinality extends \Predis\InlineCommand {
  928. public function getCommandId() { return 'ZCARD'; }
  929. }
  930. class ZSetScore extends \Predis\BulkCommand {
  931. public function getCommandId() { return 'ZSCORE'; }
  932. }
  933. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  934. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  935. }
  936. /* multiple databases handling commands */
  937. class SelectDatabase extends \Predis\InlineCommand {
  938. public function canBeHashed() { return false; }
  939. public function getCommandId() { return 'SELECT'; }
  940. }
  941. class MoveKey extends \Predis\InlineCommand {
  942. public function canBeHashed() { return false; }
  943. public function getCommandId() { return 'MOVE'; }
  944. public function parseResponse($data) { return (bool) $data; }
  945. }
  946. class FlushDatabase extends \Predis\InlineCommand {
  947. public function canBeHashed() { return false; }
  948. public function getCommandId() { return 'FLUSHDB'; }
  949. }
  950. class FlushAll extends \Predis\InlineCommand {
  951. public function canBeHashed() { return false; }
  952. public function getCommandId() { return 'FLUSHALL'; }
  953. }
  954. /* sorting */
  955. class Sort extends \Predis\InlineCommand {
  956. public function getCommandId() { return 'SORT'; }
  957. public function filterArguments($arguments) {
  958. if (count($arguments) === 1) {
  959. return $arguments;
  960. }
  961. // TODO: add more parameters checks
  962. $query = array($arguments[0]);
  963. $sortParams = $arguments[1];
  964. if (isset($sortParams['by'])) {
  965. $query[] = 'BY ' . $sortParams['by'];
  966. }
  967. if (isset($sortParams['get'])) {
  968. $query[] = 'GET ' . $sortParams['get'];
  969. }
  970. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  971. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  972. }
  973. if (isset($sortParams['sort'])) {
  974. $query[] = strtoupper($sortParams['sort']);
  975. }
  976. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  977. $query[] = 'ALPHA';
  978. }
  979. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  980. $query[] = 'STORE ' . $sortParams['store'];
  981. }
  982. return $query;
  983. }
  984. }
  985. /* persistence control commands */
  986. class Save extends \Predis\InlineCommand {
  987. public function canBeHashed() { return false; }
  988. public function getCommandId() { return 'SAVE'; }
  989. }
  990. class BackgroundSave extends \Predis\InlineCommand {
  991. public function canBeHashed() { return false; }
  992. public function getCommandId() { return 'BGSAVE'; }
  993. }
  994. class LastSave extends \Predis\InlineCommand {
  995. public function canBeHashed() { return false; }
  996. public function getCommandId() { return 'LASTSAVE'; }
  997. }
  998. class Shutdown extends \Predis\InlineCommand {
  999. public function canBeHashed() { return false; }
  1000. public function getCommandId() { return 'SHUTDOWN'; }
  1001. public function closesConnection() { return true; }
  1002. }
  1003. /* remote server control commands */
  1004. class Info extends \Predis\InlineCommand {
  1005. public function canBeHashed() { return false; }
  1006. public function getCommandId() { return 'INFO'; }
  1007. public function parseResponse($data) {
  1008. $info = array();
  1009. $infoLines = explode("\r\n", $data, -1);
  1010. foreach ($infoLines as $row) {
  1011. list($k, $v) = explode(':', $row);
  1012. if (!preg_match('/^db\d+$/', $k)) {
  1013. $info[$k] = $v;
  1014. }
  1015. else {
  1016. $db = array();
  1017. foreach (explode(',', $v) as $dbvar) {
  1018. list($dbvk, $dbvv) = explode('=', $dbvar);
  1019. $db[trim($dbvk)] = $dbvv;
  1020. }
  1021. $info[$k] = $db;
  1022. }
  1023. }
  1024. return $info;
  1025. }
  1026. }
  1027. class SlaveOf extends \Predis\InlineCommand {
  1028. public function canBeHashed() { return false; }
  1029. public function getCommandId() { return 'SLAVEOF'; }
  1030. public function filterArguments($arguments) {
  1031. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1032. }
  1033. }
  1034. ?>