packages feed

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

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}

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

import Control.Exception (ErrorCall (..), SomeException, throwIO, toException, try)
import Control.Monad (void)
import Control.Monad.Logger.CallStack (LogLevel (..), fromLogStr, runLoggingT, runNoLoggingT)
import Control.Retry (limitRetries)
import qualified Data.ByteString.Lazy as LB
import Data.Foldable (toList)
import Data.IORef (modifyIORef', newIORef, readIORef)
import qualified Data.Sequence as Seq
import qualified Data.Set as Set
import Data.Streaming.Zlib (ZlibException (..))
import qualified Data.Text as Text
import qualified Data.Text.Encoding as TE
import Network.HTTP.Client
import Network.HTTP.Client.Internal (Response (..), ResponseClose (..), throwHttp)
import Network.HTTP.Env.HttpClient.Retry
import Network.HTTP.Env.LogPolicy
import Network.HTTP.Types (Status, http11, mkStatus, status200, status400, status404, status502, status503)
import Network.Wai (responseLBS)
import qualified Network.Wai.Handler.Warp as Warp
import Test.Syd

spec :: Spec
spec = do
  let apiKeyPolicy :: LogPolicy
      apiKeyPolicy =
        defaultLogPolicy
          { logPolicyHeadersToRedact = Set.insert "X-Api-Key" defaultHeadersToRedact
          }

  -- [ref:NoUnscrubbedHttpException]
  -- Nothing listens on port 1 of the loopback interface, so this fails at once.
  let secretRequest =
        defaultRequest
          { host = "127.0.0.1",
            port = 1,
            requestHeaders =
              [ ("Content-Type", "text/plain"),
                ("X-Api-Key", "wnxczrmtabdywlrw")
              ]
          }

  let responseWithStatus :: Status -> Response LB.ByteString
      responseWithStatus status =
        Response
          { responseStatus = status,
            responseVersion = http11,
            responseHeaders = [],
            responseBody = "body",
            responseCookieJar = mempty,
            responseClose' = ResponseClose (pure ()),
            responseOriginalRequest = defaultRequest,
            responseEarlyHints = []
          }

  describe "shouldRetryStatusCode" $
    it "says a 5xx is worth retrying and nothing else is" $
      map
        (shouldRetryStatusCode . (`mkStatus` ""))
        [200, 399, 404, 499, 500, 503, 599, 600]
        `shouldBe` [False, False, False, False, True, True, True, False]

  describe "shouldRetryHttpResponse" $ do
    it "retries a response that says the server is faulty" $
      shouldRetryHttpResponse (responseWithStatus status503) `shouldBe` True
    it "does not retry a response that says no" $
      shouldRetryHttpResponse (responseWithStatus status404) `shouldBe` False

  describe "shouldRetryHttpException" $ do
    it "does not retry a URL that could not be parsed" $
      shouldRetryHttpException (InvalidUrlException "nonsense" "invalid") `shouldBe` False
    it "retries a thrown 5xx" $
      shouldRetryHttpException
        (HttpExceptionRequest defaultRequest (StatusCodeException (void (responseWithStatus status503)) ""))
        `shouldBe` True
    it "does not retry a thrown 4xx" $
      shouldRetryHttpException
        (HttpExceptionRequest defaultRequest (StatusCodeException (void (responseWithStatus status404)) ""))
        `shouldBe` False
    it "retries every failure of the connection or of the response arriving" $
      map
        (shouldRetryHttpException . HttpExceptionRequest defaultRequest)
        [ ResponseTimeout,
          ConnectionTimeout,
          ConnectionFailure (toException (userError "refused")),
          InternalException (toException (userError "internal")),
          ProxyConnectException "proxy.example.com" 8080 status503,
          NoResponseDataReceived,
          ResponseBodyTooShort 10 5,
          InvalidChunkHeaders,
          IncompleteHeaders,
          HttpZlibException (ZlibException (-3)),
          ConnectionClosed
        ]
        `shouldBe` replicate 11 True
    it "does not retry a request that was refused before it was sent" $
      map
        (shouldRetryHttpException . HttpExceptionRequest defaultRequest)
        [ TooManyRedirects [],
          OverlongHeaders,
          InvalidStatusLine "nonsense"
        ]
        `shouldBe` [False, False, False]

  describe "describeHttpFault" $ do
    it "describes a 5xx response, rendered through the policy" $
      describeHttpFault apiKeyPolicy (Right (responseWithStatus status503))
        `shouldBe` Just (renderResponseForLogging apiKeyPolicy (responseWithStatus status503))
    it "does not describe a response that says no" $
      describeHttpFault apiKeyPolicy (Right (responseWithStatus status404)) `shouldBe` Nothing
    it "does not describe a success" $
      describeHttpFault apiKeyPolicy (Right (responseWithStatus status200)) `shouldBe` Nothing
    it "describes a connection failure, rendered through the policy" $ do
      let exception = HttpExceptionRequest secretRequest ConnectionTimeout
      describeHttpFault apiKeyPolicy (Left exception)
        `shouldBe` Just (renderHttpExceptionForLogging apiKeyPolicy exception)
    it "does not describe a URL that could not be parsed" $
      describeHttpFault apiKeyPolicy (Left (InvalidUrlException "nonsense" "invalid")) `shouldBe` Nothing

  describe "catchAsHttpException" $ do
    it "lets an error call through rather than calling it a failed request" $ do
      thrown <- try (catchAsHttpException apiKeyPolicy secretRequest (throwIO (ErrorCall "a bug in a client library") :: IO ()))
      case thrown of
        Left (ErrorCall message) -> message `shouldBe` "a bug in a client library"
        Right errOrUnit -> expectationFailure (unwords ["expected the error call to propagate, got", show @(Either HttpException ()) errOrUnit])

    it "hands back an exception with the credential header redacted" $ do
      man <- newManager defaultManagerSettings
      errOrUnit <- catchAsHttpException apiKeyPolicy secretRequest (void (httpLbs secretRequest man))
      case errOrUnit :: Either HttpException () of
        Right () -> expectationFailure "expected the action to throw"
        Left err -> do
          let shown = Text.pack (show @HttpException err)
          Text.isInfixOf "wnxczrmtabdywlrw" shown `shouldBe` False
          Text.isInfixOf "<REDACTED>" shown `shouldBe` True
          Text.isInfixOf "text/plain" shown `shouldBe` True

    it "folds a socket error into a failed request" $ do
      errOrUnit <-
        catchAsHttpException apiKeyPolicy secretRequest $
          throwIO (userError "connection reset")
      case errOrUnit :: Either HttpException () of
        Left (HttpExceptionRequest _ (InternalException e)) ->
          Text.isInfixOf "connection reset" (Text.pack (show @SomeException e)) `shouldBe` True
        other -> expectationFailure (unwords ["expected an internal exception, got", show @(Either HttpException ()) other])

    it "folds http-client's request-less failure into a failed request" $ do
      errOrUnit <-
        catchAsHttpException apiKeyPolicy secretRequest $
          throwHttp ConnectionClosed
      case errOrUnit :: Either HttpException () of
        Left (HttpExceptionRequest _ ConnectionClosed) -> pure ()
        other -> expectationFailure (unwords ["expected a closed connection, got", show @(Either HttpException ()) other])

  describe "catchConnectionException" $ do
    it "hands back an exception with the credential header redacted" $ do
      man <- newManager defaultManagerSettings
      errOrUnit <- catchConnectionException apiKeyPolicy (void (httpLbs secretRequest man))
      case errOrUnit :: Either SomeException () of
        Right () -> expectationFailure "expected the action to throw"
        Left err -> do
          let shown = Text.pack (show @SomeException err)
          Text.isInfixOf "wnxczrmtabdywlrw" shown `shouldBe` False
          Text.isInfixOf "<REDACTED>" shown `shouldBe` True

    it "hands back a socket error" $ do
      errOrUnit <- catchConnectionException apiKeyPolicy (throwIO (userError "connection reset"))
      case errOrUnit :: Either SomeException () of
        Left err -> Text.isInfixOf "connection reset" (Text.pack (show @SomeException err)) `shouldBe` True
        Right () -> expectationFailure "expected the action to throw"

    it "lets an error call through" $ do
      thrown <- try (catchConnectionException apiKeyPolicy (throwIO (ErrorCall "a bug") :: IO ()))
      case thrown of
        Left (ErrorCall message) -> message `shouldBe` "a bug"
        Right _ -> expectationFailure "expected the error call to propagate"

  describe "exceptionRepeatSafety" $ do
    it "says a request that could not connect never left" $ do
      request <- parseRequest "POST http://127.0.0.1:1/"
      map
        (exceptionRepeatSafety . HttpExceptionRequest request)
        [ConnectionFailure (toException (userError "refused")), ConnectionTimeout, ProxyConnectException "proxy" 8080 status502]
        `shouldBe` [RepeatSafetySafe, RepeatSafetySafe, RepeatSafetySafe]
    it "says nothing of a request that may have arrived" $ do
      request <- parseRequest "POST http://127.0.0.1:1/"
      map
        (exceptionRepeatSafety . HttpExceptionRequest request)
        [ResponseTimeout, ConnectionClosed, NoResponseDataReceived]
        `shouldBe` [RepeatSafetyUnsafe, RepeatSafetyUnsafe, RepeatSafetyUnsafe]
    it "says nothing of a URL that could not be read" $
      exceptionRepeatSafety (InvalidUrlException "nope" "bad") `shouldBe` RepeatSafetyUnsafe

  describe "methodRepeatSafety" $ do
    it "calls the methods RFC 9110 calls idempotent idempotent" $
      map methodRepeatSafety ["GET", "HEAD", "OPTIONS", "TRACE", "PUT", "DELETE"]
        `shouldBe` replicate 6 RepeatSafetySafe
    it "calls the others not idempotent" $
      map methodRepeatSafety ["POST", "PATCH", "CONNECT"]
        `shouldBe` replicate 3 RepeatSafetyUnsafe

  describe "headersRepeatSafety" $ do
    it "may repeat a request that carries an idempotency key" $
      headersRepeatSafety [("Content-Type", "text/plain"), ("Idempotency-Key", "cbfhzlwqmvsxkdte")]
        `shouldBe` RepeatSafetySafe
    it "must not repeat a request without one" $
      headersRepeatSafety [("Content-Type", "text/plain")] `shouldBe` RepeatSafetyUnsafe

  describe "requestRepeatSafety" $ do
    it "may repeat an idempotent method or a request with an idempotency key" $
      [requestRepeatSafety "PUT" [], requestRepeatSafety "POST" [("Idempotency-Key", "cbfhzlwqmvsxkdte")]]
        `shouldBe` [RepeatSafetySafe, RepeatSafetySafe]
    it "must not repeat a POST without a key" $
      requestRepeatSafety "POST" [] `shouldBe` RepeatSafetyUnsafe

  describe "httpRepeatSafety" $ do
    it "may repeat anything when the call says it may" $ do
      request <- parseRequest "POST http://127.0.0.1:1/"
      map (httpRepeatSafety RepeatableAlways request) [Left (InvalidUrlException "nope" "bad"), Right ()]
        `shouldBe` [RepeatSafetySafe, RepeatSafetySafe]
    it "may repeat a POST that never left" $ do
      request <- parseRequest "POST http://127.0.0.1:1/"
      httpRepeatSafety RepeatableIfIdempotent request (Left (HttpExceptionRequest request ConnectionTimeout) :: Either HttpException ())
        `shouldBe` RepeatSafetySafe
    it "must not repeat a POST that may have arrived" $ do
      request <- parseRequest "POST http://127.0.0.1:1/"
      map (httpRepeatSafety RepeatableIfIdempotent request) [Left (HttpExceptionRequest request ResponseTimeout), Right ()]
        `shouldBe` [RepeatSafetyUnsafe, RepeatSafetyUnsafe]
    it "may repeat a request with an idempotency key that may have arrived" $ do
      request <- parseRequest "POST http://127.0.0.1:1/"
      let keyed = request {requestHeaders = [("Idempotency-Key", "cbfhzlwqmvsxkdte")]}
      httpRepeatSafety RepeatableIfIdempotent keyed (Left (HttpExceptionRequest keyed ResponseTimeout) :: Either HttpException ())
        `shouldBe` RepeatSafetySafe

  describe "httpLbsWithRetry" $ do
    let serving status = pure $ \_ respond -> respond (responseLBS status [] "body")
    let warningsWhile status policy = do
          man <- newManager defaultManagerSettings
          Warp.testWithApplication (serving status) $ \serverPort -> do
            request <- parseRequest (concat ["http://127.0.0.1:", show serverPort, "/path?client_secret=hunter2"])
            warningsRef <- newIORef Seq.empty
            let capture _ _ level message =
                  case level of
                    LevelWarn -> modifyIORef' warningsRef (Seq.|> TE.decodeUtf8Lenient (fromLogStr message))
                    _ -> pure ()
            _ <- runLoggingT (httpLbsWithRetry apiKeyPolicy Nothing Nothing policy RepeatableIfIdempotent request man) capture
            warnings <- toList <$> readIORef warningsRef
            pure (serverPort, warnings)

    it "does not send a POST again after a fault it throws" $ do
      man <- newManager defaultManagerSettings
      served <- newIORef (0 :: Int)
      let application _ respond = do
            modifyIORef' served (+ 1)
            respond (responseLBS status503 [] "")
      Warp.testWithApplication (pure application) $ \serverPort -> do
        request <- parseUrlThrow (concat ["POST http://127.0.0.1:", show serverPort, "/"])
        _ <- runNoLoggingT (httpLbsWithRetry apiKeyPolicy Nothing Nothing (limitRetries 3) RepeatableIfIdempotent request man)
        readIORef served `shouldReturn` 1

    it "sends a POST that carries an idempotency key again after a fault" $ do
      man <- newManager defaultManagerSettings
      served <- newIORef (0 :: Int)
      let application _ respond = do
            modifyIORef' served (+ 1)
            respond (responseLBS status503 [] "")
      Warp.testWithApplication (pure application) $ \serverPort -> do
        request <- parseRequest (concat ["POST http://127.0.0.1:", show serverPort, "/"])
        let keyed = request {requestHeaders = [("Idempotency-Key", "cbfhzlwqmvsxkdte")]}
        _ <- runNoLoggingT (httpLbsWithRetry apiKeyPolicy Nothing Nothing (limitRetries 3) RepeatableIfIdempotent keyed man)
        readIORef served `shouldReturn` 4

    it "sends a POST again when it could not connect" $ do
      man <- newManager defaultManagerSettings
      request <- parseRequest "POST http://127.0.0.1:1/"
      warningsRef <- newIORef (0 :: Int)
      let capture _ _ level _ = case level of
            LevelWarn -> modifyIORef' warningsRef (+ 1)
            _ -> pure ()
      _ <- runLoggingT (httpLbsWithRetry apiKeyPolicy Nothing Nothing (limitRetries 3) RepeatableIfIdempotent request man) capture
      readIORef warningsRef `shouldReturn` 4

    it "warns about a response that says no, with the query string scrubbed" $ do
      (servedPort, warnings) <- warningsWhile status404 (limitRetries 0)
      warnings
        `shouldBe` [Text.pack (unwords ["404 status code while fetching", concat ["http://127.0.0.1:", show servedPort, "/path?client_secret=~REDACTED~"]])]

    it "warns about the smallest status that says no" $ do
      (servedPort, warnings) <- warningsWhile status400 (limitRetries 0)
      warnings
        `shouldBe` [Text.pack (unwords ["400 status code while fetching", concat ["http://127.0.0.1:", show servedPort, "/path?client_secret=~REDACTED~"]])]

    it "does not warn about a success" $ do
      (_, warnings) <- warningsWhile status200 (limitRetries 0)
      warnings `shouldBe` []

    it "warns about a faulty response only once, as a fault" $ do
      (_, warnings) <- warningsWhile status503 (limitRetries 0)
      -- A prefix, because the response carries the date it was served.
      map (Text.isPrefixOf "Request attempt 1 failed: Response {responseStatus = Status {statusCode = 503") warnings
        `shouldBe` [True]

    it "warns about each attempt once, saying which it was" $ do
      (_, warnings) <- warningsWhile status503 (limitRetries 1)
      map (Text.takeWhile (/= ':')) warnings
        `shouldBe` ["Request attempt 1 failed", "Request attempt 2 failed"]