PhpiredisStreamConnection.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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\Command\CommandInterface;
  12. use Predis\NotSupportedException;
  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 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.
  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 'redis', '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. * - async_connect: performs the connection asynchronously.
  38. * - tcp_nodelay: enables or disables Nagle's algorithm for coalescing.
  39. * - persistent: the connection is left intact after a GC collection.
  40. *
  41. * @link https://github.com/nrk/phpiredis
  42. *
  43. * @author Daniele Alessandri <suppakilla@gmail.com>
  44. */
  45. class PhpiredisStreamConnection extends StreamConnection
  46. {
  47. private $reader;
  48. /**
  49. * {@inheritdoc}
  50. */
  51. public function __construct(ParametersInterface $parameters)
  52. {
  53. $this->assertExtensions();
  54. parent::__construct($parameters);
  55. $this->reader = $this->createReader();
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. public function __destruct()
  61. {
  62. phpiredis_reader_destroy($this->reader);
  63. parent::__destruct();
  64. }
  65. /**
  66. * Checks if the phpiredis extension is loaded in PHP.
  67. */
  68. private function assertExtensions()
  69. {
  70. if (!extension_loaded('phpiredis')) {
  71. throw new NotSupportedException(
  72. 'The "phpiredis" extension is required by this connection backend.'
  73. );
  74. }
  75. }
  76. /**
  77. * {@inheritdoc}
  78. */
  79. protected function tcpStreamInitializer(ParametersInterface $parameters)
  80. {
  81. $uri = "tcp://[{$parameters->host}]:{$parameters->port}";
  82. $flags = STREAM_CLIENT_CONNECT;
  83. $socket = null;
  84. if (isset($parameters->async_connect) && (bool) $parameters->async_connect) {
  85. $flags |= STREAM_CLIENT_ASYNC_CONNECT;
  86. }
  87. if (isset($parameters->persistent) && (bool) $parameters->persistent) {
  88. $flags |= STREAM_CLIENT_PERSISTENT;
  89. $uri .= strpos($path = $parameters->path, '/') === 0 ? $path : "/$path";
  90. }
  91. $resource = @stream_socket_client($uri, $errno, $errstr, (float) $parameters->timeout, $flags);
  92. if (!$resource) {
  93. $this->onConnectionError(trim($errstr), $errno);
  94. }
  95. if (isset($parameters->read_write_timeout) && function_exists('socket_import_stream')) {
  96. $rwtimeout = (float) $parameters->read_write_timeout;
  97. $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
  98. $timeout = array(
  99. 'sec' => $timeoutSeconds = floor($rwtimeout),
  100. 'usec' => ($rwtimeout - $timeoutSeconds) * 1000000,
  101. );
  102. $socket = $socket ?: socket_import_stream($resource);
  103. @socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout);
  104. @socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout);
  105. }
  106. if (isset($parameters->tcp_nodelay) && function_exists('socket_import_stream')) {
  107. $socket = $socket ?: socket_import_stream($resource);
  108. socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay);
  109. }
  110. return $resource;
  111. }
  112. /**
  113. * Creates a new instance of the protocol reader resource.
  114. *
  115. * @return resource
  116. */
  117. private function createReader()
  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. * Returns the underlying protocol reader resource.
  126. *
  127. * @return resource
  128. */
  129. protected function getReader()
  130. {
  131. return $this->reader;
  132. }
  133. /**
  134. * Returns the handler used by the protocol reader for inline responses.
  135. *
  136. * @return \Closure
  137. */
  138. protected function getStatusHandler()
  139. {
  140. return function ($payload) {
  141. return StatusResponse::get($payload);
  142. };
  143. }
  144. /**
  145. * Returns the handler used by the protocol reader for error responses.
  146. *
  147. * @return \Closure
  148. */
  149. protected function getErrorHandler()
  150. {
  151. return function ($errorMessage) {
  152. return new ErrorResponse($errorMessage);
  153. };
  154. }
  155. /**
  156. * {@inheritdoc}
  157. */
  158. public function read()
  159. {
  160. $socket = $this->getResource();
  161. $reader = $this->reader;
  162. while (PHPIREDIS_READER_STATE_INCOMPLETE === $state = phpiredis_reader_get_state($reader)) {
  163. $buffer = stream_socket_recvfrom($socket, 4096);
  164. if ($buffer === false || $buffer === '') {
  165. $this->onConnectionError('Error while reading bytes from the server.');
  166. }
  167. phpiredis_reader_feed($reader, $buffer);
  168. }
  169. if ($state === PHPIREDIS_READER_STATE_COMPLETE) {
  170. return phpiredis_reader_get_reply($reader);
  171. } else {
  172. $this->onProtocolError(phpiredis_reader_get_error($reader));
  173. return;
  174. }
  175. }
  176. /**
  177. * {@inheritdoc}
  178. */
  179. public function writeRequest(CommandInterface $command)
  180. {
  181. $arguments = $command->getArguments();
  182. array_unshift($arguments, $command->getId());
  183. $this->write(phpiredis_format_command($arguments));
  184. }
  185. /**
  186. * {@inheritdoc}
  187. */
  188. public function __wakeup()
  189. {
  190. $this->assertExtensions();
  191. $this->reader = $this->createReader();
  192. }
  193. }