CurlMultiHandler.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. <?php
  2. namespace GuzzleHttp\Handler;
  3. use GuzzleHttp\Promise as P;
  4. use GuzzleHttp\Promise\Promise;
  5. use GuzzleHttp\Promise\PromiseInterface;
  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|\CurlMultiHandle $_mh Internal use only. Lazy loaded multi-handle.
  16. *
  17. * @final
  18. */
  19. class CurlMultiHandler
  20. {
  21. /**
  22. * @var CurlFactoryInterface
  23. */
  24. private $factory;
  25. /**
  26. * @var int
  27. */
  28. private $selectTimeout;
  29. /**
  30. * @var int Will be higher than 0 when `curl_multi_exec` is still running.
  31. */
  32. private $active = 0;
  33. /**
  34. * @var array Request entry handles, indexed by handle id in `addRequest`.
  35. *
  36. * @see CurlMultiHandler::addRequest
  37. */
  38. private $handles = [];
  39. /**
  40. * @var array<int, float> An array of delay times, indexed by handle id in `addRequest`.
  41. *
  42. * @see CurlMultiHandler::addRequest
  43. */
  44. private $delays = [];
  45. /**
  46. * @var array<mixed> An associative array of CURLMOPT_* options and corresponding values for curl_multi_setopt()
  47. */
  48. private $options = [];
  49. /**
  50. * This handler accepts the following options:
  51. *
  52. * - handle_factory: An optional factory used to create curl handles
  53. * - select_timeout: Optional timeout (in seconds) to block before timing
  54. * out while selecting curl handles. Defaults to 1 second.
  55. * - options: An associative array of CURLMOPT_* options and
  56. * corresponding values for curl_multi_setopt()
  57. */
  58. public function __construct(array $options = [])
  59. {
  60. $this->factory = $options['handle_factory'] ?? new CurlFactory(50);
  61. if (isset($options['select_timeout'])) {
  62. $this->selectTimeout = $options['select_timeout'];
  63. } elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) {
  64. @trigger_error('Since guzzlehttp/guzzle 7.2.0: Using environment variable GUZZLE_CURL_SELECT_TIMEOUT is deprecated. Use option "select_timeout" instead.', \E_USER_DEPRECATED);
  65. $this->selectTimeout = (int) $selectTimeout;
  66. } else {
  67. $this->selectTimeout = 1;
  68. }
  69. $this->options = $options['options'] ?? [];
  70. }
  71. /**
  72. * @param string $name
  73. *
  74. * @return resource|\CurlMultiHandle
  75. *
  76. * @throws \BadMethodCallException when another field as `_mh` will be gotten
  77. * @throws \RuntimeException when curl can not initialize a multi handle
  78. */
  79. public function __get($name)
  80. {
  81. if ($name !== '_mh') {
  82. throw new \BadMethodCallException("Can not get other property as '_mh'.");
  83. }
  84. $multiHandle = \curl_multi_init();
  85. if (false === $multiHandle) {
  86. throw new \RuntimeException('Can not initialize curl multi handle.');
  87. }
  88. $this->_mh = $multiHandle;
  89. foreach ($this->options as $option => $value) {
  90. // A warning is raised in case of a wrong option.
  91. curl_multi_setopt($this->_mh, $option, $value);
  92. }
  93. return $this->_mh;
  94. }
  95. public function __destruct()
  96. {
  97. if (isset($this->_mh)) {
  98. \curl_multi_close($this->_mh);
  99. unset($this->_mh);
  100. }
  101. }
  102. public function __invoke(RequestInterface $request, array $options): PromiseInterface
  103. {
  104. $easy = $this->factory->create($request, $options);
  105. $id = (int) $easy->handle;
  106. $promise = new Promise(
  107. [$this, 'execute'],
  108. function () use ($id) {
  109. return $this->cancel($id);
  110. }
  111. );
  112. $this->addRequest(['easy' => $easy, 'deferred' => $promise]);
  113. return $promise;
  114. }
  115. /**
  116. * Ticks the curl event loop.
  117. */
  118. public function tick(): void
  119. {
  120. // Add any delayed handles if needed.
  121. if ($this->delays) {
  122. $currentTime = Utils::currentTime();
  123. foreach ($this->delays as $id => $delay) {
  124. if ($currentTime >= $delay) {
  125. unset($this->delays[$id]);
  126. \curl_multi_add_handle(
  127. $this->_mh,
  128. $this->handles[$id]['easy']->handle
  129. );
  130. }
  131. }
  132. }
  133. // Step through the task queue which may add additional requests.
  134. P\Utils::queue()->run();
  135. if ($this->active && \curl_multi_select($this->_mh, $this->selectTimeout) === -1) {
  136. // Perform a usleep if a select returns -1.
  137. // See: https://bugs.php.net/bug.php?id=61141
  138. \usleep(250);
  139. }
  140. while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM);
  141. $this->processMessages();
  142. }
  143. /**
  144. * Runs until all outstanding connections have completed.
  145. */
  146. public function execute(): void
  147. {
  148. $queue = P\Utils::queue();
  149. while ($this->handles || !$queue->isEmpty()) {
  150. // If there are no transfers, then sleep for the next delay
  151. if (!$this->active && $this->delays) {
  152. \usleep($this->timeToNext());
  153. }
  154. $this->tick();
  155. }
  156. }
  157. private function addRequest(array $entry): void
  158. {
  159. $easy = $entry['easy'];
  160. $id = (int) $easy->handle;
  161. $this->handles[$id] = $entry;
  162. if (empty($easy->options['delay'])) {
  163. \curl_multi_add_handle($this->_mh, $easy->handle);
  164. } else {
  165. $this->delays[$id] = Utils::currentTime() + ($easy->options['delay'] / 1000);
  166. }
  167. }
  168. /**
  169. * Cancels a handle from sending and removes references to it.
  170. *
  171. * @param int $id Handle ID to cancel and remove.
  172. *
  173. * @return bool True on success, false on failure.
  174. */
  175. private function cancel($id): bool
  176. {
  177. if (!is_int($id)) {
  178. trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an integer to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
  179. }
  180. // Cannot cancel if it has been processed.
  181. if (!isset($this->handles[$id])) {
  182. return false;
  183. }
  184. $handle = $this->handles[$id]['easy']->handle;
  185. unset($this->delays[$id], $this->handles[$id]);
  186. \curl_multi_remove_handle($this->_mh, $handle);
  187. \curl_close($handle);
  188. return true;
  189. }
  190. private function processMessages(): void
  191. {
  192. while ($done = \curl_multi_info_read($this->_mh)) {
  193. if ($done['msg'] !== \CURLMSG_DONE) {
  194. // if it's not done, then it would be premature to remove the handle. ref https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216
  195. continue;
  196. }
  197. $id = (int) $done['handle'];
  198. \curl_multi_remove_handle($this->_mh, $done['handle']);
  199. if (!isset($this->handles[$id])) {
  200. // Probably was cancelled.
  201. continue;
  202. }
  203. $entry = $this->handles[$id];
  204. unset($this->handles[$id], $this->delays[$id]);
  205. $entry['easy']->errno = $done['result'];
  206. $entry['deferred']->resolve(
  207. CurlFactory::finish($this, $entry['easy'], $this->factory)
  208. );
  209. }
  210. }
  211. private function timeToNext(): int
  212. {
  213. $currentTime = Utils::currentTime();
  214. $nextTime = \PHP_INT_MAX;
  215. foreach ($this->delays as $time) {
  216. if ($time < $nextTime) {
  217. $nextTime = $time;
  218. }
  219. }
  220. return ((int) \max(0, $nextTime - $currentTime)) * 1000000;
  221. }
  222. }