packages feed

http-env-gen (empty) → 0.0.0.0

raw patch · 29 files changed

+5094/−0 lines, 29 filesdep +QuickCheckdep +aesondep +autodocodecsetup-changed

Dependencies added: QuickCheck, aeson, autodocodec, base, bytestring, containers, genvalidity, genvalidity-containers, genvalidity-sydtest, genvalidity-time, http-client, http-client-tls, http-env, http-env-gen, http-types, monad-logger, opt-env-conf, opt-env-conf-test, prometheus, retry, servant, servant-client, servant-client-core, streaming-commons, sydtest, text, time, token-limiter-concurrent, unliftio, wai, warp

Files

+ CHANGELOG.md view
@@ -0,0 +1,8 @@+# Changelog++## [0.0.0.0] - 2026-11-30++### Added++* `GenValid` instances for the settings, the circuit breaker's and the failure+  budget's types, and the rate-limit header conventions.
+ LICENSE view
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Tom Sydney Kerckhove++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ http-env-gen.cabal view
@@ -0,0 +1,112 @@+cabal-version: 1.12++-- This file has been generated from package.yaml by hpack version 0.38.3.+--+-- see: https://github.com/sol/hpack++name:           http-env-gen+version:        0.0.0.0+synopsis:       Generators and tests for http-env+description:    GenValid instances for the types of http-env, and its test suite.+                .+                For more info, see <https://github.com/NorfairKing/http-env the readme>.+category:       Testing+homepage:       https://github.com/NorfairKing/http-env#readme+bug-reports:    https://github.com/NorfairKing/http-env/issues+author:         Tom Sydney Kerckhove+maintainer:     syd@cs-syd.eu+copyright:      Copyright (c) 2026 Tom Sydney Kerckhove+license:        MIT+license-file:   LICENSE+build-type:     Simple+extra-source-files:+    LICENSE+    CHANGELOG.md+    test_resources/http-env-settings.txt+    test_resources/http-settings.txt++source-repository head+  type: git+  location: https://github.com/NorfairKing/http-env++library+  exposed-modules:+      Network.HTTP.Env.CircuitBreaker.Gen+      Network.HTTP.Env.FailureBudget.Gen+      Network.HTTP.Env.OptParse.Gen+      Network.HTTP.Env.RateLimit.Gen+  other-modules:+      Paths_http_env_gen+  hs-source-dirs:+      src+  ghc-options: -Wall -Wincomplete-uni-patterns -Wincomplete-record-updates -Wpartial-fields -Widentities -Wredundant-constraints -Wcpp-undef -Wunused-packages+  build-depends:+      QuickCheck+    , base >=4.20 && <5+    , containers+    , genvalidity+    , genvalidity-containers+    , genvalidity-time+    , http-env+    , time+  default-language: Haskell2010++test-suite http-env-test+  type: exitcode-stdio-1.0+  main-is: Main.hs+  other-modules:+      Network.HTTP.Env.CircuitBreaker.RetrySpec+      Network.HTTP.Env.CircuitBreakerSpec+      Network.HTTP.Env.FailureBudgetSpec+      Network.HTTP.Env.HttpClient.RetrySpec+      Network.HTTP.Env.HttpClientSpec+      Network.HTTP.Env.LogPolicySpec+      Network.HTTP.Env.ManagerSpec+      Network.HTTP.Env.MetricsSpec+      Network.HTTP.Env.NumericSpec+      Network.HTTP.Env.OptParse.DurationSpec+      Network.HTTP.Env.OptParseSpec+      Network.HTTP.Env.PacingSpec+      Network.HTTP.Env.RateLimitSpec+      Network.HTTP.Env.Servant.ClientSpec+      Network.HTTP.Env.Servant.RetrySpec+      Network.HTTP.Env.ServantSpec+      Network.HTTP.EnvSpec+      Spec+      Paths_http_env_gen+  hs-source-dirs:+      test+  ghc-options: -Wall -Wincomplete-uni-patterns -Wincomplete-record-updates -Wpartial-fields -Widentities -Wredundant-constraints -Wcpp-undef -Wunused-packages -threaded -rtsopts "-with-rtsopts=-N"+  build-tool-depends:+      sydtest-discover:sydtest-discover+  build-depends:+      QuickCheck+    , aeson+    , autodocodec+    , base >=4.20 && <5+    , bytestring+    , containers+    , genvalidity-sydtest+    , genvalidity-time+    , http-client+    , http-client-tls+    , http-env+    , http-env-gen+    , http-types+    , monad-logger+    , opt-env-conf+    , opt-env-conf-test+    , prometheus+    , retry+    , servant+    , servant-client+    , servant-client-core+    , streaming-commons+    , sydtest+    , text+    , time+    , token-limiter-concurrent+    , unliftio+    , wai+    , warp+  default-language: Haskell2010
+ src/Network/HTTP/Env/CircuitBreaker/Gen.hs view
@@ -0,0 +1,44 @@+{-# LANGUAGE RecordWildCards #-}+{-# OPTIONS_GHC -fno-warn-orphans #-}++module Network.HTTP.Env.CircuitBreaker.Gen where++import Data.GenValidity+import Data.GenValidity.Time ()+import Network.HTTP.Env.CircuitBreaker+import Network.HTTP.Env.CircuitBreaker.Retry (Attempts (..))+import Test.QuickCheck (suchThat)++instance GenValid Outcome where+  genValid = genValidStructurallyWithoutExtraChecking+  shrinkValid = shrinkValidStructurallyWithoutExtraFiltering++instance GenValid Admission where+  genValid = genValidStructurallyWithoutExtraChecking+  shrinkValid = shrinkValidStructurallyWithoutExtraFiltering++instance GenValid Decision where+  genValid = genValidStructurallyWithoutExtraChecking+  shrinkValid = shrinkValidStructurallyWithoutExtraFiltering++instance GenValid CircuitReport where+  genValid = genValidStructurallyWithoutExtraChecking+  shrinkValid = shrinkValidStructurallyWithoutExtraFiltering++instance (GenValid e) => GenValid (CircuitBreakerError e) where+  genValid = genValidStructurallyWithoutExtraChecking+  shrinkValid = shrinkValidStructurallyWithoutExtraFiltering++instance GenValid CircuitState where+  genValid = genValidStructurallyWithoutExtraChecking+  shrinkValid = shrinkValidStructurallyWithoutExtraFiltering++instance GenValid CircuitBreakerSettings where+  -- Zero is rejected rather than added to, because adding one wraps 'maxBound'.+  genValid = do+    circuitBreakerSettingsFailureThreshold <- genValid `suchThat` (>= 1)+    circuitBreakerSettingsResetTimeout <- (abs <$> genValid) `suchThat` (> 0)+    pure CircuitBreakerSettings {..}++instance GenValid Attempts where+  genValid = Attempts <$> genValid `suchThat` (>= 1)
+ src/Network/HTTP/Env/FailureBudget/Gen.hs view
@@ -0,0 +1,34 @@+{-# LANGUAGE RecordWildCards #-}+{-# OPTIONS_GHC -fno-warn-orphans #-}++module Network.HTTP.Env.FailureBudget.Gen where++import Data.GenValidity+import Data.GenValidity.Containers ()+import Data.GenValidity.Time ()+import qualified Data.Sequence as Seq+import Network.HTTP.Env.FailureBudget+import Network.HTTP.Env.Numeric (intToWord, wordToInt)+import Test.QuickCheck (suchThat)++instance GenValid FailureBudgetSettings where+  -- Zero is rejected rather than added to, because adding one wraps 'maxBound'.+  genValid = do+    failureBudgetSettingsFailures <- genValid `suchThat` (>= 1)+    failureBudgetSettingsWindow <- (abs <$> genValid) `suchThat` (> 0)+    pure FailureBudgetSettings {..}++instance GenValid FailureBudget where+  genValid = do+    failureBudgetLimit <- genValid `suchThat` (\limit -> limit >= 1 && limit <= intToWord maxBound)+    failureBudgetWindowNanos <- genValid+    failureBudgetFailures <- Seq.take (wordToInt failureBudgetLimit) <$> genValid+    pure FailureBudget {..}++instance GenValid FailureBudgetStatus where+  genValid = genValidStructurallyWithoutExtraChecking+  shrinkValid = shrinkValidStructurallyWithoutExtraFiltering++instance GenValid FailureBudgetReport where+  genValid = genValidStructurallyWithoutExtraChecking+  shrinkValid = shrinkValidStructurallyWithoutExtraFiltering
+ src/Network/HTTP/Env/OptParse/Gen.hs view
@@ -0,0 +1,54 @@+{-# OPTIONS_GHC -fno-warn-orphans #-}++module Network.HTTP.Env.OptParse.Gen where++import Data.GenValidity+import Data.GenValidity.Time ()+import Data.Time (NominalDiffTime)+import Network.HTTP.Env.CircuitBreaker.Gen ()+import Network.HTTP.Env.FailureBudget.Gen ()+import Network.HTTP.Env.OptParse+import Network.HTTP.Env.RateLimit.Gen ()+import Test.QuickCheck (Gen, oneof, suchThat)++instance GenValid BackoffSettings where+  genValid = BackoffSettings <$> positiveDuration <*> positiveDuration <*> positiveDuration++instance GenValid BackoffOverrides where+  genValid =+    BackoffOverrides+      <$> optionalOf positiveDuration+      <*> optionalOf positiveDuration+      <*> optionalOf positiveDuration++instance GenValid HttpEnvSettings where+  genValid = genValidStructurallyWithoutExtraChecking+  shrinkValid = shrinkValidStructurallyWithoutExtraFiltering++instance GenValid HttpEnvOverrides where+  genValid =+    HttpEnvOverrides+      <$> genValid+      <*> genValid+      <*> genValid+      <*> genValid+      <*> genValid+  shrinkValid = shrinkValidStructurallyWithoutExtraFiltering++instance GenValid CircuitBreakerOverrides where+  genValid =+    CircuitBreakerOverrides+      <$> optionalOf (genValid `suchThat` (>= 1))+      <*> optionalOf positiveDuration++instance GenValid FailureBudgetOverrides where+  genValid =+    FailureBudgetOverrides+      <$> optionalOf (genValid `suchThat` (>= 1))+      <*> optionalOf positiveDuration++optionalOf :: Gen a -> Gen (Maybe a)+optionalOf g = oneof [pure Nothing, Just <$> g]++positiveDuration :: Gen NominalDiffTime+positiveDuration = (abs <$> genValid) `suchThat` (> 0)
+ src/Network/HTTP/Env/RateLimit/Gen.hs view
@@ -0,0 +1,10 @@+{-# OPTIONS_GHC -fno-warn-orphans #-}++module Network.HTTP.Env.RateLimit.Gen where++import Data.GenValidity+import Network.HTTP.Env.RateLimit++instance GenValid RateLimitHeaders where+  genValid = genValidStructurallyWithoutExtraChecking+  shrinkValid = shrinkValidStructurallyWithoutExtraFiltering
+ test/Main.hs view
@@ -0,0 +1,7 @@+module Main (main) where++import Spec (spec)+import Test.Syd++main :: IO ()+main = sydTest spec
+ test/Network/HTTP/Env/CircuitBreaker/RetrySpec.hs view
@@ -0,0 +1,399 @@+{-# 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)
+ test/Network/HTTP/Env/CircuitBreakerSpec.hs view
@@ -0,0 +1,387 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE NumericUnderscores #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}++module Network.HTTP.Env.CircuitBreakerSpec (spec) where++import Control.Concurrent (threadDelay)+import Control.Exception (IOException, throwIO, try)+import Control.Monad (replicateM_)+import Control.Monad.Logger.CallStack+  ( LogLevel+      ( LevelError,+        LevelInfo+      ),+    fromLogStr,+    runLoggingT,+    runNoLoggingT,+  )+import Data.Word (Word64)+import Network.HTTP.Env.CircuitBreaker+import Network.HTTP.Env.CircuitBreaker.Gen ()+import Test.Syd+import Test.Syd.Validity+import UnliftIO+  ( atomically,+    mapConcurrently,+    modifyIORef',+    modifyTVar',+    newIORef,+    newTVarIO,+    readIORef,+    readTVarIO,+  )++spec :: Spec+spec = do+  let t0 :: Word64+      t0 = 1_000_000_000++  let seconds :: Word64 -> Word64+      seconds n = n * 1_000_000_000++  describe "GenValid" $ do+    genValidSpec @CircuitBreakerSettings+    genValidSpec @CircuitState+    genValidSpec @Outcome+    genValidSpec @Admission+    genValidSpec @Decision+    genValidSpec @CircuitReport+    genValidSpec @(CircuitBreakerError Bool)++  let settings =+        CircuitBreakerSettings+          { circuitBreakerSettingsFailureThreshold = 3,+            circuitBreakerSettingsResetTimeout = 30+          }++  describe "decide" $ do+    it "rejects while open before a reset timeout too long to count in nanoseconds" $+      let limits = circuitBreakerLimits defaultCircuitBreakerSettings {circuitBreakerSettingsResetTimeout = 18446744073.709551616}+       in fst (decide limits 2_000_000_000 (CircuitStateOpen 1_000_000_000)) `shouldBe` DecisionReject+    it "admits and leaves the state unchanged when closed" $+      decide (circuitBreakerLimits settings) t0 (CircuitStateClosed 1) `shouldBe` (DecisionAllow AdmissionClosed, CircuitStateClosed 1)+    it "rejects while a fresh probe is in flight (half-open)" $+      decide (circuitBreakerLimits settings) t0 (CircuitStateHalfOpen t0) `shouldBe` (DecisionReject, CircuitStateHalfOpen t0)+    it "admits a fresh probe once a half-open has been stale for the reset timeout" $+      decide (circuitBreakerLimits settings) (t0 + seconds 30) (CircuitStateHalfOpen t0) `shouldBe` (DecisionAllow (AdmissionProbe (t0 + seconds 30)), CircuitStateHalfOpen (t0 + seconds 30))+    it "rejects while open, before the reset timeout" $+      decide (circuitBreakerLimits settings) (t0 + seconds 29) (CircuitStateOpen t0) `shouldBe` (DecisionReject, CircuitStateOpen t0)+    it "admits a probe once the reset timeout has elapsed" $+      decide (circuitBreakerLimits settings) (t0 + seconds 30) (CircuitStateOpen t0) `shouldBe` (DecisionAllow (AdmissionProbe (t0 + seconds 30)), CircuitStateHalfOpen (t0 + seconds 30))+    it "rejects while open when the stamp is later than the time it is given" $+      decide (circuitBreakerLimits settings) t0 (CircuitStateOpen (t0 + seconds 1)) `shouldBe` (DecisionReject, CircuitStateOpen (t0 + seconds 1))+    it "rejects at the moment it opened, however short the reset timeout" $+      decide+        (circuitBreakerLimits (settings {circuitBreakerSettingsResetTimeout = 0.000000000001}))+        t0+        (CircuitStateOpen t0)+        `shouldBe` (DecisionReject, CircuitStateOpen t0)++  describe "recordOutcome" $ do+    it "ignores a call admitted before the probe while half-open" $+      map+        (\outcome -> recordOutcome (circuitBreakerLimits settings) (t0 + seconds 1) AdmissionClosed outcome (CircuitStateHalfOpen t0))+        [OutcomeCircuitShouldStayClosed, OutcomeCircuitShouldOpen]+        `shouldBe` [CircuitStateHalfOpen t0, CircuitStateHalfOpen t0]+    it "ignores a stale probe while half-open" $+      map+        (\outcome -> recordOutcome (circuitBreakerLimits settings) (t0 + seconds 1) (AdmissionProbe (t0 - 1)) outcome (CircuitStateHalfOpen t0))+        [OutcomeCircuitShouldStayClosed, OutcomeCircuitShouldOpen]+        `shouldBe` [CircuitStateHalfOpen t0, CircuitStateHalfOpen t0]+    it "lets a probe's success close the breaker after an older call failed late" $+      let limits = circuitBreakerLimits defaultCircuitBreakerSettings+       in recordOutcome limits 3 (AdmissionProbe 1) OutcomeCircuitShouldStayClosed (recordOutcome limits 2 AdmissionClosed OutcomeCircuitShouldOpen (CircuitStateHalfOpen 1))+            `shouldBe` CircuitStateClosed 0+    it "clears the failure count on success" $+      recordOutcome (circuitBreakerLimits settings) t0 AdmissionClosed OutcomeCircuitShouldStayClosed (CircuitStateClosed 2) `shouldBe` CircuitStateClosed 0+    it "increments the failure count below the threshold" $+      recordOutcome (circuitBreakerLimits settings) t0 AdmissionClosed OutcomeCircuitShouldOpen (CircuitStateClosed 1) `shouldBe` CircuitStateClosed 2+    it "opens once the failure count reaches the threshold" $+      recordOutcome (circuitBreakerLimits settings) t0 AdmissionClosed OutcomeCircuitShouldOpen (CircuitStateClosed 2) `shouldBe` CircuitStateOpen t0+    it "closes when the half-open probe succeeds" $+      recordOutcome (circuitBreakerLimits settings) t0 (AdmissionProbe t0) OutcomeCircuitShouldStayClosed (CircuitStateHalfOpen t0) `shouldBe` CircuitStateClosed 0+    it "re-opens when the half-open probe fails" $+      recordOutcome (circuitBreakerLimits settings) t0 (AdmissionProbe t0) OutcomeCircuitShouldOpen (CircuitStateHalfOpen t0) `shouldBe` CircuitStateOpen t0+    it "leaves an already-open circuit open on a late success" $+      recordOutcome (circuitBreakerLimits settings) (t0 + seconds 5) AdmissionClosed OutcomeCircuitShouldStayClosed (CircuitStateOpen t0) `shouldBe` CircuitStateOpen t0+    it "leaves an already-open circuit open on a late failure" $+      recordOutcome (circuitBreakerLimits settings) (t0 + seconds 5) AdmissionClosed OutcomeCircuitShouldOpen (CircuitStateOpen t0) `shouldBe` CircuitStateOpen t0++  describe "circuitReport" $ do+    it "is closed when a closed circuit has nothing against it" $+      circuitReport (circuitBreakerLimits settings) t0 (CircuitStateClosed 0) `shouldBe` CircuitReportClosed+    it "is closed when a closed circuit has counted a failure" $+      circuitReport (circuitBreakerLimits settings) t0 (CircuitStateClosed 1) `shouldBe` CircuitReportClosed+    it "is rejecting while open, before the reset timeout" $+      circuitReport (circuitBreakerLimits settings) (t0 + seconds 29) (CircuitStateOpen t0) `shouldBe` CircuitReportRejecting+    it "is probing while a fresh probe is in flight" $+      circuitReport (circuitBreakerLimits settings) t0 (CircuitStateHalfOpen t0) `shouldBe` CircuitReportProbing+    it "is probing once an open circuit would admit a probe" $+      circuitReport (circuitBreakerLimits settings) (t0 + seconds 30) (CircuitStateOpen t0) `shouldBe` CircuitReportProbing+    it "is probing once a stale half-open would admit a fresh probe" $+      circuitReport (circuitBreakerLimits settings) (t0 + seconds 30) (CircuitStateHalfOpen t0) `shouldBe` CircuitReportProbing++  describe "defaultCircuitBreakerSettings" $ do+    it "has valid default settings" $+      shouldBeValid defaultCircuitBreakerSettings+    it "opens after five failures, probes after thirty seconds" $+      defaultCircuitBreakerSettings+        `shouldBe` CircuitBreakerSettings+          { circuitBreakerSettingsFailureThreshold = 5,+            circuitBreakerSettingsResetTimeout = 30+          }++  describe "Validity CircuitBreakerSettings" $ do+    it "accepts the smallest settings that make sense" $+      shouldBeValid+        CircuitBreakerSettings+          { circuitBreakerSettingsFailureThreshold = 1,+            circuitBreakerSettingsResetTimeout = 0.000000000001+          }+    it "refuses a failure threshold of zero" $+      shouldBeInvalid settings {circuitBreakerSettingsFailureThreshold = 0}+    it "refuses a reset timeout of zero" $+      shouldBeInvalid settings {circuitBreakerSettingsResetTimeout = 0}++  describe "circuitBreakerName" $+    it "gives back the name the breaker was created with" $+      forAllValid $ \name -> do+        breaker <- runNoLoggingT (newCircuitBreaker name defaultCircuitBreakerSettings)+        circuitBreakerName breaker `shouldBe` name++  let classify = \case+        Left () -> OutcomeCircuitShouldOpen+        Right () -> OutcomeCircuitShouldStayClosed+  let failing = pure (Left () :: Either () ())+  let succeeding = pure (Right () :: Either () ())+  let shortReset = 0.05+  let pastShortReset = threadDelay 250_000++  describe "peekCircuitBreaker" $ do+    -- A long cooldown, so a loaded machine cannot cross it mid-test.+    it "follows the breaker from closed down to rejecting" $ do+      breaker <-+        runNoLoggingT+          ( newCircuitBreaker+              "test"+              ( CircuitBreakerSettings+                  { circuitBreakerSettingsFailureThreshold = 2,+                    circuitBreakerSettingsResetTimeout = 3_600+                  }+              )+          )+      peekCircuitBreaker breaker `shouldReturn` CircuitReportClosed++      _ <- guardCircuitBreaker breaker classify failing+      peekCircuitBreaker breaker `shouldReturn` CircuitReportClosed++      _ <- guardCircuitBreaker breaker classify failing+      peekCircuitBreaker breaker `shouldReturn` CircuitReportRejecting++    it "follows the breaker from rejecting back up to closed" $ do+      breaker <-+        runNoLoggingT+          ( newCircuitBreaker+              "test"+              ( CircuitBreakerSettings+                  { circuitBreakerSettingsFailureThreshold = 1,+                    circuitBreakerSettingsResetTimeout = shortReset+                  }+              )+          )+      _ <- guardCircuitBreaker breaker classify failing++      pastShortReset+      peekCircuitBreaker breaker `shouldReturn` CircuitReportProbing++      guardCircuitBreaker breaker classify succeeding `shouldReturn` Right ()+      peekCircuitBreaker breaker `shouldReturn` CircuitReportClosed++    it "leaves the probe for a real caller to spend" $ do+      breaker <-+        runNoLoggingT+          ( newCircuitBreaker+              "test"+              ( CircuitBreakerSettings+                  { circuitBreakerSettingsFailureThreshold = 1,+                    circuitBreakerSettingsResetTimeout = shortReset+                  }+              )+          )+      _ <- guardCircuitBreaker breaker classify failing+      pastShortReset++      replicateM_ 5 (peekCircuitBreaker breaker `shouldReturn` CircuitReportProbing)++      guardCircuitBreaker breaker classify succeeding `shouldReturn` Right ()+      peekCircuitBreaker breaker `shouldReturn` CircuitReportClosed++  describe "guardCircuitBreaker" $ do+    it "admits a probe once the reset timeout has elapsed, and closes on success" $ do+      breaker <-+        runNoLoggingT+          ( newCircuitBreaker+              "test"+              ( CircuitBreakerSettings+                  { circuitBreakerSettingsFailureThreshold = 3,+                    circuitBreakerSettingsResetTimeout = shortReset+                  }+              )+          )++      replicateM_ 3 (guardCircuitBreaker breaker classify failing)++      pastShortReset+      guardCircuitBreaker breaker classify succeeding `shouldReturn` Right ()+      guardCircuitBreaker breaker classify failing `shouldReturn` Left (CircuitBreakerErrorUnderlying ())++    it "opens on in-band failures and then rejects" $ do+      breaker <-+        runNoLoggingT+          ( newCircuitBreaker+              "test"+              ( CircuitBreakerSettings+                  { circuitBreakerSettingsFailureThreshold = 2,+                    circuitBreakerSettingsResetTimeout = 3600+                  }+              )+          )+      r1 <- guardCircuitBreaker breaker classify failing+      r2 <- guardCircuitBreaker breaker classify failing+      r1 `shouldBe` Left (CircuitBreakerErrorUnderlying ())+      r2 `shouldBe` Left (CircuitBreakerErrorUnderlying ())+      guardCircuitBreaker breaker classify failing `shouldReturn` Left CircuitBreakerErrorOpen++    it "admits at most one probe when many callers cross the half-open boundary at once" $ do+      -- A wide reset window, so a thread delayed under load cannot re-probe.+      let wideReset = 0.5+      breaker <-+        runNoLoggingT+          ( newCircuitBreaker+              "test"+              ( CircuitBreakerSettings+                  { circuitBreakerSettingsFailureThreshold = 1,+                    circuitBreakerSettingsResetTimeout = wideReset+                  }+              )+          )+      _ <- guardCircuitBreaker breaker classify failing+      threadDelay 600_000+      admittedVar <- newTVarIO (0 :: Int)+      let probe =+            guardCircuitBreaker breaker classify $ do+              atomically $ modifyTVar' admittedVar (+ 1)+              -- Held so that the other callers reach 'admit' while it is in flight.+              threadDelay 100_000+              pure (Left () :: Either () ())+      _ <- mapConcurrently (const probe) [1 .. 50 :: Int]+      admitted <- readTVarIO admittedVar+      admitted `shouldBe` 1++    it "recovers if a half-open probe throws instead of reporting (no permanent wedge)" $ do+      breaker <-+        runNoLoggingT+          ( newCircuitBreaker+              "test"+              ( CircuitBreakerSettings+                  { circuitBreakerSettingsFailureThreshold = 1,+                    circuitBreakerSettingsResetTimeout = shortReset+                  }+              )+          )+      _ <- guardCircuitBreaker breaker classify failing+      pastShortReset+      let throwing = throwIO (userError "boom") :: IO (Either () ())+      _ <-+        ( try (guardCircuitBreaker breaker classify throwing) ::+            IO (Either IOException (Either (CircuitBreakerError ()) ()))+        )+      pastShortReset+      guardCircuitBreaker breaker classify succeeding `shouldReturn` Right ()++    it "logs an error naming the breaker when it opens" $ do+      logsRef <- newIORef []+      let captureLogger _loc _source level msg =+            modifyIORef' logsRef ((level, fromLogStr msg) :)+      breaker <-+        runLoggingT+          ( newCircuitBreaker+              "named-breaker"+              ( CircuitBreakerSettings+                  { circuitBreakerSettingsFailureThreshold = 1,+                    circuitBreakerSettingsResetTimeout = 3600+                  }+              )+          )+          captureLogger+      _ <- guardCircuitBreaker breaker classify failing+      logs <- readIORef logsRef+      logs `shouldBe` [(LevelError, "Circuit breaker opened: named-breaker")]++    it "does not log an error again when a failed probe re-opens the breaker" $ do+      logsRef <- newIORef []+      let captureLogger _loc _source level msg =+            modifyIORef' logsRef ((level, fromLogStr msg) :)+      breaker <-+        runLoggingT+          ( newCircuitBreaker+              "named-breaker"+              ( CircuitBreakerSettings+                  { circuitBreakerSettingsFailureThreshold = 1,+                    circuitBreakerSettingsResetTimeout = shortReset+                  }+              )+          )+          captureLogger+      _ <- guardCircuitBreaker breaker classify failing+      pastShortReset+      _ <- guardCircuitBreaker breaker classify failing+      logs <- readIORef logsRef+      logs `shouldBe` [(LevelError, "Circuit breaker opened: named-breaker")]++    it "does not log when the breaker stays closed" $ do+      logsRef <- newIORef []+      let captureLogger _loc _source level msg =+            modifyIORef' logsRef ((level, fromLogStr msg) :)+      breaker <-+        runLoggingT+          ( newCircuitBreaker+              "named-breaker"+              ( CircuitBreakerSettings+                  { circuitBreakerSettingsFailureThreshold = 3,+                    circuitBreakerSettingsResetTimeout = 3600+                  }+              )+          )+          captureLogger+      _ <- guardCircuitBreaker breaker classify failing+      _ <- guardCircuitBreaker breaker classify succeeding+      logs <- readIORef logsRef+      logs `shouldBe` []++    it "logs info naming the breaker when it closes again" $ do+      logsRef <- newIORef []+      let captureLogger _loc _source level msg =+            modifyIORef' logsRef ((level, fromLogStr msg) :)+      breaker <-+        runLoggingT+          ( newCircuitBreaker+              "named-breaker"+              ( CircuitBreakerSettings+                  { circuitBreakerSettingsFailureThreshold = 1,+                    circuitBreakerSettingsResetTimeout = shortReset+                  }+              )+          )+          captureLogger+      _ <- guardCircuitBreaker breaker classify failing+      pastShortReset+      _ <- guardCircuitBreaker breaker classify succeeding+      logs <- readIORef logsRef+      logs+        `shouldBe` [ (LevelInfo, "Circuit breaker closed: named-breaker"),+                     (LevelError, "Circuit breaker opened: named-breaker")+                   ]
+ test/Network/HTTP/Env/FailureBudgetSpec.hs view
@@ -0,0 +1,171 @@+{-# LANGUAGE NumericUnderscores #-}+{-# LANGUAGE TypeApplications #-}++module Network.HTTP.Env.FailureBudgetSpec (spec) where++import Control.Monad (replicateM_)+import qualified Data.Sequence as Seq+import Data.Word (Word64)+import Network.HTTP.Env.FailureBudget+import Network.HTTP.Env.FailureBudget.Gen ()+import Network.HTTP.Env.Numeric (intToWord)+import Test.Syd+import Test.Syd.Validity++spec :: Spec+spec = do+  let t0 :: Word64+      t0 = 1_000_000_000_000++  let seconds :: Word64 -> Word64+      seconds n = n * 1_000_000_000++  describe "GenValid" $ do+    genValidSpec @FailureBudgetSettings+    genValidSpec @FailureBudget+    genValidSpec @FailureBudgetStatus+    genValidSpec @FailureBudgetReport++  describe "defaultFailureBudgetSettings" $ do+    it "is valid" $+      shouldBeValid defaultFailureBudgetSettings+    it "allows ten failures an hour" $+      defaultFailureBudgetSettings+        `shouldBe` FailureBudgetSettings+          { failureBudgetSettingsFailures = 10,+            failureBudgetSettingsWindow = 3_600+          }++  describe "Validity FailureBudgetSettings" $ do+    it "accepts the smallest settings that make sense" $+      shouldBeValid+        FailureBudgetSettings+          { failureBudgetSettingsFailures = 1,+            failureBudgetSettingsWindow = 0.000000000001+          }+    it "refuses a budget of no failures" $+      shouldBeInvalid defaultFailureBudgetSettings {failureBudgetSettingsFailures = 0}+    it "refuses a window of zero" $+      shouldBeInvalid defaultFailureBudgetSettings {failureBudgetSettingsWindow = 0}++  let settings =+        FailureBudgetSettings+          { failureBudgetSettingsFailures = 3,+            failureBudgetSettingsWindow = 60+          }++  let empty = emptyFailureBudget settings+  let holding :: [Word64] -> FailureBudget+      holding stamps = empty {failureBudgetFailures = Seq.fromList stamps}++  describe "emptyFailureBudget" $+    it "resolves the settings and holds no failure" $+      emptyFailureBudget settings+        `shouldBe` FailureBudget+          { failureBudgetLimit = 3,+            failureBudgetWindowNanos = seconds 60,+            failureBudgetFailures = Seq.empty+          }++  describe "recordFailure" $ do+    it "records a failure in an empty budget" $+      recordFailure t0 empty `shouldBe` holding [t0]+    it "records the newest failure first" $+      recordFailure (t0 + seconds 1) (holding [t0])+        `shouldBe` holding [t0 + seconds 1, t0]+    it "forgets the oldest failure once it keeps as many as it allows" $+      recordFailure (t0 + seconds 3) (holding [t0 + seconds 2, t0 + seconds 1, t0])+        `shouldBe` holding [t0 + seconds 3, t0 + seconds 2, t0 + seconds 1]+    it "produces a valid budget" $+      forAllValid $ \now ->+        forAllValid $ \budget ->+          shouldBeValid (recordFailure now budget)++  describe "failuresWithin" $ do+    it "counts a failure within a window too long to count in nanoseconds" $+      let budget = recordFailure 1_000_000_000 (emptyFailureBudget defaultFailureBudgetSettings {failureBudgetSettingsWindow = 18446744073.709551616})+       in failuresWithin 2_000_000_000 budget `shouldBe` 1+    it "counts nothing in an empty budget" $+      failuresWithin t0 empty `shouldBe` 0+    it "counts a failure just before the edge of the window" $+      failuresWithin (t0 + seconds 60 - 1) (holding [t0]) `shouldBe` 1+    it "does not count a failure exactly at the edge of the window" $+      failuresWithin (t0 + seconds 60) (holding [t0]) `shouldBe` 0+    it "counts a failure stamped later than the time it is given" $+      failuresWithin t0 (holding [t0 + seconds 1]) `shouldBe` 1+    it "counts only the failures within the window" $+      failuresWithin (t0 + seconds 90) (holding [t0 + seconds 80, t0 + seconds 40, t0])+        `shouldBe` 2+    it "counts at most the budget's limit" $+      forAllValid $ \now ->+        forAllValid $ \budget ->+          failuresWithin now budget `shouldSatisfy` (<= failureBudgetLimit budget)++  describe "failureBudgetReport" $ do+    let recordAll :: [Word64] -> FailureBudget+        recordAll = foldl' (flip recordFailure) empty+    it "is within budget after a single failure" $+      failureBudgetReport t0 (recordAll [t0])+        `shouldBe` FailureBudgetReport+          { failureBudgetReportFailures = 1,+            failureBudgetReportStatus = FailureBudgetStatusWithin+          }+    it "is within budget one failure short of it" $+      failureBudgetReport (t0 + seconds 2) (recordAll [t0, t0 + seconds 1])+        `shouldBe` FailureBudgetReport+          { failureBudgetReportFailures = 2,+            failureBudgetReportStatus = FailureBudgetStatusWithin+          }+    it "is exhausted once the budget's worth of failures falls within the window" $+      failureBudgetReport (t0 + seconds 2) (recordAll [t0, t0 + seconds 1, t0 + seconds 2])+        `shouldBe` FailureBudgetReport+          { failureBudgetReportFailures = 3,+            failureBudgetReportStatus = FailureBudgetStatusExhausted+          }+    it "is within budget when the same failures are spread wider than the window" $+      failureBudgetReport (t0 + seconds 60) (recordAll [t0, t0 + seconds 30, t0 + seconds 60])+        `shouldBe` FailureBudgetReport+          { failureBudgetReportFailures = 2,+            failureBudgetReportStatus = FailureBudgetStatusWithin+          }+    it "is exhausted by the newest failures however many came before" $+      failureBudgetReport (t0 + seconds 102) (recordAll (map (\n -> t0 + seconds n) [0 .. 102]))+        `shouldBe` FailureBudgetReport+          { failureBudgetReportFailures = 3,+            failureBudgetReportStatus = FailureBudgetStatusExhausted+          }+    it "is within budget again once the failures age out" $+      failureBudgetReport (t0 + seconds 62) (recordAll [t0, t0 + seconds 1, t0 + seconds 2])+        `shouldBe` FailureBudgetReport+          { failureBudgetReportFailures = 0,+            failureBudgetReportStatus = FailureBudgetStatusWithin+          }++  describe "Validity FailureBudget" $ do+    it "refuses a budget that keeps more failures than it allows" $+      shouldBeInvalid (holding [t0, t0, t0, t0])+    it "accepts a budget that keeps as many failures as it allows" $+      shouldBeValid (holding [t0, t0, t0])+    it "refuses a budget that allows no failure" $+      shouldBeInvalid empty {failureBudgetLimit = 0}+    it "accepts the largest limit a sequence can count" $+      shouldBeValid empty {failureBudgetLimit = intToWord maxBound}+    it "refuses a limit larger than a sequence can count" $+      shouldBeInvalid empty {failureBudgetLimit = intToWord maxBound + 1}++  describe "FailureBudgetEnv" $ do+    it "reports nothing before any failure" $ do+      env <- newFailureBudget settings+      peekFailureBudget env+        `shouldReturn` FailureBudgetReport+          { failureBudgetReportFailures = 0,+            failureBudgetReportStatus = FailureBudgetStatusWithin+          }+    it "reports the failures recorded into it" $ do+      env <- newFailureBudget settings+      replicateM_ 3 (recordFailureNow env)+      peekFailureBudget env+        `shouldReturn` FailureBudgetReport+          { failureBudgetReportFailures = 3,+            failureBudgetReportStatus = FailureBudgetStatusExhausted+          }
+ test/Network/HTTP/Env/HttpClient/RetrySpec.hs view
@@ -0,0 +1,310 @@+{-# 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"]
+ test/Network/HTTP/Env/HttpClientSpec.hs view
@@ -0,0 +1,520 @@+{-# 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
+ test/Network/HTTP/Env/LogPolicySpec.hs view
@@ -0,0 +1,472 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeApplications #-}++module Network.HTTP.Env.LogPolicySpec (spec) where++import Control.Exception (try)+import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as LB+import qualified Data.Set as Set+import qualified Data.Text as Text+import Network.HTTP.Client+import Network.HTTP.Client.Internal (Response (..), ResponseClose (..))+import Network.HTTP.Env.LogPolicy+import Network.HTTP.Types (http11, status400, status500)+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+          }++  describe "headerLogPolicy" $ do+    it "redacts a standard credential header" $+      headerLogPolicy defaultLogPolicy "Authorization" `shouldBe` HeaderLogPolicyRedactValue++    it "logs a standard header" $+      headerLogPolicy defaultLogPolicy "Content-Type" `shouldBe` HeaderLogPolicyLogValue++    it "drops a header nobody has vouched for" $+      headerLogPolicy defaultLogPolicy "X-Some-New-Header" `shouldBe` HeaderLogPolicyDrop++    it "redacts a header an application added to the redaction list" $+      headerLogPolicy apiKeyPolicy "X-Api-Key" `shouldBe` HeaderLogPolicyRedactValue++    it "logs a header an application vouched for" $+      headerLogPolicy+        defaultLogPolicy {logPolicyHeadersToLog = Set.insert "X-Trace" defaultHeadersToLog}+        "X-Trace"+        `shouldBe` HeaderLogPolicyLogValue++    it "redacts a header on both lists" $+      headerLogPolicy+        defaultLogPolicy {logPolicyHeadersToLog = Set.insert "Authorization" defaultHeadersToLog}+        "Authorization"+        `shouldBe` HeaderLogPolicyRedactValue++  describe "scrubHeadersForLogging" $+    it "applies all three outcomes in one pass" $+      scrubHeadersForLogging+        apiKeyPolicy+        [ ("X-Api-Key", "wnxczrmtabdywlrw"),+          ("Content-Type", "text/plain"),+          ("X-Some-New-Header", "whatever")+        ]+        `shouldBe` [ ("X-Api-Key", "<REDACTED>"),+                     ("Content-Type", "text/plain")+                   ]++  describe "queryParamLogPolicy" $ do+    it "logs a parameter that has been vouched for" $+      queryParamLogPolicy defaultLogPolicy "client_id" `shouldBe` QueryParamLogPolicyLogValue++    it "redacts a known credential" $+      queryParamLogPolicy defaultLogPolicy "client_secret" `shouldBe` QueryParamLogPolicyRedactValue++    it "redacts a parameter nobody has vouched for" $+      queryParamLogPolicy defaultLogPolicy "some_new_parameter" `shouldBe` QueryParamLogPolicyRedactValue++    it "redacts a parameter on the deny list although it is also vouched for" $+      queryParamLogPolicy+        defaultLogPolicy {logPolicyParamsToLog = Set.insert "state" defaultParamsToLog}+        "state"+        `shouldBe` QueryParamLogPolicyRedactValue++  describe "defaultParamsToRedact" $+    it "names exactly the OAuth2 credentials" $+      defaultParamsToRedact+        `shouldBe` Set.fromList+          [ "access_token",+            "client_secret",+            "code",+            "refresh_token",+            "state"+          ]++  describe "defaultHeadersToRedact" $+    it "names exactly the standard credential headers" $+      defaultHeadersToRedact+        `shouldBe` Set.fromList ["Authorization", "Cookie", "Proxy-Authorization", "Set-Cookie"]++  describe "defaultHeadersToLog" $+    it "names exactly these headers" $+      defaultHeadersToLog+        `shouldBe` Set.fromList+          [ "Accept",+            "Accept-Charset",+            "Accept-Encoding",+            "Accept-Language",+            "Accept-Ranges",+            "Age",+            "Allow",+            "Cache-Control",+            "Connection",+            "Content-Disposition",+            "Content-Encoding",+            "Content-Language",+            "Content-Length",+            "Content-Location",+            "Content-MD5",+            "Content-Range",+            "Content-Type",+            "Date",+            "ETag",+            "Expect",+            "Expires",+            "From",+            "Host",+            "If-Match",+            "If-Modified-Since",+            "If-None-Match",+            "If-Range",+            "If-Unmodified-Since",+            "Last-Modified",+            "Location",+            "MIME-Version",+            "Max-Forwards",+            "Origin",+            "Pragma",+            "Prefer",+            "Preference-Applied",+            "Proxy-Authenticate",+            "Range",+            "Referer",+            "Retry-After",+            "Server",+            "TE",+            "Trailer",+            "Transfer-Encoding",+            "Upgrade",+            "User-Agent",+            "Vary",+            "Via",+            "WWW-Authenticate",+            "Warning",+            "X-Forwarded-For",+            "X-Forwarded-Host",+            "X-Forwarded-Proto",+            "X-Forwarded-Server",+            "X-Real-IP",+            "X-Request-ID"+          ]++  describe "quotaHeaders" $ do+    it "names exactly the headers a spent quota is read from" $+      quotaHeaders+        `shouldBe` Set.fromList+          [ "Retry-After",+            "X-RateLimit-Limit",+            "X-RateLimit-Remaining",+            "X-RateLimit-Reset",+            "X-RateLimit-Resource",+            "X-RateLimit-Used",+            "RateLimit",+            "RateLimit-Limit",+            "RateLimit-Policy",+            "RateLimit-Remaining",+            "RateLimit-Reset"+          ]+    it "is logged by a policy that logs nothing else" $+      map (headerLogPolicy defaultLogPolicy {logPolicyHeadersToLog = Set.empty}) (Set.toList quotaHeaders)+        `shouldBe` map (const HeaderLogPolicyLogValue) (Set.toList quotaHeaders)+    it "is still redacted by a policy that redacts it" $+      headerLogPolicy defaultLogPolicy {logPolicyHeadersToRedact = Set.singleton "Retry-After"} "Retry-After"+        `shouldBe` HeaderLogPolicyRedactValue++  describe "headerLogPolicy" $+    it "logs an idempotency key under a policy that logs nothing else" $+      headerLogPolicy defaultLogPolicy {logPolicyHeadersToLog = Set.empty} "Idempotency-Key"+        `shouldBe` HeaderLogPolicyLogValue++  describe "defaultParamsToLog" $+    it "names exactly the OAuth2 parameters that carry no credential" $+      defaultParamsToLog+        `shouldBe` Set.fromList+          [ "client_id",+            "grant_type",+            "iss",+            "redirect_uri",+            "response_type",+            "scope"+          ]++  describe "scrubQueryForLogging" $ do+    it "redacts the value of a parameter nobody has vouched for" $+      scrubQueryForLogging+        defaultLogPolicy+        [ ("client_id", Just "Iv1.0123456789abcdef"),+          ("client_secret", Just "not-a-real-client-secret")+        ]+        `shouldBe` [ ("client_id", Just "Iv1.0123456789abcdef"),+                     ("client_secret", Just "~REDACTED~")+                   ]++    it "leaves a valueless parameter without a value" $+      scrubQueryForLogging defaultLogPolicy [("someflag", Nothing)]+        `shouldBe` [("someflag", Nothing)]++  describe "scrubUriForLogging" $ do+    let tokenRequest =+          parseRequest_ $+            concat+              [ "https://github.com/login/oauth/access_token",+                "?client_id=Iv1.0123456789abcdef",+                "&client_secret=not-a-real-client-secret",+                "&grant_type=refresh_token",+                "&refresh_token=ghr_notarealrefreshtoken"+              ]++    it "keeps an OAuth client secret and refresh token out of the rendered URI" $ do+      let rendered = Text.pack $ show $ scrubUriForLogging defaultLogPolicy $ getUri tokenRequest+      Text.isInfixOf "not-a-real-client-secret" rendered `shouldBe` False+      Text.isInfixOf "ghr_notarealrefreshtoken" rendered `shouldBe` False++    it "renders the whole URI with only the vouched-for values left" $+      Text.pack (show (scrubUriForLogging defaultLogPolicy (getUri tokenRequest)))+        `shouldBe` Text.concat+          [ "https://github.com/login/oauth/access_token",+            "?client_id=Iv1.0123456789abcdef",+            "&client_secret=~REDACTED~",+            "&grant_type=refresh_token",+            "&refresh_token=~REDACTED~"+          ]++  describe "scrubHttpException" $ do+    it "scrubs every response of a redirect loop, and keeps them all" $ do+      let response =+            Response+              { responseStatus = status500,+                responseVersion = http11,+                responseHeaders = [("Set-Cookie", "session=hunter2"), ("Location", "/")],+                responseBody = LB.empty,+                responseCookieJar = mempty,+                responseClose' = ResponseClose (pure ()),+                responseOriginalRequest = defaultRequest,+                responseEarlyHints = []+              }+      case scrubHttpException apiKeyPolicy (HttpExceptionRequest defaultRequest (TooManyRedirects [response, response])) of+        HttpExceptionRequest _ (TooManyRedirects scrubbed) ->+          map responseHeaders scrubbed `shouldBe` replicate 2 [("Set-Cookie", "<REDACTED>"), ("Location", "/")]+        _ -> expectationFailure "expected the redirects"++    it "redacts the secret header on the request it carries" $ do+      let request =+            defaultRequest+              { host = "api.github.com",+                requestHeaders = [("X-Api-Key", "wnxczrmtabdywlrw")]+              }+      let shown =+            Text.pack $+              show @HttpException $+                scrubHttpException apiKeyPolicy (HttpExceptionRequest request ConnectionTimeout)+      Text.isInfixOf "wnxczrmtabdywlrw" shown `shouldBe` False+      Text.isInfixOf "<REDACTED>" shown `shouldBe` True++    it "redacts the response headers it carries too" $ do+      let response =+            Response+              { responseStatus = status500,+                responseVersion = http11,+                responseHeaders = [("Set-Cookie", "session=hunter2")],+                responseBody = (),+                responseCookieJar = mempty,+                responseClose' = ResponseClose (pure ()),+                responseOriginalRequest = defaultRequest,+                responseEarlyHints = []+              }+      let shown =+            Text.pack $+              show @HttpException $+                scrubHttpException+                  apiKeyPolicy+                  (HttpExceptionRequest defaultRequest (StatusCodeException response ""))+      Text.isInfixOf "hunter2" shown `shouldBe` False+      Text.isInfixOf "<REDACTED>" shown `shouldBe` True++    it "redacts the secrets in the query string of the request it carries" $ do+      let request =+            parseRequest_ $+              concat+                [ "https://github.com/login/oauth/access_token",+                  "?client_id=Iv1.0123456789abcdef",+                  "&client_secret=not-a-real-client-secret",+                  "&grant_type=refresh_token",+                  "&refresh_token=ghr_notarealrefreshtoken"+                ]+      let shown =+            Text.pack $+              show @HttpException $+                scrubHttpException apiKeyPolicy (HttpExceptionRequest request ConnectionTimeout)+      Text.isInfixOf "not-a-real-client-secret" shown `shouldBe` False+      Text.isInfixOf "ghr_notarealrefreshtoken" shown `shouldBe` False+      Text.isInfixOf "client_id=Iv1.0123456789abcdef" shown `shouldBe` True+      Text.isInfixOf "client_secret=~REDACTED~" shown `shouldBe` True+      Text.isInfixOf "grant_type=refresh_token" shown `shouldBe` True+      Text.isInfixOf "refresh_token=~REDACTED~" shown `shouldBe` True++    let unchangedTest label content =+          it (unwords ["leaves", label, "alone"]) $+            show @HttpException (scrubHttpException apiKeyPolicy (HttpExceptionRequest defaultRequest content))+              `shouldBe` show @HttpException (HttpExceptionRequest defaultRequest content)+    unchangedTest "a connection timeout" ConnectionTimeout+    unchangedTest "a response timeout" ResponseTimeout++  describe "renderHttpExceptionForLogging" $ do+    it "puts the request it carries through the policy itself" $ do+      let request =+            parseRequest_ $+              concat+                [ "https://github.com/login/oauth/access_token",+                  "?client_secret=not-a-real-client-secret",+                  "&refresh_token=ghr_notarealrefreshtoken"+                ]+      let rendered =+            Text.pack $+              renderHttpExceptionForLogging apiKeyPolicy $+                HttpExceptionRequest+                  request {requestHeaders = [("X-Api-Key", "wnxczrmtabdywlrw")]}+                  ConnectionTimeout+      Text.isInfixOf "not-a-real-client-secret" rendered `shouldBe` False+      Text.isInfixOf "ghr_notarealrefreshtoken" rendered `shouldBe` False+      Text.isInfixOf "wnxczrmtabdywlrw" rendered `shouldBe` False++    it "never says what was in the request body" $ do+      let request =+            urlEncodedBody+              [ ("client_id", "some-client"),+                ("client_secret", "wnxczrmtabdywlrw"),+                ("grant_type", "authorization_code")+              ]+              defaultRequest+      let rendered =+            Text.pack $+              renderHttpExceptionForLogging apiKeyPolicy $+                HttpExceptionRequest request ConnectionTimeout+      Text.isInfixOf "wnxczrmtabdywlrw" rendered `shouldBe` False++      Text.isInfixOf "TRAILING" rendered `shouldBe` False++    it "cuts a body an exception arrived with, however long it was" $ do+      let response =+            Response+              { responseStatus = status500,+                responseVersion = http11,+                responseHeaders = [],+                responseBody = (),+                responseCookieJar = mempty,+                responseClose' = ResponseClose (pure ()),+                responseOriginalRequest = defaultRequest,+                responseEarlyHints = []+              }+      let body = ByteString.concat [ByteString.replicate 1024 0x7a, "TRAILING"]+      let rendered =+            Text.pack $+              renderHttpExceptionForLogging apiKeyPolicy $+                HttpExceptionRequest defaultRequest (StatusCodeException response body)+      Text.count "z" rendered `shouldBe` 1024+      Text.isInfixOf "TRAILING" rendered `shouldBe` False++    it "keeps the query string secrets out of a refusal thrown for them" $ do+      man <- newManager defaultManagerSettings+      let application _ respond =+            respond $ responseLBS status400 [] "{\"error\":\"invalid_grant\"}"+      Warp.testWithApplication (pure application) $ \serverPort -> do+        request <-+          parseUrlThrow $+            concat+              [ "http://127.0.0.1:",+                show serverPort,+                "/oauth/token",+                "?client_secret=not-a-real-client-secret",+                "&refresh_token=not-a-real-refresh-token"+              ]+        result <- try (httpLbs request man)+        case result of+          Right response ->+            expectationFailure (unwords ["expected a refusal, got", show (responseStatus response)])+          Left err -> do+            let rendered = Text.pack (renderHttpExceptionForLogging apiKeyPolicy err)+            Text.isInfixOf "not-a-real-client-secret" rendered `shouldBe` False+            Text.isInfixOf "not-a-real-refresh-token" rendered `shouldBe` False++  describe "renderResponseForLogging" $ do+    it "keeps the query string secrets out of a refusal handed back for them" $ do+      man <- newManager defaultManagerSettings+      let application _ respond =+            respond $ responseLBS status400 [] "{\"error\":\"invalid_grant\"}"+      Warp.testWithApplication (pure application) $ \serverPort -> do+        request <-+          parseRequest $+            concat+              [ "http://127.0.0.1:",+                show serverPort,+                "/oauth/token",+                "?client_secret=not-a-real-client-secret",+                "&refresh_token=not-a-real-refresh-token"+              ]+        response <- httpLbs request man+        let rendered = Text.pack (renderResponseForLogging defaultLogPolicy response)+        Text.isInfixOf "not-a-real-client-secret" rendered `shouldBe` False+        Text.isInfixOf "not-a-real-refresh-token" rendered `shouldBe` False++    it "drops a header nobody has vouched for" $ do+      let response =+            Response+              { responseStatus = status500,+                responseVersion = http11,+                responseHeaders = [("Private-Token", "wnxczrmtabdywlrw")],+                responseBody = "{}",+                responseCookieJar = mempty,+                responseClose' = ResponseClose (pure ()),+                responseOriginalRequest = defaultRequest,+                responseEarlyHints = []+              }+      let rendered = Text.pack (renderResponseForLogging defaultLogPolicy response)+      Text.isInfixOf "wnxczrmtabdywlrw" rendered `shouldBe` False+      Text.isInfixOf "Private-Token" rendered `shouldBe` False++    it "redacts a secret it keeps the name of" $ do+      let response =+            Response+              { responseStatus = status500,+                responseVersion = http11,+                responseHeaders = [("Authorization", "Bearer wnxczrmtabdywlrw")],+                responseBody = "{}",+                responseCookieJar = mempty,+                responseClose' = ResponseClose (pure ()),+                responseOriginalRequest = defaultRequest,+                responseEarlyHints = []+              }+      let rendered = Text.pack (renderResponseForLogging defaultLogPolicy response)+      Text.isInfixOf "wnxczrmtabdywlrw" rendered `shouldBe` False+      Text.isInfixOf "<REDACTED>" rendered `shouldBe` True++    it "keeps the same body prefix http-client would have kept" $ do+      let response =+            Response+              { responseStatus = status500,+                responseVersion = http11,+                responseHeaders = [],+                responseBody = LB.concat [LB.replicate 1024 0x7a, "TRAILING"],+                responseCookieJar = mempty,+                responseClose' = ResponseClose (pure ()),+                responseOriginalRequest = defaultRequest,+                responseEarlyHints = []+              }+      let rendered = Text.pack (renderResponseForLogging defaultLogPolicy response)+      Text.count "z" rendered `shouldBe` 1024++  describe "withheldResponseBody" $+    it "says why the body was left out" $+      withheldResponseBody `shouldBe` "<WITHHELD: may contain a credential>"++  describe "renderBodyForLogging" $+    it "keeps the same prefix of a body as of a response" $ do+      let rendered = renderBodyForLogging (LB.concat [LB.replicate 1024 0x7a, "TRAILING"])+      Text.count "z" (Text.pack rendered) `shouldBe` 1024+      Text.isInfixOf "TRAILING" (Text.pack rendered) `shouldBe` False
+ test/Network/HTTP/Env/ManagerSpec.hs view
@@ -0,0 +1,89 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++module Network.HTTP.Env.ManagerSpec (spec) where++import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as LB+import Network.HTTP.Client (HttpException, ManagerSettings (..), httpLbs, newManager, parseRequest, requestHeaders, responseBody)+import Network.HTTP.Client.TLS (tlsManagerSettings)+import Network.HTTP.Env.Manager (tlsManagerSettingsWithMaxHeaderLength, withUserAgent)+import Network.HTTP.Types (status200)+import Network.Wai (responseLBS)+import qualified Network.Wai as Wai+import qualified Network.Wai.Handler.Warp as Warp+import Test.Syd+import UnliftIO (try)++spec :: Spec+spec = do+  describe "tlsManagerSettingsWithMaxHeaderLength" $ do+    it "reads a response carrying a header field up to the limit" $ do+      man <- newManager (tlsManagerSettingsWithMaxHeaderLength (16 * 1024))+      let application _ respond =+            respond $+              responseLBS+                status200+                [("Content-Security-Policy", ByteString.replicate (9 * 1024) 0x78)]+                "hello"+      Warp.testWithApplication (pure application) $ \port -> do+        request <- parseRequest (concat ["http://127.0.0.1:", show port])+        response <- httpLbs request man+        responseBody response `shouldBe` "hello"++    it "refuses a response carrying a header field past the limit" $ do+      man <- newManager (tlsManagerSettingsWithMaxHeaderLength 1024)+      let application _ respond =+            respond $+              responseLBS+                status200+                [("Content-Security-Policy", ByteString.replicate (64 * 1024) 0x78)]+                "hello"+      Warp.testWithApplication (pure application) $ \port -> do+        request <- parseRequest (concat ["http://127.0.0.1:", show port])+        result <- try (httpLbs request man)+        case result of+          Left (_ :: HttpException) -> pure ()+          Right _ -> expectationFailure "the overlong header was read"++  describe "withUserAgent" $ do+    it "sends its user agent in place of the one a request already carries" $ do+      man <- newManager (withUserAgent "some-agent" tlsManagerSettings)+      let application request respond =+            respond $+              responseLBS+                status200+                []+                (LB.fromStrict (ByteString.intercalate "," [v | ("User-Agent", v) <- Wai.requestHeaders request]))+      Warp.testWithApplication (pure application) $ \port -> do+        request <- parseRequest (concat ["http://127.0.0.1:", show port])+        response <- httpLbs request {requestHeaders = [("User-Agent", "something-else")]} man+        responseBody response `shouldBe` "some-agent"++    it "keeps the request modifier of the settings it is given" $ do+      let inner =+            tlsManagerSettings+              { managerModifyRequest = \request ->+                  -- Replacing rather than adding, because http-client may run a+                  -- modifier more than once on one request.+                  pure request {requestHeaders = ("X-Inner", "1") : filter ((/= "X-Inner") . fst) (requestHeaders request)}+              }+      man <- newManager (withUserAgent "some-agent" inner)+      let application request respond =+            respond $+              responseLBS+                status200+                []+                ( LB.fromStrict+                    ( ByteString.intercalate+                        ","+                        [ v+                        | (name, v) <- Wai.requestHeaders request,+                          name `elem` ["User-Agent", "X-Inner"]+                        ]+                    )+                )+      Warp.testWithApplication (pure application) $ \port -> do+        request <- parseRequest (concat ["http://127.0.0.1:", show port])+        response <- httpLbs request man+        responseBody response `shouldBe` "1,some-agent"
+ test/Network/HTTP/Env/MetricsSpec.hs view
@@ -0,0 +1,72 @@+{-# LANGUAGE OverloadedStrings #-}++module Network.HTTP.Env.MetricsSpec (spec) where++import Network.HTTP.Env.CircuitBreaker (CircuitReport (..))+import Network.HTTP.Env.FailureBudget (FailureBudgetReport (..), FailureBudgetStatus (..))+import Network.HTTP.Env.HttpClient (HttpEnvReport (..))+import Network.HTTP.Env.Metrics (httpEnvReportValue, httpEnvSample)+import qualified System.Metrics.Prometheus.Metric as Prometheus (MetricSample (..))+import qualified System.Metrics.Prometheus.Metric.Gauge as Prometheus (GaugeSample (..))+import qualified System.Metrics.Prometheus.MetricId as Labels+import qualified System.Metrics.Prometheus.MetricId as Prometheus (MetricId (..), Name (..))+import Test.Syd++spec :: Spec+spec = do+  let within =+        FailureBudgetReport+          { failureBudgetReportFailures = 1,+            failureBudgetReportStatus = FailureBudgetStatusWithin+          }+  let exhausted =+        FailureBudgetReport+          { failureBudgetReportFailures = 5,+            failureBudgetReportStatus = FailureBudgetStatusExhausted+          }+  let report circuit budget =+        HttpEnvReport+          { httpEnvReportCircuit = circuit,+            httpEnvReportFailureBudget = budget+          }++  -- [check:tag CircuitBreakerGaugeScale] A dashboard colours these four+  -- readings with thresholds of its own. A reading that moves, or a fifth+  -- one, needs a threshold step to match.+  describe "httpEnvReportValue" $ do+    it "reads the whole scale from healthy down to rejecting" $+      map+        httpEnvReportValue+        [ report (Just CircuitReportClosed) (Just within),+          report (Just CircuitReportClosed) (Just exhausted),+          report (Just CircuitReportProbing) (Just within),+          report (Just CircuitReportRejecting) (Just within)+        ]+        `shouldBe` [1, 0.75, 0.5, 0]+    it "reads the worse of the breaker and the budget" $+      map+        httpEnvReportValue+        [ report (Just CircuitReportProbing) (Just exhausted),+          report (Just CircuitReportRejecting) (Just exhausted)+        ]+        `shouldBe` [0.5, 0]+    it "reads an env with neither a breaker nor a budget as healthy" $+      httpEnvReportValue (report Nothing Nothing) `shouldBe` 1+    it "reads either half alone" $+      map+        httpEnvReportValue+        [ report Nothing (Just exhausted),+          report (Just CircuitReportRejecting) Nothing+        ]+        `shouldBe` [0.75, 0]++  describe "httpEnvSample" $+    it "reports the value of a report under the name and labels given" $+      case httpEnvSample "some_metric" (Labels.fromList [("dependency", "exhausted-one")]) (report (Just CircuitReportClosed) (Just exhausted)) of+        (metricId, Prometheus.GaugeMetricSample (Prometheus.GaugeSample value)) ->+          ( Prometheus.unName (Prometheus.name metricId),+            Labels.toList (Prometheus.labels metricId),+            value+          )+            `shouldBe` ("some_metric", [("dependency", "exhausted-one")], 0.75)+        _ -> expectationFailure "expected a gauge"
+ test/Network/HTTP/Env/NumericSpec.hs view
@@ -0,0 +1,33 @@+{-# LANGUAGE NumericUnderscores #-}++module Network.HTTP.Env.NumericSpec (spec) where++import Data.Word (Word64)+import Network.HTTP.Env.Numeric+import Test.Syd++spec :: Spec+spec = do+  describe "integerToCount" $ do+    it "reads every count from zero to the largest Int" $+      map integerToCount [0, 1, toInteger (maxBound :: Int)]+        `shouldBe` [Just 0, Just 1, Just 9223372036854775807]+    it "reads nothing below zero or above the largest Int" $+      map integerToCount [-1, toInteger (maxBound :: Int) + 1]+        `shouldBe` [Nothing, Nothing]++  describe "nominalDiffTimeToNanos" $ do+    it "rounds to the nearest nanosecond" $+      nominalDiffTimeToNanos 1.0000000016 `shouldBe` 1_000_000_002+    it "holds a negative duration at zero" $+      nominalDiffTimeToNanos (-1) `shouldBe` 0+    it "holds a duration too long to count at the largest count" $+      nominalDiffTimeToNanos 18446744073.709551616 `shouldBe` (maxBound :: Word64)++  describe "nominalDiffTimeToMicros" $ do+    it "rounds to the nearest microsecond" $+      nominalDiffTimeToMicros 1.0000016 `shouldBe` 1_000_002+    it "holds a negative duration at zero" $+      nominalDiffTimeToMicros (-1) `shouldBe` 0+    it "holds a duration too long to count at the largest count" $+      nominalDiffTimeToMicros 9223372036854.775808 `shouldBe` (maxBound :: Int)
+ test/Network/HTTP/Env/OptParse/DurationSpec.hs view
@@ -0,0 +1,128 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}++module Network.HTTP.Env.OptParse.DurationSpec (spec) where++import Autodocodec (parseJSONViaCodec, toJSONViaCodec)+import qualified Data.Aeson as JSON+import Data.Aeson.Types (parseEither)+import Data.GenValidity.Time ()+import Data.Time (NominalDiffTime)+import Network.HTTP.Env.OptParse.Duration+import Test.Syd+import Test.Syd.Validity++spec :: Spec+spec = do+  describe "formatDuration" $ do+    it "formats zero in seconds" $+      formatDuration (Duration 0) `shouldBe` "0s"+    it "formats seconds" $+      formatDuration (Duration 30) `shouldBe` "30s"+    it "formats a minute less a second in seconds" $+      formatDuration (Duration 59) `shouldBe` "59s"+    it "formats minutes" $+      formatDuration (Duration 120) `shouldBe` "2m"+    it "formats what no minute divides in seconds" $+      formatDuration (Duration 3599) `shouldBe` "3599s"+    it "formats a fraction of a second exactly" $+      formatDuration (Duration 0.1) `shouldBe` "0.1s"+    it "formats hours" $+      formatDuration (Duration 7200) `shouldBe` "2h"+    it "formats what no hour divides in the largest unit that does" $+      formatDuration (Duration 5400) `shouldBe` "90m"+    it "formats days" $+      formatDuration (Duration 172800) `shouldBe` "2d"+    it "formats weeks" $+      formatDuration (Duration 1209600) `shouldBe` "2w"+    it "formats months" $+      formatDuration (Duration 5184000) `shouldBe` "2M"+    it "formats each unit from the moment it is filled once" $+      map (formatDuration . Duration) [60, 3600, 86400, 604800, 2592000]+        `shouldBe` ["1m", "1h", "1d", "1w", "1M"]++  describe "renderDurationParseError" $+    it "renders each error" $+      map+        renderDurationParseError+        [ DurationParseErrorMustStartWithNumber,+          DurationParseErrorInvalidNumber,+          DurationParseErrorUnknownUnit "x"+        ]+        `shouldBe` [ "Duration must start with a number",+                     "Invalid number",+                     "Unknown duration unit: x. Valid units: s, m, h, d, w, M, seconds, minutes, hours, days, weeks, months"+                   ]++  describe "parseDuration" $ do+    it "parses plain numbers as seconds" $+      parseDuration "3600" `shouldBe` Right (Duration 3600)+    it "parses s suffix" $+      parseDuration "30s" `shouldBe` Right (Duration 30)+    it "parses m suffix" $+      parseDuration "5m" `shouldBe` Right (Duration 300)+    it "parses h suffix" $+      parseDuration "2h" `shouldBe` Right (Duration 7200)+    it "parses d suffix" $+      parseDuration "7d" `shouldBe` Right (Duration 604800)+    it "parses w suffix" $+      parseDuration "2w" `shouldBe` Right (Duration 1209600)+    it "parses M suffix" $+      parseDuration "3M" `shouldBe` Right (Duration 7776000)+    it "parses 'seconds' word" $+      parseDuration "30 seconds" `shouldBe` Right (Duration 30)+    it "parses 'minutes' word" $+      parseDuration "5 minutes" `shouldBe` Right (Duration 300)+    it "parses 'hours' word" $+      parseDuration "2 hours" `shouldBe` Right (Duration 7200)+    it "parses 'days' word" $+      parseDuration "7 days" `shouldBe` Right (Duration 604800)+    it "parses 'weeks' word" $+      parseDuration "2 weeks" `shouldBe` Right (Duration 1209600)+    it "parses 'months' word" $+      parseDuration "3 months" `shouldBe` Right (Duration 7776000)+    it "parses words case-insensitively" $+      parseDuration "2 Hours" `shouldBe` Right (Duration 7200)+    it "parses with spaces" $+      parseDuration "90 d" `shouldBe` Right (Duration 7776000)+    it "parses decimals" $+      parseDuration "1.5h" `shouldBe` Right (Duration 5400)+    it "fails on input without a number" $+      parseDuration "days" `shouldBe` Left DurationParseErrorMustStartWithNumber+    it "fails on a number that does not read" $+      parseDuration "1.2.3s" `shouldBe` Left DurationParseErrorInvalidNumber+    it "fails on invalid unit" $+      parseDuration "10x" `shouldBe` Left (DurationParseErrorUnknownUnit "x")++  describe "roundtrip" $ do+    it "format-parse-format re-renders identically" $+      forAllValid $ \(seconds :: NominalDiffTime) -> do+        let rendered = formatDuration (Duration (abs seconds))+        fmap formatDuration (parseDuration rendered) `shouldBe` Right rendered++    let unitBoundaryTest duration =+          it (unwords ["roundtrips the exact unit boundary", show duration]) $+            parseDuration (formatDuration duration) `shouldBe` Right duration+    unitBoundaryTest (Duration 0)+    unitBoundaryTest (Duration 60)+    unitBoundaryTest (Duration 3600)+    unitBoundaryTest (Duration 86400)+    unitBoundaryTest (Duration 604800)+    unitBoundaryTest (Duration 2592000)++  describe "codec" $ do+    it "decodes what it encodes" $+      forAllValid $ \(seconds :: NominalDiffTime) ->+        let duration = Duration (abs seconds)+         in parseEither (parseJSONViaCodec @Duration) (toJSONViaCodec duration) `shouldBe` Right duration+    it "decodes a duration with a unit" $+      parseEither (parseJSONViaCodec @Duration) (JSON.String "5m") `shouldBe` Right (Duration 300)+    it "decodes a whole number of seconds" $+      parseEither (parseJSONViaCodec @Duration) (JSON.Number 90) `shouldBe` Right (Duration 90)+    it "refuses a string that is not a duration" $+      case parseEither (parseJSONViaCodec @Duration) (JSON.String "soon") of+        Left _ -> pure ()+        Right d -> expectationFailure (unwords ["parsed", show d])+    it "encodes as a duration with a unit" $+      toJSONViaCodec (Duration 7200) `shouldBe` JSON.String "2h"
+ test/Network/HTTP/Env/OptParseSpec.hs view
@@ -0,0 +1,410 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE NumericUnderscores #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeApplications #-}++module Network.HTTP.Env.OptParseSpec (spec) where++import Control.Monad.Logger.CallStack (runNoLoggingT)+import Control.Retry (simulatePolicy)+import qualified Data.Aeson as JSON+import qualified Data.Aeson.KeyMap as KeyMap+import Data.List (isInfixOf)+import qualified Data.Set as Set+import Network.HTTP.Client (HttpException (..), HttpExceptionContent (..), defaultManagerSettings, newManager, parseUrlThrow, responseHeaders)+import Network.HTTP.Env.CircuitBreaker+import Network.HTTP.Env.CircuitBreaker.Retry (Attempts (..))+import Network.HTTP.Env.FailureBudget+import Network.HTTP.Env.HttpClient (HttpEnv (..), HttpEnvError (..), HttpEnvReport (..), httpCall, peekHttpEnv)+import Network.HTTP.Env.LogPolicy (LogPolicy (..), defaultHeadersToLog, defaultLogPolicy)+import Network.HTTP.Env.Numeric (wordToInt)+import Network.HTTP.Env.OptParse+import Network.HTTP.Env.OptParse.Gen ()+import Network.HTTP.Env.RateLimit (RateLimitHeaders (..))+import Network.HTTP.Env.RateLimit.Gen ()+import Network.HTTP.Types (status404, status504)+import Network.Wai (responseLBS)+import qualified Network.Wai.Handler.Warp as Warp+import OptEnvConf (settingsParser)+import OptEnvConf.Args (parseArgs)+import qualified OptEnvConf.EnvMap as EnvMap+import OptEnvConf.Test (allCapabilities, goldenParserReferenceDocumentationSpec, goldenSettingsReferenceDocumentationSpec, runParserOn)+import Test.QuickCheck (choose, forAll)+import Test.Syd+import Test.Syd.Validity++spec :: Spec+spec = do+  describe "GenValid" $ do+    genValidSpec @BackoffSettings+    genValidSpec @BackoffOverrides+    genValidSpec @RateLimitHeaders+    genValidSpec @HttpEnvSettings+    genValidSpec @HttpEnvOverrides+    genValidSpec @CircuitBreakerOverrides+    genValidSpec @FailureBudgetOverrides++  describe "HttpEnvOverrides" $ do+    let parseResultFromConf conf = runParserOn allCapabilities Nothing (httpEnvOverridesParser noHttpEnvOverrides) (parseArgs []) EnvMap.empty (Just (KeyMap.fromList conf))+    let parseFromConf :: [(KeyMap.Key, JSON.Value)] -> IO HttpEnvOverrides+        parseFromConf conf =+          parseResultFromConf conf >>= \case+            Left errors -> expectationFailure (show errors)+            Right parsed -> pure parsed+    let parseErrorsFromConf :: [(KeyMap.Key, JSON.Value)] -> IO String+        parseErrorsFromConf conf =+          parseResultFromConf conf >>= \case+            Left errors -> pure (show errors)+            Right parsed -> expectationFailure (unwords ["expected it to be refused, but it parsed to", show parsed])+    it "overrides nothing when nothing is configured" $+      parseFromConf [] `shouldReturn` noHttpEnvOverrides+    it "reads every field from a configuration file" $+      parseFromConf+        [ ("attempts-per-request", JSON.Number 7),+          ("backoff", JSON.object [("base", JSON.String "2s"), ("max-delay", JSON.String "10s"), ("max-total-delay", JSON.String "20s")]),+          ("circuit-breaker", JSON.object [("failure-threshold", JSON.Number 9), ("reset-timeout", JSON.String "0.5s")]),+          ("failure-budget", JSON.object [("failures", JSON.Number 3), ("window", JSON.String "10m")]),+          ("rate-limit-headers", JSON.String "x-ratelimit")+        ]+        `shouldReturn` HttpEnvOverrides+          { httpEnvOverridesAttemptsPerRequest = Just (Attempts 7),+            httpEnvOverridesBackoff =+              BackoffOverrides+                { backoffOverridesBase = Just 2,+                  backoffOverridesMaxDelay = Just 10,+                  backoffOverridesMaxTotalDelay = Just 20+                },+            httpEnvOverridesCircuitBreaker =+              CircuitBreakerOverrides+                { circuitBreakerOverridesFailureThreshold = Just 9,+                  circuitBreakerOverridesResetTimeout = Just 0.5+                },+            httpEnvOverridesFailureBudget =+              FailureBudgetOverrides+                { failureBudgetOverridesFailures = Just 3,+                  failureBudgetOverridesWindow = Just 600+                },+            httpEnvOverridesRateLimitHeaders = Just (Just RateLimitHeadersXRateLimit)+          }+    let refuses :: KeyMap.Key -> JSON.Value -> String -> Spec+        refuses key value reason =+          it (unwords ["refuses", show value, "for", show key]) $ do+            errors <- parseErrorsFromConf [(key, value)]+            errors `shouldSatisfy` isInfixOf reason+    refuses "attempts-per-request" (JSON.Number 0) "a call must be allowed at least one request"+    let refusesOnTheCommandLine :: [String] -> Spec+        refusesOnTheCommandLine args =+          it (unwords ["refuses", show args]) $ do+            result <- runParserOn allCapabilities Nothing (httpEnvOverridesParser noHttpEnvOverrides) (parseArgs args) EnvMap.empty Nothing+            case result of+              Left _ -> pure ()+              Right parsed -> expectationFailure (unwords ["expected it to be refused, but it parsed to", show parsed])+    it "reads a count on the command line" $ do+      result <- runParserOn allCapabilities Nothing (httpEnvOverridesParser noHttpEnvOverrides) (parseArgs ["--attempts-per-request", "3"]) EnvMap.empty Nothing+      case result of+        Left errors -> expectationFailure (show errors)+        Right parsed -> httpEnvOverridesAttemptsPerRequest parsed `shouldBe` Just (Attempts 3)+    it "says which count it cannot read" $ do+      result <- runParserOn allCapabilities Nothing (httpEnvOverridesParser noHttpEnvOverrides) (parseArgs ["--attempts-per-request", "-1"]) EnvMap.empty Nothing+      case result of+        Left errors -> show errors `shouldSatisfy` isInfixOf "not a count: \\\"-1\\\""+        Right parsed -> expectationFailure (show parsed)+    refusesOnTheCommandLine ["--attempts-per-request", "-1"]+    refusesOnTheCommandLine ["--circuit-breaker-failure-threshold", "-1"]+    refusesOnTheCommandLine ["--failure-budget-failures", "-1"]+    refusesOnTheCommandLine ["--attempts-per-request", "18446744073709551617"]+    refusesOnTheCommandLine ["--attempts-per-request", "9223372036854775808"]+    refusesOnTheCommandLine ["--failure-budget-failures", "9223372036854775808"]+    refuses "backoff" (JSON.object [("base", JSON.String "0s")]) "the backoff base must be positive"+    refuses "backoff" (JSON.object [("max-delay", JSON.String "0s")]) "the longest wait must be positive"+    refuses "backoff" (JSON.object [("max-total-delay", JSON.String "0s")]) "the longest total wait must be positive"+    refuses "circuit-breaker" (JSON.object [("failure-threshold", JSON.Number 0)]) "the circuit-breaker failure threshold must be at least 1"+    refuses "circuit-breaker" (JSON.object [("reset-timeout", JSON.String "0s")]) "the circuit-breaker reset timeout must be positive"+    refuses "failure-budget" (JSON.object [("failures", JSON.Number 0)]) "the failure budget must allow at least one failure"+    refuses "failure-budget" (JSON.object [("window", JSON.String "0s")]) "the failure budget window must be positive"+    refuses "rate-limit-headers" (JSON.String "github") "unknown rate-limit headers: \\\"github\\\""+    it "reads none as no rate-limit headers" $+      parseFromConf [("rate-limit-headers", JSON.String "none")]+        `shouldReturn` noHttpEnvOverrides {httpEnvOverridesRateLimitHeaders = Just Nothing}+    it "accepts one for every count" $+      parseFromConf+        [ ("attempts-per-request", JSON.Number 1),+          ("circuit-breaker", JSON.object [("failure-threshold", JSON.Number 1)]),+          ("failure-budget", JSON.object [("failures", JSON.Number 1)])+        ]+        `shouldReturn` noHttpEnvOverrides+          { httpEnvOverridesAttemptsPerRequest = Just (Attempts 1),+            httpEnvOverridesCircuitBreaker = (httpEnvOverridesCircuitBreaker noHttpEnvOverrides) {circuitBreakerOverridesFailureThreshold = Just 1},+            httpEnvOverridesFailureBudget = (httpEnvOverridesFailureBudget noHttpEnvOverrides) {failureBudgetOverridesFailures = Just 1}+          }+    goldenParserReferenceDocumentationSpec (httpEnvOverridesParser noHttpEnvOverrides) "test_resources/http-settings.txt" "example"++  describe "applyHttpEnvOverrides" $ do+    it "changes nothing when it overrides nothing" $+      forAllValid $ \settings ->+        applyHttpEnvOverrides noHttpEnvOverrides settings `shouldBe` settings+    it "sets every field it is given" $+      forAllValid $ \settings ->+        applyHttpEnvOverrides+          HttpEnvOverrides+            { httpEnvOverridesAttemptsPerRequest = Just (Attempts 7),+              httpEnvOverridesBackoff =+                BackoffOverrides+                  { backoffOverridesBase = Just 2,+                    backoffOverridesMaxDelay = Just 10,+                    backoffOverridesMaxTotalDelay = Just 20+                  },+              httpEnvOverridesCircuitBreaker =+                CircuitBreakerOverrides+                  { circuitBreakerOverridesFailureThreshold = Just 9,+                    circuitBreakerOverridesResetTimeout = Just 0.5+                  },+              httpEnvOverridesFailureBudget =+                FailureBudgetOverrides+                  { failureBudgetOverridesFailures = Just 3,+                    failureBudgetOverridesWindow = Just 600+                  },+              httpEnvOverridesRateLimitHeaders = Just (Just RateLimitHeadersRateLimitReset)+            }+          settings+          `shouldBe` HttpEnvSettings+            { httpEnvSettingsAttemptsPerRequest = Attempts 7,+              httpEnvSettingsBackoff =+                BackoffSettings+                  { backoffSettingsBase = 2,+                    backoffSettingsMaxDelay = 10,+                    backoffSettingsMaxTotalDelay = 20+                  },+              httpEnvSettingsCircuitBreaker =+                CircuitBreakerSettings+                  { circuitBreakerSettingsFailureThreshold = 9,+                    circuitBreakerSettingsResetTimeout = 0.5+                  },+              httpEnvSettingsFailureBudget =+                FailureBudgetSettings+                  { failureBudgetSettingsFailures = 3,+                    failureBudgetSettingsWindow = 600+                  },+              httpEnvSettingsRateLimitHeaders = Just RateLimitHeadersRateLimitReset+            }+    it "produces valid settings from valid ones" $+      forAllValid $ \overrides ->+        forAllValid $ \settings ->+          shouldBeValid (applyHttpEnvOverrides overrides settings)++  describe "resolveHttpEnvSettings" $ do+    it "gives the global settings to a dependency whose block sets nothing" $+      forAllValid $ \global ->+        resolveHttpEnvSettings global noHttpEnvOverrides `shouldBe` global+    it "gives a dependency whose block sets everything only what its block sets" $+      forAllValid $ \global ->+        forAllValid $ \own ->+          resolveHttpEnvSettings global (fullHttpEnvOverrides own) `shouldBe` own++  describe "HttpEnvSettings" $ do+    let parseResultFromConf conf = runParserOn allCapabilities Nothing (settingsParser @HttpEnvSettings) (parseArgs []) EnvMap.empty (Just (KeyMap.fromList conf))+    let parseFromConf :: [(KeyMap.Key, JSON.Value)] -> IO HttpEnvSettings+        parseFromConf conf =+          parseResultFromConf conf >>= \case+            Left errors -> expectationFailure (show errors)+            Right parsed -> pure parsed+    let parseErrorsFromConf :: [(KeyMap.Key, JSON.Value)] -> IO String+        parseErrorsFromConf conf =+          parseResultFromConf conf >>= \case+            Left errors -> pure (show errors)+            Right parsed -> expectationFailure (unwords ["expected it to be refused, but it parsed to", show parsed])+    it "defaults to the default settings" $+      parseFromConf [] `shouldReturn` defaultHttpEnvSettings+    it "reads a field from a configuration file and keeps the defaults of the others" $+      parseFromConf [("attempts-per-request", JSON.Number 7)]+        `shouldReturn` defaultHttpEnvSettings {httpEnvSettingsAttemptsPerRequest = Attempts 7}+    it "refuses an invalid field" $ do+      errors <- parseErrorsFromConf [("attempts-per-request", JSON.Number 0)]+      errors `shouldSatisfy` isInfixOf "a call must be allowed at least one request"+    goldenSettingsReferenceDocumentationSpec @HttpEnvSettings "test_resources/http-env-settings.txt" "example"++  describe "httpEnvOverridesParser" $ do+    let chosen =+          noHttpEnvOverrides+            { httpEnvOverridesAttemptsPerRequest = Just (Attempts 2),+              httpEnvOverridesBackoff = (httpEnvOverridesBackoff noHttpEnvOverrides) {backoffOverridesBase = Just 0.1},+              httpEnvOverridesRateLimitHeaders = Just (Just RateLimitHeadersXRateLimit)+            }+    let parseResultFromConf conf = runParserOn allCapabilities Nothing (httpEnvOverridesParser chosen) (parseArgs []) EnvMap.empty (Just (KeyMap.fromList conf))+    let parseFromConf :: [(KeyMap.Key, JSON.Value)] -> IO HttpEnvOverrides+        parseFromConf conf =+          parseResultFromConf conf >>= \case+            Left errors -> expectationFailure (show errors)+            Right parsed -> pure parsed+    let parseErrorsFromConf :: [(KeyMap.Key, JSON.Value)] -> IO String+        parseErrorsFromConf conf =+          parseResultFromConf conf >>= \case+            Left errors -> pure (show errors)+            Right parsed -> expectationFailure (unwords ["expected it to be refused, but it parsed to", show parsed])+    it "defaults to the application's choice" $+      parseFromConf [] `shouldReturn` chosen+    it "takes what the operator sets over the application's choice, and leaves the rest unset" $+      parseFromConf [("attempts-per-request", JSON.Number 3), ("failure-budget", JSON.object [("failures", JSON.Number 9)])]+        `shouldReturn` chosen+          { httpEnvOverridesAttemptsPerRequest = Just (Attempts 3),+            httpEnvOverridesFailureBudget = (httpEnvOverridesFailureBudget chosen) {failureBudgetOverridesFailures = Just 9}+          }+    it "checks a value the operator sets over the application's choice" $ do+      errors <- parseErrorsFromConf [("attempts-per-request", JSON.Number 0)]+      errors `shouldSatisfy` isInfixOf "a call must be allowed at least one request"++  describe "Validity HttpEnvOverrides" $ do+    it "accepts overrides of the smallest values that make sense" $+      shouldBeValid+        HttpEnvOverrides+          { httpEnvOverridesAttemptsPerRequest = Just (Attempts 1),+            httpEnvOverridesBackoff = (httpEnvOverridesBackoff noHttpEnvOverrides) {backoffOverridesBase = Just 0.000000000001},+            httpEnvOverridesCircuitBreaker =+              CircuitBreakerOverrides+                { circuitBreakerOverridesFailureThreshold = Just 1,+                  circuitBreakerOverridesResetTimeout = Just 0.000000000001+                },+            httpEnvOverridesFailureBudget =+              FailureBudgetOverrides+                { failureBudgetOverridesFailures = Just 1,+                  failureBudgetOverridesWindow = Just 0.000000000001+                },+            httpEnvOverridesRateLimitHeaders = Just Nothing+          }+    it "refuses a backoff base of zero" $+      shouldBeInvalid (httpEnvOverridesBackoff noHttpEnvOverrides) {backoffOverridesBase = Just 0}+    it "refuses a failure threshold of zero" $+      shouldBeInvalid (httpEnvOverridesCircuitBreaker noHttpEnvOverrides) {circuitBreakerOverridesFailureThreshold = Just 0}+    it "refuses a reset timeout of zero" $+      shouldBeInvalid (httpEnvOverridesCircuitBreaker noHttpEnvOverrides) {circuitBreakerOverridesResetTimeout = Just 0}+    it "refuses a failure budget of no failures" $+      shouldBeInvalid (httpEnvOverridesFailureBudget noHttpEnvOverrides) {failureBudgetOverridesFailures = Just 0}+    it "refuses a failure budget window of zero" $+      shouldBeInvalid (httpEnvOverridesFailureBudget noHttpEnvOverrides) {failureBudgetOverridesWindow = Just 0}++  describe "Validity BackoffSettings" $ do+    it "accepts the smallest durations that make sense" $+      shouldBeValid (BackoffSettings 0.000000000001 0.000000000001 0.000000000001)+    it "refuses a base of zero" $+      shouldBeInvalid defaultBackoffSettings {backoffSettingsBase = 0}+    it "refuses a longest wait of zero" $+      shouldBeInvalid defaultBackoffSettings {backoffSettingsMaxDelay = 0}+    it "refuses a longest total wait of zero" $+      shouldBeInvalid defaultBackoffSettings {backoffSettingsMaxTotalDelay = 0}++  describe "Validity BackoffOverrides" $ do+    it "refuses a longest wait of zero" $+      shouldBeInvalid (httpEnvOverridesBackoff noHttpEnvOverrides) {backoffOverridesMaxDelay = Just 0}+    it "refuses a longest total wait of zero" $+      shouldBeInvalid (httpEnvOverridesBackoff noHttpEnvOverrides) {backoffOverridesMaxTotalDelay = Just 0}++  describe "defaultBackoffSettings" $+    it "waits based on a second, at most 30s at a time and a minute in all" $+      defaultBackoffSettings+        `shouldBe` BackoffSettings+          { backoffSettingsBase = 1,+            backoffSettingsMaxDelay = 30,+            backoffSettingsMaxTotalDelay = 60+          }++  describe "backoffPolicy" $ do+    it "waits between half the base and the base before the first retry" $ do+      delays <- simulatePolicy 2 (backoffPolicy defaultBackoffSettings {backoffSettingsBase = 2})+      case [delay | (0, Just delay) <- delays] of+        [delay] -> delay `shouldSatisfy` (\d -> d >= 1_000_000 && d <= 2_000_000)+        _ -> expectationFailure (show delays)+    it "never waits longer than the longest wait" $ do+      delays <- simulatePolicy 8 (backoffPolicy (BackoffSettings 1 3 1000))+      [delay | (_, Just delay) <- delays] `shouldSatisfy` all (<= 3_000_000)+    it "makes no further attempt once the waits add up to the longest total" $ do+      delays <- simulatePolicy 8 (backoffPolicy (BackoffSettings 1 3 5))+      sum [delay | (_, Just delay) <- delays] `shouldSatisfy` (<= 5_000_000)+      [() | (_, Nothing) <- delays] `shouldSatisfy` (not . null)++  describe "defaultHttpEnvSettings" $+    it "is valid" $+      shouldBeValid defaultHttpEnvSettings++  let fastSettings =+        defaultHttpEnvSettings+          { httpEnvSettingsBackoff =+              defaultBackoffSettings+                { backoffSettingsBase = 0.000001,+                  backoffSettingsMaxDelay = 0.000001+                }+          }++  describe "newHttpEnv" $ do+    it "reads the rate-limit headers the settings choose" $ do+      man <- newManager defaultManagerSettings+      env <-+        runNoLoggingT $+          newHttpEnv (HttpEnvName "test") fastSettings {httpEnvSettingsRateLimitHeaders = Just RateLimitHeadersStructured} defaultLogPolicy man+      httpEnvRateLimitHeaders env `shouldBe` Just RateLimitHeadersStructured++    it "guards the env with a breaker of the given name" $ do+      man <- newManager defaultManagerSettings+      env <-+        runNoLoggingT $+          newHttpEnv (HttpEnvName "some-dependency") fastSettings defaultLogPolicy man+      fmap circuitBreakerName (httpEnvCircuitBreaker env) `shouldBe` Just "some-dependency"++    it "gives the env a failure budget with nothing in it" $ do+      man <- newManager defaultManagerSettings+      env <-+        runNoLoggingT $+          newHttpEnv (HttpEnvName "some-dependency") fastSettings defaultLogPolicy man+      peekHttpEnv env+        `shouldReturn` HttpEnvReport+          { httpEnvReportCircuit = Just CircuitReportClosed,+            httpEnvReportFailureBudget =+              Just+                FailureBudgetReport+                  { failureBudgetReportFailures = 0,+                    failureBudgetReportStatus = FailureBudgetStatusWithin+                  }+          }++    it "leaves a default breaker closed after one request whose every attempt fails" $ do+      man <- newManager defaultManagerSettings+      env <-+        runNoLoggingT $+          newHttpEnv (HttpEnvName "test") fastSettings defaultLogPolicy man+      let application _ respond = respond (responseLBS status504 [] "")+      Warp.testWithApplication (pure application) $ \port -> do+        request <- parseUrlThrow (concat ["http://127.0.0.1:", show port, "/"])+        _ <- runNoLoggingT (httpCall env request)+        fmap httpEnvReportCircuit (peekHttpEnv env) `shouldReturn` Just CircuitReportClosed++    it "caps the policy it builds at the attempts per request" $+      forAll (choose (1, 32)) $ \attempts -> do+        man <- newManager defaultManagerSettings+        env <-+          runNoLoggingT $+            newHttpEnv+              (HttpEnvName "test")+              fastSettings {httpEnvSettingsAttemptsPerRequest = Attempts attempts}+              defaultLogPolicy+              man+        delays <- simulatePolicy 64 (httpEnvRetryPolicy env)+        let requests = 1 + length [() | (_, Just _) <- delays]+        requests `shouldBe` wordToInt attempts++    it "scrubs the failures of its calls with the log policy it is given" $ do+      man <- newManager defaultManagerSettings+      let policy :: LogPolicy+          policy =+            defaultLogPolicy+              { logPolicyHeadersToLog = Set.insert "X-Kept" defaultHeadersToLog+              }+      env <-+        runNoLoggingT $+          newHttpEnv (HttpEnvName "test") fastSettings policy man+      let application _ respond = respond (responseLBS status404 [("X-Kept", "1")] "")+      Warp.testWithApplication (pure application) $ \port -> do+        request <- parseUrlThrow (concat ["http://127.0.0.1:", show port, "/"])+        result <- runNoLoggingT (httpCall env request)+        case result of+          Left (HttpEnvErrorFailed (HttpExceptionRequest _ (StatusCodeException response _))) ->+            lookup "X-Kept" (responseHeaders response) `shouldBe` Just "1"+          _ -> expectationFailure "expected the server's own 404"
+ test/Network/HTTP/Env/PacingSpec.hs view
@@ -0,0 +1,108 @@+{-# LANGUAGE ScopedTypeVariables #-}++module Network.HTTP.Env.PacingSpec (spec) where++import Control.Concurrent.TokenLimiter.Concurrent+  ( Count,+    TokenLimitConfig (..),+    TokenLimiter (..),+  )+import Network.HTTP.Env.Pacing+import Test.Syd+import Test.Syd.Validity+import UnliftIO.Async (replicateConcurrently)++spec :: Spec+spec = do+  describe "requestsPerHourConfig" $ do+    it "affords exactly the configured number of requests an hour" $+      forAllValid $ \(requestsPerHour :: Count) -> do+        tokenLimitConfigTokensPerSecond (requestsPerHourConfig requestsPerHour)+          `shouldBe` max 1 requestsPerHour+        requestTokenCost `shouldBe` 3600++    it "never builds a bucket that cannot refill" $+      tokenLimitConfigTokensPerSecond (requestsPerHourConfig 0)+        `shouldBe` 1++    it "starts full, so a quiet key can answer a burst at once" $+      forAllValid $ \(requestsPerHour :: Count) -> do+        let config = requestsPerHourConfig requestsPerHour+        tokenLimitConfigInitialTokens config+          `shouldBe` tokenLimitConfigMaxTokens config++    it "holds a burst of fifty requests" $+      forAllValid $ \(requestsPerHour :: Count) ->+        tokenLimitConfigMaxTokens (requestsPerHourConfig requestsPerHour)+          `shouldBe` 180000++  describe "keyedLimiter" $ do+    it "gives the same key the same limiter" $+      forAllValid $ \(key :: Int) -> do+        limiters <- newKeyedLimiters 4500+        first <- keyedLimiter limiters key+        second <- keyedLimiter limiters key+        (first == second) `shouldBe` True++    it "gives different keys different limiters" $+      forAllValid $ \(key :: Int) -> do+        limiters <- newKeyedLimiters 4500+        first <- keyedLimiter limiters key+        second <- keyedLimiter limiters (key + 1)+        (first == second) `shouldBe` False++    it "keeps every key's limiter as the others are used" $+      forAllValid $ \(key :: Int) -> do+        limiters <- newKeyedLimiters 4500+        one <- keyedLimiter limiters key+        other <- keyedLimiter limiters (key + 1)+        oneAgain <- keyedLimiter limiters key+        otherAgain <- keyedLimiter limiters (key + 1)+        (one == oneAgain, other == otherAgain) `shouldBe` (True, True)++    it "gives concurrent callers on one key the same limiter" $+      forAllValid $ \(key :: Int) -> do+        limiters <- newKeyedLimiters 4500+        gotten <- replicateConcurrently 16 (keyedLimiter limiters key)+        case gotten of+          [] -> expectationFailure "asked for no limiters"+          firstLimiter : rest -> all (== firstLimiter) rest `shouldBe` True++  describe "repaceRequestLimiter" $ do+    it "paces at the new rate" $ do+      limiter <- newRequestLimiter 4500+      repaceRequestLimiter limiter 9000+      tokenLimiter <- requestLimiterTokenLimiter limiter+      tokenLimitConfigTokensPerSecond (tokenLimiterConfig tokenLimiter) `shouldBe` 9000++    it "keeps the same bucket when the rate is the one it already paces at" $ do+      limiter <- newRequestLimiter 9000+      beforehand <- requestLimiterTokenLimiter limiter+      repaceRequestLimiter limiter 9000+      afterwards <- requestLimiterTokenLimiter limiter+      (tokenLimiterLastServiced beforehand == tokenLimiterLastServiced afterwards) `shouldBe` True++  describe "observeRequestsPerHour" $ do+    it "paces a key at what the dependency says it is allowed" $+      forAllValid $ \(key :: Int) ->+        forAllValid $ \(generated :: Count) -> do+          let allowed = 1 + min generated 99999+          limiters <- newKeyedLimiters 4500+          observeRequestsPerHour limiters key allowed+          tokenLimiter <- keyedLimiter limiters key >>= requestLimiterTokenLimiter+          tokenLimitConfigTokensPerSecond (tokenLimiterConfig tokenLimiter) `shouldBe` allowed++    it "repaces a limiter that was already handed out" $+      forAllValid $ \(key :: Int) -> do+        limiters <- newKeyedLimiters 4500+        limiter <- keyedLimiter limiters key+        observeRequestsPerHour limiters key 9000+        tokenLimiter <- requestLimiterTokenLimiter limiter+        tokenLimitConfigTokensPerSecond (tokenLimiterConfig tokenLimiter) `shouldBe` 9000++    it "paces no key but the one the dependency answered about" $+      forAllValid $ \(key :: Int) -> do+        limiters <- newKeyedLimiters 4500+        observeRequestsPerHour limiters key 12500+        tokenLimiter <- keyedLimiter limiters (key + 1) >>= requestLimiterTokenLimiter+        tokenLimitConfigTokensPerSecond (tokenLimiterConfig tokenLimiter) `shouldBe` 4500
+ test/Network/HTTP/Env/RateLimitSpec.hs view
@@ -0,0 +1,521 @@+{-# LANGUAGE OverloadedStrings #-}++module Network.HTTP.Env.RateLimitSpec (spec) where++import qualified Data.Set as Set+import Data.Time.Clock.POSIX (posixSecondsToUTCTime)+import Network.HTTP.Client+  ( HttpException (..),+    HttpExceptionContent (..),+    defaultRequest,+  )+import Network.HTTP.Client.Internal (Response (..), ResponseClose (..))+import Network.HTTP.Env.LogPolicy (LogPolicy (..), defaultHeadersToLog, defaultLogPolicy, scrubHttpException)+import Network.HTTP.Env.RateLimit+import Network.HTTP.Types (http11, mkStatus)+import Test.Syd++spec :: Spec+spec = do+  describe "renderRateLimitHeaders" $+    it "is read back by parseRateLimitHeaders" $+      map (parseRateLimitHeaders . renderRateLimitHeaders) [minBound .. maxBound]+        `shouldBe` map Just [minBound .. maxBound]++  describe "parseRateLimitHeaders" $+    it "reads nothing it does not render" $+      parseRateLimitHeaders "github" `shouldBe` Nothing++  describe "conventions other than RateLimitHeadersXRateLimit" $ do+    let corroboratedForbidden = [("X-RateLimit-Remaining", "0"), ("Retry-After", "120")]+    it "do not read a 403 as a spent quota, however corroborated" $+      map (\convention -> isRateLimited convention 403 corroboratedForbidden) [RateLimitHeadersRateLimitReset, RateLimitHeadersStructured]+        `shouldBe` [False, False]+    it "do not read X-RateLimit-Limit" $+      map (\convention -> rateLimitLimit convention [("X-RateLimit-Limit", "5000")]) [RateLimitHeadersRateLimitReset, RateLimitHeadersStructured]+        `shouldBe` [Nothing, Nothing]+    it "do not read an exception for a corroborated 403 as a spent quota" $ do+      let response =+            Response+              { responseStatus = mkStatus 403 "Forbidden",+                responseVersion = http11,+                responseHeaders = corroboratedForbidden,+                responseBody = (),+                responseCookieJar = mempty,+                responseClose' = ResponseClose (pure ()),+                responseOriginalRequest = defaultRequest,+                responseEarlyHints = []+              }+      map+        (\convention -> httpExceptionRateLimitWait convention (posixSecondsToUTCTime 0) (HttpExceptionRequest defaultRequest (StatusCodeException response "")))+        [RateLimitHeadersRateLimitReset, RateLimitHeadersStructured]+        `shouldBe` [Nothing, Nothing]++  describe "RateLimitHeadersXRateLimit" $ do+    describe "isRateLimited" $ do+      it "recognises the primary hourly limit, which GitHub answers with 403" $+        isRateLimited+          RateLimitHeadersXRateLimit+          403+          [ ("X-RateLimit-Limit", "5000"),+            ("X-RateLimit-Remaining", "0"),+            ("X-RateLimit-Reset", "1790250380")+          ]+          `shouldBe` True++      it "takes a 429 at its word" $+        isRateLimited RateLimitHeadersXRateLimit 429 []+          `shouldBe` True++      it "recognises a refusal that only says to come back later" $+        isRateLimited RateLimitHeadersXRateLimit 403 [("X-RateLimit-Remaining", "4999"), ("Retry-After", "60")]+          `shouldBe` True++      it "does not mistake a missing permission for a spent quota" $+        isRateLimited RateLimitHeadersXRateLimit 403 [("X-RateLimit-Remaining", "4999")]+          `shouldBe` False++      it "counts a Retry-After given as an HTTP date" $+        isRateLimited RateLimitHeadersXRateLimit 403 [("X-RateLimit-Remaining", "4999"), ("Retry-After", "Mon, 12 Jan 1970 13:56:40 GMT")]+          `shouldBe` True++      it "does not count a Retry-After it cannot read" $+        isRateLimited RateLimitHeadersXRateLimit 403 [("X-RateLimit-Remaining", "4999"), ("Retry-After", "soon")]+          `shouldBe` False++      it "does not read a spent quota out of a successful response" $+        isRateLimited RateLimitHeadersXRateLimit 200 [("X-RateLimit-Remaining", "0")]+          `shouldBe` False++      it "does not read a spent quota out of a not-found" $+        isRateLimited RateLimitHeadersXRateLimit 404 []+          `shouldBe` False++    describe "rateLimitWait" $ do+      let answeredAt = posixSecondsToUTCTime 1000000++      it "prefers Retry-After to the primary window's reset" $+        rateLimitWait+          RateLimitHeadersXRateLimit+          answeredAt+          [("Retry-After", "600"), ("X-RateLimit-Reset", "1002000")]+          `shouldBe` 605++      it "waits out the primary window, and a little past it" $+        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("X-RateLimit-Reset", "1001000")]+          `shouldBe` 1005++      it "falls back to the floor when the reset has already passed" $+        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("X-RateLimit-Reset", "999000")]+          `shouldBe` 60++      it "falls back to the floor when neither header is there" $+        rateLimitWait RateLimitHeadersXRateLimit answeredAt []+          `shouldBe` 60++      it "falls back to the floor when the header is not a number" $+        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("X-RateLimit-Reset", "whenever")]+          `shouldBe` 60++      it "falls back to the floor when the header has trailing rubbish" $+        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("Retry-After", "60s")]+          `shouldBe` 60++      it "does not go below the floor when asked for less" $+        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("Retry-After", "1")]+          `shouldBe` 60++      it "does not go above a whole window plus the floor" $+        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("X-RateLimit-Reset", "9999999999")]+          `shouldBe` 3660++      it "survives a reset too large to fit in an Int" $+        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("X-RateLimit-Reset", "99999999999999999999999999")]+          `shouldBe` 60++      it "survives a Retry-After too large to fit in an Int" $+        rateLimitWait RateLimitHeadersXRateLimit answeredAt [("Retry-After", "99999999999999999999999999")]+          `shouldBe` 60++    describe "httpExceptionRateLimitWait" $ do+      let answeredAt = posixSecondsToUTCTime 1789999000++      it "answers the wait GitHub asked for" $ do+        let response =+              Response+                { responseStatus = mkStatus 403 "Forbidden",+                  responseVersion = http11,+                  responseHeaders =+                    [ ("X-RateLimit-Limit", "5000"),+                      ("X-RateLimit-Remaining", "0"),+                      ("X-RateLimit-Reset", "1790000000")+                    ],+                  responseBody = (),+                  responseCookieJar = mempty,+                  responseClose' = ResponseClose (pure ()),+                  responseOriginalRequest = defaultRequest,+                  responseEarlyHints = []+                }+        httpExceptionRateLimitWait+          RateLimitHeadersXRateLimit+          answeredAt+          (HttpExceptionRequest defaultRequest (StatusCodeException response "irrelevant"))+          `shouldBe` Just 1005++      it "answers nothing for a refusal that is not a spent quota" $ do+        let response =+              Response+                { responseStatus = mkStatus 403 "Forbidden",+                  responseVersion = http11,+                  responseHeaders = [("X-RateLimit-Remaining", "4999")],+                  responseBody = (),+                  responseCookieJar = mempty,+                  responseClose' = ResponseClose (pure ()),+                  responseOriginalRequest = defaultRequest,+                  responseEarlyHints = []+                }+        httpExceptionRateLimitWait+          RateLimitHeadersXRateLimit+          answeredAt+          (HttpExceptionRequest defaultRequest (StatusCodeException response "irrelevant"))+          `shouldBe` Nothing++      it "answers nothing for a failure that never got a response" $+        httpExceptionRateLimitWait+          RateLimitHeadersXRateLimit+          answeredAt+          (HttpExceptionRequest defaultRequest ConnectionTimeout)+          `shouldBe` Nothing++    describe "rateLimitLimit" $ do+      it "reads the allowance GitHub reports" $+        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "12500")]+          `shouldBe` Just 12500++      it "reads the 5000 an App installation is guaranteed" $+        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "5000")]+          `shouldBe` Just 5000++      it "says nothing when the header is absent" $+        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Remaining", "4999")]+          `shouldBe` Nothing++      it "refuses an allowance of zero" $+        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "0")]+          `shouldBe` Nothing++      it "takes an allowance of one, which is slow rather than stopped" $+        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "1")]+          `shouldBe` Just 1++      it "refuses a negative allowance" $+        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "-1")]+          `shouldBe` Nothing++      it "refuses a value with trailing rubbish" $+        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "5000x")]+          `shouldBe` Nothing++      it "refuses a value that is not a number at all" $+        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "unlimited")]+          `shouldBe` Nothing++      it "refuses an allowance that is not the core one" $+        rateLimitLimit+          RateLimitHeadersXRateLimit+          [ ("X-RateLimit-Limit", "30"),+            ("X-RateLimit-Resource", "search")+          ]+          `shouldBe` Nothing++      it "refuses the graphql allowance" $+        rateLimitLimit+          RateLimitHeadersXRateLimit+          [ ("X-RateLimit-Limit", "5000"),+            ("X-RateLimit-Resource", "graphql")+          ]+          `shouldBe` Nothing++      it "reads the allowance when the resource says core" $+        rateLimitLimit+          RateLimitHeadersXRateLimit+          [ ("X-RateLimit-Limit", "12500"),+            ("X-RateLimit-Resource", "core")+          ]+          `shouldBe` Just 12500++      it "takes a response with no resource header as core" $+        rateLimitLimit RateLimitHeadersXRateLimit [("X-RateLimit-Limit", "12500")]+          `shouldBe` Just 12500++  describe "RateLimitHeadersRateLimitReset" $ do+    describe "isRateLimited" $ do+      it "recognises a throttled call" $+        isRateLimited RateLimitHeadersRateLimitReset 429 [] `shouldBe` True++      it "does not mistake a permission refusal for a spent quota" $+        isRateLimited RateLimitHeadersRateLimitReset 403 [] `shouldBe` False++      it "does not read a spent quota out of a successful response" $+        isRateLimited RateLimitHeadersRateLimitReset 200 [] `shouldBe` False++      it "does not read a spent quota out of a server fault" $+        isRateLimited RateLimitHeadersRateLimitReset 503 [] `shouldBe` False++    describe "rateLimitWait" $ do+      let answeredAt = posixSecondsToUTCTime 1000000++      it "reads a Retry-After given as an HTTP date" $+        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("Retry-After", "Mon, 12 Jan 1970 13:48:40 GMT")]+          `shouldBe` 125+      it "reads a Retry-After given as an RFC 850 date" $+        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("Retry-After", "Monday, 12-Jan-70 13:48:40 GMT")]+          `shouldBe` 125+      it "reads a Retry-After given as an asctime date" $+        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("Retry-After", "Mon Jan 12 13:48:40 1970")]+          `shouldBe` 125+      it "reads an HTTP date with space around it" $+        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("Retry-After", " Mon, 12 Jan 1970 13:48:40 GMT ")]+          `shouldBe` 125++      it "prefers Retry-After to the window's reset" $+        rateLimitWait+          RateLimitHeadersRateLimitReset+          answeredAt+          [("Retry-After", "600"), ("RateLimit-Reset", "1002000")]+          `shouldBe` 605++      it "waits out the window, and a little past it" $+        rateLimitWait+          RateLimitHeadersRateLimitReset+          answeredAt+          [ ("RateLimit-Limit", "500"),+            ("RateLimit-Observed", "500"),+            ("RateLimit-Remaining", "0"),+            ("RateLimit-Reset", "1001000")+          ]+          `shouldBe` 1005++      it "does not read the X-prefixed spelling" $+        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("X-RateLimit-Reset", "1001000")]+          `shouldBe` 60++      it "falls back to the floor when the reset has already passed" $+        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("RateLimit-Reset", "999000")]+          `shouldBe` 60++      it "falls back to the floor when neither header is there" $+        rateLimitWait RateLimitHeadersRateLimitReset answeredAt []+          `shouldBe` 60++      it "falls back to the floor when the header is not a number" $+        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("RateLimit-Reset", "whenever")]+          `shouldBe` 60++      it "falls back to the floor when the header has trailing rubbish" $+        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("Retry-After", "60s")]+          `shouldBe` 60++      it "does not go below the floor when asked for less" $+        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("Retry-After", "1")]+          `shouldBe` 60++      it "does not go above a whole window plus the floor" $+        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("RateLimit-Reset", "9999999999")]+          `shouldBe` 3660++      it "survives a reset too large to fit in an Int" $+        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("RateLimit-Reset", "99999999999999999999999999")]+          `shouldBe` 60++      it "survives a Retry-After too large to fit in an Int" $+        rateLimitWait RateLimitHeadersRateLimitReset answeredAt [("Retry-After", "99999999999999999999999999")]+          `shouldBe` 60++    describe "httpExceptionRateLimitWait" $ do+      let answeredAt = posixSecondsToUTCTime 1000000++      it "reads a spent quota out of a thrown refusal" $ do+        let response =+              Response+                { responseStatus = mkStatus 429 "Too Many Requests",+                  responseVersion = http11,+                  responseHeaders = [("RateLimit-Reset", "1001000")],+                  responseBody = (),+                  responseCookieJar = mempty,+                  responseClose' = ResponseClose (pure ()),+                  responseOriginalRequest = defaultRequest,+                  responseEarlyHints = []+                }+        httpExceptionRateLimitWait+          RateLimitHeadersRateLimitReset+          answeredAt+          (HttpExceptionRequest defaultRequest (StatusCodeException response "irrelevant"))+          `shouldBe` Just 1005++      it "answers nothing for a thrown refusal that is not a spent quota" $ do+        let response =+              Response+                { responseStatus = mkStatus 403 "Forbidden",+                  responseVersion = http11,+                  responseHeaders = [],+                  responseBody = (),+                  responseCookieJar = mempty,+                  responseClose' = ResponseClose (pure ()),+                  responseOriginalRequest = defaultRequest,+                  responseEarlyHints = []+                }+        httpExceptionRateLimitWait+          RateLimitHeadersRateLimitReset+          answeredAt+          (HttpExceptionRequest defaultRequest (StatusCodeException response "irrelevant"))+          `shouldBe` Nothing++      it "answers nothing for a failure that never got a response" $+        httpExceptionRateLimitWait+          RateLimitHeadersRateLimitReset+          answeredAt+          (HttpExceptionRequest defaultRequest ConnectionTimeout)+          `shouldBe` Nothing++  describe "RateLimitHeadersStructured" $ do+    describe "isRateLimited" $ do+      it "recognises a throttled call" $+        isRateLimited RateLimitHeadersStructured 429 [] `shouldBe` True++      it "does not mistake a permission refusal for a spent quota" $+        isRateLimited RateLimitHeadersStructured 403 [] `shouldBe` False++      it "does not read a spent quota out of a successful response" $+        isRateLimited RateLimitHeadersStructured 200 [] `shouldBe` False++      it "does not read a spent quota out of a server fault" $+        isRateLimited RateLimitHeadersStructured 503 [] `shouldBe` False++    describe "structuredParameter" $ do+      it "reads the seconds until the quota refills" $+        structuredParameter "t" [("RateLimit", "\"baseline\";r=1999;t=600")]+          `shouldBe` Just 600++      it "reads what is left of the quota" $+        structuredParameter "r" [("RateLimit", "\"baseline\";r=1999;t=600")]+          `shouldBe` Just 1999++      it "reads a value padded with whitespace" $+        structuredParameter "t" [("RateLimit", "\"baseline\" ; r=1999 ; t = 600 ")]+          `shouldBe` Just 600++      it "does not read the policy name as a parameter" $+        structuredParameter "t" [("RateLimit", "t=5;r=1999")]+          `shouldBe` Nothing++      it "answers nothing for a parameter that is not there" $+        structuredParameter "t" [("RateLimit", "\"baseline\";r=1999")]+          `shouldBe` Nothing++      it "answers nothing when the header is not there" $+        structuredParameter "t" []+          `shouldBe` Nothing++      it "answers nothing for a parameter that is not a whole number" $+        structuredParameter "t" [("RateLimit", "\"baseline\";t=600s")]+          `shouldBe` Nothing++    describe "rateLimitWait" $ do+      it "prefers Retry-After to the quota header" $+        rateLimitWait RateLimitHeadersStructured (posixSecondsToUTCTime 0) [("Retry-After", "60"), ("RateLimit", "\"baseline\";r=0;t=600")]+          `shouldBe` 65++      it "waits out the window Forgejo counts down, and a little past it" $+        rateLimitWait RateLimitHeadersStructured (posixSecondsToUTCTime 0) [("RateLimit", "\"baseline\";r=0;t=600")]+          `shouldBe` 605++      it "does not read the spellings the other forges use" $+        rateLimitWait RateLimitHeadersStructured (posixSecondsToUTCTime 0) [("X-RateLimit-Reset", "600"), ("RateLimit-Reset", "600")]+          `shouldBe` 60++      it "falls back to the floor when neither header is there" $+        rateLimitWait RateLimitHeadersStructured (posixSecondsToUTCTime 0) []+          `shouldBe` 60++      it "does not go below the floor when asked for less" $+        rateLimitWait RateLimitHeadersStructured (posixSecondsToUTCTime 0) [("Retry-After", "1")]+          `shouldBe` 60++      it "does not go above a whole window plus the floor" $+        rateLimitWait RateLimitHeadersStructured (posixSecondsToUTCTime 0) [("RateLimit", "\"baseline\";t=9999999")]+          `shouldBe` 3660++      it "survives a countdown too large to fit in an Int" $+        rateLimitWait RateLimitHeadersStructured (posixSecondsToUTCTime 0) [("RateLimit", "\"baseline\";t=99999999999999999999999999")]+          `shouldBe` 60++    describe "httpExceptionRateLimitWait" $ do+      it "answers the wait Codeberg asked for" $ do+        let response =+              Response+                { responseStatus = mkStatus 429 "Too Many Requests",+                  responseVersion = http11,+                  responseHeaders =+                    [ ("RateLimit-Policy", "\"baseline\";q=2000;w=600"),+                      ("RateLimit", "\"baseline\";r=0;t=600")+                    ],+                  responseBody = (),+                  responseCookieJar = mempty,+                  responseClose' = ResponseClose (pure ()),+                  responseOriginalRequest = defaultRequest,+                  responseEarlyHints = []+                }+        httpExceptionRateLimitWait+          RateLimitHeadersStructured+          (posixSecondsToUTCTime 0)+          (HttpExceptionRequest defaultRequest (StatusCodeException response "irrelevant"))+          `shouldBe` Just 605++      it "answers nothing for a refusal that is not a spent quota" $ do+        let response =+              Response+                { responseStatus = mkStatus 403 "Forbidden",+                  responseVersion = http11,+                  responseHeaders = [("RateLimit", "\"baseline\";r=1999;t=600")],+                  responseBody = (),+                  responseCookieJar = mempty,+                  responseClose' = ResponseClose (pure ()),+                  responseOriginalRequest = defaultRequest,+                  responseEarlyHints = []+                }+        httpExceptionRateLimitWait+          RateLimitHeadersStructured+          (posixSecondsToUTCTime 0)+          (HttpExceptionRequest defaultRequest (StatusCodeException response "irrelevant"))+          `shouldBe` Nothing++      it "answers nothing for a failure that never got a response" $+        httpExceptionRateLimitWait+          RateLimitHeadersStructured+          (posixSecondsToUTCTime 0)+          (HttpExceptionRequest defaultRequest ConnectionTimeout)+          `shouldBe` Nothing++      it "still reads the wait after a policy that logs the header has scrubbed the exception" $ do+        let response =+              Response+                { responseStatus = mkStatus 429 "Too Many Requests",+                  responseVersion = http11,+                  responseHeaders =+                    [ ("RateLimit", "\"baseline\";r=0;t=600"),+                      ("Set-Cookie", "session=wnxczrmtabdywlrw")+                    ],+                  responseBody = (),+                  responseCookieJar = mempty,+                  responseClose' = ResponseClose (pure ()),+                  responseOriginalRequest = defaultRequest,+                  responseEarlyHints = []+                }+        httpExceptionRateLimitWait+          RateLimitHeadersStructured+          (posixSecondsToUTCTime 0)+          ( scrubHttpException defaultLogPolicy {logPolicyHeadersToLog = Set.insert "RateLimit" defaultHeadersToLog} $+              HttpExceptionRequest defaultRequest (StatusCodeException response "irrelevant")+          )+          `shouldBe` Just 605
+ test/Network/HTTP/Env/Servant/ClientSpec.hs view
@@ -0,0 +1,340 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeApplications #-}++module Network.HTTP.Env.Servant.ClientSpec (spec) where++import Control.Monad (replicateM_)+import Control.Monad.Logger.CallStack (LogLevel (..), runNoLoggingT, runWriterLoggingT)+import Control.Retry (limitRetries)+import Data.Foldable (toList)+import Data.IORef+import Data.Maybe (isNothing)+import Data.Proxy (Proxy (..))+import qualified Data.Set as Set+import qualified Data.Text as Text+import qualified Data.Text.Encoding as TE+import Data.Time (NominalDiffTime)+import Data.Time.Clock.POSIX (getPOSIXTime)+import Network.HTTP.Client (defaultManagerSettings, newManager)+import qualified Network.HTTP.Client as HTTP+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+import Network.HTTP.Env.Pacing (newRequestLimiter, waitForRequest)+import Network.HTTP.Env.RateLimit (RateLimitHeaders (..), rateLimitMinimumWait)+import Network.HTTP.Env.Servant.Client+import Network.HTTP.Types (Header, Status, status200, status403, status404, status429, status503)+import Network.Wai (Application, responseLBS)+import qualified Network.Wai.Handler.Warp as Warp+import Servant.API (Get, JSON, Post)+import Servant.Client (BaseUrl (..), ClientError (..), ClientM, Scheme (Http), client, responseHeaders)+import qualified Servant.Client.Streaming as Streaming+import System.Timeout (timeout)+import Test.Syd++type NumberAPI = Get '[JSON] Int++type PostNumberAPI = Post '[JSON] Int++spec :: Spec+spec = do+  let numberClient :: ClientM Int+      numberClient = client (Proxy @NumberAPI)+  let postNumberClient :: ClientM Int+      postNumberClient = client (Proxy @PostNumberAPI)+  let streamingNumberClient :: Streaming.ClientM Int+      streamingNumberClient = Streaming.client (Proxy @NumberAPI)+  let streamingPostNumberClient :: Streaming.ClientM Int+      streamingPostNumberClient = Streaming.client (Proxy @PostNumberAPI)++  let serving :: IORef Int -> Status -> Application+      serving served status _ respond = do+        atomicModifyIORef' served (\n -> (n + 1, ()))+        respond $+          responseLBS+            status+            [("Content-Type", "application/json"), ("X-Api-Key", "wnxczrmtabdywlrw")]+            "1"++  let withServer :: Status -> (IORef Int -> BaseUrl -> IO ()) -> IO ()+      withServer status act = do+        served <- newIORef 0+        Warp.testWithApplication (pure (serving served status)) $ \port ->+          act served (BaseUrl Http "127.0.0.1" port "")++  let apiKeyPolicy :: LogPolicy+      apiKeyPolicy =+        defaultLogPolicy+          { logPolicyHeadersToRedact = Set.insert "X-Api-Key" defaultHeadersToRedact+          }++  let newEnv :: Word -> Int -> IO HttpEnv+      newEnv threshold retries = do+        man <- newManager defaultManagerSettings+        budget <-+          newFailureBudget+            FailureBudgetSettings+              { failureBudgetSettingsFailures = 100,+                failureBudgetSettingsWindow = 3600+              }+        breaker <-+          runNoLoggingT+            ( newCircuitBreaker+                "test"+                ( CircuitBreakerSettings+                    { circuitBreakerSettingsFailureThreshold = threshold,+                      circuitBreakerSettingsResetTimeout = 3600+                    }+                )+            )+        pure+          HttpEnv+            { httpEnvManager = man,+              httpEnvRetryPolicy = limitRetries retries,+              httpEnvCircuitBreaker = Just breaker,+              httpEnvFailureBudget = Just budget,+              httpEnvRequestLimiter = Nothing,+              httpEnvLogPolicy = apiKeyPolicy,+              httpEnvRateLimitHeaders = Nothing+            }++  describe "servantClientEnv" $ do+    it "calls the base URL it is given" $+      withServer status200 $ \_ baseUrl -> do+        httpEnv <- newEnv 5 0+        result <- runNoLoggingT (callClient (servantClientEnv httpEnv baseUrl (const LevelError)) numberClient)+        result `shouldBe` Right 1++    it "retries as often as the http env's policy says" $+      withServer status503 $ \served baseUrl -> do+        httpEnv <- newEnv 10 2+        _ <- runNoLoggingT (callClient (servantClientEnv httpEnv baseUrl (const LevelError)) numberClient)+        readIORef served `shouldReturn` 3++    it "shares the http env's breaker" $+      withServer status503 $ \served baseUrl -> do+        httpEnv <- newEnv 1 0+        _ <- runNoLoggingT (callClient (servantClientEnv httpEnv baseUrl (const LevelError)) numberClient)+        request <- HTTP.parseRequest (concat ["http://127.0.0.1:", show (baseUrlPort baseUrl), "/"])+        result <- runNoLoggingT (httpCall httpEnv request)+        case result of+          Left HttpEnvErrorCircuitOpen -> pure ()+          _ -> expectationFailure "expected the breaker the servant call opened to reject the plain call"+        readIORef served `shouldReturn` 1++    it "counts each failed request against the http env's failure budget" $+      withServer status503 $ \_ baseUrl -> do+        httpEnv <- newEnv 10 2+        let clientEnv = servantClientEnv httpEnv baseUrl (const LevelError)+        _ <- runNoLoggingT (callClient clientEnv numberClient)+        peekClientEnv clientEnv+          `shouldReturn` HttpEnvReport+            { httpEnvReportCircuit = Just CircuitReportClosed,+              httpEnvReportFailureBudget =+                Just+                  FailureBudgetReport+                    { failureBudgetReportFailures = 3,+                      failureBudgetReportStatus = FailureBudgetStatusWithin+                    }+            }++    it "tells a spent quota apart, in the convention of the http env" $+      withServer status429 $ \_ baseUrl -> do+        httpEnv <- newEnv 5 0+        let clientEnv = servantClientEnv httpEnv {httpEnvRateLimitHeaders = Just RateLimitHeadersRateLimitReset} baseUrl (const LevelError)+        result <- runNoLoggingT (callClient clientEnv numberClient)+        case result of+          Left (HttpEnvErrorRateLimited quotaWait _) -> quotaWait `shouldBe` rateLimitMinimumWait+          _ -> expectationFailure "expected a spent quota"++    it "calls a 429 a failure without a convention to read it in" $+      withServer status429 $ \_ baseUrl -> do+        httpEnv <- newEnv 5 0+        result <- runNoLoggingT (callClient (servantClientEnv httpEnv baseUrl (const LevelError)) numberClient)+        case result of+          Left (HttpEnvErrorFailed _) -> pure ()+          _ -> expectationFailure "expected a failure"++    it "scrubs with the http env's log policy" $+      withServer status404 $ \_ baseUrl -> do+        httpEnv <- newEnv 5 0+        result <- runNoLoggingT (callClient (servantClientEnv httpEnv baseUrl (const LevelError)) numberClient)+        case result of+          Left (HttpEnvErrorFailed (FailureResponse _ response)) ->+            lookup "X-Api-Key" (toList (responseHeaders response)) `shouldBe` Just "<REDACTED>"+          _ -> expectationFailure "expected the server's own 404"++    it "logs a failure at the level it is given" $+      withServer status404 $ \_ baseUrl -> do+        httpEnv <- newEnv 5 0+        (_, logs) <- runWriterLoggingT (callClient (servantClientEnv httpEnv baseUrl (const (LevelOther "chosen"))) numberClient)+        [() | (_, _, LevelOther "chosen", _) <- logs] `shouldBe` [()]++    it "sends a POST again when it could not connect, since nothing was sent" $ do+      httpEnv <- newEnv 100 3+      (_, logs) <- runWriterLoggingT (callClient (servantClientEnv httpEnv (BaseUrl Http "127.0.0.1" 1 "") (const LevelError)) postNumberClient)+      length [() | (_, _, LevelWarn, _) <- logs] `shouldBe` 4++    it "does not send a POST again after a fault" $+      withServer status503 $ \served baseUrl -> do+        httpEnv <- newEnv 100 3+        _ <- runNoLoggingT (callClient (servantClientEnv httpEnv baseUrl (const LevelError)) postNumberClient)+        readIORef served `shouldReturn` 1++    it "sends a POST again after a fault when the call says it may" $+      withServer status503 $ \served baseUrl -> do+        httpEnv <- newEnv 100 3+        _ <- runNoLoggingT (callClientWith RepeatableAlways (servantClientEnv httpEnv baseUrl (const LevelError)) postNumberClient)+        readIORef served `shouldReturn` 4++    it "sends a GET again after a fault" $+      withServer status503 $ \served baseUrl -> do+        httpEnv <- newEnv 100 3+        _ <- runNoLoggingT (callClient (servantClientEnv httpEnv baseUrl (const LevelError)) numberClient)+        readIORef served `shouldReturn` 4++    it "logs a failure it does not retry at no level but the one it is given" $+      withServer status404 $ \_ baseUrl -> do+        httpEnv <- newEnv 5 0+        (_, logs) <- runWriterLoggingT (callClient (servantClientEnv httpEnv baseUrl (const LevelDebug)) numberClient)+        [level | (_, _, level, _) <- logs] `shouldBe` [LevelDebug]++    it "answers that the breaker is open without waiting for the request limiter" $+      withServer status200 $ \served baseUrl -> do+        httpEnv <- newEnv 1 0+        _ <- runNoLoggingT (callClient (servantClientEnv httpEnv {httpEnvRetryPolicy = limitRetries 0} (BaseUrl Http "127.0.0.1" 1 "") (const LevelError)) numberClient)+        limiter <- newRequestLimiter 1+        replicateM_ 50 (waitForRequest limiter)+        result <- timeout 200000 (runNoLoggingT (callClient (servantClientEnv (withRequestLimiter limiter httpEnv) baseUrl (const LevelError)) numberClient))+        case result of+          Just (Left HttpEnvErrorCircuitOpen) -> pure ()+          _ -> expectationFailure "expected the breaker to answer at once"+        readIORef served `shouldReturn` 0++    it "waits on the http env's token limiter" $+      withServer status200 $ \served baseUrl -> do+        httpEnv <- newEnv 5 0+        limiter <- newRequestLimiter 1+        let clientEnv = servantClientEnv (withRequestLimiter limiter httpEnv) baseUrl (const LevelError)+        replicateM_ 50 (runNoLoggingT (callClient clientEnv numberClient) `shouldReturn` Right 1)+        result <- timeout 200000 (runNoLoggingT (callClient clientEnv numberClient))+        isNothing result `shouldBe` True+        readIORef served `shouldReturn` 50++  describe "clientErrorRateLimitWait" $ do+    let answering :: Status -> [Header] -> RateLimitHeaders -> IO (Either (HttpEnvError ClientError) Int)+        answering status headers convention = do+          let application _ respond = respond (responseLBS status (("Content-Type", "application/json") : headers) "1")+          Warp.testWithApplication (pure application) $ \serverPort -> do+            httpEnv <- newEnv 5 0+            let clientEnv = servantClientEnv httpEnv {httpEnvRateLimitHeaders = Just convention} (BaseUrl Http "127.0.0.1" serverPort "") (const LevelError)+            runNoLoggingT (callClient clientEnv numberClient)+    let waitOf :: Either (HttpEnvError ClientError) Int -> Maybe NominalDiffTime+        waitOf = \case+          Left (HttpEnvErrorRateLimited quotaWait _) -> Just quotaWait+          Left (HttpEnvErrorFailed _) -> Nothing+          Left HttpEnvErrorCircuitOpen -> Nothing+          Right _ -> Nothing+    it "reads the wait the headers ask for" $+      waitOf <$> answering status429 [("Retry-After", "120")] RateLimitHeadersRateLimitReset+        `shouldReturn` Just 125+    it "reads the reset in the convention of the env" $ do+      now <- getPOSIXTime+      let reset = TE.encodeUtf8 (Text.pack (show (round (now + 600) :: Int)))+      quotaWait <- waitOf <$> answering status429 [("RateLimit-Reset", reset)] RateLimitHeadersRateLimitReset+      quotaWait `shouldSatisfy` maybe False (> 300)+      xQuotaWait <- waitOf <$> answering status429 [("X-RateLimit-Reset", reset)] RateLimitHeadersXRateLimit+      xQuotaWait `shouldSatisfy` maybe False (> 300)++    it "reads a corroborated 403 in the convention that allows it" $+      waitOf <$> answering status403 [("X-RateLimit-Remaining", "0")] RateLimitHeadersXRateLimit+        `shouldReturn` Just rateLimitMinimumWait+    it "does not read a corroborated 403 in a convention that does not" $+      waitOf <$> answering status403 [("X-RateLimit-Remaining", "0")] RateLimitHeadersRateLimitReset+        `shouldReturn` Nothing+    it "does not read any other failure as a spent quota" $+      waitOf <$> answering status404 [("Retry-After", "120")] RateLimitHeadersRateLimitReset+        `shouldReturn` Nothing++  describe "callStreamingClient" $ do+    it "tells a spent quota apart" $+      withServer status429 $ \_ baseUrl -> do+        httpEnv <- newEnv 5 0+        let clientEnv = servantClientEnv httpEnv {httpEnvRateLimitHeaders = Just RateLimitHeadersRateLimitReset} baseUrl (const LevelError)+        result <- runNoLoggingT (callStreamingClient clientEnv streamingNumberClient)+        case result of+          Left (HttpEnvErrorRateLimited quotaWait _) -> quotaWait `shouldBe` rateLimitMinimumWait+          _ -> expectationFailure "expected a spent quota"++    it "calls the base URL" $+      withServer status200 $ \_ baseUrl -> do+        httpEnv <- newEnv 5 0+        result <- runNoLoggingT (callStreamingClient (servantClientEnv httpEnv baseUrl (const LevelError)) streamingNumberClient)+        result `shouldBe` Right 1++    it "goes through the breaker" $+      withServer status503 $ \served baseUrl -> do+        httpEnv <- newEnv 1 0+        let clientEnv = servantClientEnv httpEnv baseUrl (const LevelError)+        _ <- runNoLoggingT (callStreamingClient clientEnv streamingNumberClient)+        result <- runNoLoggingT (callStreamingClient clientEnv streamingNumberClient)+        result `shouldBe` Left HttpEnvErrorCircuitOpen+        readIORef served `shouldReturn` 1++    it "counts each failed request against the failure budget" $+      withServer status503 $ \_ baseUrl -> do+        httpEnv <- newEnv 10 2+        let clientEnv = servantClientEnv httpEnv baseUrl (const LevelError)+        _ <- runNoLoggingT (callStreamingClient clientEnv streamingNumberClient)+        fmap failureBudgetReportFailures . httpEnvReportFailureBudget <$> peekHttpEnv httpEnv+          `shouldReturn` Just 3++    it "logs a failure at the level it is given" $+      withServer status404 $ \_ baseUrl -> do+        httpEnv <- newEnv 5 0+        (_, logs) <- runWriterLoggingT (callStreamingClient (servantClientEnv httpEnv baseUrl (const (LevelOther "chosen"))) streamingNumberClient)+        [() | (_, _, LevelOther "chosen", _) <- logs] `shouldBe` [()]++    it "does not send a POST again after a fault" $+      withServer status503 $ \served baseUrl -> do+        httpEnv <- newEnv 100 3+        _ <- runNoLoggingT (callStreamingClient (servantClientEnv httpEnv baseUrl (const LevelError)) streamingPostNumberClient)+        readIORef served `shouldReturn` 1++    it "sends a POST again after a fault when the call says it may" $+      withServer status503 $ \served baseUrl -> do+        httpEnv <- newEnv 100 3+        _ <- runNoLoggingT (callStreamingClientWith RepeatableAlways (servantClientEnv httpEnv baseUrl (const LevelError)) streamingPostNumberClient)+        readIORef served `shouldReturn` 4++    it "logs a failure it does not retry at no level but the one it is given" $+      withServer status404 $ \_ baseUrl -> do+        httpEnv <- newEnv 5 0+        (_, logs) <- runWriterLoggingT (callStreamingClient (servantClientEnv httpEnv baseUrl (const LevelDebug)) streamingNumberClient)+        [level | (_, _, level, _) <- logs] `shouldBe` [LevelDebug]++    it "answers that the breaker is open without waiting for the request limiter" $+      withServer status200 $ \served baseUrl -> do+        httpEnv <- newEnv 1 0+        _ <- runNoLoggingT (callStreamingClient (servantClientEnv httpEnv {httpEnvRetryPolicy = limitRetries 0} (BaseUrl Http "127.0.0.1" 1 "") (const LevelError)) streamingNumberClient)+        limiter <- newRequestLimiter 1+        replicateM_ 50 (waitForRequest limiter)+        result <- timeout 200000 (runNoLoggingT (callStreamingClient (servantClientEnv (withRequestLimiter limiter httpEnv) baseUrl (const LevelError)) streamingNumberClient))+        case result of+          Just (Left HttpEnvErrorCircuitOpen) -> pure ()+          _ -> expectationFailure "expected the breaker to answer at once"+        readIORef served `shouldReturn` 0++    it "waits on the token limiter" $+      withServer status200 $ \served baseUrl -> do+        httpEnv <- newEnv 5 0+        limiter <- newRequestLimiter 1+        let clientEnv = servantClientEnv (withRequestLimiter limiter httpEnv) baseUrl (const LevelError)+        replicateM_ 50 (runNoLoggingT (callStreamingClient clientEnv streamingNumberClient) `shouldReturn` Right 1)+        result <- timeout 200000 (runNoLoggingT (callStreamingClient clientEnv streamingNumberClient))+        isNothing result `shouldBe` True+        readIORef served `shouldReturn` 50
+ test/Network/HTTP/Env/Servant/RetrySpec.hs view
@@ -0,0 +1,444 @@+{-# 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")))
+ test/Network/HTTP/Env/ServantSpec.hs view
@@ -0,0 +1,27 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeApplications #-}++module Network.HTTP.Env.ServantSpec (spec) where++import Control.Monad.Logger.CallStack (LogLevel (..), runNoLoggingT)+import Data.Proxy (Proxy (..))+import Network.HTTP.Client (newManager)+import Network.HTTP.Env.Servant+import Network.HTTP.Types (status200)+import Network.Wai (responseLBS)+import qualified Network.Wai.Handler.Warp as Warp+import Servant.API (Get, JSON)+import Servant.Client (BaseUrl (..), Scheme (Http), client)+import Test.Syd++spec :: Spec+spec =+  describe "Network.HTTP.Env.Servant" $+    it "is enough to make a servant client env and call a dependency through it" $ do+      man <- newManager (tlsManagerSettingsWithMaxHeaderLength 65536)+      httpEnv <- runNoLoggingT (newHttpEnv (HttpEnvName "test") defaultHttpEnvSettings defaultLogPolicy man)+      Warp.testWithApplication (pure (\_ respond -> respond (responseLBS status200 [("Content-Type", "application/json")] "1"))) $ \serverPort -> do+        let clientEnv = servantClientEnv httpEnv (BaseUrl Http "127.0.0.1" serverPort "") (const LevelError)+        result <- runNoLoggingT (callClient clientEnv (client (Proxy @(Get '[JSON] Int))))+        result `shouldBe` Right 1
+ test/Network/HTTP/EnvSpec.hs view
@@ -0,0 +1,24 @@+{-# LANGUAGE OverloadedStrings #-}++module Network.HTTP.EnvSpec (spec) where++import Control.Monad.Logger.CallStack (runNoLoggingT)+import Network.HTTP.Client (newManager, parseUrlThrow, responseBody)+import Network.HTTP.Env+import Network.HTTP.Types (status200)+import Network.Wai (responseLBS)+import qualified Network.Wai.Handler.Warp as Warp+import Test.Syd++spec :: Spec+spec =+  describe "Network.HTTP.Env" $+    it "is enough to make an env and call a dependency through it" $ do+      man <- newManager (withUserAgent "http-env-test" (tlsManagerSettingsWithMaxHeaderLength 65536))+      env <- runNoLoggingT (newHttpEnv (HttpEnvName "test") defaultHttpEnvSettings defaultLogPolicy man)+      Warp.testWithApplication (pure (\_ respond -> respond (responseLBS status200 [] "hello"))) $ \serverPort -> do+        request <- parseUrlThrow (concat ["http://127.0.0.1:", show serverPort, "/"])+        result <- runNoLoggingT (httpCall env request)+        case result of+          Right response -> responseBody response `shouldBe` "hello"+          Left err -> expectationFailure (show err)
+ test/Spec.hs view
@@ -0,0 +1,1 @@+{-# OPTIONS_GHC -F -pgmF sydtest-discover -optF --no-main #-}
+ test_resources/http-env-settings.txt view
@@ -0,0 +1,182 @@+[36mUsage: [m[33mexample[m [36m[[m[37m--attempts-per-request[m [33mCOUNT[m[36m][m [36m[[m[37m--backoff-base[m [33mDURATION[m[36m][m [36m[[m[37m--backoff-max-delay[m [33mDURATION[m[36m][m [36m[[m[37m--backoff-max-total-delay[m [33mDURATION[m[36m][m [36m[[m[37m--circuit-breaker-failure-threshold[m [33mCOUNT[m[36m][m [36m[[m[37m--circuit-breaker-reset-timeout[m [33mDURATION[m[36m][m [36m[[m[37m--failure-budget-failures[m [33mCOUNT[m[36m][m [36m[[m[37m--failure-budget-window[m [33mDURATION[m[36m][m [36m[[m[37m--rate-limit-headers[m [33mHEADERS[m[36m][m++[36mAll settings[m:+  [34mShow this help text[m+  switch: [37m-h[m[36m|[m[37m--help[m++  [34mOutput version information[m+  switch: [37m--version[m++  [34mRequests per call, retries included[m+  option: [37m--attempts-per-request[m [33mCOUNT[m+  env: [37mATTEMPTS_PER_REQUEST[m [33mCOUNT[m+  config:+    [37mattempts-per-request[m: # [32mor null[m+      [33m<integer>[m # [32m64 bit unsigned integer[m+  default: [33m4[m++  [34mBase of the random wait between attempts, doubled once per attempt[m+  option: [37m--backoff-base[m [33mDURATION[m+  env: [37mBACKOFF_BASE[m [33mDURATION[m+  config:+    [37mbackoff.base[m: # [32many of[m+      [ [33mnull[m+      , [33m<string>[m+      , [33m<integer>[m # [32m64 bit signed integer[m+      ]+  default: [33m1s[m++  [34mLongest wait between two attempts[m+  option: [37m--backoff-max-delay[m [33mDURATION[m+  env: [37mBACKOFF_MAX_DELAY[m [33mDURATION[m+  config:+    [37mbackoff.max-delay[m: # [32many of[m+      [ [33mnull[m+      , [33m<string>[m+      , [33m<integer>[m # [32m64 bit signed integer[m+      ]+  default: [33m30s[m++  [34mMost one call waits between its attempts in all[m+  option: [37m--backoff-max-total-delay[m [33mDURATION[m+  env: [37mBACKOFF_MAX_TOTAL_DELAY[m [33mDURATION[m+  config:+    [37mbackoff.max-total-delay[m: # [32many of[m+      [ [33mnull[m+      , [33m<string>[m+      , [33m<integer>[m # [32m64 bit signed integer[m+      ]+  default: [33m60s[m++  [34mConsecutive failed requests that open the circuit breaker[m+  option: [37m--circuit-breaker-failure-threshold[m [33mCOUNT[m+  env: [37mCIRCUIT_BREAKER_FAILURE_THRESHOLD[m [33mCOUNT[m+  config:+    [37mcircuit-breaker.failure-threshold[m: # [32mor null[m+      [33m<integer>[m # [32m64 bit unsigned integer[m+  default: [33m5[m++  [34mHow long the circuit breaker stays open before a probe[m+  option: [37m--circuit-breaker-reset-timeout[m [33mDURATION[m+  env: [37mCIRCUIT_BREAKER_RESET_TIMEOUT[m [33mDURATION[m+  config:+    [37mcircuit-breaker.reset-timeout[m: # [32many of[m+      [ [33mnull[m+      , [33m<string>[m+      , [33m<integer>[m # [32m64 bit signed integer[m+      ]+  default: [33m30s[m++  [34mFailed requests within the window that report a dependency as unwell[m+  option: [37m--failure-budget-failures[m [33mCOUNT[m+  env: [37mFAILURE_BUDGET_FAILURES[m [33mCOUNT[m+  config:+    [37mfailure-budget.failures[m: # [32mor null[m+      [33m<integer>[m # [32m64 bit unsigned integer[m+  default: [33m10[m++  [34mHow long a failed request counts towards the failure budget[m+  option: [37m--failure-budget-window[m [33mDURATION[m+  env: [37mFAILURE_BUDGET_WINDOW[m [33mDURATION[m+  config:+    [37mfailure-budget.window[m: # [32many of[m+      [ [33mnull[m+      , [33m<string>[m+      , [33m<integer>[m # [32m64 bit signed integer[m+      ]+  default: [33m3600s[m++  [34mHeaders the dependency reports a spent quota in: none, x-ratelimit, ratelimit-reset or ratelimit[m+  option: [37m--rate-limit-headers[m [33mHEADERS[m+  env: [37mRATE_LIMIT_HEADERS[m [33mHEADERS[m+  config:+    [37mrate-limit-headers[m: # [32mor null[m+      [33m<string>[m+  default: [33mnone[m++[36mOptions[m:+  [37m-h[m[36m|[m[37m--help[m                           [34mShow this help text[m                                                                                            +  [37m--version[m                           [34mOutput version information[m                                                                                     +  [37m--attempts-per-request[m              [34mRequests per call, retries included[m                                                              default: [33m4[m    +  [37m--backoff-base[m                      [34mBase of the random wait between attempts, doubled once per attempt[m                               default: [33m1s[m   +  [37m--backoff-max-delay[m                 [34mLongest wait between two attempts[m                                                                default: [33m30s[m  +  [37m--backoff-max-total-delay[m           [34mMost one call waits between its attempts in all[m                                                  default: [33m60s[m  +  [37m--circuit-breaker-failure-threshold[m [34mConsecutive failed requests that open the circuit breaker[m                                        default: [33m5[m    +  [37m--circuit-breaker-reset-timeout[m     [34mHow long the circuit breaker stays open before a probe[m                                           default: [33m30s[m  +  [37m--failure-budget-failures[m           [34mFailed requests within the window that report a dependency as unwell[m                             default: [33m10[m   +  [37m--failure-budget-window[m             [34mHow long a failed request counts towards the failure budget[m                                      default: [33m3600s[m+  [37m--rate-limit-headers[m                [34mHeaders the dependency reports a spent quota in: none, x-ratelimit, ratelimit-reset or ratelimit[m default: [33mnone[m ++[36mEnvironment Variables[m:+  [37mATTEMPTS_PER_REQUEST[m [33mCOUNT[m                [34mRequests per call, retries included[m                                                                default: [33m4[m    +  [37mBACKOFF_BASE[m [33mDURATION[m                     [34mBase of the random wait between attempts, doubled once per attempt[m                                 default: [33m1s[m   +  [37mBACKOFF_MAX_DELAY[m [33mDURATION[m                [34mLongest wait between two attempts[m                                                                  default: [33m30s[m  +  [37mBACKOFF_MAX_TOTAL_DELAY[m [33mDURATION[m          [34mMost one call waits between its attempts in all[m                                                    default: [33m60s[m  +  [37mCIRCUIT_BREAKER_FAILURE_THRESHOLD[m [33mCOUNT[m   [34mConsecutive failed requests that open the circuit breaker[m                                          default: [33m5[m    +  [37mCIRCUIT_BREAKER_RESET_TIMEOUT[m [33mDURATION[m    [34mHow long the circuit breaker stays open before a probe[m                                             default: [33m30s[m  +  [37mFAILURE_BUDGET_FAILURES[m [33mCOUNT[m             [34mFailed requests within the window that report a dependency as unwell[m                               default: [33m10[m   +  [37mFAILURE_BUDGET_WINDOW[m [33mDURATION[m            [34mHow long a failed request counts towards the failure budget[m                                        default: [33m3600s[m+  [37mRATE_LIMIT_HEADERS[m [33mHEADERS[m                [34mHeaders the dependency reports a spent quota in: none, x-ratelimit, ratelimit-reset or ratelimit[m   default: [33mnone[m ++[36mConfiguration Values[m:+  [34mRequests per call, retries included[m+  default: [33m4[m+  [37mattempts-per-request[m:+    # [32mor null[m+    [33m<integer>[m # [32m64 bit unsigned integer[m+  [34mBase of the random wait between attempts, doubled once per attempt[m+  default: [33m1s[m+  [37mbackoff.base[m:+    # [32many of[m+    [ [33mnull[m+    , [33m<string>[m+    , [33m<integer>[m # [32m64 bit signed integer[m+    ]+  [34mLongest wait between two attempts[m+  default: [33m30s[m+  [37mbackoff.max-delay[m:+    # [32many of[m+    [ [33mnull[m+    , [33m<string>[m+    , [33m<integer>[m # [32m64 bit signed integer[m+    ]+  [34mMost one call waits between its attempts in all[m+  default: [33m60s[m+  [37mbackoff.max-total-delay[m:+    # [32many of[m+    [ [33mnull[m+    , [33m<string>[m+    , [33m<integer>[m # [32m64 bit signed integer[m+    ]+  [34mConsecutive failed requests that open the circuit breaker[m+  default: [33m5[m+  [37mcircuit-breaker.failure-threshold[m:+    # [32mor null[m+    [33m<integer>[m # [32m64 bit unsigned integer[m+  [34mHow long the circuit breaker stays open before a probe[m+  default: [33m30s[m+  [37mcircuit-breaker.reset-timeout[m:+    # [32many of[m+    [ [33mnull[m+    , [33m<string>[m+    , [33m<integer>[m # [32m64 bit signed integer[m+    ]+  [34mFailed requests within the window that report a dependency as unwell[m+  default: [33m10[m+  [37mfailure-budget.failures[m:+    # [32mor null[m+    [33m<integer>[m # [32m64 bit unsigned integer[m+  [34mHow long a failed request counts towards the failure budget[m+  default: [33m3600s[m+  [37mfailure-budget.window[m:+    # [32many of[m+    [ [33mnull[m+    , [33m<string>[m+    , [33m<integer>[m # [32m64 bit signed integer[m+    ]+  [34mHeaders the dependency reports a spent quota in: none, x-ratelimit, ratelimit-reset or ratelimit[m+  default: [33mnone[m+  [37mrate-limit-headers[m:+    # [32mor null[m+    [33m<string>[m+
+ test_resources/http-settings.txt view
@@ -0,0 +1,164 @@+[36mUsage: [m[33mexample[m [36m[[m[37m--attempts-per-request[m [33mCOUNT[m[36m][m [36m[[m[37m--backoff-base[m [33mDURATION[m[36m][m [36m[[m[37m--backoff-max-delay[m [33mDURATION[m[36m][m [36m[[m[37m--backoff-max-total-delay[m [33mDURATION[m[36m][m [36m[[m[37m--circuit-breaker-failure-threshold[m [33mCOUNT[m[36m][m [36m[[m[37m--circuit-breaker-reset-timeout[m [33mDURATION[m[36m][m [36m[[m[37m--failure-budget-failures[m [33mCOUNT[m[36m][m [36m[[m[37m--failure-budget-window[m [33mDURATION[m[36m][m [36m[[m[37m--rate-limit-headers[m [33mHEADERS[m[36m][m++[36mAll settings[m:+  [34mShow this help text[m+  switch: [37m-h[m[36m|[m[37m--help[m++  [34mOutput version information[m+  switch: [37m--version[m++  [34mRequests per call, retries included[m+  option: [37m--attempts-per-request[m [33mCOUNT[m+  env: [37mATTEMPTS_PER_REQUEST[m [33mCOUNT[m+  config:+    [37mattempts-per-request[m: # [32mor null[m+      [33m<integer>[m # [32m64 bit unsigned integer[m++  [34mBase of the random wait between attempts, doubled once per attempt[m+  option: [37m--backoff-base[m [33mDURATION[m+  env: [37mBACKOFF_BASE[m [33mDURATION[m+  config:+    [37mbackoff.base[m: # [32many of[m+      [ [33mnull[m+      , [33m<string>[m+      , [33m<integer>[m # [32m64 bit signed integer[m+      ]++  [34mLongest wait between two attempts[m+  option: [37m--backoff-max-delay[m [33mDURATION[m+  env: [37mBACKOFF_MAX_DELAY[m [33mDURATION[m+  config:+    [37mbackoff.max-delay[m: # [32many of[m+      [ [33mnull[m+      , [33m<string>[m+      , [33m<integer>[m # [32m64 bit signed integer[m+      ]++  [34mMost one call waits between its attempts in all[m+  option: [37m--backoff-max-total-delay[m [33mDURATION[m+  env: [37mBACKOFF_MAX_TOTAL_DELAY[m [33mDURATION[m+  config:+    [37mbackoff.max-total-delay[m: # [32many of[m+      [ [33mnull[m+      , [33m<string>[m+      , [33m<integer>[m # [32m64 bit signed integer[m+      ]++  [34mConsecutive failed requests that open the circuit breaker[m+  option: [37m--circuit-breaker-failure-threshold[m [33mCOUNT[m+  env: [37mCIRCUIT_BREAKER_FAILURE_THRESHOLD[m [33mCOUNT[m+  config:+    [37mcircuit-breaker.failure-threshold[m: # [32mor null[m+      [33m<integer>[m # [32m64 bit unsigned integer[m++  [34mHow long the circuit breaker stays open before a probe[m+  option: [37m--circuit-breaker-reset-timeout[m [33mDURATION[m+  env: [37mCIRCUIT_BREAKER_RESET_TIMEOUT[m [33mDURATION[m+  config:+    [37mcircuit-breaker.reset-timeout[m: # [32many of[m+      [ [33mnull[m+      , [33m<string>[m+      , [33m<integer>[m # [32m64 bit signed integer[m+      ]++  [34mFailed requests within the window that report a dependency as unwell[m+  option: [37m--failure-budget-failures[m [33mCOUNT[m+  env: [37mFAILURE_BUDGET_FAILURES[m [33mCOUNT[m+  config:+    [37mfailure-budget.failures[m: # [32mor null[m+      [33m<integer>[m # [32m64 bit unsigned integer[m++  [34mHow long a failed request counts towards the failure budget[m+  option: [37m--failure-budget-window[m [33mDURATION[m+  env: [37mFAILURE_BUDGET_WINDOW[m [33mDURATION[m+  config:+    [37mfailure-budget.window[m: # [32many of[m+      [ [33mnull[m+      , [33m<string>[m+      , [33m<integer>[m # [32m64 bit signed integer[m+      ]++  [34mHeaders the dependency reports a spent quota in: none, x-ratelimit, ratelimit-reset or ratelimit[m+  option: [37m--rate-limit-headers[m [33mHEADERS[m+  env: [37mRATE_LIMIT_HEADERS[m [33mHEADERS[m+  config:+    [37mrate-limit-headers[m: # [32mor null[m+      [33m<string>[m++[36mOptions[m:+  [37m-h[m[36m|[m[37m--help[m                           [34mShow this help text[m                                                                             +  [37m--version[m                           [34mOutput version information[m                                                                      +  [37m--attempts-per-request[m              [34mRequests per call, retries included[m                                                             +  [37m--backoff-base[m                      [34mBase of the random wait between attempts, doubled once per attempt[m                              +  [37m--backoff-max-delay[m                 [34mLongest wait between two attempts[m                                                               +  [37m--backoff-max-total-delay[m           [34mMost one call waits between its attempts in all[m                                                 +  [37m--circuit-breaker-failure-threshold[m [34mConsecutive failed requests that open the circuit breaker[m                                       +  [37m--circuit-breaker-reset-timeout[m     [34mHow long the circuit breaker stays open before a probe[m                                          +  [37m--failure-budget-failures[m           [34mFailed requests within the window that report a dependency as unwell[m                            +  [37m--failure-budget-window[m             [34mHow long a failed request counts towards the failure budget[m                                     +  [37m--rate-limit-headers[m                [34mHeaders the dependency reports a spent quota in: none, x-ratelimit, ratelimit-reset or ratelimit[m++[36mEnvironment Variables[m:+  [37mATTEMPTS_PER_REQUEST[m [33mCOUNT[m                [34mRequests per call, retries included[m                                                             +  [37mBACKOFF_BASE[m [33mDURATION[m                     [34mBase of the random wait between attempts, doubled once per attempt[m                              +  [37mBACKOFF_MAX_DELAY[m [33mDURATION[m                [34mLongest wait between two attempts[m                                                               +  [37mBACKOFF_MAX_TOTAL_DELAY[m [33mDURATION[m          [34mMost one call waits between its attempts in all[m                                                 +  [37mCIRCUIT_BREAKER_FAILURE_THRESHOLD[m [33mCOUNT[m   [34mConsecutive failed requests that open the circuit breaker[m                                       +  [37mCIRCUIT_BREAKER_RESET_TIMEOUT[m [33mDURATION[m    [34mHow long the circuit breaker stays open before a probe[m                                          +  [37mFAILURE_BUDGET_FAILURES[m [33mCOUNT[m             [34mFailed requests within the window that report a dependency as unwell[m                            +  [37mFAILURE_BUDGET_WINDOW[m [33mDURATION[m            [34mHow long a failed request counts towards the failure budget[m                                     +  [37mRATE_LIMIT_HEADERS[m [33mHEADERS[m                [34mHeaders the dependency reports a spent quota in: none, x-ratelimit, ratelimit-reset or ratelimit[m++[36mConfiguration Values[m:+  [34mRequests per call, retries included[m+  [37mattempts-per-request[m:+    # [32mor null[m+    [33m<integer>[m # [32m64 bit unsigned integer[m+  [34mBase of the random wait between attempts, doubled once per attempt[m+  [37mbackoff.base[m:+    # [32many of[m+    [ [33mnull[m+    , [33m<string>[m+    , [33m<integer>[m # [32m64 bit signed integer[m+    ]+  [34mLongest wait between two attempts[m+  [37mbackoff.max-delay[m:+    # [32many of[m+    [ [33mnull[m+    , [33m<string>[m+    , [33m<integer>[m # [32m64 bit signed integer[m+    ]+  [34mMost one call waits between its attempts in all[m+  [37mbackoff.max-total-delay[m:+    # [32many of[m+    [ [33mnull[m+    , [33m<string>[m+    , [33m<integer>[m # [32m64 bit signed integer[m+    ]+  [34mConsecutive failed requests that open the circuit breaker[m+  [37mcircuit-breaker.failure-threshold[m:+    # [32mor null[m+    [33m<integer>[m # [32m64 bit unsigned integer[m+  [34mHow long the circuit breaker stays open before a probe[m+  [37mcircuit-breaker.reset-timeout[m:+    # [32many of[m+    [ [33mnull[m+    , [33m<string>[m+    , [33m<integer>[m # [32m64 bit signed integer[m+    ]+  [34mFailed requests within the window that report a dependency as unwell[m+  [37mfailure-budget.failures[m:+    # [32mor null[m+    [33m<integer>[m # [32m64 bit unsigned integer[m+  [34mHow long a failed request counts towards the failure budget[m+  [37mfailure-budget.window[m:+    # [32many of[m+    [ [33mnull[m+    , [33m<string>[m+    , [33m<integer>[m # [32m64 bit signed integer[m+    ]+  [34mHeaders the dependency reports a spent quota in: none, x-ratelimit, ratelimit-reset or ratelimit[m+  [37mrate-limit-headers[m:+    # [32mor null[m+    [33m<string>[m+