CurlMultiHandler.php 6.3 KB

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