packages feed

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

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}

module Network.HTTP.Env.HttpClientSpec (spec) where

import Control.Monad (replicateM_)
import Control.Monad.Logger.CallStack (LogLevel (LevelInfo, LevelWarn), runLoggingT, runNoLoggingT)
import Control.Retry (limitRetries)
import qualified Data.ByteString as SB
import qualified Data.ByteString.Lazy as LB
import Data.Either (isLeft)
import Data.Foldable (toList)
import Data.IORef
import Data.List (isInfixOf)
import Data.Maybe (isNothing)
import qualified Data.Sequence as Seq
import qualified Data.Set as Set
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Network.HTTP.Client
import Network.HTTP.Env.CircuitBreaker
import Network.HTTP.Env.FailureBudget
import Network.HTTP.Env.HttpClient
import Network.HTTP.Env.HttpClient.Retry (Repeatable (..))
import Network.HTTP.Env.LogPolicy (LogPolicy (..), defaultLogPolicy)
import Network.HTTP.Env.Pacing (keyedLimiter, newKeyedLimiters, newRequestLimiter, waitForRequest)
import Network.HTTP.Env.RateLimit (RateLimitHeaders (..))
import Network.HTTP.Types (status200, status302, status403, status429, status503)
import Network.Wai (responseLBS)
import qualified Network.Wai.Handler.Warp as Warp
import System.Timeout (timeout)
import Test.Syd

spec :: Spec
spec = do
  describe "httpEnvResetTimeout" $ do
    it "is the reset timeout of the env's breaker" $ do
      man <- newManager defaultManagerSettings
      breaker <-
        runNoLoggingT
          ( newCircuitBreaker
              "test"
              ( CircuitBreakerSettings
                  { circuitBreakerSettingsFailureThreshold = 2,
                    circuitBreakerSettingsResetTimeout = 1234
                  }
              )
          )
      httpEnvResetTimeout
        HttpEnv
          { httpEnvManager = man,
            httpEnvRetryPolicy = limitRetries 0,
            httpEnvCircuitBreaker = Just breaker,
            httpEnvFailureBudget = Nothing,
            httpEnvRequestLimiter = Nothing,
            httpEnvLogPolicy = defaultLogPolicy,
            httpEnvRateLimitHeaders = Nothing
          }
        `shouldBe` Just 1234
    it "is nothing without a breaker" $ do
      man <- newManager defaultManagerSettings
      httpEnvResetTimeout
        HttpEnv
          { httpEnvManager = man,
            httpEnvRetryPolicy = limitRetries 0,
            httpEnvCircuitBreaker = Nothing,
            httpEnvFailureBudget = Nothing,
            httpEnvRequestLimiter = Nothing,
            httpEnvLogPolicy = defaultLogPolicy,
            httpEnvRateLimitHeaders = Nothing
          }
        `shouldBe` Nothing

  describe "httpEnvErrorCircuitBreakerError" $
    it "forgets only whether a failure was a spent quota" $
      map
        httpEnvErrorCircuitBreakerError
        [HttpEnvErrorCircuitOpen, HttpEnvErrorRateLimited 60 (), HttpEnvErrorFailed ()]
        `shouldBe` [CircuitBreakerErrorOpen, CircuitBreakerErrorUnderlying (), CircuitBreakerErrorUnderlying ()]

  describe "httpEnvError" $ do
    let now = posixSecondsToUTCTime 0
    it "says nothing was sent when the breaker is open" $
      httpEnvError (Just (\_ () -> Just 60)) now (CircuitBreakerErrorOpen :: CircuitBreakerError ())
        `shouldBe` HttpEnvErrorCircuitOpen
    it "tells a spent quota apart" $
      httpEnvError (Just (\_ () -> Just 60)) now (CircuitBreakerErrorUnderlying ())
        `shouldBe` HttpEnvErrorRateLimited 60 ()
    it "calls any other failure a failure" $
      httpEnvError (Just (\_ () -> Nothing)) now (CircuitBreakerErrorUnderlying ())
        `shouldBe` HttpEnvErrorFailed ()
    it "reads no quota without headers to read it from" $
      httpEnvError Nothing now (CircuitBreakerErrorUnderlying ())
        `shouldBe` HttpEnvErrorFailed ()

  describe "httpCall" $ do
    it "leaves the cookies of a redirect loop out of what it returns" $ do
      man <- newManager defaultManagerSettings
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 0,
                httpEnvCircuitBreaker = Nothing,
                httpEnvFailureBudget = Nothing,
                httpEnvRequestLimiter = Nothing,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Nothing
              }
      let application _ respond = respond (responseLBS status302 [("Location", "/"), ("Set-Cookie", "s=cookiesecretvalue")] "")
      Warp.testWithApplication (pure application) $ \serverPort -> do
        req <- parseRequest (concat ["http://127.0.0.1:", show serverPort, "/"])
        result <- runNoLoggingT (httpCall env req)
        case result of
          Left (HttpEnvErrorFailed exception) -> show exception `shouldNotSatisfy` isInfixOf "cookiesecretvalue"
          _ -> expectationFailure "expected a failure"

    it "tells a spent quota apart whatever headers the log policy keeps" $ do
      man <- newManager defaultManagerSettings
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 0,
                httpEnvCircuitBreaker = Nothing,
                httpEnvFailureBudget = Nothing,
                httpEnvRequestLimiter = Nothing,
                httpEnvLogPolicy = defaultLogPolicy {logPolicyHeadersToLog = Set.fromList ["X-Request-ID"]},
                httpEnvRateLimitHeaders = Just RateLimitHeadersRateLimitReset
              }
      let application _ respond = respond (responseLBS status429 [("Retry-After", "600")] "")
      Warp.testWithApplication (pure application) $ \serverPort -> do
        req <- parseUrlThrow (concat ["http://127.0.0.1:", show serverPort, "/"])
        result <- runNoLoggingT (httpCall env req)
        case result of
          Left (HttpEnvErrorRateLimited quotaWait _) -> quotaWait `shouldBe` 605
          _ -> expectationFailure "expected a spent quota"

    it "answers that the breaker is open without waiting for the request limiter" $ do
      man <- newManager defaultManagerSettings
      breaker <- runNoLoggingT (newCircuitBreaker "test" defaultCircuitBreakerSettings {circuitBreakerSettingsFailureThreshold = 1})
      _ <- guardCircuitBreaker breaker (const OutcomeCircuitShouldOpen) (pure (Left () :: Either () ()))
      limiter <- newRequestLimiter 1
      replicateM_ 50 (waitForRequest limiter)
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 0,
                httpEnvCircuitBreaker = Just breaker,
                httpEnvFailureBudget = Nothing,
                httpEnvRequestLimiter = Just limiter,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Nothing
              }
      req <- parseRequest "http://127.0.0.1:1/"
      result <- timeout 200000 (runNoLoggingT (httpCall env req))
      case result of
        Just (Left HttpEnvErrorCircuitOpen) -> pure ()
        _ -> expectationFailure "expected the breaker to answer at once"

    it "sends a POST again when it could not connect, since nothing was sent" $ do
      man <- newManager defaultManagerSettings
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 3,
                httpEnvCircuitBreaker = Nothing,
                httpEnvFailureBudget = Nothing,
                httpEnvRequestLimiter = Nothing,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Nothing
              }
      req <- parseRequest "POST http://127.0.0.1:1/"
      warnings <- newIORef (0 :: Int)
      let captureLogger _loc _source level _msg =
            if level == LevelWarn then atomicModifyIORef' warnings (\n -> (n + 1, ())) else pure ()
      _ <- runLoggingT (httpCall env req) captureLogger
      readIORef warnings `shouldReturn` 4

    it "does not send a POST again after a fault" $ do
      man <- newManager defaultManagerSettings
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 3,
                httpEnvCircuitBreaker = Nothing,
                httpEnvFailureBudget = Nothing,
                httpEnvRequestLimiter = Nothing,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Nothing
              }
      served <- newIORef (0 :: Int)
      let application _ respond = do
            modifyIORef' served (+ 1)
            respond (responseLBS status503 [] "")
      Warp.testWithApplication (pure application) $ \serverPort -> do
        req <- parseRequest (concat ["POST http://127.0.0.1:", show serverPort, "/"])
        _ <- runNoLoggingT (httpCall env req)
        readIORef served `shouldReturn` 1
        writeIORef served 0
        _ <- runNoLoggingT (httpCallWith RepeatableAlways env req)
        readIORef served `shouldReturn` 4

    it "reads a response that was not thrown by the env's own convention" $ do
      man <- newManager defaultManagerSettings
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 0,
                httpEnvCircuitBreaker = Nothing,
                httpEnvFailureBudget = Nothing,
                httpEnvRequestLimiter = Nothing,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Just RateLimitHeadersRateLimitReset
              }
      let application _ respond = respond (responseLBS status403 [("X-RateLimit-Remaining", "0")] "")
      Warp.testWithApplication (pure application) $ \serverPort -> do
        req <- parseRequest (concat ["http://127.0.0.1:", show serverPort, "/"])
        result <- runNoLoggingT (httpCall env req)
        case result of
          Right response -> responseStatus response `shouldBe` status403
          Left _ -> expectationFailure "expected the 403 itself"

    it "reads the wait of a response that was not thrown by the env's own convention" $ do
      man <- newManager defaultManagerSettings
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 0,
                httpEnvCircuitBreaker = Nothing,
                httpEnvFailureBudget = Nothing,
                httpEnvRequestLimiter = Nothing,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Just RateLimitHeadersRateLimitReset
              }
      let application _ respond = respond (responseLBS status429 [("RateLimit", "\"default\";r=0;t=600")] "")
      Warp.testWithApplication (pure application) $ \serverPort -> do
        req <- parseRequest (concat ["http://127.0.0.1:", show serverPort, "/"])
        result <- runNoLoggingT (httpCall env req)
        case result of
          Left (HttpEnvErrorRateLimited quotaWait _) -> quotaWait `shouldBe` 60
          _ -> expectationFailure "expected a spent quota"

    it "reads the wait of a response that was not thrown by no convention but the env's" $ do
      man <- newManager defaultManagerSettings
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 0,
                httpEnvCircuitBreaker = Nothing,
                httpEnvFailureBudget = Nothing,
                httpEnvRequestLimiter = Nothing,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Just RateLimitHeadersStructured
              }
      let application _ respond = respond (responseLBS status429 [("RateLimit-Reset", "9999999999")] "")
      Warp.testWithApplication (pure application) $ \serverPort -> do
        req <- parseRequest (concat ["http://127.0.0.1:", show serverPort, "/"])
        result <- runNoLoggingT (httpCall env req)
        case result of
          Left (HttpEnvErrorRateLimited quotaWait _) -> quotaWait `shouldBe` 60
          _ -> expectationFailure "expected a spent quota"

    it "tells a spent quota apart in a response that was not thrown" $ do
      man <- newManager defaultManagerSettings
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 0,
                httpEnvCircuitBreaker = Nothing,
                httpEnvFailureBudget = Nothing,
                httpEnvRequestLimiter = Nothing,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Just RateLimitHeadersRateLimitReset
              }
      let application _ respond = respond (responseLBS status429 [("Retry-After", "120")] (LB.replicate 2000 120))
      Warp.testWithApplication (pure application) $ \serverPort -> do
        req <- parseRequest (concat ["http://127.0.0.1:", show serverPort, "/"])
        result <- runNoLoggingT (httpCall env req)
        case result of
          Left (HttpEnvErrorRateLimited quotaWait (HttpExceptionRequest _ (StatusCodeException response body))) -> do
            quotaWait `shouldBe` 125
            responseStatus response `shouldBe` status429
            body `shouldBe` SB.replicate 1024 120
          _ -> expectationFailure "expected a spent quota"

    it "counts a spent quota as an answer, which resets the breaker's count of failures" $ do
      man <- newManager defaultManagerSettings
      breaker <- runNoLoggingT (newCircuitBreaker "test" defaultCircuitBreakerSettings {circuitBreakerSettingsFailureThreshold = 3})
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 0,
                httpEnvCircuitBreaker = Just breaker,
                httpEnvFailureBudget = Nothing,
                httpEnvRequestLimiter = Nothing,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Just RateLimitHeadersRateLimitReset
              }
      let answering status _ respond = respond (responseLBS status [] "")
      Warp.testWithApplication (pure (answering status503)) $ \failingPort ->
        Warp.testWithApplication (pure (answering status429)) $ \limitingPort -> do
          failing <- parseUrlThrow (concat ["http://127.0.0.1:", show failingPort, "/"])
          limiting <- parseUrlThrow (concat ["http://127.0.0.1:", show limitingPort, "/"])
          _ <- runNoLoggingT (httpCall env failing)
          readCircuitBreakerState breaker `shouldReturn` CircuitStateClosed 1
          _ <- runNoLoggingT (httpCall env limiting)
          readCircuitBreakerState breaker `shouldReturn` CircuitStateClosed 0

    it "paces a limiter from Network.HTTP.Env.Pacing at its rate in requests" $ do
      man <- newManager defaultManagerSettings
      limiters <- newKeyedLimiters 1
      limiter <- keyedLimiter limiters ()
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 0,
                httpEnvCircuitBreaker = Nothing,
                httpEnvFailureBudget = Nothing,
                httpEnvRequestLimiter = Just limiter,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Nothing
              }
      let answering _ respond = respond (responseLBS status200 [] "")
      Warp.testWithApplication (pure answering) $ \serverPort -> do
        req <- parseUrlThrow (concat ["http://127.0.0.1:", show serverPort, "/"])
        replicateM_ 50 (runNoLoggingT (httpCall env req))
        result <- timeout 200000 (runNoLoggingT (httpCall env req))
        result `shouldSatisfy` isNothing

    it "tells a spent quota apart, counting it against neither the breaker nor the budget" $ do
      man <- newManager defaultManagerSettings
      breaker <- runNoLoggingT (newCircuitBreaker "test" defaultCircuitBreakerSettings {circuitBreakerSettingsFailureThreshold = 1})
      budget <- newFailureBudget defaultFailureBudgetSettings {failureBudgetSettingsFailures = 1}
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 2,
                httpEnvCircuitBreaker = Just breaker,
                httpEnvFailureBudget = Just budget,
                httpEnvRequestLimiter = Nothing,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Just RateLimitHeadersRateLimitReset
              }
      served <- newIORef (0 :: Int)
      let application _ respond = do
            modifyIORef' served (+ 1)
            respond (responseLBS status429 [("Retry-After", "120")] "")
      Warp.testWithApplication (pure application) $ \serverPort -> do
        req <- parseUrlThrow (concat ["http://127.0.0.1:", show serverPort, "/"])
        result <- runNoLoggingT (httpCall env req)
        case result of
          Left (HttpEnvErrorRateLimited quotaWait _) -> quotaWait `shouldBe` 125
          _ -> expectationFailure "expected a spent quota"
        readIORef served `shouldReturn` 1
        peekHttpEnv env
          `shouldReturn` HttpEnvReport
            { httpEnvReportCircuit = Just CircuitReportClosed,
              httpEnvReportFailureBudget =
                Just
                  FailureBudgetReport
                    { failureBudgetReportFailures = 0,
                      failureBudgetReportStatus = FailureBudgetStatusWithin
                    }
            }

    it "surfaces a connection failure when there is no circuit breaker" $ do
      man <- newManager defaultManagerSettings
      req <- parseRequest "http://127.0.0.1:1/"
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 0,
                httpEnvCircuitBreaker = Nothing,
                httpEnvFailureBudget = Nothing,
                httpEnvRequestLimiter = Nothing,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Nothing
              }
      r <- runNoLoggingT (httpCall env req)
      r `shouldSatisfy` isLeft

    it "logs every attempt that fails to connect at warn, once" $ do
      man <- newManager defaultManagerSettings
      req <- parseRequest "http://127.0.0.1:1/"
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 1,
                httpEnvCircuitBreaker = Nothing,
                httpEnvFailureBudget = Nothing,
                httpEnvRequestLimiter = Nothing,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Nothing
              }
      logsRef <- newIORef Seq.empty
      let captureLogger _loc _source level _msg =
            atomicModifyIORef' logsRef (\logs -> (logs Seq.|> level, ()))
      _ <- runLoggingT (httpCall env req) captureLogger
      toList <$> readIORef logsRef
        `shouldReturn` [LevelInfo, LevelWarn, LevelInfo, LevelWarn]

    it "counts each failed attempt against the failure budget" $ do
      man <- newManager defaultManagerSettings
      budget <- newFailureBudget defaultFailureBudgetSettings
      req <- parseRequest "http://127.0.0.1:1/"
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 1,
                httpEnvCircuitBreaker = Nothing,
                httpEnvFailureBudget = Just budget,
                httpEnvRequestLimiter = Nothing,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Nothing
              }
      _ <- runNoLoggingT (httpCall env req)
      peekHttpEnv env
        `shouldReturn` HttpEnvReport
          { httpEnvReportCircuit = Nothing,
            httpEnvReportFailureBudget =
              Just
                FailureBudgetReport
                  { failureBudgetReportFailures = 2,
                    failureBudgetReportStatus = FailureBudgetStatusWithin
                  }
          }

    it "trips the circuit breaker after repeated connection failures, then fails fast" $ do
      man <- newManager defaultManagerSettings
      breaker <-
        runNoLoggingT
          ( newCircuitBreaker
              "test"
              ( CircuitBreakerSettings
                  { circuitBreakerSettingsFailureThreshold = 2,
                    circuitBreakerSettingsResetTimeout = 3600
                  }
              )
          )
      req <- parseRequest "http://127.0.0.1:1/"
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 0,
                httpEnvCircuitBreaker = Just breaker,
                httpEnvFailureBudget = Nothing,
                httpEnvRequestLimiter = Nothing,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Nothing
              }
      (r1, r2, r3) <- runNoLoggingT $ do
        a <- httpCall env req
        b <- httpCall env req
        c <- httpCall env req
        pure (a, b, c)
      r1 `shouldSatisfy` isLeft
      r2 `shouldSatisfy` isLeft
      r3 `shouldSatisfy` \case
        Left HttpEnvErrorCircuitOpen -> True
        _ -> False

    it "counts each attempt against the breaker, so a retry budget cannot outrun the threshold" $ do
      man <- newManager defaultManagerSettings
      breaker <-
        runNoLoggingT
          ( newCircuitBreaker
              "test"
              ( CircuitBreakerSettings
                  { circuitBreakerSettingsFailureThreshold = 3,
                    circuitBreakerSettingsResetTimeout = 3600
                  }
              )
          )
      served <- newIORef (0 :: Int)
      let application _ respond = do
            atomicModifyIORef' served (\n -> (n + 1, ()))
            respond (responseLBS status503 [] "unavailable")
      Warp.testWithApplication (pure application) $ \servedPort -> do
        req <- parseRequest (concat ["http://127.0.0.1:", show servedPort, "/"])
        let env =
              HttpEnv
                { httpEnvManager = man,
                  httpEnvRetryPolicy = limitRetries 10,
                  httpEnvCircuitBreaker = Just breaker,
                  httpEnvFailureBudget = Nothing,
                  httpEnvRequestLimiter = Nothing,
                  httpEnvLogPolicy = defaultLogPolicy,
                  httpEnvRateLimitHeaders = Nothing
                }
        r1 <- runNoLoggingT (httpCall env req)
        context "requests the dependency was asked to serve before the breaker opened" $
          readIORef served `shouldReturn` 3
        case r1 of
          Right response -> responseStatus response `shouldBe` status503
          Left HttpEnvErrorCircuitOpen -> expectationFailure "the call was attempted, so it must not report the breaker's fast-fail"
          Left (HttpEnvErrorFailed e) -> expectationFailure (unwords ["expected the server's own 503, got", show e])
          Left (HttpEnvErrorRateLimited _ e) -> expectationFailure (unwords ["expected the server's own 503, got a spent quota:", show e])

        r2 <- runNoLoggingT (httpCall env req)
        context "requests after the breaker opened" $
          readIORef served `shouldReturn` 3
        r2 `shouldSatisfy` \case
          Left HttpEnvErrorCircuitOpen -> True
          _ -> False

    it "waits on the token limiter before attempting the request" $ do
      man <- newManager defaultManagerSettings
      req <- parseRequest "http://127.0.0.1:1/"
      limiter <- newRequestLimiter 1
      let env =
            HttpEnv
              { httpEnvManager = man,
                httpEnvRetryPolicy = limitRetries 0,
                httpEnvCircuitBreaker = Nothing,
                httpEnvFailureBudget = Nothing,
                httpEnvRequestLimiter = Just limiter,
                httpEnvLogPolicy = defaultLogPolicy,
                httpEnvRateLimitHeaders = Nothing
              }
      replicateM_ 50 (runNoLoggingT (httpCall env req))
      result <- timeout 200000 (runNoLoggingT (httpCall env req))
      result `shouldSatisfy` isNothing