CurlMultiHandler.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. <?php
  2. namespace GuzzleHttp\Handler;
  3. use GuzzleHttp\Exception\InvalidArgumentException;
  4. use GuzzleHttp\Promise as P;
  5. use GuzzleHttp\Promise\Promise;
  6. use GuzzleHttp\Utils;
  7. use Psr\Http\Message\RequestInterface;
  8. /**
  9. * Returns an asynchronous response using curl_multi_* functions.
  10. *
  11. * When using the CurlMultiHandler, custom curl options can be specified as an
  12. * associative array of curl option constants mapping to values in the
  13. * **curl** key of the provided request options.
  14. *
  15. * @property resource $_mh Internal use only. Lazy loaded multi-handle.
  16. */
  17. class CurlMultiHandler
  18. {
  19. /** @var CurlFactoryInterface */
  20. private $factory;
  21. private $selectTimeout;
  22. private $active;
  23. private $handles = [];
  24. private $delays = [];
  25. private $options = [];
  26. /**
  27. * This handler accepts the following options:
  28. *
  29. * - handle_factory: An optional factory used to create curl handles
  30. * - select_timeout: Optional timeout (in seconds) to block before timing
  31. * out while selecting curl handles. Defaults to 1 second.
  32. * - options: An associative array of CURLMOPT_* options and
  33. * corresponding values for curl_multi_setopt()
  34. *
  35. * @param array $options
  36. */
  37. public function __construct(array $options = [])
  38. {
  39. $this->factory = isset($options['handle_factory'])
  40. ? $options['handle_factory'] : new CurlFactory(50);
  41. if (isset($options['select_timeout'])) {
  42. $this->selectTimeout = $options['select_timeout'];
  43. } elseif ($selectTimeout = getenv('GUZZLE_CURL_SELECT_TIMEOUT')) {
  44. $this->selectTimeout = $selectTimeout;
  45. } else {
  46. $this->selectTimeout = 1;
  47. }
  48. $this->options = isset($options['options']) ? $options['options'] : [];
  49. }
  50. public function __get($name)
  51. {
  52. if ($name === '_mh') {
  53. $this->_mh = curl_multi_init();
  54. foreach ($this->options as $option => $value) {
  55. // A warning is raised in case of a wrong option.
  56. curl_multi_setopt($this->_mh, $option, $value);
  57. }
  58. // Further calls to _mh will return the value directly, without entering the
  59. // __get() method at all.
  60. return $this->_mh;
  61. }
  62. throw new \BadMethodCallException();
  63. }
  64. public function __destruct()
  65. {
  66. if (isset($this->_mh)) {
  67. curl_multi_close($this->_mh);
  68. unset($this->_mh);
  69. }
  70. }
  71. public function __invoke(RequestInterface $request, array $options)
  72. {
  73. $easy = $this->factory->create($request, $options);
  74. $id = (int) $easy->handle;
  75. $promise = new Promise(
  76. [$this, 'execute'],
  77. function () use ($id) {
  78. return $this->cancel($id);
  79. }
  80. );
  81. $this->addRequest(['easy' => $easy, 'deferred' => $promise]);
  82. return $promise;
  83. }
  84. /**
  85. * Ticks the curl event loop.
  86. */
  87. public function tick()
  88. {
  89. // Add any delayed handles if needed.
  90. if ($this->delays) {
  91. $currentTime = Utils::currentTime();
  92. foreach ($this->delays as $id => $delay) {
  93. if ($currentTime >= $delay) {
  94. unset($this->delays[$id]);
  95. curl_multi_add_handle(
  96. $this->_mh,
  97. $this->handles[$id]['easy']->handle
  98. );
  99. }
  100. }
  101. }
  102. // Step through the task queue which may add additional requests.
  103. P\queue()->run();
  104. if ($this->active &&
  105. curl_multi_select($this->_mh, $this->selectTimeout) === -1
  106. ) {
  107. // Perform a usleep if a select returns -1.
  108. // See: https://bugs.php.net/bug.php?id=61141
  109. usleep(250);
  110. }
  111. while (curl_multi_exec($this->_mh, $this->active) === CURLM_CALL_MULTI_PERFORM);
  112. $this->processMessages();
  113. }
  114. /**
  115. * Runs until all outstanding connections have completed.
  116. */
  117. public function execute()
  118. {
  119. $queue = P\queue();
  120. while ($this->handles || !$queue->isEmpty()) {
  121. // If there are no transfers, then sleep for the next delay
  122. if (!$this->active && $this->delays) {
  123. usleep($this->timeToNext());
  124. }
  125. $this->tick();
  126. }
  127. }
  128. private function addRequest(array $entry)
  129. {
  130. $easy = $entry['easy'];
  131. $id = (int) $easy->handle;
  132. $this->handles[$id] = $entry;
  133. if (empty($easy->options['delay'])) {
  134. curl_multi_add_handle($this->_mh, $easy->handle);
  135. } else {
  136. $this->delays[$id] = Utils::currentTime() + ($easy->options['delay'] / 1000);
  137. }
  138. }
  139. /**
  140. * Cancels a handle from sending and removes references to it.
  141. *
  142. * @param int $id Handle ID to cancel and remove.
  143. *
  144. * @return bool True on success, false on failure.
  145. */
  146. private function cancel($id)
  147. {
  148. // Cannot cancel if it has been processed.
  149. if (!isset($this->handles[$id])) {
  150. return false;
  151. }
  152. $handle = $this->handles[$id]['easy']->handle;
  153. unset($this->delays[$id], $this->handles[$id]);
  154. curl_multi_remove_handle($this->_mh, $handle);
  155. curl_close($handle);
  156. return true;
  157. }
  158. private function processMessages()
  159. {
  160. while ($done = curl_multi_info_read($this->_mh)) {
  161. $id = (int) $done['handle'];
  162. curl_multi_remove_handle($this->_mh, $done['handle']);
  163. if (!isset($this->handles[$id])) {
  164. // Probably was cancelled.
  165. continue;
  166. }
  167. $entry = $this->handles[$id];
  168. unset($this->handles[$id], $this->delays[$id]);
  169. $entry['easy']->errno = $done['result'];
  170. $entry['deferred']->resolve(
  171. CurlFactory::finish(
  172. $this,
  173. $entry['easy'],
  174. $this->factory
  175. )
  176. );
  177. }
  178. }
  179. private function timeToNext()
  180. {
  181. $currentTime = Utils::currentTime();
  182. $nextTime = PHP_INT_MAX;
  183. foreach ($this->delays as $time) {
  184. if ($time < $nextTime) {
  185. $nextTime = $time;
  186. }
  187. }
  188. return max(0, $nextTime - $currentTime) * 1000000;
  189. }
  190. }