packages feed

http-env-0.0.0.0: src/Network/HTTP/Env/HttpClient/Retry.hs

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TypeApplications #-}

-- | Retrying HTTP requests, and where an 'HttpException' becomes a value.
--
-- [tag:NoUnscrubbedHttpException] Every 'HttpException' handed out of this
-- module has been through 'scrubHttpException', because showing one prints its
-- request's headers and http-client redacts only @Authorization@.
-- A new path out of this module must scrub too.
module Network.HTTP.Env.HttpClient.Retry
  ( httpLbsWithRetry,
    Repeatable (..),
    RepeatSafety (..),
    httpRepeatSafety,
    requestRepeatSafety,
    exceptionRepeatSafety,
    methodRepeatSafety,
    headersRepeatSafety,
    responseAsHttpException,
    catchAsHttpException,
    catchConnectionException,
    shouldRetryStatusCode,
    describeHttpFault,
    shouldRetryHttpResponse,
    shouldRetryHttpException,
  )
where

import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Logger.CallStack
import Control.Retry
import Data.Bifunctor (first)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LB
import qualified Data.Text as Text
import Network.HTTP.Client as HTTP
import Network.HTTP.Client.Internal as HTTP
import Network.HTTP.Env.CircuitBreaker
import Network.HTTP.Env.CircuitBreaker.Retry (RepeatSafety (..), anyRepeatSafe, retryingWithCircuitBreaker)
import Network.HTTP.Env.FailureBudget (FailureBudgetEnv)
import Network.HTTP.Env.LogPolicy (LogPolicy, hIdempotencyKey, renderHttpExceptionForLogging, renderResponseForLogging, scrubHttpException, scrubUriForLogging)
import Network.HTTP.Types as HTTP
import Network.URI (URI)
import UnliftIO

-- | Whether a call may be sent again after a fault.
data Repeatable
  = -- | Only when its method is idempotent, it carries an idempotency key, or
    -- it was never sent.
    RepeatableIfIdempotent
  | -- | Whatever its method, such as when the server deduplicates it.
    RepeatableAlways

-- | Whether a call may be sent again after this result.
httpRepeatSafety :: Repeatable -> Request -> Either HttpException a -> RepeatSafety
httpRepeatSafety repeatable request res = case repeatable of
  RepeatableAlways -> RepeatSafetySafe
  RepeatableIfIdempotent ->
    anyRepeatSafe
      [ requestRepeatSafety (method request) (requestHeaders request),
        case res of
          Left exception -> exceptionRepeatSafety exception
          Right _ -> RepeatSafetyUnsafe
      ]

-- | 'RepeatSafetySafe' for a request with an idempotent method or an idempotency key.
requestRepeatSafety :: Method -> [Header] -> RepeatSafety
requestRepeatSafety requestMethod headers =
  anyRepeatSafe [methodRepeatSafety requestMethod, headersRepeatSafety headers]

-- | 'RepeatSafetySafe' for a connection that never opened, so the request never left.
exceptionRepeatSafety :: HttpException -> RepeatSafety
exceptionRepeatSafety = \case
  InvalidUrlException _ _ -> RepeatSafetyUnsafe
  HttpExceptionRequest _ content -> case content of
    ConnectionFailure _ -> RepeatSafetySafe
    ConnectionTimeout -> RepeatSafetySafe
    ProxyConnectException _ _ _ -> RepeatSafetySafe
    _ -> RepeatSafetyUnsafe

-- | 'RepeatSafetySafe' for the methods RFC 9110 calls idempotent.
methodRepeatSafety :: Method -> RepeatSafety
methodRepeatSafety m =
  if m `elem` [methodGet, methodHead, methodOptions, methodTrace, methodPut, methodDelete]
    then RepeatSafetySafe
    else RepeatSafetyUnsafe

-- | 'RepeatSafetySafe' for headers with an 'hIdempotencyKey', which asks the server
-- to answer a resend as it answered the first.
headersRepeatSafety :: [Header] -> RepeatSafety
headersRepeatSafety headers =
  if any ((== hIdempotencyKey) . fst) headers then RepeatSafetySafe else RepeatSafetyUnsafe

-- | Perform an HTTP request, running each attempt through the breaker.
httpLbsWithRetry ::
  (MonadLogger m, MonadUnliftIO m) =>
  LogPolicy ->
  Maybe CircuitBreakerEnv ->
  Maybe FailureBudgetEnv ->
  RetryPolicyM m ->
  Repeatable ->
  HTTP.Request ->
  HTTP.Manager ->
  m (Either (CircuitBreakerError HttpException) (HTTP.Response LB.ByteString))
httpLbsWithRetry logPolicy mBreaker mBudget policy repeatable request man =
  retryingWithCircuitBreaker mBreaker mBudget policy (describeHttpFault logPolicy) (httpRepeatSafety repeatable request) $ \_ ->
    catchAsHttpException logPolicy request (tryHttpOnce logPolicy request man)

-- | Fold what an HTTP request can throw into a scrubbed 'HttpException'.
-- An 'Control.Exception.ErrorCall' propagates: it is a bug, not evidence that the server is down.
-- [ref:NoUnscrubbedHttpException]
catchAsHttpException :: (MonadUnliftIO m) => LogPolicy -> Request -> m a -> m (Either HttpException a)
catchAsHttpException logPolicy request action =
  fmap (first (scrubHttpException logPolicy)) $
    (Right <$> action)
      `catches` [ Handler $ \e ->
                    pure
                      ( Left
                          ( HttpExceptionRequest
                              request
                              (InternalException (SomeException (e :: IOError)))
                          )
                      ),
                  Handler $ \e -> pure (Left (toHttpException request e)),
                  Handler $ \e -> pure (Left (e :: HttpException))
                ]

-- | The scrubbed exception 'Network.HTTP.Client.parseUrlThrow' would have
-- thrown for this response.
-- [ref:NoUnscrubbedHttpException]
responseAsHttpException :: LogPolicy -> Request -> Response LB.ByteString -> HttpException
responseAsHttpException logPolicy request response =
  scrubHttpException logPolicy $
    HttpExceptionRequest request $
      StatusCodeException (void response) (LB.toStrict (LB.take 1024 (responseBody response)))

-- | Catch a scrubbed 'HttpException' or an 'IOException', and nothing else.
-- [ref:NoUnscrubbedHttpException]
catchConnectionException :: (MonadUnliftIO m) => LogPolicy -> m a -> m (Either SomeException a)
catchConnectionException logPolicy action =
  (Right <$> action)
    `catches` [ Handler $ \e -> pure (Left (toException (scrubHttpException logPolicy (e :: HttpException)))),
                Handler $ \e -> pure (Left (toException (e :: IOException)))
              ]

tryHttpOnce ::
  (MonadLogger m, MonadIO m) =>
  LogPolicy ->
  HTTP.Request ->
  HTTP.Manager ->
  m (HTTP.Response LB.ByteString)
tryHttpOnce logPolicy request man = do
  -- Never the raw 'getUri': OAuth2 token endpoints take secrets in the query.
  let loggedUri = scrubUriForLogging logPolicy (getUri request)
  logInfo $ Text.pack $ unwords [concat [show @ByteString (method request), "-ing"], show @URI loggedUri]
  response <- liftIO $ httpLbs request man
  let c = HTTP.statusCode (responseStatus response)
  when (c >= 400 && not (shouldRetryHttpResponse response)) $
    logWarn $
      Text.pack $
        unwords [show @Int c, "status code while fetching", show @URI loggedUri]
  pure response

-- | Describe a connection failure or a 5xx; a 2xx or 4xx is no fault.
describeHttpFault :: LogPolicy -> Either HttpException (Response LB.ByteString) -> Maybe String
describeHttpFault logPolicy = \case
  Left exception
    | shouldRetryHttpException exception -> Just (renderHttpExceptionForLogging logPolicy exception)
    | otherwise -> Nothing
  Right response
    | shouldRetryHttpResponse response -> Just (renderResponseForLogging logPolicy response)
    | otherwise -> Nothing

-- | A response with a 5xx.
shouldRetryHttpResponse :: Response LB.ByteString -> Bool
shouldRetryHttpResponse response =
  shouldRetryStatusCode $ responseStatus response

-- | A 5xx.
shouldRetryStatusCode :: Status -> Bool
shouldRetryStatusCode status =
  let c = HTTP.statusCode status
   in c >= 500 && c < 600

-- | A connection failure, a timeout, or a 5xx.
shouldRetryHttpException :: HttpException -> Bool
shouldRetryHttpException = \case
  InvalidUrlException _ _ -> False
  HttpExceptionRequest _ exceptionContent -> case exceptionContent of
    StatusCodeException response _ -> shouldRetryStatusCode (responseStatus response)
    ResponseTimeout -> True
    ConnectionTimeout -> True
    ConnectionFailure _ -> True
    InternalException _ -> True
    ProxyConnectException _ _ _ -> True
    NoResponseDataReceived -> True
    ResponseBodyTooShort _ _ -> True
    InvalidChunkHeaders -> True
    IncompleteHeaders -> True
    HttpZlibException _ -> True
    ConnectionClosed -> True
    _ -> False