PhpiredisStreamConnection.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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\ResponseQueued;
  14. use Predis\Command\CommandInterface;
  15. /**
  16. * This class provides the implementation of a Predis connection that uses PHP's
  17. * streams for network communication and wraps the phpiredis C extension (PHP
  18. * bindings for hiredis) to parse and serialize the Redis protocol. Everything
  19. * is highly experimental (even the very same phpiredis since it is quite new),
  20. * so use it at your own risk.
  21. *
  22. * This class is mainly intended to provide an optional low-overhead alternative
  23. * for processing replies from Redis compared to the standard pure-PHP classes.
  24. * Differences in speed when dealing with short inline replies are practically
  25. * nonexistent, the actual speed boost is for long multibulk replies when this
  26. * protocol processor can parse and return replies very fast.
  27. *
  28. * For instructions on how to build and install the phpiredis extension, please
  29. * consult the repository of the project.
  30. *
  31. * The connection parameters supported by this class are:
  32. *
  33. * - scheme: it can be either 'tcp' or 'unix'.
  34. * - host: hostname or IP address of the server.
  35. * - port: TCP port of the server.
  36. * - path: path of a UNIX domain socket when scheme is 'unix'.
  37. * - timeout: timeout to perform the connection.
  38. * - read_write_timeout: timeout of read / write operations.
  39. * - async_connect: performs the connection asynchronously.
  40. * - tcp_nodelay: enables or disables Nagle's algorithm for coalescing.
  41. * - persistent: the connection is left intact after a GC collection.
  42. *
  43. * @link https://github.com/nrk/phpiredis
  44. * @author Daniele Alessandri <suppakilla@gmail.com>
  45. */
  46. class PhpiredisStreamConnection extends StreamConnection
  47. {
  48. private $reader;
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function __construct(ConnectionParametersInterface $parameters)
  53. {
  54. $this->checkExtensions();
  55. $this->initializeReader();
  56. parent::__construct($parameters);
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. public function __destruct()
  62. {
  63. phpiredis_reader_destroy($this->reader);
  64. parent::__destruct();
  65. }
  66. /**
  67. * Checks if the phpiredis extension is loaded in PHP.
  68. */
  69. protected function checkExtensions()
  70. {
  71. if (!function_exists('phpiredis_reader_create')) {
  72. throw new NotSupportedException(
  73. 'The phpiredis extension must be loaded in order to be able to use this connection class'
  74. );
  75. }
  76. }
  77. /**
  78. * {@inheritdoc}
  79. */
  80. protected function checkParameters(ConnectionParametersInterface $parameters)
  81. {
  82. if (isset($parameters->iterable_multibulk)) {
  83. $this->onInvalidOption('iterable_multibulk', $parameters);
  84. }
  85. return parent::checkParameters($parameters);
  86. }
  87. /**
  88. * {@inheritdoc}
  89. */
  90. protected function tcpStreamInitializer(ConnectionParametersInterface $parameters)
  91. {
  92. $uri = "tcp://{$parameters->host}:{$parameters->port}";
  93. $flags = STREAM_CLIENT_CONNECT;
  94. $socket = null;
  95. if (isset($parameters->async_connect) && $parameters->async_connect) {
  96. $flags |= STREAM_CLIENT_ASYNC_CONNECT;
  97. }
  98. if (isset($parameters->persistent) && $parameters->persistent) {
  99. $flags |= STREAM_CLIENT_PERSISTENT;
  100. $uri .= strpos($path = $parameters->path, '/') === 0 ? $path : "/$path";
  101. }
  102. $resource = @stream_socket_client($uri, $errno, $errstr, $parameters->timeout, $flags);
  103. if (!$resource) {
  104. $this->onConnectionError(trim($errstr), $errno);
  105. }
  106. if (isset($parameters->read_write_timeout) && function_exists('socket_import_stream')) {
  107. $rwtimeout = (float) $parameters->read_write_timeout;
  108. $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
  109. $timeout = array(
  110. 'sec' => $timeoutSeconds = floor($rwtimeout),
  111. 'usec' => ($rwtimeout - $timeoutSeconds) * 1000000,
  112. );
  113. $socket = $socket ?: socket_import_stream($resource);
  114. @socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout);
  115. @socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout);
  116. }
  117. if (isset($parameters->tcp_nodelay) && function_exists('socket_import_stream')) {
  118. $socket = $socket ?: socket_import_stream($resource);
  119. socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay);
  120. }
  121. return $resource;
  122. }
  123. /**
  124. * Initializes the protocol reader resource.
  125. */
  126. protected function initializeReader()
  127. {
  128. $reader = phpiredis_reader_create();
  129. phpiredis_reader_set_status_handler($reader, $this->getStatusHandler());
  130. phpiredis_reader_set_error_handler($reader, $this->getErrorHandler());
  131. $this->reader = $reader;
  132. }
  133. /**
  134. * Gets the handler used by the protocol reader to handle status replies.
  135. *
  136. * @return \Closure
  137. */
  138. protected function getStatusHandler()
  139. {
  140. return function ($payload) {
  141. switch ($payload) {
  142. case 'OK':
  143. return true;
  144. case 'QUEUED':
  145. return new ResponseQueued();
  146. default:
  147. return $payload;
  148. }
  149. };
  150. }
  151. /**
  152. * Gets the handler used by the protocol reader to handle Redis errors.
  153. *
  154. * @return \Closure
  155. */
  156. protected function getErrorHandler()
  157. {
  158. return function ($errorMessage) {
  159. return new ResponseError($errorMessage);
  160. };
  161. }
  162. /**
  163. * {@inheritdoc}
  164. */
  165. public function read()
  166. {
  167. $socket = $this->getResource();
  168. $reader = $this->reader;
  169. while (PHPIREDIS_READER_STATE_INCOMPLETE === $state = phpiredis_reader_get_state($reader)) {
  170. $buffer = stream_socket_recvfrom($socket, 4096);
  171. if ($buffer === false || $buffer === '') {
  172. $this->onConnectionError('Error while reading bytes from the server');
  173. }
  174. phpiredis_reader_feed($reader, $buffer);
  175. }
  176. if ($state === PHPIREDIS_READER_STATE_COMPLETE) {
  177. return phpiredis_reader_get_reply($reader);
  178. } else {
  179. $this->onProtocolError(phpiredis_reader_get_error($reader));
  180. }
  181. }
  182. /**
  183. * {@inheritdoc}
  184. */
  185. public function writeCommand(CommandInterface $command)
  186. {
  187. $cmdargs = $command->getArguments();
  188. array_unshift($cmdargs, $command->getId());
  189. $this->writeBytes(phpiredis_format_command($cmdargs));
  190. }
  191. /**
  192. * {@inheritdoc}
  193. */
  194. public function __sleep()
  195. {
  196. return array_diff(parent::__sleep(), array('mbiterable'));
  197. }
  198. /**
  199. * {@inheritdoc}
  200. */
  201. public function __wakeup()
  202. {
  203. $this->checkExtensions();
  204. $this->initializeReader();
  205. }
  206. }