Determines the delay duration that should be waited before retrying.
@param response HTTP response
@return If the HTTP response has a retry-after-ms header that will be returned,
otherwise the duration used during the construction of the policy.
774687
private Duration determineDelayDuration(HttpResponse response) {
        int code = response.statusCode();

        // Response will not have a retry-after-ms header.
        if (code != HttpResponseStatus.TOO_MANY_REQUESTS.code()
            && code != HttpResponseStatus.SERVICE_UNAVAILABLE.code()) {
            return this.delayDuration;
        }

        String retryHeader = response.headerValue(RETRY_AFTER_MS_HEADER);

        // Retry header is missing or empty, return the default delay duration.
        if (retryHeader == null || retryHeader.isEmpty()) {
            return this.delayDuration;
        }

        // Use the response delay duration, the server returned it for a reason.
        return Duration.ofMillis(Integer.parseInt(retryHeader));
    }
1091371
private HttpServletResponse getHttpServletResponseUrlEncoder(
			final Response response) {

		return new HttpServletResponse() {

			public void setLocale(Locale loc) {

			}

			public void setContentType(String type) {

			}

			public void setContentLength(int len) {

			}

			public void setBufferSize(int size) {

			}

			public void resetBuffer() {

			}

			public void reset() {

			}

			public boolean isCommitted() {
				return false;
			}

			public PrintWriter getWriter() throws IOException {
				return new PrintWriter(new RedirectWriter(getResponse()));
			}

			public ServletOutputStream getOutputStream() throws IOException {
				return null;
			}

			public Locale getLocale() {
				return null;
			}

			public int getBufferSize() {
				return 0;
			}

			public void flushBuffer() throws IOException {

			}

			public void setStatus(int sc, String sm) {

			}

			public void setStatus(int sc) {

			}

			public void setIntHeader(String name, int value) {

			}

			public void setHeader(String name, String value) {

			}

			public void setDateHeader(String name, long date) {

			}

			public void sendRedirect(String location) throws IOException {

			}

			public void sendError(int sc, String msg) throws IOException {

			}

			public void sendError(int sc) throws IOException {

			}

			public String encodeUrl(String url) {
				return response.encodeURL(url).toString();
			}

			public String encodeURL(String url) {
				return response.encodeURL(url).toString();
			}

			public String encodeRedirectUrl(String url) {
				return null;
			}

			public String encodeRedirectURL(String url) {
				return null;
			}

			public boolean containsHeader(String name) {
				return false;
			}

			public void addIntHeader(String name, int value) {

			}

			public void addHeader(String name, String value) {

			}

			public void addDateHeader(String name, long date) {

			}

			public void addCookie(Cookie cookie) {

			}

			public String getContentType() {
				return null;
			}

			public void setCharacterEncoding(String charset) {

			}

			@Override
			public String getCharacterEncoding() {
				return "UTF-8";
			}
		};
	}
542898
public boolean waitForResponse ()
        throws TimeoutException
    {
        if (_success == 0) {
            synchronized (this) {
                try {
                    // wait for the response, timing out after a while
                    if (_timeout == NO_TIMEOUT) {
                        wait();

                    } else {
                        wait(1000L * _timeout);
                    }
                    // if we get here without some sort of response, then we've timed out
                    if (_success == 0) {
                        throw new TimeoutException();
                    }

                } catch (InterruptedException ie) {
                    throw (TimeoutException)
                        new TimeoutException().initCause(ie);
                }
            }
        }

        return (_success > 0);
    }
594867
def await_response_timeout(self):
        """"""
        if _debug: ServerSSM._debug("await_response_timeout")

        abort = self.abort(AbortReason.serverTimeout)
        self.request(abort)
1155262
HTTPResponse getHTTPResponse() {
        lock.lock();
        try {
            while (response == null) {
                try {
                    ready.await();
                } catch (InterruptedException intx) {
                    LOG.log(Level.FINEST, "Interrupted", intx);
                }
            }
            return response;
        } finally {
            lock.unlock();
        }
    }
385490
private boolean pauseIfRetryNeeded(int retries) {
        if (retries >= connection.getMaxErrorRetry()) {
            return false;
        }
        long delay = (long) (Math.random() * Math.pow(4, retries) * 125);
        try {
            Thread.sleep(delay);
        } catch (Exception e) {
            throw MwsUtl.wrap(e);
        }
        return true;
    }
29923
def response_delay(self, delay):
        """"""
        if isinstance(delay, (int, float)) and delay >= 0 or delay is None:
            self._response_delay = delay
        else:
            raise ValueError(
                _format("Invalid value for response_delay: {0!A}, must be a "
                        "positive number", delay))
824903
private void setResponeHeaders(HttpServletResponse response) {

        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", System.currentTimeMillis());
        response.setContentType("text/plain; charset=utf-8");
        response.setCharacterEncoding("utf-8");
    }
1085056
public void setResponse(HttpCarbonResponse response) {
        this.response = response;
        allPromisesReceived = true;
        responseFuture.notifyPromiseAvailability();      // Response received so no more promises allowed
        responseFuture.notifyHttpListener(response);
    }
1310502
protected function delay($response)
    {
        $timeout      = $this->timeout;
        $responseData = $this->decodeData($response);
        if ($timeout) {
            $delay = $timeout;
        } else {
            if (isset($responseData['retry_after'])) {
                $delay = $responseData['retry_after'];
            } else {
                $delay = self::DEFAULT_DELAY;
            }
        }
        usleep($delay * 1000);
    }
1037313
public static boolean isCacheable(Response response, Request request) {
    // Always go to network for uncacheable response codes (RFC 7231 section 6.1),
    // This implementation doesn't support caching partial content.
    switch (response.code()) {
      case HTTP_OK:
      case HTTP_NOT_AUTHORITATIVE:
      case HTTP_NO_CONTENT:
      case HTTP_MULT_CHOICE:
      case HTTP_MOVED_PERM:
      case HTTP_NOT_FOUND:
      case HTTP_BAD_METHOD:
      case HTTP_GONE:
      case HTTP_REQ_TOO_LONG:
      case HTTP_NOT_IMPLEMENTED:
      case StatusLine.HTTP_PERM_REDIRECT:
        // These codes can be cached unless headers forbid it.
        break;

      case HTTP_MOVED_TEMP:
      case StatusLine.HTTP_TEMP_REDIRECT:
        // These codes can only be cached with the right response headers.
        // http://tools.ietf.org/html/rfc7234#section-3
        // s-maxage is not checked because OkHttp is a private cache that should ignore s-maxage.
        if (response.header("Expires") != null
            || response.cacheControl().maxAgeSeconds() != -1
            || response.cacheControl().isPublic()
            || response.cacheControl().isPrivate()) {
          break;
        }
        // Fall-through.

      default:
        // All other codes cannot be cached.
        return false;
    }

    // A 'no-store' directive on request or response prevents the response from being cached.
    return !response.cacheControl().noStore() && !request.cacheControl().noStore();
  }
1015149
public HttpClientResponseBuilder doReturn(String response, Charset charset) {
        return responseBuilder.doReturn(response, charset);
    }
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;
    }
1229857
public void onReceivedPesponse(ResponseHeader header, Response response){
        Packet packet = null;
        updateRecv();

        if (header.getXid() == -4) {
            // -4 is the xid for AuthPacket
            if(ErrorCode.AUTHENT_FAILED.equals(header.getErr())) {
                if(getStatus().isAlive()){
                    setStatus(ConnectionStatus.AUTH_FAILED);
                }
            }
                LOGGER.info("Got auth sessionid:0x" + session.id + ", error=" + header.getErr());
            return;
        }

        if (header.getXid() == -1) {
            // -1 means watcher notification
            WatcherEvent event = (WatcherEvent) response;
            if(LOGGER.isTraceEnabled()){
                LOGGER.trace("Got Watcher " + event + " for sessionid 0x" + session.id);
            }
            eventThread.queueWatcherEvent( event );
            return;
        }

        if (header.getXid() == -8) {
            // -8 means server notification
            ServerEvent event = (ServerEvent) response;

            if(response instanceof CloseSessionEvent){
                closeSession();
                return;
            }

            if(LOGGER.isTraceEnabled()){
                LOGGER.trace("Got Server " + event + " for sessionid 0x" + session.id);
            }
            eventThread.queueServerEvent( event );
            return;
        }

        if (header.getXid() == -2) {
            // -2 is the xid for pings
            if(LOGGER.isTraceEnabled()){
                LOGGER.info("Got ping response for sessionid: 0x" + session.id
                        + " after " + (System.currentTimeMillis() - lastPingSentNs) + "ms");
            }

            pingResponse.set(header);
            synchronized(pingResponse){
                pingResponse.notifyAll();
            }
            return;
        }

        synchronized(pendingQueue){
            // the XID out of order, we don't close session here.
            // it doesn't mean the data integrate has problem.
            if(pendingQueue.isEmpty()){
                LOGGER.warn("The request queue is empty, but get packet xid=" + header.getXid());
                // we don't  close session here.
                return;
            }
            int recvXid = header.getXid();
            packet = pendingQueue.remove();

            if (packet.protoHeader.getXid() != recvXid) {
                if(LOGGER.isDebugEnabled()){
                    LOGGER.debug("Packet xid out of order, type=" + packet.protoHeader.getType()
                            + ", queuedXid=" + packet.protoHeader.getXid() + ", xid=" + header.getXid());
                }

                // trim the pendingQueue to the received packet.
                if(packet.protoHeader.getXid() > recvXid){
                    LOGGER.error("Packet xid out of order, drop the received packet, xid=" + header.getXid());
                    pendingQueue.addLast(packet);
                    packet = null;
                } else {
                    while(packet.protoHeader.getXid() != recvXid){
                        LOGGER.error("Packet xid out of order, drop the queued packet, type=" + packet.protoHeader.getType()
                                + ", queuedXid=" + packet.protoHeader.getXid());
                        packet.respHeader.setErr(ErrorCode.CONNECTION_LOSS);
                        finishPacket(packet);

                        if(! pendingQueue.isEmpty()){
                            packet = pendingQueue.remove();
                        } else {
                            return ;
                        }
                    }
                }
            }
        }

        PacketLatency.receivePacket(packet);
        packet.respHeader.setXid(header.getXid());
        packet.respHeader.setErr(header.getErr());
        packet.respHeader.setDxid(header.getDxid());
        if (header.getDxid() > 0) {
            lastDxid = header.getDxid();
        }
        if (ErrorCode.OK.equals(header.getErr())) {
            packet.response = response;
        }

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Reading reply sessionid:0x"
                    + session.id + ", packet=" + packet);
        }
        finishPacket(packet);

    }
537546
public RetryPolicy<R> withDelay(DelayFunction<R, ? extends Throwable> delayFunction) {
    Assert.notNull(delayFunction, "delayFunction");
    this.delayFn = delayFunction;
    return this;
  }
342312
public static void setExpiresHeader(final HttpServletResponse response, final long expiresSeconds) {
		// Http 1.0 header, set a fix expires date.
		response.setDateHeader(HttpHeaders.EXPIRES, System.currentTimeMillis() + expiresSeconds * 1000);
		// Http 1.1 header, set a time after now.
		response.setHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=" + expiresSeconds);
	}
1267052
def is_rate_limited(response):
        
        if (response.status_code == codes.too_many_requests and 'Retry-After' in response.headers and
                int(response.headers['Retry-After']) >= 0):
            return True

        return False