WebdisConnection.php 8.8 KB

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