packages feed

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

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

-- | Retrying servant client calls, and where a 'Servant.Client.ClientError' becomes a value.
--
-- [tag:NoUnscrubbedClientError] Every 'Servant.Client.ClientError' handed out of this module
-- has been through 'scrubClientError', for the same reason as
-- [ref:NoUnscrubbedHttpException]: it carries the request we sent.
module Network.HTTP.Env.Servant.Retry
  ( runClientMWithRetries,
    runStreamingClientMWithRetries,
    runClientMWithRetries',
    shouldRetryClientError,
    describeClientFault,
    clientRepeatSafety,
    clientErrorRepeatSafety,
    scrubClientError,
    renderClientErrorForLogging,
  )
where

import Control.DeepSeq (NFData)
import Control.Exception (SomeException, fromException, toException)
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Logger.CallStack
import Control.Retry
import qualified Data.ByteString.Lazy as LB
import Data.Foldable (toList)
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import qualified Data.Text as Text
import qualified Data.Text.Encoding as TE
import Network.HTTP.Client (HttpException (..))
import Network.HTTP.Env.CircuitBreaker
import Network.HTTP.Env.CircuitBreaker.Retry (retryingWithCircuitBreaker)
import Network.HTTP.Env.FailureBudget (FailureBudgetEnv)
import Network.HTTP.Env.HttpClient.Retry
import Network.HTTP.Env.LogPolicy (LogPolicy, loggedResponseBodyBytes, scrubHeadersForLogging, scrubHttpException, scrubQueryForLogging, withheldResponseBody)
import Network.HTTP.Types.Header (Header)
import qualified Servant.Client as Oneshot
import qualified Servant.Client.Core as Core
import qualified Servant.Client.Streaming as Streaming
import Text.Show.Pretty

-- | Run a servant request, running each attempt through the breaker.
-- The final error is logged at the level the given function assigns it.
runClientMWithRetries :: (MonadIO m, MonadLogger m) => LogPolicy -> Maybe CircuitBreakerEnv -> Maybe FailureBudgetEnv -> (Oneshot.ClientError -> LogLevel) -> RetryPolicyM m -> Repeatable -> Oneshot.ClientM a -> Oneshot.ClientEnv -> m (Either (CircuitBreakerError Oneshot.ClientError) a)
runClientMWithRetries logPolicy mBreaker mBudget errorLogLevel = runClientMWithRetries' logPolicy mBreaker mBudget errorLogLevel Oneshot.runClientM

-- | Streaming counterpart of 'runClientMWithRetries'.
runStreamingClientMWithRetries :: (MonadIO m, MonadLogger m, NFData a) => LogPolicy -> Maybe CircuitBreakerEnv -> Maybe FailureBudgetEnv -> (Oneshot.ClientError -> LogLevel) -> RetryPolicyM m -> Repeatable -> Streaming.ClientM a -> Streaming.ClientEnv -> m (Either (CircuitBreakerError Oneshot.ClientError) a)
runStreamingClientMWithRetries logPolicy mBreaker mBudget errorLogLevel = runClientMWithRetries' logPolicy mBreaker mBudget errorLogLevel Streaming.runClientM

-- | 'runClientMWithRetries' over any runner.
runClientMWithRetries' :: (MonadIO m, MonadLogger m) => LogPolicy -> Maybe CircuitBreakerEnv -> Maybe FailureBudgetEnv -> (Oneshot.ClientError -> LogLevel) -> (cm a -> env -> IO (Either Oneshot.ClientError a)) -> RetryPolicyM m -> Repeatable -> cm a -> env -> m (Either (CircuitBreakerError Oneshot.ClientError) a)
runClientMWithRetries' logPolicy mBreaker mBudget errorLogLevel runner policy repeatable func clientEnv = do
  result <-
    retryingWithCircuitBreaker mBreaker mBudget policy (describeClientFault logPolicy) (clientRepeatSafety repeatable) $ \rs -> do
      let num = succ $ rsIterNumber rs
      when (num > 1) $ logDebug $ Text.pack $ unwords ["Attempt", show @Int num]
      -- The runner can throw a connection failure rather than return one,
      -- for example when streaming.
      liftIO $ do
        errOrThrow <- catchConnectionException logPolicy (runner func clientEnv)
        pure $ case errOrThrow of
          Left someException -> Left (Oneshot.ConnectionError someException)
          Right res -> res
  case result of
    Left CircuitBreakerErrorOpen -> pure (Left CircuitBreakerErrorOpen)
    Left (CircuitBreakerErrorUnderlying err) -> do
      -- [ref:NoUnscrubbedClientError]
      let scrubbed = scrubClientError logPolicy err
      logOther (errorLogLevel scrubbed) $ Text.pack $ unwords ["Servant request failed:", renderClientErrorForLogging logPolicy scrubbed]
      pure $ Left $ CircuitBreakerErrorUnderlying scrubbed
    Right a -> pure $ Right a

-- | A 'Oneshot.ClientError' scrubbed and rendered for a log line.
-- A body that failed is cut to 'loggedResponseBodyBytes'; one that could not
-- be read is withheld, since it may be a success that carries a credential.
renderClientErrorForLogging :: LogPolicy -> Oneshot.ClientError -> String
renderClientErrorForLogging policy err =
  let withheld :: Core.ResponseF LB.ByteString -> Core.ResponseF LB.ByteString
      withheld response = response {Core.responseBody = LB.fromStrict (TE.encodeUtf8 (Text.pack withheldResponseBody))}
   in ppShow @Oneshot.ClientError $ case scrubClientError policy err of
        Oneshot.FailureResponse request response ->
          Oneshot.FailureResponse request (LB.take loggedResponseBodyBytes <$> response)
        Oneshot.DecodeFailure msg response -> Oneshot.DecodeFailure msg (withheld response)
        Oneshot.UnsupportedContentType mediaType response -> Oneshot.UnsupportedContentType mediaType (withheld response)
        Oneshot.InvalidContentTypeHeader response -> Oneshot.InvalidContentTypeHeader (withheld response)
        Oneshot.ConnectionError e -> Oneshot.ConnectionError e

-- | A 'Oneshot.ClientError' with every request and response in it scrubbed.
-- A connection failure carries a second copy of the request.
scrubClientError :: LogPolicy -> Oneshot.ClientError -> Oneshot.ClientError
scrubClientError policy = \case
  Oneshot.FailureResponse request response ->
    Oneshot.FailureResponse (scrubRequest policy request) (scrubResponse policy response)
  Oneshot.DecodeFailure msg response ->
    Oneshot.DecodeFailure msg (scrubResponse policy response)
  Oneshot.UnsupportedContentType mediaType response ->
    Oneshot.UnsupportedContentType mediaType (scrubResponse policy response)
  Oneshot.InvalidContentTypeHeader response ->
    Oneshot.InvalidContentTypeHeader (scrubResponse policy response)
  Oneshot.ConnectionError e -> Oneshot.ConnectionError (scrubConnectionException policy e)

scrubRequest :: LogPolicy -> Core.RequestF body path -> Core.RequestF body path
scrubRequest policy request =
  request
    { Core.requestHeaders = scrubHeaderSeq policy (Core.requestHeaders request),
      Core.requestQueryString = Seq.fromList (scrubQueryForLogging policy (toList (Core.requestQueryString request)))
    }

scrubResponse :: LogPolicy -> Core.ResponseF body -> Core.ResponseF body
scrubResponse policy response =
  response {Core.responseHeaders = scrubHeaderSeq policy (Core.responseHeaders response)}

scrubHeaderSeq :: LogPolicy -> Seq Header -> Seq Header
scrubHeaderSeq policy = Seq.fromList . scrubHeadersForLogging policy . toList

-- | The exception behind a connection failure, put through the policy.
scrubConnectionException :: LogPolicy -> SomeException -> SomeException
scrubConnectionException policy e = case fromException e of
  Just httpException -> toException (scrubHttpException policy httpException)
  Nothing -> e

-- | Describe a connection error or a 5xx; anything else is no fault.
describeClientFault :: LogPolicy -> Either Oneshot.ClientError a -> Maybe String
describeClientFault logPolicy = \case
  Left err
    | shouldRetryClientError err -> Just (renderClientErrorForLogging logPolicy err)
    | otherwise -> Nothing
  Right _ -> Nothing

-- | Whether a call may be sent again after this result.
clientRepeatSafety :: Repeatable -> Either Oneshot.ClientError a -> RepeatSafety
clientRepeatSafety repeatable res = case repeatable of
  RepeatableAlways -> RepeatSafetySafe
  RepeatableIfIdempotent -> case res of
    Left err -> clientErrorRepeatSafety err
    Right _ -> RepeatSafetyUnsafe

-- | 'httpRepeatSafety' of the request behind an error.
-- A request the error does not carry is taken as unsafe to send again.
clientErrorRepeatSafety :: Oneshot.ClientError -> RepeatSafety
clientErrorRepeatSafety = \case
  Oneshot.FailureResponse request _ ->
    requestRepeatSafety (Core.requestMethod request) (toList (Core.requestHeaders request))
  Oneshot.ConnectionError e -> case fromException e of
    Just exception@(HttpExceptionRequest request _) ->
      httpRepeatSafety RepeatableIfIdempotent request (Left exception :: Either HttpException ())
    Just (InvalidUrlException _ _) -> RepeatSafetyUnsafe
    Nothing -> RepeatSafetyUnsafe
  Oneshot.DecodeFailure _ _ -> RepeatSafetyUnsafe
  Oneshot.UnsupportedContentType _ _ -> RepeatSafetyUnsafe
  Oneshot.InvalidContentTypeHeader _ -> RepeatSafetyUnsafe

-- | A connection failure or a 5xx.
shouldRetryClientError :: Oneshot.ClientError -> Bool
shouldRetryClientError = \case
  Oneshot.FailureResponse _ response -> shouldRetryStatusCode $ Oneshot.responseStatusCode response
  Oneshot.DecodeFailure _ _ -> False
  Oneshot.UnsupportedContentType _ _ -> False
  Oneshot.InvalidContentTypeHeader _ -> False
  Oneshot.ConnectionError _ -> True