packages feed

http-env-gen-0.0.0.0: test/Network/HTTP/Env/CircuitBreaker/RetrySpec.hs

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}

module Network.HTTP.Env.CircuitBreaker.RetrySpec (spec) where

import Control.Concurrent (threadDelay)
import Control.Exception (IOException, throwIO, try)
import Control.Monad.Logger.CallStack (LogLevel (LevelWarn), NoLoggingT, WriterLoggingT, fromLogStr, runNoLoggingT, runWriterLoggingT)
import Control.Retry (RetryPolicyM (..), RetryStatus, constantDelay, defaultRetryStatus, limitRetries, simulatePolicy)
import Data.IORef
import Network.HTTP.Env.CircuitBreaker
import Network.HTTP.Env.CircuitBreaker.Gen ()
import Network.HTTP.Env.CircuitBreaker.Retry
import Network.HTTP.Env.FailureBudget
import Network.HTTP.Env.Numeric (wordToInt)
import System.Timeout (timeout)
import Test.QuickCheck (choose, forAll)
import Test.Syd
import Test.Syd.Validity (genValidSpec, shouldBeInvalid, shouldBeValid)

spec :: Spec
spec = do
  let describeFault :: Either () () -> Maybe String
      describeFault = \case
        Left () -> Just "failed"
        Right () -> Nothing

  let countingFailure :: IORef Int -> RetryStatus -> NoLoggingT IO (Either () ())
      countingFailure attempts _ = liftIO $ do
        modifyIORef' attempts (+ 1)
        pure (Left ())

  let shortReset = 0.05
  let pastShortReset = threadDelay 250_000

  describe "anyRepeatSafe" $ do
    it "may repeat when one of them says so" $
      anyRepeatSafe [RepeatSafetyUnsafe, RepeatSafetySafe] `shouldBe` RepeatSafetySafe
    it "must not repeat when none of them says so" $
      map anyRepeatSafe [[], [RepeatSafetyUnsafe, RepeatSafetyUnsafe]] `shouldBe` [RepeatSafetyUnsafe, RepeatSafetyUnsafe]

  describe "takingTraffic" $ do
    it "admits another attempt while the breaker is closed" $
      takingTraffic (CircuitStateClosed 2) `shouldBe` True
    it "admits none while it is open" $
      takingTraffic (CircuitStateOpen 1) `shouldBe` False
    it "admits none while another caller's probe is in flight" $
      takingTraffic (CircuitStateHalfOpen 1) `shouldBe` False

  describe "breakerPolicy" $ do
    it "lets a retry go at once while the breaker is closed" $ do
      breaker <- runNoLoggingT (newCircuitBreaker "test" defaultCircuitBreakerSettings)
      getRetryPolicyM (breakerPolicy breaker) defaultRetryStatus `shouldReturn` Just 0
    it "stops retrying once the breaker opens" $ do
      breaker <- runNoLoggingT (newCircuitBreaker "test" defaultCircuitBreakerSettings {circuitBreakerSettingsFailureThreshold = 1})
      _ <- runNoLoggingT (guardCircuitBreaker breaker (const OutcomeCircuitShouldOpen) (pure (Left () :: Either () ())))
      getRetryPolicyM (breakerPolicy breaker) defaultRetryStatus `shouldReturn` Nothing

  describe "retryingWithCircuitBreaker" $ do
    it "does not try again a fault that may not be sent again" $ do
      attempts <- newIORef (0 :: Int)
      breaker <- runNoLoggingT (newCircuitBreaker "test" defaultCircuitBreakerSettings)
      r <-
        runNoLoggingT $
          retryingWithCircuitBreaker
            (Just breaker)
            Nothing
            (limitRetries 10)
            describeFault
            (const RepeatSafetyUnsafe)
            (countingFailure attempts)
      r `shouldBe` Left (CircuitBreakerErrorUnderlying ())
      readIORef attempts `shouldReturn` 1
    it "does not try again a fault that may not be sent again, without a breaker" $ do
      attempts <- newIORef (0 :: Int)
      r <-
        runNoLoggingT $
          retryingWithCircuitBreaker
            Nothing
            Nothing
            (limitRetries 10)
            describeFault
            (const RepeatSafetyUnsafe)
            (countingFailure attempts)
      r `shouldBe` Left (CircuitBreakerErrorUnderlying ())
      readIORef attempts `shouldReturn` 1
    it "counts each attempt, so a retry budget larger than the threshold cannot outrun it" $ do
      attempts <- newIORef (0 :: Int)
      breaker <-
        runNoLoggingT
          ( newCircuitBreaker
              "test"
              ( CircuitBreakerSettings
                  { circuitBreakerSettingsFailureThreshold = 3,
                    circuitBreakerSettingsResetTimeout = 3600
                  }
              )
          )
      r <-
        runNoLoggingT $
          retryingWithCircuitBreaker
            (Just breaker)
            Nothing
            (limitRetries 10)
            describeFault
            (const RepeatSafetySafe)
            (countingFailure attempts)
      r `shouldBe` Left (CircuitBreakerErrorUnderlying ())
      readIORef attempts `shouldReturn` 3

      rejected <-
        runNoLoggingT $
          retryingWithCircuitBreaker
            (Just breaker)
            Nothing
            (limitRetries 10)
            describeFault
            (const RepeatSafetySafe)
            (countingFailure attempts)
      rejected `shouldBe` Left CircuitBreakerErrorOpen
      readIORef attempts `shouldReturn` 3

    it "answers a rejected call promptly rather than sleeping through its retry budget" $ do
      attempts <- newIORef (0 :: Int)
      breaker <-
        runNoLoggingT
          ( newCircuitBreaker
              "test"
              ( CircuitBreakerSettings
                  { circuitBreakerSettingsFailureThreshold = 1,
                    circuitBreakerSettingsResetTimeout = 3600
                  }
              )
          )
      _ <-
        runNoLoggingT $
          retryingWithCircuitBreaker
            (Just breaker)
            Nothing
            (limitRetries 0)
            describeFault
            (const RepeatSafetySafe)
            (countingFailure attempts)
      readIORef attempts `shouldReturn` 1

      -- Retrying the rejection would sleep for thirty seconds.
      -- Timing out at five leaves slack for a loaded machine.
      rejected <-
        timeout 5_000_000 $
          runNoLoggingT $
            retryingWithCircuitBreaker
              (Just breaker)
              Nothing
              (constantDelay 1_000_000 <> limitRetries 30)
              describeFault
              (const RepeatSafetySafe)
              (countingFailure attempts)
      rejected `shouldBe` Just (Left CircuitBreakerErrorOpen)
      readIORef attempts `shouldReturn` 1

    it "spends the whole retry budget when there is no breaker" $ do
      attempts <- newIORef (0 :: Int)
      r <-
        runNoLoggingT $
          retryingWithCircuitBreaker
            Nothing
            Nothing
            (limitRetries 3)
            describeFault
            (const RepeatSafetySafe)
            (countingFailure attempts)
      r `shouldBe` Left (CircuitBreakerErrorUnderlying ())
      readIORef attempts `shouldReturn` 4

    it "records every faulty attempt in the failure budget, with no breaker" $ do
      attempts <- newIORef (0 :: Int)
      budget <-
        newFailureBudget
          FailureBudgetSettings
            { failureBudgetSettingsFailures = 3,
              failureBudgetSettingsWindow = 3_600
            }
      _ <-
        runNoLoggingT $
          retryingWithCircuitBreaker
            Nothing
            (Just budget)
            (limitRetries 2)
            describeFault
            (const RepeatSafetySafe)
            (countingFailure attempts)
      peekFailureBudget budget
        `shouldReturn` FailureBudgetReport
          { failureBudgetReportFailures = 3,
            failureBudgetReportStatus = FailureBudgetStatusExhausted
          }

    it "records nothing in the failure budget for a result that is not faulty" $ do
      budget <- newFailureBudget defaultFailureBudgetSettings
      _ <-
        runNoLoggingT $
          retryingWithCircuitBreaker
            Nothing
            (Just budget)
            (limitRetries 2)
            describeFault
            (const RepeatSafetySafe)
            (\_ -> pure (Right () :: Either () ()))
      peekFailureBudget budget
        `shouldReturn` FailureBudgetReport
          { failureBudgetReportFailures = 0,
            failureBudgetReportStatus = FailureBudgetStatusWithin
          }

    it "stops on a result that is not faulty even with no breaker and budget to spare" $ do
      attempts <- newIORef (0 :: Int)
      let succeeding :: RetryStatus -> NoLoggingT IO (Either () ())
          succeeding _ = liftIO $ do
            modifyIORef' attempts (+ 1)
            pure (Right ())
      r <-
        runNoLoggingT $
          retryingWithCircuitBreaker
            Nothing
            Nothing
            (limitRetries 10)
            describeFault
            (const RepeatSafetySafe)
            succeeding
      r `shouldBe` Right ()
      readIORef attempts `shouldReturn` 1

    it "stops at a result that does not say the dependency is faulty, and leaves the breaker closed" $ do
      attempts <- newIORef (0 :: Int)
      breaker <-
        runNoLoggingT
          ( newCircuitBreaker
              "test"
              ( CircuitBreakerSettings
                  { circuitBreakerSettingsFailureThreshold = 3,
                    circuitBreakerSettingsResetTimeout = 3600
                  }
              )
          )
      r <-
        runNoLoggingT $
          retryingWithCircuitBreaker
            (Just breaker)
            Nothing
            (limitRetries 10)
            (const Nothing)
            (const RepeatSafetySafe)
            (countingFailure attempts)
      r `shouldBe` Left (CircuitBreakerErrorUnderlying ())
      readIORef attempts `shouldReturn` 1
      readCircuitBreakerState breaker `shouldReturn` CircuitStateClosed 0

    it "logs every faulty attempt at warn, naming the dependency, including the ones a retry made up for" $ do
      attempts <- newIORef (0 :: Int)
      breaker <-
        runNoLoggingT
          ( newCircuitBreaker
              "test"
              ( CircuitBreakerSettings
                  { circuitBreakerSettingsFailureThreshold = 5,
                    circuitBreakerSettingsResetTimeout = 3600
                  }
              )
          )
      let failTwiceThenSucceed :: RetryStatus -> WriterLoggingT IO (Either () ())
          failTwiceThenSucceed _ = liftIO $ do
            soFar <- atomicModifyIORef' attempts (\n -> (n + 1, n))
            pure (if soFar < 2 then Left () else Right ())
      (r, logs) <-
        runWriterLoggingT
          (retryingWithCircuitBreaker (Just breaker) Nothing (limitRetries 10) describeFault (const RepeatSafetySafe) failTwiceThenSucceed)
      r `shouldBe` Right ()
      [(level, fromLogStr msg) | (_, _, level, msg) <- logs]
        `shouldBe` [ (LevelWarn, "Request attempt 1 to \"test\" failed: failed"),
                     (LevelWarn, "Request attempt 2 to \"test\" failed: failed")
                   ]

    it "stops on success and clears the failures the earlier attempts counted" $ do
      attempts <- newIORef (0 :: Int)
      breaker <-
        runNoLoggingT
          ( newCircuitBreaker
              "test"
              ( CircuitBreakerSettings
                  { circuitBreakerSettingsFailureThreshold = 5,
                    circuitBreakerSettingsResetTimeout = 3600
                  }
              )
          )
      let failTwiceThenSucceed :: RetryStatus -> NoLoggingT IO (Either () ())
          failTwiceThenSucceed _ = liftIO $ do
            soFar <- atomicModifyIORef' attempts (\n -> (n + 1, n))
            pure (if soFar < 2 then Left () else Right ())
      r <-
        runNoLoggingT $
          retryingWithCircuitBreaker
            (Just breaker)
            Nothing
            (limitRetries 10)
            describeFault
            (const RepeatSafetySafe)
            failTwiceThenSucceed
      r `shouldBe` Right ()
      readIORef attempts `shouldReturn` 3
      readCircuitBreakerState breaker `shouldReturn` CircuitStateClosed 0

    it "makes one attempt as the half-open probe and does not retry past it" $ do
      attempts <- newIORef (0 :: Int)
      breaker <-
        runNoLoggingT
          ( newCircuitBreaker
              "test"
              ( CircuitBreakerSettings
                  { circuitBreakerSettingsFailureThreshold = 1,
                    circuitBreakerSettingsResetTimeout = shortReset
                  }
              )
          )
      _ <-
        runNoLoggingT $
          retryingWithCircuitBreaker
            (Just breaker)
            Nothing
            (limitRetries 0)
            describeFault
            (const RepeatSafetySafe)
            (countingFailure attempts)
      readIORef attempts `shouldReturn` 1

      pastShortReset
      r <-
        runNoLoggingT $
          retryingWithCircuitBreaker
            (Just breaker)
            Nothing
            (limitRetries 10)
            describeFault
            (const RepeatSafetySafe)
            (countingFailure attempts)
      r `shouldBe` Left (CircuitBreakerErrorUnderlying ())
      readIORef attempts `shouldReturn` 2

    it "lets an attempt's exception propagate uncounted rather than retrying it" $ do
      attempts <- newIORef (0 :: Int)
      breaker <-
        runNoLoggingT
          ( newCircuitBreaker
              "test"
              ( CircuitBreakerSettings
                  { circuitBreakerSettingsFailureThreshold = 1,
                    circuitBreakerSettingsResetTimeout = 3600
                  }
              )
          )
      let throwing :: RetryStatus -> NoLoggingT IO (Either () ())
          throwing _ = liftIO $ do
            modifyIORef' attempts (+ 1)
            throwIO (userError "boom")
      thrown <-
        try (runNoLoggingT (retryingWithCircuitBreaker (Just breaker) Nothing (limitRetries 10) describeFault (const RepeatSafetySafe) throwing))
      case thrown of
        Left (_ :: IOException) -> pure ()
        Right r -> expectationFailure (unwords ["expected the exception to be rethrown, got", show r])
      readIORef attempts `shouldReturn` 1

      next <-
        runNoLoggingT (retryingWithCircuitBreaker (Just breaker) Nothing (limitRetries 0) describeFault (const RepeatSafetySafe) (countingFailure attempts))
      next `shouldBe` Left (CircuitBreakerErrorUnderlying ())
      readIORef attempts `shouldReturn` 2

  describe "GenValid Attempts" $
    genValidSpec @Attempts

  describe "limitAttempts" $
    it "lets a call make exactly that many requests" $
      forAll (choose (1, 32)) $ \attempts -> do
        delays <- simulatePolicy 64 (limitAttempts (Attempts attempts))
        let requests = 1 + length [() | (_, Just _) <- delays]
        requests `shouldBe` wordToInt attempts

  describe "defaultAttempts" $ do
    it "is valid" $
      shouldBeValid defaultAttempts
    it "is one fewer than the default failure threshold" $
      unAttempts defaultAttempts + 1 `shouldBe` circuitBreakerSettingsFailureThreshold defaultCircuitBreakerSettings

  describe "Validity Attempts" $ do
    it "accepts a single attempt" $
      shouldBeValid (Attempts 1)
    it "refuses zero attempts" $
      shouldBeInvalid (Attempts 0)