http-env-0.0.0.0: src/Network/HTTP/Env/CircuitBreaker/Retry.hs
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
-- | Retries with the circuit breaker inside the loop, so it counts requests.
module Network.HTTP.Env.CircuitBreaker.Retry
( retryingWithCircuitBreaker,
RepeatSafety (..),
anyRepeatSafe,
Attempts (..),
defaultAttempts,
limitAttempts,
breakerPolicy,
takingTraffic,
liftRetryPolicy,
)
where
import Control.Arrow (left)
import Control.Monad (forM_)
import Control.Monad.IO.Class
import Control.Monad.Logger.CallStack (MonadLogger, logWarn)
import Control.Retry (RetryPolicyM (..), RetryStatus (..), limitRetries, retrying)
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Validity
import GHC.Generics (Generic)
import Network.HTTP.Env.CircuitBreaker
import Network.HTTP.Env.FailureBudget (FailureBudgetEnv, recordFailureNow)
import Network.HTTP.Env.Numeric (wordToIntSaturating)
-- | Whether sending a request again risks doing its work twice.
data RepeatSafety
= RepeatSafetySafe
| RepeatSafetyUnsafe
deriving (Show, Eq)
-- | 'RepeatSafetySafe' when any of these says so.
anyRepeatSafe :: [RepeatSafety] -> RepeatSafety
anyRepeatSafe safeties = if RepeatSafetySafe `elem` safeties then RepeatSafetySafe else RepeatSafetyUnsafe
-- | Retry faulty results that may be sent again, running each attempt through
-- the breaker.
-- Fault descriptions are logged as they are, so they must already be scrubbed.
retryingWithCircuitBreaker ::
forall m e a.
(MonadLogger m, MonadIO m) =>
Maybe CircuitBreakerEnv ->
Maybe FailureBudgetEnv ->
RetryPolicyM m ->
(Either e a -> Maybe String) ->
(Either e a -> RepeatSafety) ->
(RetryStatus -> m (Either e a)) ->
m (Either (CircuitBreakerError e) a)
retryingWithCircuitBreaker mBreaker mBudget policy describeFault mayRepeat act =
let classify :: Either e a -> Outcome
classify res = case describeFault res of
Nothing -> OutcomeCircuitShouldStayClosed
Just _ -> OutcomeCircuitShouldOpen
loggedAct :: RetryStatus -> m (Either e a)
loggedAct retryStatus = do
res <- act retryStatus
forM_ (describeFault res) $ \fault -> do
forM_ mBudget recordFailureNow
logWarn $
Text.pack $
unwords $
concat
[ ["Request attempt", show @Int (succ (rsIterNumber retryStatus))],
case mBreaker of
Nothing -> []
Just breaker -> ["to", show @Text (circuitBreakerName breaker)],
["failed:", fault]
]
pure res
attempt :: RetryStatus -> m (Either (CircuitBreakerError e) a)
attempt retryStatus = case mBreaker of
Nothing -> left CircuitBreakerErrorUnderlying <$> loggedAct retryStatus
Just breaker -> guardCircuitBreaker breaker classify (loggedAct retryStatus)
retryable :: Either e a -> Bool
retryable res =
saysFaulty (classify res) && case mayRepeat res of
RepeatSafetySafe -> True
RepeatSafetyUnsafe -> False
again :: Either (CircuitBreakerError e) a -> Bool
again = \case
Left CircuitBreakerErrorOpen -> False
Left (CircuitBreakerErrorUnderlying e) -> retryable (Left e)
Right a -> retryable (Right a)
in retrying (maybe policy ((policy <>) . breakerPolicy) mBreaker) (\_ res -> pure (again res)) attempt
-- Equivalent: a rejected attempt leaves the breaker not closed, so
-- 'breakerPolicy' stops the retry whatever the predicate says.
{-# ANN retryingWithCircuitBreaker ("DisableMutation: BoolLit" :: String) #-}
-- | How many requests one call may make, including the first; at least 1.
newtype Attempts = Attempts
{ -- | The number of requests.
unAttempts :: Word
}
deriving (Show, Eq, Generic)
instance Validity Attempts where
validate = validateAttempts
-- Equivalent: genericValidate of a Word is always valid.
validateAttempts :: Attempts -> Validation
validateAttempts attempts@(Attempts n) =
mconcat
[ genericValidate attempts,
declare "a call makes at least one request" $ n >= 1
]
{-# ANN validateAttempts ("DisableMutation: ListLit" :: String) #-}
-- | Fewer than a default breaker's threshold, so one call cannot open it.
defaultAttempts :: Attempts
defaultAttempts = Attempts 4
-- | A retry policy that makes exactly this many requests.
limitAttempts :: (Monad m) => Attempts -> RetryPolicyM m
-- Subtracted in 'Int' so that zero cannot wrap the 'Word' into a huge budget.
limitAttempts (Attempts n) = limitRetries (wordToIntSaturating n - 1)
-- | Retry only while the breaker still takes traffic.
-- Reading the breaker makes its threshold a budget shared between calls.
breakerPolicy :: (MonadIO m) => CircuitBreakerEnv -> RetryPolicyM m
breakerPolicy breaker = RetryPolicyM $ \_ -> do
circuitState <- readCircuitBreakerState breaker
pure $ if takingTraffic circuitState then Just 0 else Nothing
-- | A policy in 'IO', usable in any 'MonadIO'.
liftRetryPolicy :: (MonadIO m) => RetryPolicyM IO -> RetryPolicyM m
liftRetryPolicy policy = RetryPolicyM (liftIO . getRetryPolicyM policy)
-- | Whether a breaker in this state would admit another attempt.
takingTraffic :: CircuitState -> Bool
takingTraffic = \case
CircuitStateClosed _ -> True
-- Retrying would replace the dependency's own error with a rejection.
CircuitStateOpen _ -> False
CircuitStateHalfOpen _ -> False
-- | Whether a classified result says the dependency is faulty.
saysFaulty :: Outcome -> Bool
saysFaulty = \case
OutcomeCircuitShouldOpen -> True
OutcomeCircuitShouldStayClosed -> False