http-env-0.0.0.0: src/Network/HTTP/Env/HttpClient.hs
{-# LANGUAGE LambdaCase #-}
-- | The manager and the layers every outgoing HTTP call goes through.
module Network.HTTP.Env.HttpClient
( HttpEnv (..),
httpEnvResetTimeout,
withRequestLimiter,
httpCall,
httpCallWith,
unlessRejecting,
HttpEnvError (..),
httpEnvError,
httpEnvErrorCircuitBreakerError,
HttpEnvReport (..),
peekHttpEnv,
)
where
import Control.Monad (forM_)
import Control.Monad.IO.Class
import Control.Monad.Logger.CallStack
import Control.Retry (RetryPolicyM)
import qualified Data.ByteString.Lazy as LB
import Data.Time (NominalDiffTime, UTCTime, getCurrentTime)
import Network.HTTP.Client (HttpException, Manager, Request, Response)
import Network.HTTP.Env.CircuitBreaker
import Network.HTTP.Env.CircuitBreaker.Retry (liftRetryPolicy)
import Network.HTTP.Env.FailureBudget (FailureBudgetEnv, FailureBudgetReport, peekFailureBudget)
import Network.HTTP.Env.HttpClient.Retry (Repeatable (..), httpLbsWithRetry, responseAsHttpException)
import Network.HTTP.Env.LogPolicy (LogPolicy)
import Network.HTTP.Env.Pacing (RequestLimiter, waitForRequest)
import Network.HTTP.Env.RateLimit (RateLimitHeaders, httpExceptionRateLimitWait, responseRateLimitWait)
import UnliftIO
-- | The manager and the layers that every HTTP call goes through.
data HttpEnv = HttpEnv
{ httpEnvManager :: !Manager,
httpEnvRetryPolicy :: !(RetryPolicyM IO),
httpEnvCircuitBreaker :: !(Maybe CircuitBreakerEnv),
httpEnvFailureBudget :: !(Maybe FailureBudgetEnv),
httpEnvRequestLimiter :: !(Maybe RequestLimiter),
httpEnvLogPolicy :: !LogPolicy,
-- | How the dependency says a quota is spent, if it does.
httpEnvRateLimitHeaders :: !(Maybe RateLimitHeaders)
}
-- | The env, pacing every call through the given limiter.
withRequestLimiter :: RequestLimiter -> HttpEnv -> HttpEnv
withRequestLimiter limiter env = env {httpEnvRequestLimiter = Just limiter}
-- | The reset timeout of this env's breaker, if it has one.
httpEnvResetTimeout :: HttpEnv -> Maybe NominalDiffTime
httpEnvResetTimeout = fmap circuitBreakerResetTimeout . httpEnvCircuitBreaker
-- | Perform an HTTP request through the env's layers and read the whole body.
-- A request is sent again only if its method is idempotent, it carries an
-- idempotency key, or it never left.
httpCall ::
(MonadLogger m, MonadUnliftIO m) =>
HttpEnv ->
Request ->
m (Either (HttpEnvError HttpException) (Response LB.ByteString))
httpCall = httpCallWith RepeatableIfIdempotent
-- | 'httpCall', saying whether the request may be sent again after a fault.
-- A spent quota is told apart whether the request throws on a refusal, as
-- with 'Network.HTTP.Client.parseUrlThrow', or not.
-- The request limiter is debited once per call, not per attempt.
httpCallWith ::
(MonadLogger m, MonadUnliftIO m) =>
Repeatable ->
HttpEnv ->
Request ->
m (Either (HttpEnvError HttpException) (Response LB.ByteString))
httpCallWith repeatable env request = unlessRejecting (httpEnvCircuitBreaker env) $ do
forM_ (httpEnvRequestLimiter env) waitForRequest
let policy = liftRetryPolicy (httpEnvRetryPolicy env)
result <- httpLbsWithRetry (httpEnvLogPolicy env) (httpEnvCircuitBreaker env) (httpEnvFailureBudget env) policy repeatable request (httpEnvManager env)
now <- liftIO getCurrentTime
pure $ case result of
Left err -> Left (httpEnvError (fmap httpExceptionRateLimitWait (httpEnvRateLimitHeaders env)) now err)
Right response ->
case httpEnvRateLimitHeaders env >>= \convention -> responseRateLimitWait convention now response of
Just quotaWait -> Left (HttpEnvErrorRateLimited quotaWait (responseAsHttpException (httpEnvLogPolicy env) request response))
Nothing -> Right response
-- | Answer at once while the breaker rejects, rather than wait on a limiter
-- for a call it would reject.
unlessRejecting ::
(MonadIO m) =>
Maybe CircuitBreakerEnv ->
m (Either (HttpEnvError e) a) ->
m (Either (HttpEnvError e) a)
unlessRejecting mBreaker call = do
circuit <- traverse peekCircuitBreaker mBreaker
case circuit of
Just CircuitReportRejecting -> pure (Left HttpEnvErrorCircuitOpen)
Just CircuitReportProbing -> call
Just CircuitReportClosed -> call
Nothing -> call
-- | How a call through an env failed.
data HttpEnvError e
= -- | The breaker is open, so nothing was sent.
HttpEnvErrorCircuitOpen
| -- | The dependency said a quota is spent; try again after the wait.
-- It counts as an answer, so it resets the breaker's count of
-- consecutive failures and closes a probing breaker.
HttpEnvErrorRateLimited !NominalDiffTime !e
| -- | Any other failure, with the dependency's own error.
HttpEnvErrorFailed !e
deriving (Show, Eq)
-- | Forget whether a failure was a spent quota, for a caller that treats a
-- spent quota like any other failure.
httpEnvErrorCircuitBreakerError :: HttpEnvError e -> CircuitBreakerError e
httpEnvErrorCircuitBreakerError = \case
HttpEnvErrorCircuitOpen -> CircuitBreakerErrorOpen
HttpEnvErrorRateLimited _ e -> CircuitBreakerErrorUnderlying e
HttpEnvErrorFailed e -> CircuitBreakerErrorUnderlying e
-- | Tell a spent quota apart from any other failure, given how to read one.
httpEnvError :: Maybe (UTCTime -> e -> Maybe NominalDiffTime) -> UTCTime -> CircuitBreakerError e -> HttpEnvError e
httpEnvError mRateLimitWait now = \case
CircuitBreakerErrorOpen -> HttpEnvErrorCircuitOpen
CircuitBreakerErrorUnderlying e ->
case mRateLimitWait >>= \rateLimitWait -> rateLimitWait now e of
Just quotaWait -> HttpEnvErrorRateLimited quotaWait e
Nothing -> HttpEnvErrorFailed e
-- | What an env's breaker and failure budget say, 'Nothing' for an absent one.
data HttpEnvReport = HttpEnvReport
{ -- | What the breaker is doing.
httpEnvReportCircuit :: !(Maybe CircuitReport),
-- | How much of the failure budget is spent.
httpEnvReportFailureBudget :: !(Maybe FailureBudgetReport)
}
deriving (Show, Eq)
-- | What the env has to say right now, without counting as a call.
peekHttpEnv :: (MonadIO m) => HttpEnv -> m HttpEnvReport
peekHttpEnv env = do
circuit <- traverse peekCircuitBreaker (httpEnvCircuitBreaker env)
budget <- traverse peekFailureBudget (httpEnvFailureBudget env)
pure
HttpEnvReport
{ httpEnvReportCircuit = circuit,
httpEnvReportFailureBudget = budget
}