CurlMultiHandler.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. <?php
  2. namespace GuzzleHttp\Handler;
  3. use GuzzleHttp\Promise as P;
  4. use GuzzleHttp\Promise\Promise;
  5. use GuzzleHttp\Psr7;
  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. /**
  25. * This handler accepts the following options:
  26. *
  27. * - handle_factory: An optional factory used to create curl handles
  28. * - select_timeout: Optional timeout (in seconds) to block before timing
  29. * out while selecting curl handles. Defaults to 1 second.
  30. *
  31. * @param array $options
  32. */
  33. public function __construct(array $options = [])
  34. {
  35. $this->factory = isset($options['handle_factory'])
  36. ? $options['handle_factory'] : new CurlFactory(50);
  37. $this->selectTimeout = isset($options['select_timeout'])
  38. ? $options['select_timeout'] : 1;
  39. }
  40. public function __get($name)
  41. {
  42. if ($name === '_mh') {
  43. return $this->_mh = curl_multi_init();
  44. }
  45. throw new \BadMethodCallException();
  46. }
  47. public function __destruct()
  48. {
  49. if (isset($this->_mh)) {
  50. curl_multi_close($this->_mh);
  51. unset($this->_mh);
  52. }
  53. }
  54. public function __invoke(RequestInterface $request, array $options)
  55. {
  56. $easy = $this->factory->create($request, $options);
  57. $id = (int) $easy->handle;
  58. $promise = new Promise(
  59. [$this, 'execute'],
  60. function () use ($id) {
  61. return $this->cancel($id);
  62. }
  63. );
  64. $this->addRequest(['easy' => $easy, 'deferred' => $promise]);
  65. return $promise;
  66. }
  67. /**
  68. * Ticks the curl event loop.
  69. */
  70. public function tick()
  71. {
  72. // Add any delayed handles if needed.
  73. if ($this->delays) {
  74. $currentTime = microtime(true);
  75. foreach ($this->delays as $id => $delay) {
  76. if ($currentTime >= $delay) {
  77. unset($this->delays[$id]);
  78. curl_multi_add_handle(
  79. $this->_mh,
  80. $this->handles[$id]['easy']->handle
  81. );
  82. }
  83. }
  84. }
  85. // Step through the task queue which may add additional requests.
  86. P\queue()->run();
  87. if ($this->active &&
  88. curl_multi_select($this->_mh, $this->selectTimeout) === -1
  89. ) {
  90. // Perform a usleep if a select returns -1.
  91. // See: https://bugs.php.net/bug.php?id=61141
  92. usleep(250);
  93. }
  94. while (curl_multi_exec($this->_mh, $this->active) === CURLM_CALL_MULTI_PERFORM);
  95. $this->processMessages();
  96. }
  97. /**
  98. * Runs until all outstanding connections have completed.
  99. */
  100. public function execute()
  101. {
  102. $queue = P\queue();
  103. while ($this->handles || !$queue->isEmpty()) {
  104. // If there are no transfers, then sleep for the next delay
  105. if (!$this->active && $this->delays) {
  106. usleep($this->timeToNext());
  107. }
  108. $this->tick();
  109. }
  110. }
  111. private function addRequest(array $entry)
  112. {
  113. $easy = $entry['easy'];
  114. $id = (int) $easy->handle;
  115. $this->handles[$id] = $entry;
  116. if (empty($easy->options['delay'])) {
  117. curl_multi_add_handle($this->_mh, $easy->handle);
  118. } else {
  119. $this->delays[$id] = microtime(true) + ($easy->options['delay'] / 1000);
  120. }
  121. }
  122. /**
  123. * Cancels a handle from sending and removes references to it.
  124. *
  125. * @param int $id Handle ID to cancel and remove.
  126. *
  127. * @return bool True on success, false on failure.
  128. */
  129. private function cancel($id)
  130. {
  131. // Cannot cancel if it has been processed.
  132. if (!isset($this->handles[$id])) {
  133. return false;
  134. }
  135. $handle = $this->handles[$id]['easy']->handle;
  136. unset($this->delays[$id], $this->handles[$id]);
  137. curl_multi_remove_handle($this->_mh, $handle);
  138. curl_close($handle);
  139. return true;
  140. }
  141. private function processMessages()
  142. {
  143. while ($done = curl_multi_info_read($this->_mh)) {
  144. $id = (int) $done['handle'];
  145. curl_multi_remove_handle($this->_mh, $done['handle']);
  146. if (!isset($this->handles[$id])) {
  147. // Probably was cancelled.
  148. continue;
  149. }
  150. $entry = $this->handles[$id];
  151. unset($this->handles[$id], $this->delays[$id]);
  152. $entry['easy']->errno = $done['result'];
  153. $entry['deferred']->resolve(
  154. CurlFactory::finish(
  155. $this,
  156. $entry['easy'],
  157. $this->factory
  158. )
  159. );
  160. }
  161. }
  162. private function timeToNext()
  163. {
  164. $currentTime = microtime(true);
  165. $nextTime = PHP_INT_MAX;
  166. foreach ($this->delays as $time) {
  167. if ($time < $nextTime) {
  168. $nextTime = $time;
  169. }
  170. }
  171. return max(0, $nextTime - $currentTime) * 1000000;
  172. }
  173. }