Determine the delay timeout

Attempts to read and interpret the HTTP `Retry-After` header, or defaults
to a built-in incremental back-off algorithm.

@param ResponseInterface $response
@param array $options
@return float  Delay timeout, in seconds
519656
protected function determineDelayTimeout(array $options, ResponseInterface $response = null)
    {
        if (\is_callable($options['default_retry_multiplier'])) {
            $defaultDelayTimeout = (float) \call_user_func(
                $options['default_retry_multiplier'],
                $options['retry_count'],
                $response
            );
        } else {
            $defaultDelayTimeout = (float) $options['default_retry_multiplier'] * $options['retry_count'];
        }

        // Retry-After can be a delay in seconds or a date
        // (see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After)
        if ($response && $response->hasHeader('Retry-After')) {
            return
                $this->deriveTimeoutFromHeader($response->getHeader('Retry-After')[0])
                ?: $defaultDelayTimeout;
        }

        return $defaultDelayTimeout;
    }
943747
public function canResponseSatisfyFailedRequest(RequestInterface $request, Response $response)
    {
        $reqc = $request->getHeader('Cache-Control');
        $resc = $response->getHeader('Cache-Control');
        $requestStaleIfError = $reqc ? $reqc->getDirective('stale-if-error') : null;
        $responseStaleIfError = $resc ? $resc->getDirective('stale-if-error') : null;

        if (!$requestStaleIfError && !$responseStaleIfError) {
            return false;
        }

        if (is_numeric($requestStaleIfError) && $response->getAge() - $response->getMaxAge() > $requestStaleIfError) {
            return false;
        }

        if (is_numeric($responseStaleIfError) && $response->getAge() - $response->getMaxAge() > $responseStaleIfError) {
            return false;
        }

        return true;
    }
755756
public function save(ResponseInterface $response)
    {
        $this->setStatusCode($response->getStatusCode());
        $this->setStatusPhrase($response->getReasonPhrase());
        $this->setBody($response->getBody()->getContents());

        // rewind to previous position after reading response body
        if ($response->getBody()->isSeekable()) {
            $response->getBody()->rewind();
        }

        $this->setHeaders($response->getHeaders());
        $this->setProtocolVersion($response->getProtocolVersion());
    }
381436
public function respond(ResponseInterface $response)
    {
        // Send response
        if (!headers_sent()) {
            // Headers
            foreach ($response->getHeaders() as $name => $values) {
                $first = stripos($name, 'Set-Cookie') === 0 ? false : true;
                foreach ($values as $value) {
                    header(sprintf('%s: %s', $name, $value), $first);
                    $first = false;
                }
            }

            // Set the status _after_ the headers, because of PHP's "helpful" behavior with location headers.
            // See https://github.com/slimphp/Slim/issues/1730

            // Status
            header(sprintf(
                'HTTP/%s %s %s',
                $response->getProtocolVersion(),
                $response->getStatusCode(),
                $response->getReasonPhrase()
            ), true, $response->getStatusCode());
        }

        // Body
        $request = $this->container->get('request');
        if (!$this->isEmptyResponse($response) && !$this->isHeadRequest($request)) {
            $body = $response->getBody();
            if ($body->isSeekable()) {
                $body->rewind();
            }
            $settings = $this->container->get('settings');
            $chunkSize = $settings['responseChunkSize'];

            $contentLength = $response->getHeaderLine('Content-Length');
            if (!$contentLength) {
                $contentLength = $body->getSize();
            }


            if (isset($contentLength)) {
                $amountToRead = $contentLength;
                while ($amountToRead > 0 && !$body->eof()) {
                    $data = $body->read(min((int)$chunkSize, (int)$amountToRead));
                    echo $data;

                    $amountToRead -= strlen($data);

                    if (connection_status() != CONNECTION_NORMAL) {
                        break;
                    }
                }
            } else {
                while (!$body->eof()) {
                    echo $body->read((int)$chunkSize);
                    if (connection_status() != CONNECTION_NORMAL) {
                        break;
                    }
                }
            }
        }
    }
1348082
public function httpOptions(RequestInterface $request, ResponseInterface $response)
    {
        $methods = $this->server->getAllowedMethods($request->getPath());

        $response->setHeader('Allow', strtoupper(implode(', ', $methods)));
        $features = ['1', '3', 'extended-mkcol'];

        foreach ($this->server->getPlugins() as $plugin) {
            $features = array_merge($features, $plugin->getFeatures());
        }

        $response->setHeader('DAV', implode(', ', $features));
        $response->setHeader('MS-Author-Via', 'DAV');
        $response->setHeader('Accept-Ranges', 'bytes');
        $response->setHeader('Content-Length', '0');
        $response->setStatus(200);

        // Sending back false will interrupt the event chain and tell the server
        // we've handled this method.
        return false;
    }
405525
public function checkRedirect(
        RequestInterface $request,
        array $options,
        ResponseInterface $response
    ) {
        if (substr($response->getStatusCode(), 0, 1) != '3'
            || !$response->hasHeader('Location')
        ) {
            return $response;
        }

        $this->guardMax($request, $options);
        $nextRequest = $this->modifyRequest($request, $options, $response);

        if (isset($options['allow_redirects']['on_redirect'])) {
            call_user_func(
                $options['allow_redirects']['on_redirect'],
                $request,
                $response,
                $nextRequest->getUri()
            );
        }

        /** @var PromiseInterface|ResponseInterface $promise */
        $promise = $this($nextRequest, $options);

        // Add headers to be able to track history of redirects.
        if (!empty($options['allow_redirects']['track_redirects'])) {
            return $this->withTracking(
                $promise,
                (string) $nextRequest->getUri(),
                $response->getStatusCode()
            );
        }

        return $promise;
    }
430274
public function send(Request $request, Response $response, array $options = array()) {
    $this->setupAuth($request);
    $this->_client->send($request, $response, $options);
    return $response;
  }
859601
async def _delay(self):
        
        if self._response is None:
            await asyncio.sleep(0)
        if self._response.headers.get('retry-after'):
            await asyncio.sleep(int(self._response.headers['retry-after']))
        else:
            await asyncio.sleep(self._timeout)
390269
private function isCacheable($method, $uri, array $options, $response)
    {
        /** @var ResponseInterface $statusCode */
        $statusCode = $response->getStatusCode();

        //cache only 2** responses
        if ($statusCode < 200 || $statusCode >= 300) {
            return false;
        }

        //GET is always safe to cache
        if ('GET' === $method) {
            return true;
        }

        //POST may be cached for certain endpoints only (forgive us Roy Fielding)
        if ('POST' === $method) {
            return in_array($uri, self::CACHEABLE_POST_ENDPOINTS);
        }

        //assume not cacheable in all other cases
        return false;
    }
1021655
private function setCacheLifetime(Response $response)
    {
        $response->headers->set(
            SuluHttpCache::HEADER_REVERSE_PROXY_TTL,
            $response->getAge() + $this->container->getParameter('sulu_website.sitemap.cache.lifetime')
        );

        return $response->setMaxAge(240)
            ->setSharedMaxAge(960);
    }
530355
public static function getCurlOptionFromResponse(Response $response, $option = 0)
    {
        switch ($option) {
            case 0: // 0 == array of all curl options
                $info = array();
                foreach (self::$curlInfoList as $option => $key) {
                    $info[$key] = $response->getCurlInfo($key);
                }
                break;
            case CURLINFO_HTTP_CODE:
                $info = (int)$response->getStatusCode();
                break;
            case CURLINFO_SIZE_DOWNLOAD:
                $info = $response->getHeader('Content-Length');
                break;
            case CURLINFO_HEADER_SIZE:
                $info =  mb_strlen(HttpUtil::formatAsStatusWithHeadersString($response), 'ISO-8859-1');
                break;
            default:
                $info = $response->getCurlInfo($option);
                break;
        }

        if (!is_null($info)) {
            return $info;
        }

        $constants = get_defined_constants(true);
        $constantNames = array_flip($constants['curl']);
        throw new \BadMethodCallException("Not implemented: {$constantNames[$option]} ({$option}) ");
    }
167048
public function processResponse(RequestInterface $request, array $options, ResponseInterface $response)
    {
        $response = $response
            ->withHeader('X-Blackfire-Profile-Uuid', $request->getHeader('X-Blackfire-Profile-Uuid'))
            ->withHeader('X-Blackfire-Profile-Url', $request->getHeader('X-Blackfire-Profile'))
        ;

        if (!$response->hasHeader('X-Blackfire-Response')) {
            if (null !== $this->logger) {
                $this->logger->warning('Profile request failed.', array(
                    'profile-uuid' => $request->getHeader('X-Blackfire-Profile-Uuid'),
                    'profile-url' => $request->getHeader('X-Blackfire-Profile-Url'),
                ));
            }

            return $response;
        }

        parse_str($response->getHeader('X-Blackfire-Response')[0], $values);

        if (!isset($values['continue']) || 'true' !== $values['continue']) {
            if (null !== $this->logger) {
                $this->logger->debug('Profile request succeeded.', array(
                    'profile-uuid' => $request->getHeader('X-Blackfire-Profile-Uuid'),
                    'profile-url' => $request->getHeader('X-Blackfire-Profile'),
                ));
            }

            return $response;
        }

        Psr7\rewind_body($request);

        /* @var PromiseInterface|ResponseInterface $promise */
        return $this($request, $options);
    }
599820
protected function finalize(ResponseInterface $response)
    {
        // stop PHP sending a Content-Type automatically
        ini_set('default_mimetype', '');

        $request = $this->container->get('request');
        if ($this->isEmptyResponse($response) && !$this->isHeadRequest($request)) {
            return $response->withoutHeader('Content-Type')->withoutHeader('Content-Length');
        }

        // Add Content-Length header if `addContentLengthHeader` setting is set
        if (isset($this->container->get('settings')['addContentLengthHeader']) &&
            $this->container->get('settings')['addContentLengthHeader'] == true) {
            if (ob_get_length() > 0) {
                throw new RuntimeException("Unexpected data in output buffer. " .
                    "Maybe you have characters before an opening <?php tag?");
            }
            $size = $response->getBody()->getSize();
            if ($size !== null && !$response->hasHeader('Content-Length')) {
                $response = $response->withHeader('Content-Length', (string) $size);
            }
        }

        // clear the body if this is a HEAD request
        if ($this->isHeadRequest($request)) {
            return $response->withBody(new Body(fopen('php://temp', 'r+')));
        }

        return $response;
    }
886762
protected function onRejected(RequestInterface $request, array $options)
    {
        return function ($reason) use ($request, $options) {
            // If was bad response exception, test if we retry based on the response headers
            if ($reason instanceof BadResponseException) {
                if ($this->shouldRetryHttpResponse($options, $reason->getResponse())) {
                    return $this->doRetry($request, $options, $reason->getResponse());
                }
            // If this was a connection exception, test to see if we should retry based on connect timeout rules
            } elseif ($reason instanceof ConnectException) {
                // If was another type of exception, test if we should retry based on timeout rules
                if ($this->shouldRetryConnectException($reason, $options)) {
                    return $this->doRetry($request, $options);
                }
            }

            // If made it here, then we have decided not to retry the request
            return \GuzzleHttp\Promise\rejection_for($reason);
        };
    }
927784
protected function finalizeResponse(ResponseInterface $response) : ResponseInterface
    {
        // stop PHP sending a Content-Type automatically
        ini_set('default_mimetype', '');
        if ($this->isEmptyResponseCode($response->getStatusCode())) {
            return $response->withoutHeader('Content-Type')->withoutHeader('Content-Length');
        }

        return $response;
    }
998967
public function send(DispatcherResponseInterface $response)
    {
        $request  = $response->getRequest();

        if($response->isStreamable())
        {
            //Explicitly set the Accept Ranges header to bytes to inform client we accept range requests
            $response->headers->set('Accept-Ranges', 'bytes');

            if($request->isStreaming())
            {
                if($response->isSuccess())
                {
                    if(ini_get('zlib.output_compression')) {
                        @ini_set('zlib.output_compression', 'Off');
                    }

                    //Fix for IE7/8
                    if(function_exists('apache_setenv')) {
                        @apache_setenv('no-gzip', '1');
                    }

                    //Remove PHP time limit
                    if(!ini_get('safe_mode')) {
                        @set_time_limit(0);
                    }

                    //Default Content-Type Header
                    if(!$response->headers->has('Content-Type')) {
                        $response->headers->set('Content-Type', 'application/octet-stream');
                    }

                    //Content Range Headers
                    $offset = $this->getOffset($response);
                    $range  = $this->getRange($response);
                    $size   = $this->getFileSize($response);

                    $response->setStatus(HttpResponse::PARTIAL_CONTENT);
                    $response->headers->set('Content-Length', $range - $offset + 1);
                    $response->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $offset, $range, $size));
                }

                if($response->isError())
                {
                    /**
                     * A server sending a response with status code 416 (Requested range not satisfiable) SHOULD include a
                     * Content-Range field with a byte-range- resp-spec of "*". The instance-length specifies the current
                     * length of the selected resource.
                     *
                     * @see : http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16
                     */
                    if($response->getStatusCode() == HttpResponse::REQUESTED_RANGE_NOT_SATISFIED)
                    {
                        $size = $this->getFileSize($response);
                        $response->headers->set('Content-Range', sprintf('bytes */%s', $size));
                    }
                }
            }
        }

        return parent::send($response);
    }
405869
public function canResponseSatisfyRequest(RequestInterface $request, Response $response)
    {
        $responseAge = $response->calculateAge();
        $reqc = $request->getHeader('Cache-Control');
        $resc = $response->getHeader('Cache-Control');

        // Check the request's max-age header against the age of the response
        if ($reqc && $reqc->hasDirective('max-age') &&
            $responseAge > $reqc->getDirective('max-age')) {
            return false;
        }

        // Check the response's max-age header
        if ($response->isFresh() === false) {
            $maxStale = $reqc ? $reqc->getDirective('max-stale') : null;
            if (null !== $maxStale) {
                if ($maxStale !== true && $response->getFreshness() < (-1 * $maxStale)) {
                    return false;
                }
            } elseif ($resc && $resc->hasDirective('max-age')
                && $responseAge > $resc->getDirective('max-age')
            ) {
                return false;
            }
        }

        if ($this->revalidation->shouldRevalidate($request, $response)) {
            try {
                return $this->revalidation->revalidate($request, $response);
            } catch (CurlException $e) {
                $request->getParams()->set('cache.hit', 'error');
                return $this->canResponseSatisfyFailedRequest($request, $response);
            }
        }

        return true;
    }