WebdisConnection.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Predis\Connection;
  11. use Predis\NotSupportedException;
  12. use Predis\ResponseError;
  13. use Predis\ResponseObjectInterface;
  14. use Predis\Command\CommandInterface;
  15. use Predis\Connection\ConnectionException;
  16. use Predis\Protocol\ProtocolException;
  17. /**
  18. * This class implements a Predis connection that actually talks with Webdis
  19. * instead of connecting directly to Redis. It relies on the cURL extension to
  20. * communicate with the web server and the phpiredis extension to parse the
  21. * protocol of the replies returned in the http response bodies.
  22. *
  23. * Some features are not yet available or they simply cannot be implemented:
  24. * - Pipelining commands.
  25. * - Publish / Subscribe.
  26. * - MULTI / EXEC transactions (not yet supported by Webdis).
  27. *
  28. * The connection parameters supported by this class are:
  29. *
  30. * - scheme: must be 'http'.
  31. * - host: hostname or IP address of the server.
  32. * - port: TCP port of the server.
  33. * - timeout: timeout to perform the connection.
  34. * - user: username for authentication.
  35. * - pass: password for authentication.
  36. *
  37. * @link http://webd.is
  38. * @link http://github.com/nicolasff/webdis
  39. * @link http://github.com/seppo0010/phpiredis
  40. * @author Daniele Alessandri <suppakilla@gmail.com>
  41. */
  42. class WebdisConnection implements SingleConnectionInterface
  43. {
  44. const ERR_MSG_EXTENSION = 'The %s extension must be loaded in order to be able to use this connection class';
  45. private $parameters;
  46. private $resource;
  47. private $reader;
  48. /**
  49. * @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
  50. */
  51. public function __construct(ConnectionParametersInterface $parameters)
  52. {
  53. $this->checkExtensions();
  54. if ($parameters->scheme !== 'http') {
  55. throw new \InvalidArgumentException("Invalid scheme: {$parameters->scheme}");
  56. }
  57. $this->parameters = $parameters;
  58. $this->resource = $this->initializeCurl($parameters);
  59. $this->reader = $this->initializeReader($parameters);
  60. }
  61. /**
  62. * Frees the underlying cURL and protocol reader resources when PHP's
  63. * garbage collector kicks in.
  64. */
  65. public function __destruct()
  66. {
  67. curl_close($this->resource);
  68. phpiredis_reader_destroy($this->reader);
  69. }
  70. /**
  71. * Helper method used to throw on unsupported methods.
  72. */
  73. private function throwNotSupportedException($function)
  74. {
  75. $class = __CLASS__;
  76. throw new NotSupportedException("The method $class::$function() is not supported");
  77. }
  78. /**
  79. * Checks if the cURL and phpiredis extensions are loaded in PHP.
  80. */
  81. private function checkExtensions()
  82. {
  83. if (!function_exists('curl_init')) {
  84. throw new NotSupportedException(sprintf(self::ERR_MSG_EXTENSION, 'curl'));
  85. }
  86. if (!function_exists('phpiredis_reader_create')) {
  87. throw new NotSupportedException(sprintf(self::ERR_MSG_EXTENSION, 'phpiredis'));
  88. }
  89. }
  90. /**
  91. * Initializes cURL.
  92. *
  93. * @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
  94. * @return resource
  95. */
  96. private function initializeCurl(ConnectionParametersInterface $parameters)
  97. {
  98. $options = array(
  99. CURLOPT_FAILONERROR => true,
  100. CURLOPT_CONNECTTIMEOUT_MS => $parameters->timeout * 1000,
  101. CURLOPT_URL => "{$parameters->scheme}://{$parameters->host}:{$parameters->port}",
  102. CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  103. CURLOPT_POST => true,
  104. CURLOPT_WRITEFUNCTION => array($this, 'feedReader'),
  105. );
  106. if (isset($parameters->user, $parameters->pass)) {
  107. $options[CURLOPT_USERPWD] = "{$parameters->user}:{$parameters->pass}";
  108. }
  109. curl_setopt_array($resource = curl_init(), $options);
  110. return $resource;
  111. }
  112. /**
  113. * Initializes phpiredis' protocol reader.
  114. *
  115. * @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
  116. * @return resource
  117. */
  118. private function initializeReader(ConnectionParametersInterface $parameters)
  119. {
  120. $reader = phpiredis_reader_create();
  121. phpiredis_reader_set_status_handler($reader, $this->getStatusHandler());
  122. phpiredis_reader_set_error_handler($reader, $this->getErrorHandler());
  123. return $reader;
  124. }
  125. /**
  126. * Gets the handler used by the protocol reader to handle status replies.
  127. *
  128. * @return \Closure
  129. */
  130. protected function getStatusHandler()
  131. {
  132. return function ($payload) {
  133. return $payload === 'OK' ? true : $payload;
  134. };
  135. }
  136. /**
  137. * Gets the handler used by the protocol reader to handle Redis errors.
  138. *
  139. * @return \Closure
  140. */
  141. protected function getErrorHandler()
  142. {
  143. return function ($errorMessage) {
  144. return new ResponseError($errorMessage);
  145. };
  146. }
  147. /**
  148. * Feeds phpredis' reader resource with the data read from the network.
  149. *
  150. * @param resource $resource Reader resource.
  151. * @param string $buffer Buffer with the reply read from the network.
  152. * @return int
  153. */
  154. protected function feedReader($resource, $buffer)
  155. {
  156. phpiredis_reader_feed($this->reader, $buffer);
  157. return strlen($buffer);
  158. }
  159. /**
  160. * {@inheritdoc}
  161. */
  162. public function connect()
  163. {
  164. // NOOP
  165. }
  166. /**
  167. * {@inheritdoc}
  168. */
  169. public function disconnect()
  170. {
  171. // NOOP
  172. }
  173. /**
  174. * {@inheritdoc}
  175. */
  176. public function isConnected()
  177. {
  178. return true;
  179. }
  180. /**
  181. * Checks if the specified command is supported by this connection class.
  182. *
  183. * @param CommandInterface $command The instance of a Redis command.
  184. * @return string
  185. */
  186. protected function getCommandId(CommandInterface $command)
  187. {
  188. switch (($commandId = $command->getId())) {
  189. case 'AUTH':
  190. case 'SELECT':
  191. case 'MULTI':
  192. case 'EXEC':
  193. case 'WATCH':
  194. case 'UNWATCH':
  195. case 'DISCARD':
  196. case 'MONITOR':
  197. throw new NotSupportedException("Disabled command: {$command->getId()}");
  198. default:
  199. return $commandId;
  200. }
  201. }
  202. /**
  203. * {@inheritdoc}
  204. */
  205. public function writeCommand(CommandInterface $command)
  206. {
  207. $this->throwNotSupportedException(__FUNCTION__);
  208. }
  209. /**
  210. * {@inheritdoc}
  211. */
  212. public function readResponse(CommandInterface $command)
  213. {
  214. $this->throwNotSupportedException(__FUNCTION__);
  215. }
  216. /**
  217. * {@inheritdoc}
  218. */
  219. public function executeCommand(CommandInterface $command)
  220. {
  221. $resource = $this->resource;
  222. $commandId = $this->getCommandId($command);
  223. if ($arguments = $command->getArguments()) {
  224. $arguments = implode('/', array_map('urlencode', $arguments));
  225. $serializedCommand = "$commandId/$arguments.raw";
  226. } else {
  227. $serializedCommand = "$commandId.raw";
  228. }
  229. curl_setopt($resource, CURLOPT_POSTFIELDS, $serializedCommand);
  230. if (curl_exec($resource) === false) {
  231. $error = curl_error($resource);
  232. $errno = curl_errno($resource);
  233. throw new ConnectionException($this, trim($error), $errno);
  234. }
  235. $readerState = phpiredis_reader_get_state($this->reader);
  236. if ($readerState === PHPIREDIS_READER_STATE_COMPLETE) {
  237. $reply = phpiredis_reader_get_reply($this->reader);
  238. if ($reply instanceof ResponseObjectInterface) {
  239. return $reply;
  240. }
  241. return $command->parseResponse($reply);
  242. } else {
  243. throw new ProtocolException($this, phpiredis_reader_get_error($this->reader));
  244. }
  245. }
  246. /**
  247. * {@inheritdoc}
  248. */
  249. public function getResource()
  250. {
  251. return $this->resource;
  252. }
  253. /**
  254. * {@inheritdoc}
  255. */
  256. public function getParameters()
  257. {
  258. return $this->parameters;
  259. }
  260. /**
  261. * {@inheritdoc}
  262. */
  263. public function pushInitCommand(CommandInterface $command)
  264. {
  265. $this->throwNotSupportedException(__FUNCTION__);
  266. }
  267. /**
  268. * {@inheritdoc}
  269. */
  270. public function read()
  271. {
  272. $this->throwNotSupportedException(__FUNCTION__);
  273. }
  274. /**
  275. * {@inheritdoc}
  276. */
  277. public function __toString()
  278. {
  279. return "{$this->parameters->host}:{$this->parameters->port}";
  280. }
  281. /**
  282. * {@inheritdoc}
  283. */
  284. public function __sleep()
  285. {
  286. return array('parameters');
  287. }
  288. /**
  289. * {@inheritdoc}
  290. */
  291. public function __wakeup()
  292. {
  293. $this->checkExtensions();
  294. $parameters = $this->getParameters();
  295. $this->resource = $this->initializeCurl($parameters);
  296. $this->reader = $this->initializeReader($parameters);
  297. }
  298. }