gmail-smtp
/
google-api-php-client
/
vendor
/
guzzlehttp
/
guzzle
/
src
/
Handler
/
CurlMultiHandler.php
CurlMultiHandler.php in Gmail SMTP trunk, at google-api-php-client/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php
| 1 | <?php |
| 2 | |
| 3 | namespace GuzzleHttp\Handler; |
| 4 | |
| 5 | use Closure; |
| 6 | use GuzzleHttp\Promise as P; |
| 7 | use GuzzleHttp\Promise\Promise; |
| 8 | use GuzzleHttp\Promise\PromiseInterface; |
| 9 | use GuzzleHttp\TransportSharing; |
| 10 | use GuzzleHttp\Utils; |
| 11 | use Psr\Http\Message\RequestInterface; |
| 12 | |
| 13 | /** |
| 14 | * Returns an asynchronous response using curl_multi_* functions. |
| 15 | * |
| 16 | * When using the CurlMultiHandler, custom curl options can be specified as an |
| 17 | * associative array of curl option constants mapping to values in the |
| 18 | * **curl** key of the provided request options. |
| 19 | * |
| 20 | * @final |
| 21 | */ |
| 22 | class CurlMultiHandler |
| 23 | { |
| 24 | /** |
| 25 | * @var CurlFactoryInterface |
| 26 | */ |
| 27 | private $factory; |
| 28 | |
| 29 | /** |
| 30 | * @var CurlShareHandleState|null |
| 31 | */ |
| 32 | private $shareHandleState; |
| 33 | |
| 34 | /** |
| 35 | * @var int |
| 36 | */ |
| 37 | private $selectTimeout; |
| 38 | |
| 39 | /** |
| 40 | * @var int Will be higher than 0 when `curl_multi_exec` is still running. |
| 41 | */ |
| 42 | private $active = 0; |
| 43 | |
| 44 | /** |
| 45 | * @var array Request entry handles, indexed by handle id in `addRequest`. |
| 46 | * |
| 47 | * @see CurlMultiHandler::addRequest |
| 48 | */ |
| 49 | private $handles = []; |
| 50 | |
| 51 | /** |
| 52 | * @var array<int, float> An array of delay times, indexed by handle id in `addRequest`. |
| 53 | * |
| 54 | * @see CurlMultiHandler::addRequest |
| 55 | */ |
| 56 | private $delays = []; |
| 57 | |
| 58 | /** |
| 59 | * @var array<mixed> An associative array of CURLMOPT_* options and corresponding values for curl_multi_setopt() |
| 60 | */ |
| 61 | private $options = []; |
| 62 | |
| 63 | /** @var resource|\CurlMultiHandle */ |
| 64 | private $_mh; |
| 65 | |
| 66 | /** |
| 67 | * @var bool |
| 68 | */ |
| 69 | private $executingMulti = false; |
| 70 | |
| 71 | /** |
| 72 | * @var array<int, EasyHandle> |
| 73 | */ |
| 74 | private $deferredCancels = []; |
| 75 | |
| 76 | /** |
| 77 | * This handler accepts the following options: |
| 78 | * |
| 79 | * - handle_factory: An optional factory used to create curl handles |
| 80 | * - transport_sharing: Optional transport sharing mode. |
| 81 | * - select_timeout: Optional timeout (in seconds) to block before timing |
| 82 | * out while selecting curl handles. Defaults to 1 second. |
| 83 | * - options: An associative array of CURLMOPT_* options and |
| 84 | * corresponding values for curl_multi_setopt() |
| 85 | */ |
| 86 | public function __construct(array $options = []) |
| 87 | { |
| 88 | CurlShareHandleState::assertNoRequiredSharingCustomFactoryConflict($options, 'CurlMultiHandler'); |
| 89 | $transportSharing = $options['transport_sharing'] ?? null; |
| 90 | $sharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing'); |
| 91 | |
| 92 | if (\array_key_exists('handle_factory', $options) && $options['handle_factory'] !== null) { |
| 93 | $this->shareHandleState = null; |
| 94 | $this->factory = $options['handle_factory']; |
| 95 | } else { |
| 96 | $this->shareHandleState = $sharingMode !== TransportSharing::NONE |
| 97 | ? CurlShareHandleState::fromOption($transportSharing) |
| 98 | : null; |
| 99 | |
| 100 | $this->factory = $this->shareHandleState !== null |
| 101 | ? new CurlFactory(50, $this->shareHandleState->mode, $this->shareHandleState->handle) |
| 102 | : new CurlFactory(50); |
| 103 | } |
| 104 | |
| 105 | if (isset($options['select_timeout'])) { |
| 106 | $this->selectTimeout = $options['select_timeout']; |
| 107 | } elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) { |
| 108 | \trigger_deprecation('guzzlehttp/guzzle', '7.2', 'The GUZZLE_CURL_SELECT_TIMEOUT environment variable is deprecated; use the "select_timeout" option instead.'); |
| 109 | $this->selectTimeout = (int) $selectTimeout; |
| 110 | } else { |
| 111 | $this->selectTimeout = 1; |
| 112 | } |
| 113 | |
| 114 | $this->options = $options['options'] ?? []; |
| 115 | |
| 116 | // unsetting the property forces the first access to go through |
| 117 | // __get(). |
| 118 | unset($this->_mh); |
| 119 | } |
| 120 | |
| 121 | /** |
| 122 | * @param string $name |
| 123 | * |
| 124 | * @return resource|\CurlMultiHandle |
| 125 | * |
| 126 | * @throws \BadMethodCallException when another field as `_mh` will be gotten |
| 127 | * @throws \RuntimeException when curl can not initialize a multi handle |
| 128 | */ |
| 129 | public function __get($name) |
| 130 | { |
| 131 | if ($name !== '_mh') { |
| 132 | throw new \BadMethodCallException("Can not get other property as '_mh'."); |
| 133 | } |
| 134 | |
| 135 | $multiHandle = \curl_multi_init(); |
| 136 | |
| 137 | if (false === $multiHandle) { |
| 138 | throw new \RuntimeException('Can not initialize curl multi handle.'); |
| 139 | } |
| 140 | |
| 141 | $this->_mh = $multiHandle; |
| 142 | |
| 143 | foreach ($this->options as $option => $value) { |
| 144 | // A warning is raised in case of a wrong option. |
| 145 | curl_multi_setopt($this->_mh, $option, $value); |
| 146 | } |
| 147 | |
| 148 | return $this->_mh; |
| 149 | } |
| 150 | |
| 151 | public function __destruct() |
| 152 | { |
| 153 | if (isset($this->_mh)) { |
| 154 | try { |
| 155 | \curl_multi_close($this->_mh); |
| 156 | } catch (\Throwable $e) { |
| 157 | // Destructors must not throw. |
| 158 | } finally { |
| 159 | unset($this->_mh); |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | public function __invoke(RequestInterface $request, array $options): PromiseInterface |
| 165 | { |
| 166 | $easy = $this->factory->create($request, $options); |
| 167 | $id = (int) $easy->handle; |
| 168 | |
| 169 | $promise = new Promise( |
| 170 | [$this, 'execute'], |
| 171 | function () use ($id) { |
| 172 | return $this->cancel($id); |
| 173 | } |
| 174 | ); |
| 175 | |
| 176 | $this->addRequest(['easy' => $easy, 'deferred' => $promise]); |
| 177 | |
| 178 | return $promise; |
| 179 | } |
| 180 | |
| 181 | /** |
| 182 | * Ticks the curl event loop. |
| 183 | */ |
| 184 | public function tick(): void |
| 185 | { |
| 186 | // Add any delayed handles if needed. |
| 187 | if ($this->delays) { |
| 188 | $currentTime = Utils::currentTime(); |
| 189 | foreach ($this->delays as $id => $delay) { |
| 190 | if ($currentTime >= $delay) { |
| 191 | unset($this->delays[$id]); |
| 192 | \curl_multi_add_handle( |
| 193 | $this->_mh, |
| 194 | $this->handles[$id]['easy']->handle |
| 195 | ); |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | // Run curl_multi_exec in the queue to enable other async tasks to run |
| 201 | P\Utils::queue()->add(Closure::fromCallable([$this, 'tickInQueue'])); |
| 202 | |
| 203 | // Step through the task queue which may add additional requests. |
| 204 | P\Utils::queue()->run(); |
| 205 | |
| 206 | if ($this->active && \curl_multi_select($this->_mh, $this->selectTimeout) === -1) { |
| 207 | // Perform a usleep if a select returns -1. |
| 208 | // See: https://bugs.php.net/bug.php?id=61141 |
| 209 | \usleep(250); |
| 210 | } |
| 211 | |
| 212 | do { |
| 213 | $this->executingMulti = true; |
| 214 | |
| 215 | try { |
| 216 | $exec = \curl_multi_exec($this->_mh, $this->active); |
| 217 | } finally { |
| 218 | $this->executingMulti = false; |
| 219 | $this->cleanupDeferredCancels(); |
| 220 | } |
| 221 | |
| 222 | // Prevent busy looping for slow HTTP requests. |
| 223 | if ($exec === \CURLM_CALL_MULTI_PERFORM) { |
| 224 | \curl_multi_select($this->_mh, $this->selectTimeout); |
| 225 | } |
| 226 | } while ($exec === \CURLM_CALL_MULTI_PERFORM); |
| 227 | |
| 228 | $this->processMessages(); |
| 229 | } |
| 230 | |
| 231 | /** |
| 232 | * Runs \curl_multi_exec() inside the event loop, to prevent busy looping |
| 233 | */ |
| 234 | private function tickInQueue(): void |
| 235 | { |
| 236 | $this->executingMulti = true; |
| 237 | |
| 238 | try { |
| 239 | $exec = \curl_multi_exec($this->_mh, $this->active); |
| 240 | } finally { |
| 241 | $this->executingMulti = false; |
| 242 | $this->cleanupDeferredCancels(); |
| 243 | } |
| 244 | |
| 245 | if ($exec === \CURLM_CALL_MULTI_PERFORM) { |
| 246 | \curl_multi_select($this->_mh, 0); |
| 247 | P\Utils::queue()->add(Closure::fromCallable([$this, 'tickInQueue'])); |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | /** |
| 252 | * Runs until all outstanding connections have completed. |
| 253 | */ |
| 254 | public function execute(): void |
| 255 | { |
| 256 | $queue = P\Utils::queue(); |
| 257 | |
| 258 | while ($this->handles || !$queue->isEmpty()) { |
| 259 | // If there are no transfers, then sleep for the next delay |
| 260 | if (!$this->active && $this->delays) { |
| 261 | \usleep($this->timeToNext()); |
| 262 | } |
| 263 | $this->tick(); |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | private function addRequest(array $entry): void |
| 268 | { |
| 269 | $easy = $entry['easy']; |
| 270 | $id = (int) $easy->handle; |
| 271 | $this->handles[$id] = $entry; |
| 272 | if (empty($easy->options['delay'])) { |
| 273 | \curl_multi_add_handle($this->_mh, $easy->handle); |
| 274 | } else { |
| 275 | $this->delays[$id] = Utils::currentTime() + ($easy->options['delay'] / 1000); |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | /** |
| 280 | * Cancels a handle from sending and removes references to it. |
| 281 | * |
| 282 | * @param int $id Handle ID to cancel and remove. |
| 283 | * |
| 284 | * @return bool True on success, false on failure. |
| 285 | */ |
| 286 | private function cancel($id): bool |
| 287 | { |
| 288 | if (!is_int($id)) { |
| 289 | \trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); |
| 290 | } |
| 291 | |
| 292 | // Cannot cancel if it has been processed. |
| 293 | if (!isset($this->handles[$id])) { |
| 294 | return false; |
| 295 | } |
| 296 | |
| 297 | $easy = $this->handles[$id]['easy']; |
| 298 | unset($this->delays[$id], $this->handles[$id]); |
| 299 | |
| 300 | if ($this->executingMulti) { |
| 301 | $this->deferredCancels[$id] = $easy; |
| 302 | |
| 303 | return true; |
| 304 | } |
| 305 | |
| 306 | $this->cleanupCancelledHandle($easy); |
| 307 | |
| 308 | return true; |
| 309 | } |
| 310 | |
| 311 | private function cleanupDeferredCancels(): void |
| 312 | { |
| 313 | if ($this->deferredCancels === []) { |
| 314 | return; |
| 315 | } |
| 316 | |
| 317 | $entries = $this->deferredCancels; |
| 318 | $this->deferredCancels = []; |
| 319 | |
| 320 | foreach ($entries as $easy) { |
| 321 | $this->cleanupCancelledHandle($easy); |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | private function cleanupCancelledHandle(EasyHandle $easy): void |
| 326 | { |
| 327 | $handle = $easy->handle; |
| 328 | \curl_multi_remove_handle($this->_mh, $handle); |
| 329 | |
| 330 | if (PHP_VERSION_ID < 80000) { |
| 331 | \curl_close($handle); |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | private function processMessages(): void |
| 336 | { |
| 337 | while ($done = \curl_multi_info_read($this->_mh)) { |
| 338 | if ($done['msg'] !== \CURLMSG_DONE) { |
| 339 | // if it's not done, then it would be premature to remove the handle. ref https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216 |
| 340 | continue; |
| 341 | } |
| 342 | if (!isset($done['handle'])) { |
| 343 | // Work around a PHP issue where cancelled transfers may omit the handle. |
| 344 | // Remove this once we no longer support PHP versions before the fix in |
| 345 | // https://github.com/php/php-src/pull/16302. |
| 346 | continue; |
| 347 | } |
| 348 | $id = (int) $done['handle']; |
| 349 | \curl_multi_remove_handle($this->_mh, $done['handle']); |
| 350 | |
| 351 | if (!isset($this->handles[$id])) { |
| 352 | // Probably was cancelled. |
| 353 | continue; |
| 354 | } |
| 355 | |
| 356 | $entry = $this->handles[$id]; |
| 357 | unset($this->handles[$id], $this->delays[$id]); |
| 358 | $entry['easy']->errno = $done['result']; |
| 359 | |
| 360 | try { |
| 361 | $result = CurlFactory::finish($this, $entry['easy'], $this->factory); |
| 362 | } catch (\Throwable $e) { |
| 363 | $entry['deferred']->reject($e); |
| 364 | |
| 365 | continue; |
| 366 | } |
| 367 | |
| 368 | $entry['deferred']->resolve($result); |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | private function timeToNext(): int |
| 373 | { |
| 374 | $currentTime = Utils::currentTime(); |
| 375 | $nextTime = \PHP_INT_MAX; |
| 376 | foreach ($this->delays as $time) { |
| 377 | if ($time < $nextTime) { |
| 378 | $nextTime = $time; |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | return ((int) \max(0, $nextTime - $currentTime)) * 1000000; |
| 383 | } |
| 384 | } |
| 385 |