PageRenderTime 53ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/core/resources/libraries/phpfastcache/phpfastcache/_extensions/predis-1.0/src/Connection/PhpiredisSocketConnection.php

https://github.com/otto-torino/gino
PHP | 392 lines | 216 code | 65 blank | 111 comment | 33 complexity | fced1a025cfc8390a9827b6469929eb9 MD5 | raw file
  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\Command\CommandInterface;
  13. use Predis\Response\Error as ErrorResponse;
  14. use Predis\Response\Status as StatusResponse;
  15. /**
  16. * This class provides the implementation of a Predis connection that uses the
  17. * PHP socket extension for network communication and wraps the phpiredis C
  18. * extension (PHP bindings for hiredis) to parse the Redis protocol.
  19. *
  20. * This class is intended to provide an optional low-overhead alternative for
  21. * processing responses from Redis compared to the standard pure-PHP classes.
  22. * Differences in speed when dealing with short inline responses are practically
  23. * nonexistent, the actual speed boost is for big multibulk responses when this
  24. * protocol processor can parse and return responses very fast.
  25. *
  26. * For instructions on how to build and install the phpiredis extension, please
  27. * consult the repository of the project.
  28. *
  29. * The connection parameters supported by this class are:
  30. *
  31. * - scheme: it can be either 'tcp' or 'unix'.
  32. * - host: hostname or IP address of the server.
  33. * - port: TCP port of the server.
  34. * - path: path of a UNIX domain socket when scheme is 'unix'.
  35. * - timeout: timeout to perform the connection.
  36. * - read_write_timeout: timeout of read / write operations.
  37. *
  38. * @link http://github.com/nrk/phpiredis
  39. * @author Daniele Alessandri <suppakilla@gmail.com>
  40. */
  41. class PhpiredisSocketConnection extends AbstractConnection
  42. {
  43. private $reader;
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function __construct(ParametersInterface $parameters)
  48. {
  49. $this->assertExtensions();
  50. parent::__construct($parameters);
  51. $this->reader = $this->createReader();
  52. }
  53. /**
  54. * Disconnects from the server and destroys the underlying resource and the
  55. * protocol reader resource when PHP's garbage collector kicks in.
  56. */
  57. public function __destruct()
  58. {
  59. phpiredis_reader_destroy($this->reader);
  60. parent::__destruct();
  61. }
  62. /**
  63. * Checks if the socket and phpiredis extensions are loaded in PHP.
  64. */
  65. protected function assertExtensions()
  66. {
  67. if (!extension_loaded('sockets')) {
  68. throw new NotSupportedException(
  69. 'The "sockets" extension is required by this connection backend.'
  70. );
  71. }
  72. if (!extension_loaded('phpiredis')) {
  73. throw new NotSupportedException(
  74. 'The "phpiredis" extension is required by this connection backend.'
  75. );
  76. }
  77. }
  78. /**
  79. * {@inheritdoc}
  80. */
  81. protected function assertParameters(ParametersInterface $parameters)
  82. {
  83. if (isset($parameters->persistent)) {
  84. throw new NotSupportedException(
  85. "Persistent connections are not supported by this connection backend."
  86. );
  87. }
  88. return parent::assertParameters($parameters);
  89. }
  90. /**
  91. * Creates a new instance of the protocol reader resource.
  92. *
  93. * @return resource
  94. */
  95. private function createReader()
  96. {
  97. $reader = phpiredis_reader_create();
  98. phpiredis_reader_set_status_handler($reader, $this->getStatusHandler());
  99. phpiredis_reader_set_error_handler($reader, $this->getErrorHandler());
  100. return $reader;
  101. }
  102. /**
  103. * Returns the underlying protocol reader resource.
  104. *
  105. * @return resource
  106. */
  107. protected function getReader()
  108. {
  109. return $this->reader;
  110. }
  111. /**
  112. * Returns the handler used by the protocol reader for inline responses.
  113. *
  114. * @return \Closure
  115. */
  116. private function getStatusHandler()
  117. {
  118. return function ($payload) {
  119. return StatusResponse::get($payload);
  120. };
  121. }
  122. /**
  123. * Returns the handler used by the protocol reader for error responses.
  124. *
  125. * @return \Closure
  126. */
  127. protected function getErrorHandler()
  128. {
  129. return function ($payload) {
  130. return new ErrorResponse($payload);
  131. };
  132. }
  133. /**
  134. * Helper method used to throw exceptions on socket errors.
  135. */
  136. private function emitSocketError()
  137. {
  138. $errno = socket_last_error();
  139. $errstr = socket_strerror($errno);
  140. $this->disconnect();
  141. $this->onConnectionError(trim($errstr), $errno);
  142. }
  143. /**
  144. * {@inheritdoc}
  145. */
  146. protected function createResource()
  147. {
  148. $isUnix = $this->parameters->scheme === 'unix';
  149. $domain = $isUnix ? AF_UNIX : AF_INET;
  150. $protocol = $isUnix ? 0 : SOL_TCP;
  151. $socket = @call_user_func('socket_create', $domain, SOCK_STREAM, $protocol);
  152. if (!is_resource($socket)) {
  153. $this->emitSocketError();
  154. }
  155. $this->setSocketOptions($socket, $this->parameters);
  156. return $socket;
  157. }
  158. /**
  159. * Sets options on the socket resource from the connection parameters.
  160. *
  161. * @param resource $socket Socket resource.
  162. * @param ParametersInterface $parameters Parameters used to initialize the connection.
  163. */
  164. private function setSocketOptions($socket, ParametersInterface $parameters)
  165. {
  166. if ($parameters->scheme !== 'tcp') {
  167. return;
  168. }
  169. if (!socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1)) {
  170. $this->emitSocketError();
  171. }
  172. if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
  173. $this->emitSocketError();
  174. }
  175. if (isset($parameters->read_write_timeout)) {
  176. $rwtimeout = (float) $parameters->read_write_timeout;
  177. $timeoutSec = floor($rwtimeout);
  178. $timeoutUsec = ($rwtimeout - $timeoutSec) * 1000000;
  179. $timeout = array(
  180. 'sec' => $timeoutSec,
  181. 'usec' => $timeoutUsec,
  182. );
  183. if (!socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout)) {
  184. $this->emitSocketError();
  185. }
  186. if (!socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout)) {
  187. $this->emitSocketError();
  188. }
  189. }
  190. }
  191. /**
  192. * Gets the address from the connection parameters.
  193. *
  194. * @param ParametersInterface $parameters Parameters used to initialize the connection.
  195. *
  196. * @return string
  197. */
  198. protected static function getAddress(ParametersInterface $parameters)
  199. {
  200. if ($parameters->scheme === 'unix') {
  201. return $parameters->path;
  202. }
  203. $host = $parameters->host;
  204. if (ip2long($host) === false) {
  205. if (false === $addresses = gethostbynamel($host)) {
  206. return false;
  207. }
  208. return $addresses[array_rand($addresses)];
  209. }
  210. return $host;
  211. }
  212. /**
  213. * Opens the actual connection to the server with a timeout.
  214. *
  215. * @param ParametersInterface $parameters Parameters used to initialize the connection.
  216. *
  217. * @return string
  218. */
  219. private function connectWithTimeout(ParametersInterface $parameters)
  220. {
  221. if (false === $host = self::getAddress($parameters)) {
  222. $this->onConnectionError("Cannot resolve the address of '$parameters->host'.");
  223. }
  224. $socket = $this->getResource();
  225. socket_set_nonblock($socket);
  226. if (@socket_connect($socket, $host, (int) $parameters->port) === false) {
  227. $error = socket_last_error();
  228. if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
  229. $this->emitSocketError();
  230. }
  231. }
  232. socket_set_block($socket);
  233. $null = null;
  234. $selectable = array($socket);
  235. $timeout = (float) $parameters->timeout;
  236. $timeoutSecs = floor($timeout);
  237. $timeoutUSecs = ($timeout - $timeoutSecs) * 1000000;
  238. $selected = socket_select($selectable, $selectable, $null, $timeoutSecs, $timeoutUSecs);
  239. if ($selected === 2) {
  240. $this->onConnectionError('Connection refused.', SOCKET_ECONNREFUSED);
  241. }
  242. if ($selected === 0) {
  243. $this->onConnectionError('Connection timed out.', SOCKET_ETIMEDOUT);
  244. }
  245. if ($selected === false) {
  246. $this->emitSocketError();
  247. }
  248. }
  249. /**
  250. * {@inheritdoc}
  251. */
  252. public function connect()
  253. {
  254. if (parent::connect()) {
  255. $this->connectWithTimeout($this->parameters);
  256. if ($this->initCommands) {
  257. foreach ($this->initCommands as $command) {
  258. $this->executeCommand($command);
  259. }
  260. }
  261. }
  262. }
  263. /**
  264. * {@inheritdoc}
  265. */
  266. public function disconnect()
  267. {
  268. if ($this->isConnected()) {
  269. socket_close($this->getResource());
  270. parent::disconnect();
  271. }
  272. }
  273. /**
  274. * {@inheritdoc}
  275. */
  276. protected function write($buffer)
  277. {
  278. $socket = $this->getResource();
  279. while (($length = strlen($buffer)) > 0) {
  280. $written = socket_write($socket, $buffer, $length);
  281. if ($length === $written) {
  282. return;
  283. }
  284. if ($written === false) {
  285. $this->onConnectionError('Error while writing bytes to the server.');
  286. }
  287. $buffer = substr($buffer, $written);
  288. }
  289. }
  290. /**
  291. * {@inheritdoc}
  292. */
  293. public function read()
  294. {
  295. $socket = $this->getResource();
  296. $reader = $this->reader;
  297. while (PHPIREDIS_READER_STATE_INCOMPLETE === $state = phpiredis_reader_get_state($reader)) {
  298. if (@socket_recv($socket, $buffer, 4096, 0) === false || $buffer === '') {
  299. $this->emitSocketError();
  300. }
  301. phpiredis_reader_feed($reader, $buffer);
  302. }
  303. if ($state === PHPIREDIS_READER_STATE_COMPLETE) {
  304. return phpiredis_reader_get_reply($reader);
  305. } else {
  306. $this->onProtocolError(phpiredis_reader_get_error($reader));
  307. return;
  308. }
  309. }
  310. /**
  311. * {@inheritdoc}
  312. */
  313. public function writeRequest(CommandInterface $command)
  314. {
  315. $arguments = $command->getArguments();
  316. array_unshift($arguments, $command->getId());
  317. $this->write(phpiredis_format_command($arguments));
  318. }
  319. /**
  320. * {@inheritdoc}
  321. */
  322. public function __wakeup()
  323. {
  324. $this->assertExtensions();
  325. $this->reader = $this->createReader();
  326. }
  327. }