@brief Retry the request after waiting for the rate limit to roll over

@param int $wait
@param $curlHandle

@return mixed
166387
public function retry($wait, $curlHandle)
    {
        sleep($wait);
        $result = curl_exec($curlHandle);
        $this->_lastStatusCode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
        return $result;
    }
879056
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        /*
        // TODO : ajouter le header "Retry-After" avec une gestion des options, genre durée de la maintenance, et durée avant de faire un refresh !!!!
        // https://github.com/php-middleware/maintenance/blob/master/src/MaintenanceMiddleware.php
                $headers = [];
                if ($this->retryAfter !== '') {
                    $headers['Retry-After'] = $this->retryAfter;
                    if ($this->refresh > 0) { // seconds
                        $headers['Refresh'] = (string) $this->refresh;
                    }
                }


        // TODO : version alternative pour ajouter le header !!!!
        //https://github.com/middlewares/shutdown/blob/master/src/Shutdown.php#L46
                if (is_int($this->retryAfter)) {
                    return $response->withHeader(self::RETRY_AFTER, (string) $this->retryAfter);
                }
                if ($this->retryAfter instanceof DateTimeInterface) {
                    return $response->withHeader(self::RETRY_AFTER, $this->retryAfter->format('D, d M Y H:i:s \G\M\T')); //$datetime->format(DateTime::RFC2822);
                }

        */

        //if ($this->app->isDownForMaintenance() && !in_array($this->request->getClientIp(), ['86.10.190.248', '86.4.7.24']))
//        $config = $this->container->config;
        //if ($config['settings.isDownForMaintenance']) {
        if ($this->isDown === true) {
            //return (new Response(503))->withHeader('Refresh', 10)->write('Be right back !');

            //$retryAfter = $config['settings.maintenanceRetryAfter'];

            /*
                        if (is_int($retryAfter)) {
                            $retryAfter = (string) $retryAfter;
                        }
            */

            throw new ServiceUnavailableHttpException($this->retryAfter);
        }

        /*
        //https://github.com/juliangut/janitor/blob/master/src/Handler/Render.php#L65
                if ($watcher instanceof ScheduledWatcherInterface) {
                    $response = $response
                        ->withHeader('Expires', $watcher->getEnd()->format('D, d M Y H:i:s e'))
                        ->withHeader('Retry-After', $watcher->getEnd()->format('D, d M Y H:i:s e'));
                } else {
                    $response = $response->withHeader('Cache-Control', 'max-age=0')
                        ->withHeader('Cache-Control', 'no-cache, must-revalidate')
                        ->withHeader('Pragma', 'no-cache');
                }
                return $response->withStatus(503)
                    ->withHeader('Content-Type', $contentType)
                    ->withBody($body);
        */

        //https://www.shellhacks.com/redirect-site-maintenance-page-apache-htaccess/
        // Header Set Cache-Control "max-age=0, no-store"

        return $handler->handle($request);
    }
1325921
def retry(retries=10, wait=5, catch=None):
    
    catch = catch or (Exception,)

    def real_retry(function):

        def wrapper(*args, **kwargs):
            for _ in range(retries):
                try:
                    ret = function(*args, **kwargs)
                    return ret
                except catch:
                    time.sleep(wait)
                except Exception as e:
                    raise e
                else:
                    raise DSBException('Retries limit exceded.')

        return wrapper

    return real_retry
412555
public function wait()
    {
        curl_multi_exec($this->mh, $active); // Start requests.
        do {
            // if cURL handle is running, use curl_multi_select()
            // otherwise, just sleep until nearest time
            $this->scheduler->isEmpty()
                ? $this->delayer->sleep()
                : curl_multi_select($this->mh, $this->options['interval']) < 0
                  && usleep($this->options['interval'] * 1000000);
            curl_multi_exec($this->mh, $active);
            $this->scheduler->consume();
            $this->delayer->consume();
        } while (!$this->haltException && (!$this->scheduler->isEmpty() || !$this->delayer->isEmpty()));
        if ($this->haltException) {
            throw $this->haltException;
        }
    }
204779
public static function pollEvery(float $wait)
    {
        if (false === strpos((string) $wait, '.')) {
            self::$sleep = (int) $wait;
            self::$usleep = 0;
        } else {
            list($seconds, $hundreds) = explode('.', (string) $wait);
            self::$sleep = (int) $seconds;
            self::$usleep = (int) (((float) sprintf('0.%d', $hundreds)) * 1000000);
        }
    }
1198370
protected function processCurlResponse(int $statusCode, $curlHandle)
    {
        foreach ($this->runningRequests as $index => $request) {
            if ($request->getCurl()->getHandle() === $curlHandle) {
                $this->parseResponse($request, $statusCode)
                     ->triggerCallback($request->getOnCompleteCallback(), $request);

                $this->multiCurl->removeCurl($request->getCurl());
                unset($this->runningRequests[$index]);
                break;
            }
        }
        return $this;
    }
453456
public HTTPRequest retry(final int maxRetries, final Retryable retryable, final WaitStrategy waitStrategy) {
        if (maxRetries <= 0) {
            throw new IllegalArgumentException("maxRetries must be > 0");
        }
        if (retryable == null) {
            throw new IllegalArgumentException("retryable must not be null");
        }
        if (waitStrategy == null) {
            throw new IllegalArgumentException("waitStrategy must not be null");
        }
        this.maxRetries = maxRetries;
        this.retryable = retryable;
        this.waitStrategy = waitStrategy;
        return this;
    }
171971
async def retry_get(config, url, *args, **kwargs):
    
    return await _retry_do(config.session.get, url, *args,
                           **_make_headers(config, kwargs))
764970
private function start($value, $wait = true, $throw = null)
    {
        $return = null;
        // For convenience, all values are wrapped into generator
        $con = YieldableUtils::normalize($this->getRootGenerator($throw, $value, $return));
        $promise = $this->processGeneratorContainerRunning($con);
        if ($promise instanceof ExtendedPromiseInterface) {
            // This is actually 100% true; just used for unwrapping Exception thrown.
            $promise->done();
        }
        // We have to wait $return only if $wait
        if ($wait) {
            $this->pool->wait();
            return $return;
        }
    }
233301
public function streaming_write_callback($curl_handle, $data)
    {
        $code = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
        
        if (intval($code) / 100 != 2)
        {
            $this->response_error_body .= $data;
            return strlen($data);
        }

        $length = strlen($data);
        $written_total = 0;
        $written_last = 0;
        
        while ($written_total < $length) {
            $written_last = fwrite($this->write_stream, substr($data, $written_total));

            if ($written_last === false) {
                return $written_total;
            }

            $written_total += $written_last;
        }

        // Execute callback function
        if ($this->registered_streaming_write_callback) {
            call_user_func($this->registered_streaming_write_callback, $curl_handle, $written_total);
        }

        return $written_total;
    }
701742
public function getWaitTime($attempt)
    {
        $waitTime = call_user_func($this->getStrategy(), $attempt);

        return $this->jitter($this->cap($waitTime));
    }
250646
public function pollForCertificate(string $location): Promise {
        return call(function () use ($location) {
            do {
                /** @var Response $response */
                $response = yield $this->acmeClient->get($location);

                if ($response->getStatus() === 202) {
                    if (!$response->hasHeader('retry-after')) {
                        // throw new AcmeException("Protocol Violation: No Retry-After Header!");

                        yield new Delayed(1000);
                        continue;
                    }

                    $waitTime = $this->parseRetryAfter($response->getHeader('retry-after'));
                    $waitTime = min(max($waitTime, 2), 60);

                    yield new Delayed($waitTime * 1000);

                    continue;
                }

                if ($response->getStatus() === 200) {
                    $pem = chunk_split(base64_encode(yield $response->getBody()), 64, "\n");
                    $pem = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n";

                    $certificates = [
                        $pem,
                    ];

                    // prevent potential infinite loop
                    $maximumChainLength = 5;

                    while ($response->hasHeader('link')) {
                        if (!$maximumChainLength--) {
                            throw new AcmeException('Too long certificate chain');
                        }

                        $links = $response->getHeaderArray('link');

                        foreach ($links as $link) {
                            if (preg_match('#<(.*?)>;rel="up"#x', $link, $match)) {
                                $uri = \Sabre\Uri\resolve($response->getRequest()->getUri(), $match[1]);
                                $response = yield $this->acmeClient->get($uri);

                                $pem = chunk_split(base64_encode(yield $response->getBody()), 64, "\n");
                                $pem = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n";
                                $certificates[] = $pem;
                            }
                        }
                    }

                    return $certificates;
                }
            } while (1);

            throw new AcmeException("Couldn't fetch certificate");
        });
    }
1161679
private function getRetryDelay() {
		return function ( $numberOfRetries, Response $response = null ) {
			// The $response argument is only passed as of Guzzle 6.2.2.
			if ( $response !== null ) {
				// Retry-After may be a number of seconds or an absolute date (RFC 7231,
				// section 7.1.3).
				$retryAfter = $response->getHeaderLine( 'Retry-After' );

				if ( is_numeric( $retryAfter ) ) {
					return 1000 * $retryAfter;
				}

				if ( $retryAfter ) {
					$seconds = strtotime( $retryAfter ) - time();
					return 1000 * max( 1, $seconds );
				}
			}

			return 1000 * $numberOfRetries;
		};
	}
369643
public function restart($wait = true)
    {
        return $this->forge->restartDaemon($this->serverId, $this->id, $wait);
    }
258078
public function execute(\Closure $callback = null)
    {
        $stacks = $this->buildStacks();

        foreach ($stacks as $requests) {
            foreach ($requests as $request) {
                $status = curl_multi_add_handle($this->handle, $request->getHandle());
                if ($status !== CURLM_OK) {
                    throw new \Exception(sprintf(
                        'Unable to add request to cURL multi handle (code #%u)',
                        $status
                    ));
                }
            }

            $this->dispatch();

            foreach ($requests as $request) {
                $request->setRawResponse(curl_multi_getcontent($request->getHandle()));
                curl_multi_remove_handle($this->handle, $request->getHandle());

                if ($callback !== null) {
                    $callback($request->getResponse());
                }
            }
        }
    }
761895
public function _open($opentimeout = 0.0, $waittimeout = 5.0)
    {
        global $_web_access_retry_timeout_max;

        if (!isset($this->_spool[0]['State'])) {
            return false;
        }
        $time = time();

        // if async, in error, then return false until timeout or if > max)
        if (!$this->_wait && $this->_state == 'BAD' &&
            (($this->_bad_timeout > $_web_access_retry_timeout_max) ||
                (($time - $this->_bad_time) < $this->_bad_timeout))) {
            $this->console->writeln($this->_webaccess_str.'wait to retry ('.($time - $this->_bad_time).' / '.$this->_bad_timeout.')');

            return false;
        }

        // if the socket is probably in timeout, close it
        if ($this->_socket && $this->_state == 'OPENED' &&
            ($this->_serv_keepalive_timeout <= ($time - $this->_query_time))) {

            $this->console->writeln($this->_webaccess_str.'timeout, closed it!');
            $this->_state = 'CLOSED';
            @fclose($this->_socket);
            $this->_socket = null;
        }

        // if socket is not opened, open it
        if (!$this->_socket || $this->_state != 'OPENED') {
            $this->_open_socket($opentimeout);
        }

        // if socket is open, send data if possible
        if ($this->_socket) {
            $this->_read_time = microtime(true);

            // if wait (synchronous query) then go on all pending write/read until the last
            if ($this->_wait) {
                @stream_set_timeout($this->_socket, 0, 10000);

                while (isset($this->_spool[0]['State']) &&
                    ($this->_spool[0]['State'] == 'OPEN' ||
                        $this->_spool[0]['State'] == 'SEND' ||
                        $this->_spool[0]['State'] == 'RECEIVE')) {
                    echo 'State='.$this->_spool[0]['State']." (".count($this->_spool).")\n";
                    if (!$this->_socket || $this->_state != 'OPENED') {
                        $this->_open_socket($opentimeout);
                    }

						$query_state = $this->_spool[0]['State'];
                    if ($this->_spool[0]['State'] == 'OPEN') {
                        $time = microtime(true);
                        $this->_spool[0]['Times']['send'][0] = $time;
                        $this->_send($waittimeout);
                    } elseif ($this->_spool[0]['State'] == 'SEND') {
                        $this->_send($waittimeout);
                    } elseif ($this->_spool[0]['State'] == 'RECEIVE') {
                        $this->_receive($waittimeout * 4);
                    }

                    // if timeout then error
                    if ($query_state != 'RECEIVE' && ($difftime = microtime(true) - $this->_read_time) > $waittimeout) {
                        $this->_bad("Request timeout, in _open ({$difftime} > {$waittimeout}s) state=".$this->_spool[0]['State']
                        );

                        return;
                    }
                }
                if ($this->_socket) {
                    @stream_set_timeout($this->_socket, 0, 2000);
                }
            } // else just do a send on the current
            elseif (isset($this->_spool[0]['State']) && $this->_spool[0]['State'] == 'OPEN') {
                @stream_set_timeout($this->_socket, 0, 2000);  // timeout 2 ms
                $this->_send($waittimeout);
            }
        }
    }
93393
public function retry(callable $callback)
    {
        $userHandlerCloned = $providerHandlerCloned = false;

        return \ScriptFUSION\Retry\retry(
            $this->maxFetchAttempts,
            $callback,
            function (\Exception $exception) use (&$userHandlerCloned, &$providerHandlerCloned) {
                // Throw exception instead of retrying, if unrecoverable.
                if (!$exception instanceof RecoverableConnectorException) {
                    throw $exception;
                }

                // Call provider's exception handler, if defined.
                if ($this->resourceFetchExceptionHandler) {
                    self::invokeHandler($this->resourceFetchExceptionHandler, $exception, $providerHandlerCloned);
                }

                // Call user's exception handler.
                self::invokeHandler($this->fetchExceptionHandler, $exception, $userHandlerCloned);
            }
        );
    }