http-env-gen-0.0.0.0: test/Network/HTTP/Env/Servant/RetrySpec.hs
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
module Network.HTTP.Env.Servant.RetrySpec (spec) where
import Control.Exception (toException)
import Control.Monad.Logger.CallStack
import Control.Retry (limitRetries)
import qualified Data.ByteString.Lazy as LB
import Data.Foldable (toList)
import Data.IORef
import Data.Proxy (Proxy (..))
import qualified Data.Sequence as Seq
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.Encoding as TE
import qualified Network.HTTP.Client as HTTP
import Network.HTTP.Env.CircuitBreaker
import Network.HTTP.Env.HttpClient.Retry (RepeatSafety (..), Repeatable (..))
import Network.HTTP.Env.LogPolicy
import Network.HTTP.Env.Servant.Retry (clientErrorRepeatSafety, clientRepeatSafety, describeClientFault, renderClientErrorForLogging, runClientMWithRetries, runStreamingClientMWithRetries, scrubClientError, shouldRetryClientError)
import Network.HTTP.Types
import Network.Wai (responseLBS)
import qualified Network.Wai.Handler.Warp as Warp
import Servant.API (Get, JSON, (:>))
import qualified Servant.API as API
import qualified Servant.Client as Oneshot
import Servant.Client.Core
import qualified Servant.Client.Streaming as Streaming
import Test.Syd
type NumberAPI = API.Header "X-Api-Key" Text :> Get '[JSON] Int
type TokenAPI = API.QueryParam "access_token" Text :> Get '[JSON] Int
spec :: Spec
spec = do
let apiKeyPolicy :: LogPolicy
apiKeyPolicy =
defaultLogPolicy
{ logPolicyHeadersToRedact = Set.insert "X-Api-Key" defaultHeadersToRedact
}
let failureResponseWith :: Status -> ClientError
failureResponseWith status =
FailureResponse
Request
{ requestPath = (BaseUrl Https "cache.nixos.org" 443 "", "/nar/whatever.nar.xz"),
requestQueryString = mempty,
requestBody = Nothing,
requestAccept = mempty,
requestHeaders = mempty,
requestHttpVersion = http11,
requestMethod = methodHead
}
Response
{ responseStatusCode = status,
responseHeaders = mempty,
responseHttpVersion = http11,
responseBody = ""
}
let failureResponseWithHeader :: Status -> ClientError
failureResponseWithHeader status =
case failureResponseWith status of
FailureResponse request response ->
FailureResponse request {requestHeaders = Seq.fromList [("X-Api-Key", "wnxczrmtabdywlrw")]} response
other -> other
describe "scrubClientError" $ do
it "redacts a credential header but keeps the others" $
scrubClientError
apiKeyPolicy
( FailureResponse
Request
{ requestPath = (BaseUrl Https "api.example.com" 443 "", "/job/some-uuid/started"),
requestQueryString = mempty,
requestBody = Nothing,
requestAccept = mempty,
requestHeaders =
Seq.fromList
[ ("Content-Type", "dec"),
("X-Api-Key", "wnxczrmtabdywlrw")
],
requestHttpVersion = http11,
requestMethod = methodPut
}
Response
{ responseStatusCode = status401,
responseHeaders = Seq.fromList [("Server", "nginx"), ("Set-Cookie", "session=hunter2")],
responseHttpVersion = http11,
responseBody = ""
}
)
`shouldBe` FailureResponse
Request
{ requestPath = (BaseUrl Https "api.example.com" 443 "", "/job/some-uuid/started"),
requestQueryString = mempty,
requestBody = Nothing,
requestAccept = mempty,
requestHeaders =
Seq.fromList
[ ("Content-Type", "dec"),
("X-Api-Key", "<REDACTED>")
],
requestHttpVersion = http11,
requestMethod = methodPut
}
Response
{ responseStatusCode = status401,
responseHeaders = Seq.fromList [("Server", "nginx"), ("Set-Cookie", "<REDACTED>")],
responseHttpVersion = http11,
responseBody = ""
}
it "drops a header nobody has vouched for" $
scrubClientError
apiKeyPolicy
( InvalidContentTypeHeader
Response
{ responseStatusCode = status500,
responseHeaders = Seq.fromList [("X-Some-New-Header", "whatever")],
responseHttpVersion = http11,
responseBody = ""
}
)
`shouldBe` InvalidContentTypeHeader
Response
{ responseStatusCode = status500,
responseHeaders = mempty,
responseHttpVersion = http11,
responseBody = ""
}
describe "renderClientErrorForLogging" $ do
let readable =
Response
{ responseStatusCode = status200,
responseHeaders = mempty,
responseHttpVersion = http11,
responseBody = "bodysecretvalue"
}
it "withholds a body whose content type it could not use" $
map
(Text.isInfixOf "bodysecretvalue" . Text.pack . renderClientErrorForLogging defaultLogPolicy)
[UnsupportedContentType "text/plain" readable, InvalidContentTypeHeader readable]
`shouldBe` [False, False]
describe "what runClientMWithRetries logs and returns" $ do
let runAgainst :: Status -> LB.ByteString -> Oneshot.ClientM Int -> IO (Either (CircuitBreakerError ClientError) Int, [Text])
runAgainst status body client = do
man <- HTTP.newManager HTTP.defaultManagerSettings
let application _ respond = respond (responseLBS status [("Content-Type", "application/json")] body)
Warp.testWithApplication (pure application) $ \port -> do
(result, logs) <-
runWriterLoggingT $
runClientMWithRetries defaultLogPolicy Nothing Nothing (const LevelError) (limitRetries 1) RepeatableIfIdempotent client (Oneshot.mkClientEnv man (BaseUrl Http "127.0.0.1" port ""))
pure (result, [TE.decodeUtf8Lenient (fromLogStr msg) | (_, _, _, msg) <- logs])
it "leaves a credential in the query string out of what it logs and returns" $ do
(result, logged) <- runAgainst status500 "" (Oneshot.client (Proxy @TokenAPI) (Just "qpsecretvalue"))
logged `shouldNotBe` []
filter (Text.isInfixOf "qpsecretvalue") (Text.pack (show result) : logged) `shouldBe` []
it "leaves a body it could not decode out of what it logs" $ do
(_, logged) <- runAgainst status200 "{\"access_token\":\"bodysecretvalue\"}" (Oneshot.client (Proxy @TokenAPI) Nothing)
logged `shouldNotBe` []
filter (Text.isInfixOf "bodysecretvalue") logged `shouldBe` []
it "cuts a long body short in what it logs" $ do
(_, logged) <- runAgainst status500 (LB.replicate 1000000 120) (Oneshot.client (Proxy @TokenAPI) Nothing)
logged `shouldNotBe` []
filter ((> 4096) . Text.length) logged `shouldBe` []
describe "runClientMWithRetries" $ do
let withServer :: Status -> (IORef Int -> Oneshot.ClientEnv -> IO ()) -> IO ()
withServer status act = do
served <- newIORef 0
man <- HTTP.newManager HTTP.defaultManagerSettings
let application _ respond = do
atomicModifyIORef' served (\n -> (n + 1, ()))
respond (responseLBS status [("Content-Type", "application/json")] "1")
Warp.testWithApplication (pure application) $ \port ->
act served (Oneshot.mkClientEnv man (BaseUrl Http "127.0.0.1" port ""))
let numberClient :: Oneshot.ClientM Int
numberClient = Oneshot.client (Proxy @NumberAPI) (Just "wnxczrmtabdywlrw")
let newBreaker :: Word -> IO CircuitBreakerEnv
newBreaker threshold =
runNoLoggingT
( newCircuitBreaker
"test"
( CircuitBreakerSettings
{ circuitBreakerSettingsFailureThreshold = threshold,
circuitBreakerSettingsResetTimeout = 3600
}
)
)
let statusOf :: Either (CircuitBreakerError ClientError) Int -> Maybe Status
statusOf = \case
Left (CircuitBreakerErrorUnderlying (FailureResponse _ response)) -> Just (responseStatusCode response)
_ -> Nothing
it "never writes a credential header to the log" $
withServer status401 $ \_ clientEnv -> do
(_, logs) <-
runWriterLoggingT $
runClientMWithRetries apiKeyPolicy Nothing Nothing (const LevelError) (limitRetries 3) RepeatableIfIdempotent numberClient clientEnv
[() | (_, _, _, msg) <- logs, Text.isInfixOf "wnxczrmtabdywlrw" (TE.decodeUtf8Lenient (fromLogStr msg))]
`shouldBe` []
logs `shouldNotBe` []
it "hands back the error scrubbed" $
withServer status404 $ \_ clientEnv -> do
result <-
runNoLoggingT $
runClientMWithRetries apiKeyPolicy Nothing Nothing (const LevelError) (limitRetries 0) RepeatableIfIdempotent numberClient clientEnv
case result of
Left (CircuitBreakerErrorUnderlying (FailureResponse request _)) ->
lookup "X-Api-Key" (toList (requestHeaders request)) `shouldBe` Just "<REDACTED>"
_ -> expectationFailure "expected the server's own 404"
it "logs an error at the error level the caller assigns" $
withServer status404 $ \_ clientEnv -> do
(result, logs) <-
runWriterLoggingT $
runClientMWithRetries apiKeyPolicy Nothing Nothing (const LevelError) (limitRetries 3) RepeatableIfIdempotent numberClient clientEnv
statusOf result `shouldBe` Just status404
[() | (_, _, LevelError, _) <- logs] `shouldBe` [()]
it "logs an error at warn when the caller assigns it a lower level" $
withServer status404 $ \_ clientEnv -> do
let errLevel = \case
FailureResponse _ response | responseStatusCode response == status404 -> LevelWarn
_ -> LevelError
(result, logs) <-
runWriterLoggingT $
runClientMWithRetries apiKeyPolicy Nothing Nothing errLevel (limitRetries 3) RepeatableIfIdempotent numberClient clientEnv
statusOf result `shouldBe` Just status404
[() | (_, _, LevelError, _) <- logs] `shouldBe` []
[() | (_, _, LevelWarn, _) <- logs] `shouldNotBe` []
it "logs a failure that is not a fault once, scrubbed" $
withServer status404 $ \_ clientEnv -> do
(result, logs) <-
runWriterLoggingT $
runClientMWithRetries apiKeyPolicy Nothing Nothing (const LevelError) (limitRetries 0) RepeatableIfIdempotent numberClient clientEnv
case result of
Left (CircuitBreakerErrorUnderlying scrubbed) ->
[TE.decodeUtf8Lenient (fromLogStr msg) | (_, _, _, msg) <- logs]
`shouldBe` [Text.pack (unwords ["Servant request failed:", ppShow scrubbed])]
_ -> expectationFailure "expected the server's own 404"
it "still retries a retryable error regardless of its assigned level" $
withServer status503 $ \served clientEnv -> do
(result, logs) <-
runWriterLoggingT $
runClientMWithRetries apiKeyPolicy Nothing Nothing (const LevelWarn) (limitRetries 2) RepeatableIfIdempotent numberClient clientEnv
statusOf result `shouldBe` Just status503
readIORef served `shouldReturn` 3
[() | (_, _, LevelError, _) <- logs] `shouldBe` []
it "logs each failed attempt once, and then the outcome" $
withServer status503 $ \_ clientEnv -> do
(_, logs) <-
runWriterLoggingT $
runClientMWithRetries apiKeyPolicy Nothing Nothing (const LevelError) (limitRetries 1) RepeatableIfIdempotent numberClient clientEnv
[level | (_, _, level, _) <- logs]
`shouldBe` [LevelWarn, LevelDebug, LevelWarn, LevelError]
it "stops at the breaker's failure threshold rather than spending the whole retry budget" $
withServer status503 $ \served clientEnv -> do
breaker <- newBreaker 3
result <-
runNoLoggingT $
runClientMWithRetries apiKeyPolicy (Just breaker) Nothing (const LevelError) (limitRetries 10) RepeatableIfIdempotent numberClient clientEnv
statusOf result `shouldBe` Just status503
readIORef served `shouldReturn` 3
rejected <-
runNoLoggingT $
runClientMWithRetries apiKeyPolicy (Just breaker) Nothing (const LevelError) (limitRetries 10) RepeatableIfIdempotent numberClient clientEnv
rejected `shouldBe` Left CircuitBreakerErrorOpen
readIORef served `shouldReturn` 3
it "does not count a response that says no against the breaker" $
withServer status404 $ \served clientEnv -> do
breaker <- newBreaker 1
_ <- runNoLoggingT $ runClientMWithRetries apiKeyPolicy (Just breaker) Nothing (const LevelError) (limitRetries 0) RepeatableIfIdempotent numberClient clientEnv
second <- runNoLoggingT $ runClientMWithRetries apiKeyPolicy (Just breaker) Nothing (const LevelError) (limitRetries 0) RepeatableIfIdempotent numberClient clientEnv
statusOf second `shouldBe` Just status404
readIORef served `shouldReturn` 2
describe "runStreamingClientMWithRetries" $
it "goes through the breaker" $ do
served <- newIORef (0 :: Int)
man <- HTTP.newManager HTTP.defaultManagerSettings
let application _ respond = do
atomicModifyIORef' served (\n -> (n + 1, ()))
respond (responseLBS status503 [] "")
Warp.testWithApplication (pure application) $ \port -> do
breaker <-
runNoLoggingT
( newCircuitBreaker
"test"
( CircuitBreakerSettings
{ circuitBreakerSettingsFailureThreshold = 1,
circuitBreakerSettingsResetTimeout = 3600
}
)
)
let clientEnv = Streaming.mkClientEnv man (BaseUrl Http "127.0.0.1" port "")
let streamingNumberClient = Streaming.client (Proxy @NumberAPI) (Just "wnxczrmtabdywlrw")
_ <- runNoLoggingT $ runStreamingClientMWithRetries apiKeyPolicy (Just breaker) Nothing (const LevelError) (limitRetries 0) RepeatableIfIdempotent streamingNumberClient clientEnv
rejected <- runNoLoggingT $ runStreamingClientMWithRetries apiKeyPolicy (Just breaker) Nothing (const LevelError) (limitRetries 0) RepeatableIfIdempotent streamingNumberClient clientEnv
rejected `shouldBe` Left CircuitBreakerErrorOpen
readIORef served `shouldReturn` 1
describe "describeClientFault" $ do
it "describes a 5xx, scrubbed" $
describeClientFault apiKeyPolicy (Left (failureResponseWithHeader status503) :: Either ClientError ())
`shouldBe` Just (ppShow (scrubClientError apiKeyPolicy (failureResponseWithHeader status503)))
it "does not describe a response that says no" $
describeClientFault apiKeyPolicy (Left (failureResponseWith status404) :: Either ClientError ()) `shouldBe` Nothing
it "does not describe a success" $
describeClientFault apiKeyPolicy (Right () :: Either ClientError ()) `shouldBe` Nothing
describe "clientErrorRepeatSafety" $ do
it "may repeat a failure of an idempotent method" $
clientErrorRepeatSafety (failureResponseWith status503) `shouldBe` RepeatSafetySafe
it "may repeat a failure of a request that carries an idempotency key" $
let keyed = case failureResponseWith status503 of
FailureResponse request response ->
FailureResponse
request
{ requestMethod = methodPost,
requestHeaders = Seq.fromList [("Idempotency-Key", "cbfhzlwqmvsxkdte")]
}
response
other -> other
in clientErrorRepeatSafety keyed `shouldBe` RepeatSafetySafe
it "must not repeat a failure of a POST without a key" $
let unkeyed = case failureResponseWith status503 of
FailureResponse request response -> FailureResponse request {requestMethod = methodPost} response
other -> other
in clientErrorRepeatSafety unkeyed `shouldBe` RepeatSafetyUnsafe
it "may repeat a POST that could not connect, so never left" $ do
request <- HTTP.parseRequest "POST http://127.0.0.1:1/"
clientErrorRepeatSafety (ConnectionError (toException (HTTP.HttpExceptionRequest request HTTP.ConnectionTimeout)))
`shouldBe` RepeatSafetySafe
it "must not repeat a POST that may have arrived" $ do
request <- HTTP.parseRequest "POST http://127.0.0.1:1/"
clientErrorRepeatSafety (ConnectionError (toException (HTTP.HttpExceptionRequest request HTTP.ResponseTimeout)))
`shouldBe` RepeatSafetyUnsafe
it "may repeat a request with an idempotency key that may have arrived" $ do
request <- HTTP.parseRequest "POST http://127.0.0.1:1/"
let keyed = request {HTTP.requestHeaders = [("Idempotency-Key", "cbfhzlwqmvsxkdte")]}
clientErrorRepeatSafety (ConnectionError (toException (HTTP.HttpExceptionRequest keyed HTTP.ResponseTimeout)))
`shouldBe` RepeatSafetySafe
it "may repeat a GET that may have arrived" $ do
request <- HTTP.parseRequest "GET http://127.0.0.1:1/"
clientErrorRepeatSafety (ConnectionError (toException (HTTP.HttpExceptionRequest request HTTP.ResponseTimeout)))
`shouldBe` RepeatSafetySafe
it "must not repeat a URL that could not be read, or any other connection error" $
map
clientErrorRepeatSafety
[ ConnectionError (toException (HTTP.InvalidUrlException "nope" "bad")),
ConnectionError (toException (userError "refused"))
]
`shouldBe` [RepeatSafetyUnsafe, RepeatSafetyUnsafe]
it "must not repeat an answer it could not read, whose request it cannot tell" $ do
let someResponse =
Response
{ responseStatusCode = status200,
responseHeaders = mempty,
responseHttpVersion = http11,
responseBody = ""
}
map
clientErrorRepeatSafety
[ DecodeFailure "not json" someResponse,
UnsupportedContentType "text/plain" someResponse,
InvalidContentTypeHeader someResponse
]
`shouldBe` [RepeatSafetyUnsafe, RepeatSafetyUnsafe, RepeatSafetyUnsafe]
describe "clientRepeatSafety" $ do
it "may repeat anything when the call says it may" $
map (clientRepeatSafety RepeatableAlways) [Left (ConnectionError (toException (userError "refused"))), Right ()]
`shouldBe` [RepeatSafetySafe, RepeatSafetySafe]
it "asks the error otherwise" $
clientRepeatSafety RepeatableIfIdempotent (Left (failureResponseWith status503) :: Either ClientError ())
`shouldBe` RepeatSafetySafe
it "must not repeat a success" $
clientRepeatSafety RepeatableIfIdempotent (Right () :: Either ClientError ())
`shouldBe` RepeatSafetyUnsafe
describe "shouldRetryClientError" $ do
let someResponse =
Response
{ responseStatusCode = status200,
responseHeaders = mempty,
responseHttpVersion = http11,
responseBody = ""
}
it "retries a failure that says the server is faulty, and nothing else that came back" $
map
shouldRetryClientError
[ failureResponseWith status503,
failureResponseWith status404,
DecodeFailure "not json" someResponse,
UnsupportedContentType "text/plain" someResponse,
InvalidContentTypeHeader someResponse
]
`shouldBe` [True, False, False, False, False]
it "retries a connection error" $
shouldRetryClientError (ConnectionError (toException (userError "refused"))) `shouldBe` True
describe "scrubClientError on every constructor" $ do
let responseWithSecret =
Response
{ responseStatusCode = status200,
responseHeaders = Seq.fromList [("Set-Cookie", "session=hunter2")],
responseHttpVersion = http11,
responseBody = ""
}
let scrubbedResponse =
responseWithSecret {responseHeaders = Seq.fromList [("Set-Cookie", "<REDACTED>")]}
it "scrubs the response of a decode failure" $
scrubClientError apiKeyPolicy (DecodeFailure "not json" responseWithSecret)
`shouldBe` DecodeFailure "not json" scrubbedResponse
it "scrubs the response of an unsupported content type" $
scrubClientError apiKeyPolicy (UnsupportedContentType "text/plain" responseWithSecret)
`shouldBe` UnsupportedContentType "text/plain" scrubbedResponse
it "scrubs the request inside a connection error" $ do
let request = HTTP.defaultRequest {HTTP.requestHeaders = [("X-Api-Key", "wnxczrmtabdywlrw")]}
let scrubbed = scrubClientError apiKeyPolicy (ConnectionError (toException (HTTP.HttpExceptionRequest request HTTP.ConnectionTimeout)))
Text.isInfixOf "wnxczrmtabdywlrw" (Text.pack (show scrubbed)) `shouldBe` False
Text.isInfixOf "<REDACTED>" (Text.pack (show scrubbed)) `shouldBe` True
it "leaves a connection error that is not an HTTP exception alone" $
show (scrubClientError apiKeyPolicy (ConnectionError (toException (userError "refused"))))
`shouldBe` show (ConnectionError (toException (userError "refused")))