packages feed

http-env (empty) → 0.0.0.0

raw patch · 21 files changed

+3046/−0 lines, 21 filesdep +autodocodecdep +basedep +bytestringsetup-changed

Dependencies added: autodocodec, base, bytestring, containers, deepseq, hashable, http-client, http-client-tls, http-types, monad-logger, network-uri, opt-env-conf, pretty-show, prometheus, retry, scientific, servant-client, servant-client-core, stm-containers, text, time, token-limiter-concurrent, unliftio, validity, validity-containers, validity-time

Files

+ CHANGELOG.md view
@@ -0,0 +1,26 @@+# Changelog++## [0.0.0.0] - 2026-11-30++### Added++* `Network.HTTP.Env`: one env per outbound HTTP dependency, holding its+  retries, circuit breaker, failure budget, request limiter and log policy,+  with `httpCall` to call through it.+* `Network.HTTP.Env.Servant`: the same layers for servant-client, with+  `callClient` and `callStreamingClient`.+* Retries with a capped full-jitter backoff, sent again only for an idempotent+  method, an `Idempotency-Key` header or a request that never left, unless a+  call says it may be repeated.+* A circuit breaker that opens after consecutive failed requests, and a+  failure budget that reports a dependency as unwell without stopping any+  request.+* Spent quotas told apart from other failures, read from the `X-RateLimit-*`,+  `RateLimit-Reset` or structured `RateLimit` headers, off by default.+* Request limiters, and one per key that can be repaced at the rate a+  dependency reports.+* Reports of the breaker and the budget, and a Prometheus gauge of them.+* Scrubbed logs and errors: credentials in headers, cookies and query+  parameters are redacted.+* Settings for opt-env-conf: a global block with defaults, and a block of+  overrides per dependency.
+ 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.cabal view
@@ -0,0 +1,81 @@+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+version:        0.0.0.0+synopsis:       Call HTTP dependencies with retries, a circuit breaker and a failure budget+description:    Call a dependency through an env that holds its retries, circuit breaker, failure budget, rate limiter and log policy, configured once per process.+                .+                For more info, see <https://github.com/NorfairKing/http-env the readme>.+category:       Network+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++source-repository head+  type: git+  location: https://github.com/NorfairKing/http-env++library+  exposed-modules:+      Network.HTTP.Env+      Network.HTTP.Env.CircuitBreaker+      Network.HTTP.Env.CircuitBreaker.Retry+      Network.HTTP.Env.FailureBudget+      Network.HTTP.Env.HttpClient+      Network.HTTP.Env.HttpClient.Retry+      Network.HTTP.Env.LogPolicy+      Network.HTTP.Env.Manager+      Network.HTTP.Env.Metrics+      Network.HTTP.Env.Numeric+      Network.HTTP.Env.OptParse+      Network.HTTP.Env.OptParse.Duration+      Network.HTTP.Env.Pacing+      Network.HTTP.Env.RateLimit+      Network.HTTP.Env.Servant+      Network.HTTP.Env.Servant.Client+      Network.HTTP.Env.Servant.Retry+  other-modules:+      Paths_http_env+  hs-source-dirs:+      src+  ghc-options: -Wall -Wincomplete-uni-patterns -Wincomplete-record-updates -Wpartial-fields -Widentities -Wredundant-constraints -Wcpp-undef -Wunused-packages+  build-depends:+      autodocodec+    , base >=4.20 && <5+    , bytestring+    , containers+    , deepseq+    , hashable+    , http-client+    , http-client-tls+    , http-types+    , monad-logger+    , network-uri+    , opt-env-conf+    , pretty-show+    , prometheus+    , retry+    , scientific+    , servant-client+    , servant-client-core+    , stm-containers+    , text+    , time+    , token-limiter-concurrent+    , unliftio+    , validity+    , validity-containers+    , validity-time+  default-language: Haskell2010
+ src/Network/HTTP/Env.hs view
@@ -0,0 +1,153 @@+-- | Call each HTTP dependency through an env that holds its retries, circuit+-- breaker, failure budget, rate limiting and log policy.+--+-- Start here. For servant-client, start from "Network.HTTP.Env.Servant".+--+-- = Usage+--+-- Make one env per dependency, and make every call to it through that env:+--+-- > import Control.Monad.IO.Class (liftIO)+-- > import Control.Monad.Logger (runStderrLoggingT)+-- > import Network.HTTP.Client (newManager, parseUrlThrow)+-- > import Network.HTTP.Env+-- >+-- > main :: IO ()+-- > main = runStderrLoggingT $ do+-- >   manager <- liftIO $ newManager (withUserAgent "my-app" (tlsManagerSettingsWithMaxHeaderLength 65536))+-- >   env <- newHttpEnv (HttpEnvName "example") defaultHttpEnvSettings defaultLogPolicy manager+-- >   request <- liftIO $ parseUrlThrow "https://example.com/api"+-- >   result <- httpCall env request+-- >   case result of+-- >     Right response -> ...+-- >     Left HttpEnvErrorCircuitOpen -> ...+-- >     Left (HttpEnvErrorRateLimited wait _) -> ...+-- >     Left (HttpEnvErrorFailed exception) -> ...+--+-- A request built with 'Network.HTTP.Client.parseUrlThrow' fails on a refusal;+-- one built with 'Network.HTTP.Client.parseRequest' returns the refusal as the+-- response, except for a spent quota, which is told apart either way.+--+-- = Settings+--+-- Parse one global t'HttpEnvSettings' with opt-env-conf, with its defaults,+-- and one t'HttpEnvOverrides' per dependency with+-- 'httpEnvOverridesParser', defaulting to what the application chooses for that+-- dependency. 'resolveHttpEnvSettings' combines the two:+--+-- > data Settings = Settings {settingsHttp :: HttpEnvSettings, settingsGitHubHttp :: HttpEnvOverrides}+-- >+-- > instance HasParser Settings where+-- >   settingsParser =+-- >     Settings+-- >       <$> subSettings "http"+-- >       <*> subAll "github" (subAll "http" (httpEnvOverridesParser noHttpEnvOverrides))+-- >+-- > gitHubSettings :: Settings -> HttpEnvSettings+-- > gitHubSettings settings = resolveHttpEnvSettings (settingsHttp settings) (settingsGitHubHttp settings)+--+-- = Monitoring+--+-- Ask an env what its breaker and its failure budget say, whenever something+-- needs to know; asking does not count as a call.+-- For a notice shown to people, read the two apart:+--+-- > report <- peekHttpEnv env+-- > let down = httpEnvReportCircuit report == Just CircuitReportRejecting+-- > let unwell = fmap failureBudgetReportStatus (httpEnvReportFailureBudget report) == Just FailureBudgetStatusExhausted+--+-- For Prometheus, sample every env when it is scraped, each under labels of+-- its own. 'httpEnvReportValue' reads 1 when all is well, 0.75 while the budget+-- is exhausted, 0.5 while the breaker is probing and 0 while it rejects:+--+-- > import qualified Data.Map.Strict as Map+-- > import qualified System.Metrics.Prometheus.MetricId as Labels+-- > import System.Metrics.Prometheus.Registry (RegistrySample (..))+-- >+-- > sampleEnvs :: [(Text, HttpEnv)] -> IO RegistrySample+-- > sampleEnvs envs = do+-- >   samples <- for envs $ \(dependency, env) ->+-- >     httpEnvSample "http_env_health" (Labels.fromList [("dependency", dependency)]) <$> peekHttpEnv env+-- >   pure (RegistrySample (Map.fromList samples))+module Network.HTTP.Env+  ( -- * Settings+    HttpEnvSettings (..),+    defaultHttpEnvSettings,+    Attempts (..),+    BackoffSettings (..),+    defaultBackoffSettings,+    BackoffOverrides (..),+    CircuitBreakerSettings (..),+    FailureBudgetSettings (..),+    HttpEnvOverrides (..),+    CircuitBreakerOverrides (..),+    FailureBudgetOverrides (..),+    noHttpEnvOverrides,+    httpEnvOverridesParser,+    resolveHttpEnvSettings,+    RateLimitHeaders (..),++    -- * Making an env++    -- | One per dependency, each with a breaker and a budget of its own.+    newHttpEnv,+    HttpEnvName (..),+    HttpEnv,+    withRequestLimiter,+    RequestLimiter,+    newRequestLimiter,+    tlsManagerSettingsWithMaxHeaderLength,+    withUserAgent,+    LogPolicy (..),+    defaultLogPolicy,++    -- * Calling++    -- | A spent quota is told apart only for an env whose settings choose+    -- t'RateLimitHeaders'.+    httpCall,+    httpCallWith,+    Repeatable (..),+    HttpEnvError (..),+    httpEnvErrorCircuitBreakerError,+    CircuitBreakerError (..),++    -- * Inspecting++    -- | What an env's breaker and budget say, for a dashboard or a person.+    -- Reading does not count as a call.+    peekHttpEnv,+    HttpEnvReport (..),+    CircuitReport (..),+    FailureBudgetReport (..),+    FailureBudgetStatus (..),+    httpEnvSample,+    httpEnvReportValue,+  )+where++import Network.HTTP.Env.CircuitBreaker (CircuitBreakerError (..), CircuitBreakerSettings (..), CircuitReport (..))+import Network.HTTP.Env.CircuitBreaker.Retry (Attempts (..))+import Network.HTTP.Env.FailureBudget (FailureBudgetReport (..), FailureBudgetSettings (..), FailureBudgetStatus (..))+import Network.HTTP.Env.HttpClient (HttpEnv, HttpEnvError (..), HttpEnvReport (..), httpCall, httpCallWith, httpEnvErrorCircuitBreakerError, peekHttpEnv, withRequestLimiter)+import Network.HTTP.Env.HttpClient.Retry (Repeatable (..))+import Network.HTTP.Env.LogPolicy (LogPolicy (..), defaultLogPolicy)+import Network.HTTP.Env.Manager (tlsManagerSettingsWithMaxHeaderLength, withUserAgent)+import Network.HTTP.Env.Metrics (httpEnvReportValue, httpEnvSample)+import Network.HTTP.Env.OptParse+  ( BackoffOverrides (..),+    BackoffSettings (..),+    CircuitBreakerOverrides (..),+    FailureBudgetOverrides (..),+    HttpEnvName (..),+    HttpEnvOverrides (..),+    HttpEnvSettings (..),+    defaultBackoffSettings,+    defaultHttpEnvSettings,+    httpEnvOverridesParser,+    newHttpEnv,+    noHttpEnvOverrides,+    resolveHttpEnvSettings,+  )+import Network.HTTP.Env.Pacing (RequestLimiter, newRequestLimiter)+import Network.HTTP.Env.RateLimit (RateLimitHeaders (..))
+ src/Network/HTTP/Env/CircuitBreaker.hs view
@@ -0,0 +1,306 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}++-- | A circuit breaker guarding one dependency.+module Network.HTTP.Env.CircuitBreaker+  ( -- * Settings+    CircuitBreakerSettings (..),+    defaultCircuitBreakerSettings,+    CircuitBreakerLimits (..),+    circuitBreakerLimits,++    -- * State machine (pure)+    CircuitState (..),+    Outcome (..),+    Admission (..),+    Decision (..),+    CircuitReport (..),+    decide,+    recordOutcome,+    circuitReport,++    -- * Running actions+    CircuitBreakerEnv,+    newCircuitBreaker,+    circuitBreakerName,+    circuitBreakerResetTimeout,+    readCircuitBreakerState,+    peekCircuitBreaker,+    CircuitBreakerError (..),+    guardCircuitBreaker,+  )+where++import Control.Arrow (left)+import Control.Monad (when)+import Control.Monad.Logger.CallStack+  ( Loc,+    LogLevel,+    LogSource,+    LogStr,+    MonadLoggerIO,+    askLoggerIO,+    logError,+    logInfo,+    runLoggingT,+  )+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Time (NominalDiffTime)+import Data.Validity+import Data.Validity.Time ()+import Data.Word (Word64)+import GHC.Clock (getMonotonicTimeNSec)+import GHC.Generics (Generic)+import Network.HTTP.Env.Numeric (nanosToNominalDiffTime, nominalDiffTimeToNanos)+import UnliftIO++-- | When a breaker opens and when it probes again.+data CircuitBreakerSettings = CircuitBreakerSettings+  { -- | Consecutive failed requests that open the breaker; at least 1.+    circuitBreakerSettingsFailureThreshold :: !Word,+    -- | How long the breaker stays open before a probe.+    -- Positive: a zero cooldown would admit every concurrent caller as a probe.+    circuitBreakerSettingsResetTimeout :: !NominalDiffTime+  }+  deriving (Show, Eq, Generic)++instance Validity CircuitBreakerSettings where+  validate = validateCircuitBreakerSettings++-- Equivalent: genericValidate of a count and a duration is always valid.+-- Matched positionally so that a new field fails to compile here.+validateCircuitBreakerSettings :: CircuitBreakerSettings -> Validation+validateCircuitBreakerSettings settings@(CircuitBreakerSettings threshold resetTimeout) =+  mconcat+    [ genericValidate settings,+      declare "the failure threshold is at least 1" $ threshold >= 1,+      declare "the reset timeout is positive" $ resetTimeout > 0+    ]+{-# ANN validateCircuitBreakerSettings ("DisableMutation: ListLit" :: String) #-}++-- | Settings for a typical flaky network dependency.+defaultCircuitBreakerSettings :: CircuitBreakerSettings+defaultCircuitBreakerSettings =+  CircuitBreakerSettings+    { circuitBreakerSettingsFailureThreshold = 5,+      circuitBreakerSettingsResetTimeout = 30+    }++-- | The state of the circuit, with monotonic-clock times in nanoseconds.+data CircuitState+  = -- | Calls pass through; carries the consecutive failure count.+    CircuitStateClosed !Word+  | -- | Calls fail fast; carries when the circuit opened.+    CircuitStateOpen !Word64+  | -- | A probe is in flight since the carried time.+    -- A probe older than the reset timeout is stale and replaced, so a probe+    -- that threw cannot wedge the breaker.+    CircuitStateHalfOpen !Word64+  deriving (Show, Eq, Generic)++instance Validity CircuitState++-- | How the caller classifies the result of an admitted call.+data Outcome+  = OutcomeCircuitShouldStayClosed+  | OutcomeCircuitShouldOpen+  deriving (Show, Generic)++instance Validity Outcome++-- | What a call was admitted as, so that only the probe decides a half-open+-- circuit.+data Admission+  = -- | While closed.+    AdmissionClosed+  | -- | As the probe started at the carried time.+    AdmissionProbe !Word64+  deriving (Show, Eq, Generic)++instance Validity Admission++-- | Whether to run a call.+data Decision+  = DecisionAllow !Admission+  | DecisionReject+  deriving (Show, Eq, Generic)++instance Validity Decision++-- | What a breaker is doing, for a person or a dashboard.+data CircuitReport+  = CircuitReportClosed+  | -- | A probe is in flight, or the next caller will be one.+    CircuitReportProbing+  | -- | No probe is due yet.+    CircuitReportRejecting+  deriving (Show, Eq, Generic)++instance Validity CircuitReport++-- | Either the breaker was open, or the call failed with its own error.+data CircuitBreakerError e+  = -- | The breaker is open, so nothing was sent.+    CircuitBreakerErrorOpen+  | -- | The call was made and failed with the dependency's own error.+    CircuitBreakerErrorUnderlying !e+  deriving (Show, Eq, Generic)++instance (Validity e) => Validity (CircuitBreakerError e)++-- | Whether to admit a call, and the state to store before running it.+decide :: CircuitBreakerLimits -> Word64 -> CircuitState -> (Decision, CircuitState)+decide limits now = \case+  CircuitStateClosed n -> (DecisionAllow AdmissionClosed, CircuitStateClosed n)+  CircuitStateHalfOpen startedAt+    | expired startedAt -> (DecisionAllow (AdmissionProbe now), CircuitStateHalfOpen now)+    | otherwise -> (DecisionReject, CircuitStateHalfOpen startedAt)+  CircuitStateOpen openedAt+    | expired openedAt -> (DecisionAllow (AdmissionProbe now), CircuitStateHalfOpen now)+    | otherwise -> (DecisionReject, CircuitStateOpen openedAt)+  where+    -- Compared as integers, because a concurrent caller can stamp 't' after+    -- this one read 'now', so an unsigned difference would wrap, and adding+    -- the timeout to 't' instead could overflow.+    expired t = toInteger now - toInteger t >= toInteger resetNanos+    resetNanos = circuitBreakerLimitsResetTimeoutNanos limits++-- | Fold the outcome of an admitted call into the state.+recordOutcome :: CircuitBreakerLimits -> Word64 -> Admission -> Outcome -> CircuitState -> CircuitState+recordOutcome limits now admission outcome = \case+  CircuitStateClosed n -> case outcome of+    OutcomeCircuitShouldStayClosed -> CircuitStateClosed 0+    OutcomeCircuitShouldOpen ->+      let n' = n + 1+       in if n' >= circuitBreakerLimitsFailureThreshold limits+            then CircuitStateOpen now+            else CircuitStateClosed n'+  CircuitStateHalfOpen startedAt -> case admission of+    AdmissionProbe probeStartedAt+      | probeStartedAt == startedAt -> case outcome of+          OutcomeCircuitShouldStayClosed -> CircuitStateClosed 0+          OutcomeCircuitShouldOpen -> CircuitStateOpen now+    -- A call admitted before the probe, or a stale probe, says nothing about it.+    AdmissionProbe _ -> CircuitStateHalfOpen startedAt+    AdmissionClosed -> CircuitStateHalfOpen startedAt+  -- Only calls admitted before it opened, or a stale probe, finish while open.+  CircuitStateOpen openedAt -> CircuitStateOpen openedAt++-- | What to report about a circuit in this state at this time.+circuitReport :: CircuitBreakerLimits -> Word64 -> CircuitState -> CircuitReport+circuitReport limits now = \case+  CircuitStateClosed _ -> CircuitReportClosed+  CircuitStateHalfOpen _ -> CircuitReportProbing+  CircuitStateOpen openedAt ->+    case decide limits now (CircuitStateOpen openedAt) of+      (DecisionAllow _, _) -> CircuitReportProbing+      (DecisionReject, _) -> CircuitReportRejecting++-- | A breaker's settings in the units its state machine compares.+data CircuitBreakerLimits = CircuitBreakerLimits+  { circuitBreakerLimitsFailureThreshold :: !Word,+    circuitBreakerLimitsResetTimeoutNanos :: !Word64+  }++-- | Resolve a breaker's settings.+circuitBreakerLimits :: CircuitBreakerSettings -> CircuitBreakerLimits+circuitBreakerLimits settings =+  -- Floored at 1 ns: a sub-nanosecond timeout would round to 0 and re-admit a+  -- just-stamped half-open, breaking the single-probe guarantee.+  let resetTimeoutNanos = max 1 (nominalDiffTimeToNanos (circuitBreakerSettingsResetTimeout settings))+   in CircuitBreakerLimits+        { circuitBreakerLimitsFailureThreshold = circuitBreakerSettingsFailureThreshold settings,+          circuitBreakerLimitsResetTimeoutNanos = resetTimeoutNanos+        }++-- | A live circuit breaker.+data CircuitBreakerEnv = CircuitBreakerEnv+  { circuitBreakerEnvName :: !Text,+    circuitBreakerEnvLimits :: !CircuitBreakerLimits,+    circuitBreakerEnvState :: !(TVar CircuitState),+    circuitBreakerEnvLog :: !(Loc -> LogSource -> LogLevel -> LogStr -> IO ())+  }++-- | A closed breaker, named for the dependency it guards.+newCircuitBreaker :: (MonadLoggerIO m) => Text -> CircuitBreakerSettings -> m CircuitBreakerEnv+newCircuitBreaker name settings = do+  logFunc <- askLoggerIO+  stateVar <- newTVarIO (CircuitStateClosed 0)+  pure+    CircuitBreakerEnv+      { circuitBreakerEnvName = name,+        circuitBreakerEnvLimits = circuitBreakerLimits settings,+        circuitBreakerEnvState = stateVar,+        circuitBreakerEnvLog = logFunc+      }++-- | The name this breaker was created with.+circuitBreakerName :: CircuitBreakerEnv -> Text+circuitBreakerName = circuitBreakerEnvName++-- | How long this breaker stays open before a probe.+circuitBreakerResetTimeout :: CircuitBreakerEnv -> NominalDiffTime+circuitBreakerResetTimeout = nanosToNominalDiffTime . circuitBreakerLimitsResetTimeoutNanos . circuitBreakerEnvLimits++-- | The stored state, without advancing it.+readCircuitBreakerState :: (MonadIO m) => CircuitBreakerEnv -> m CircuitState+readCircuitBreakerState = readTVarIO . circuitBreakerEnvState++-- | What this breaker is doing right now.+-- Stores nothing, so asking cannot spend the half-open probe.+peekCircuitBreaker :: (MonadIO m) => CircuitBreakerEnv -> m CircuitReport+peekCircuitBreaker env = do+  now <- liftIO getMonotonicTimeNSec+  circuitState <- readTVarIO (circuitBreakerEnvState env)+  pure (circuitReport (circuitBreakerEnvLimits env) now circuitState)++-- | Atomically apply 'decide' and store its state.+admit :: (MonadIO m) => CircuitBreakerEnv -> m Decision+admit env = do+  now <- liftIO getMonotonicTimeNSec+  atomically $ do+    st <- readTVar (circuitBreakerEnvState env)+    let (d, !st') = decide (circuitBreakerEnvLimits env) now st+    writeTVar (circuitBreakerEnvState env) st'+    pure d++-- | Atomically fold an outcome into the state, logging opening and closing.+-- A failed probe re-opening is not logged: it is the same outage.+recordCurrent :: (MonadIO m) => CircuitBreakerEnv -> Admission -> Outcome -> m ()+recordCurrent env admission outcome = do+  now <- liftIO getMonotonicTimeNSec+  (old, new) <- atomically $ do+    old <- readTVar (circuitBreakerEnvState env)+    let !new = recordOutcome (circuitBreakerEnvLimits env) now admission outcome old+    writeTVar (circuitBreakerEnvState env) new+    pure (old, new)+  when (isClosed old && not (isClosed new)) $+    logThrough (logError (message "opened:"))+  when (not (isClosed old) && isClosed new) $+    logThrough (logInfo (message "closed:"))+  where+    logThrough act = liftIO (runLoggingT act (circuitBreakerEnvLog env))+    message verb = Text.pack (unwords ["Circuit breaker", verb, Text.unpack (circuitBreakerEnvName env)])+    isClosed = \case+      CircuitStateClosed _ -> True+      CircuitStateOpen _ -> False+      CircuitStateHalfOpen _ -> False++-- | Run an action behind the breaker, unless it is open.+-- Exceptions propagate uncounted.+guardCircuitBreaker ::+  (MonadIO m) =>+  CircuitBreakerEnv ->+  (Either e a -> Outcome) ->+  m (Either e a) ->+  m (Either (CircuitBreakerError e) a)+guardCircuitBreaker env classify action =+  admit env >>= \case+    DecisionReject -> pure (Left CircuitBreakerErrorOpen)+    DecisionAllow admission -> do+      res <- action+      recordCurrent env admission (classify res)+      pure (left CircuitBreakerErrorUnderlying res)
+ src/Network/HTTP/Env/CircuitBreaker/Retry.hs view
@@ -0,0 +1,147 @@+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}++-- | Retries with the circuit breaker inside the loop, so it counts requests.+module Network.HTTP.Env.CircuitBreaker.Retry+  ( retryingWithCircuitBreaker,+    RepeatSafety (..),+    anyRepeatSafe,+    Attempts (..),+    defaultAttempts,+    limitAttempts,+    breakerPolicy,+    takingTraffic,+    liftRetryPolicy,+  )+where++import Control.Arrow (left)+import Control.Monad (forM_)+import Control.Monad.IO.Class+import Control.Monad.Logger.CallStack (MonadLogger, logWarn)+import Control.Retry (RetryPolicyM (..), RetryStatus (..), limitRetries, retrying)+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Validity+import GHC.Generics (Generic)+import Network.HTTP.Env.CircuitBreaker+import Network.HTTP.Env.FailureBudget (FailureBudgetEnv, recordFailureNow)+import Network.HTTP.Env.Numeric (wordToIntSaturating)++-- | Whether sending a request again risks doing its work twice.+data RepeatSafety+  = RepeatSafetySafe+  | RepeatSafetyUnsafe+  deriving (Show, Eq)++-- | 'RepeatSafetySafe' when any of these says so.+anyRepeatSafe :: [RepeatSafety] -> RepeatSafety+anyRepeatSafe safeties = if RepeatSafetySafe `elem` safeties then RepeatSafetySafe else RepeatSafetyUnsafe++-- | Retry faulty results that may be sent again, running each attempt through+-- the breaker.+-- Fault descriptions are logged as they are, so they must already be scrubbed.+retryingWithCircuitBreaker ::+  forall m e a.+  (MonadLogger m, MonadIO m) =>+  Maybe CircuitBreakerEnv ->+  Maybe FailureBudgetEnv ->+  RetryPolicyM m ->+  (Either e a -> Maybe String) ->+  (Either e a -> RepeatSafety) ->+  (RetryStatus -> m (Either e a)) ->+  m (Either (CircuitBreakerError e) a)+retryingWithCircuitBreaker mBreaker mBudget policy describeFault mayRepeat act =+  let classify :: Either e a -> Outcome+      classify res = case describeFault res of+        Nothing -> OutcomeCircuitShouldStayClosed+        Just _ -> OutcomeCircuitShouldOpen+      loggedAct :: RetryStatus -> m (Either e a)+      loggedAct retryStatus = do+        res <- act retryStatus+        forM_ (describeFault res) $ \fault -> do+          forM_ mBudget recordFailureNow+          logWarn $+            Text.pack $+              unwords $+                concat+                  [ ["Request attempt", show @Int (succ (rsIterNumber retryStatus))],+                    case mBreaker of+                      Nothing -> []+                      Just breaker -> ["to", show @Text (circuitBreakerName breaker)],+                    ["failed:", fault]+                  ]+        pure res+      attempt :: RetryStatus -> m (Either (CircuitBreakerError e) a)+      attempt retryStatus = case mBreaker of+        Nothing -> left CircuitBreakerErrorUnderlying <$> loggedAct retryStatus+        Just breaker -> guardCircuitBreaker breaker classify (loggedAct retryStatus)+      retryable :: Either e a -> Bool+      retryable res =+        saysFaulty (classify res) && case mayRepeat res of+          RepeatSafetySafe -> True+          RepeatSafetyUnsafe -> False+      again :: Either (CircuitBreakerError e) a -> Bool+      again = \case+        Left CircuitBreakerErrorOpen -> False+        Left (CircuitBreakerErrorUnderlying e) -> retryable (Left e)+        Right a -> retryable (Right a)+   in retrying (maybe policy ((policy <>) . breakerPolicy) mBreaker) (\_ res -> pure (again res)) attempt+-- Equivalent: a rejected attempt leaves the breaker not closed, so+-- 'breakerPolicy' stops the retry whatever the predicate says.+{-# ANN retryingWithCircuitBreaker ("DisableMutation: BoolLit" :: String) #-}++-- | How many requests one call may make, including the first; at least 1.+newtype Attempts = Attempts+  { -- | The number of requests.+    unAttempts :: Word+  }+  deriving (Show, Eq, Generic)++instance Validity Attempts where+  validate = validateAttempts++-- Equivalent: genericValidate of a Word is always valid.+validateAttempts :: Attempts -> Validation+validateAttempts attempts@(Attempts n) =+  mconcat+    [ genericValidate attempts,+      declare "a call makes at least one request" $ n >= 1+    ]+{-# ANN validateAttempts ("DisableMutation: ListLit" :: String) #-}++-- | Fewer than a default breaker's threshold, so one call cannot open it.+defaultAttempts :: Attempts+defaultAttempts = Attempts 4++-- | A retry policy that makes exactly this many requests.+limitAttempts :: (Monad m) => Attempts -> RetryPolicyM m+-- Subtracted in 'Int' so that zero cannot wrap the 'Word' into a huge budget.+limitAttempts (Attempts n) = limitRetries (wordToIntSaturating n - 1)++-- | Retry only while the breaker still takes traffic.+-- Reading the breaker makes its threshold a budget shared between calls.+breakerPolicy :: (MonadIO m) => CircuitBreakerEnv -> RetryPolicyM m+breakerPolicy breaker = RetryPolicyM $ \_ -> do+  circuitState <- readCircuitBreakerState breaker+  pure $ if takingTraffic circuitState then Just 0 else Nothing++-- | A policy in 'IO', usable in any 'MonadIO'.+liftRetryPolicy :: (MonadIO m) => RetryPolicyM IO -> RetryPolicyM m+liftRetryPolicy policy = RetryPolicyM (liftIO . getRetryPolicyM policy)++-- | Whether a breaker in this state would admit another attempt.+takingTraffic :: CircuitState -> Bool+takingTraffic = \case+  CircuitStateClosed _ -> True+  -- Retrying would replace the dependency's own error with a rejection.+  CircuitStateOpen _ -> False+  CircuitStateHalfOpen _ -> False++-- | Whether a classified result says the dependency is faulty.+saysFaulty :: Outcome -> Bool+saysFaulty = \case+  OutcomeCircuitShouldOpen -> True+  OutcomeCircuitShouldStayClosed -> False
+ src/Network/HTTP/Env/FailureBudget.hs view
@@ -0,0 +1,181 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE NumericUnderscores #-}++-- | How many failed requests a dependency may have within a window before it+-- is reported as unwell.+-- It only reports; it never stops a request.+module Network.HTTP.Env.FailureBudget+  ( -- * Settings+    FailureBudgetSettings (..),+    defaultFailureBudgetSettings,++    -- * The budget (pure)+    FailureBudget (..),+    emptyFailureBudget,+    recordFailure,+    failuresWithin,+    FailureBudgetStatus (..),+    FailureBudgetReport (..),+    failureBudgetReport,++    -- * Running+    FailureBudgetEnv,+    newFailureBudget,+    recordFailureNow,+    peekFailureBudget,+  )+where++import Data.Sequence (Seq)+import qualified Data.Sequence as Seq+import Data.Time (NominalDiffTime)+import Data.Validity+import Data.Validity.Containers ()+import Data.Validity.Time ()+import Data.Word (Word64)+import GHC.Clock (getMonotonicTimeNSec)+import GHC.Generics (Generic)+import Network.HTTP.Env.Numeric (intToWord, nominalDiffTimeToNanos, wordToInt)+import UnliftIO++-- | How many failures a budget allows, and over how long.+data FailureBudgetSettings = FailureBudgetSettings+  { -- | Failed requests within the window that exhaust the budget; at least 1.+    failureBudgetSettingsFailures :: !Word,+    -- | How long a failed request counts against the budget; positive.+    failureBudgetSettingsWindow :: !NominalDiffTime+  }+  deriving (Show, Eq, Generic)++instance Validity FailureBudgetSettings where+  validate = validateFailureBudgetSettings++-- Equivalent: genericValidate of a count and a duration is always valid.+-- Matched positionally so that a new field fails to compile here.+validateFailureBudgetSettings :: FailureBudgetSettings -> Validation+validateFailureBudgetSettings settings@(FailureBudgetSettings failures window) =+  mconcat+    [ genericValidate settings,+      declare "the budget allows at least one failure" $ failures >= 1,+      declare "the window is positive" $ window > 0+    ]+{-# ANN validateFailureBudgetSettings ("DisableMutation: ListLit" :: String) #-}++-- | Ten failures an hour.+defaultFailureBudgetSettings :: FailureBudgetSettings+defaultFailureBudgetSettings =+  FailureBudgetSettings+    { failureBudgetSettingsFailures = 10,+      failureBudgetSettingsWindow = 3_600+    }++-- | A budget and the newest failures recorded in it.+-- It keeps no more failures than it allows: older ones cannot change whether+-- it is exhausted.+data FailureBudget = FailureBudget+  { failureBudgetLimit :: !Word,+    -- | Monotonic-clock nanoseconds.+    failureBudgetWindowNanos :: !Word64,+    -- | Monotonic-clock nanoseconds, newest recorded first.+    -- Not necessarily sorted: two recorders can read the clock in one order+    -- and record in the other.+    failureBudgetFailures :: !(Seq Word64)+  }+  deriving (Show, Eq, Generic)++instance Validity FailureBudget where+  validate = validateFailureBudget++-- Equivalent: genericValidate of these fields is always valid.+validateFailureBudget :: FailureBudget -> Validation+validateFailureBudget budget@(FailureBudget limit _ failures) =+  mconcat+    [ genericValidate budget,+      declare "the budget allows at least one failure" $ limit >= 1,+      declare "the budget allows no more failures than a sequence can count" $+        limit <= intToWord maxBound,+      declare "the budget keeps no more failures than it allows" $+        intToWord (Seq.length failures) <= limit+    ]+{-# ANN validateFailureBudget ("DisableMutation: ListLit" :: String) #-}++-- | A budget with no failure in it.+emptyFailureBudget :: FailureBudgetSettings -> FailureBudget+emptyFailureBudget settings =+  FailureBudget+    { failureBudgetLimit = failureBudgetSettingsFailures settings,+      failureBudgetWindowNanos =+        nominalDiffTimeToNanos (failureBudgetSettingsWindow settings),+      failureBudgetFailures = Seq.empty+    }++-- | Record a failure at the given time, forgetting any beyond the limit.+recordFailure :: Word64 -> FailureBudget -> FailureBudget+recordFailure !now budget =+  budget+    { failureBudgetFailures =+        Seq.take (wordToInt (failureBudgetLimit budget)) (now Seq.<| failureBudgetFailures budget)+    }++-- | How many kept failures fall within the window at the given time.+failuresWithin :: Word64 -> FailureBudget -> Word+failuresWithin now budget =+  intToWord (Seq.length (Seq.filter (isWithin budget now) (failureBudgetFailures budget)))++-- | Whether a failure at the given stamp is within the window at this time.+-- A stamp later than the time counts: a recorder can read the clock after a+-- reader did.+-- Compared as integers, so that nothing wraps or overflows.+isWithin :: FailureBudget -> Word64 -> Word64 -> Bool+isWithin budget now failedAt = toInteger now - toInteger failedAt < toInteger (failureBudgetWindowNanos budget)++-- | Whether a budget has room for more failures.+data FailureBudgetStatus+  = FailureBudgetStatusWithin+  | FailureBudgetStatusExhausted+  deriving (Show, Eq, Generic)++instance Validity FailureBudgetStatus++-- | What a budget has to say about its dependency.+data FailureBudgetReport = FailureBudgetReport+  { -- | Failed requests within the window, at most the budget's limit.+    failureBudgetReportFailures :: !Word,+    -- | Whether those exhaust the budget.+    failureBudgetReportStatus :: !FailureBudgetStatus+  }+  deriving (Show, Eq, Generic)++instance Validity FailureBudgetReport++-- | What to report about a budget at the given time.+failureBudgetReport :: Word64 -> FailureBudget -> FailureBudgetReport+failureBudgetReport now budget =+  let failures = failuresWithin now budget+   in FailureBudgetReport+        { failureBudgetReportFailures = failures,+          failureBudgetReportStatus =+            if failures >= failureBudgetLimit budget+              then FailureBudgetStatusExhausted+              else FailureBudgetStatusWithin+        }++-- | A live failure budget.+newtype FailureBudgetEnv = FailureBudgetEnv {unFailureBudgetEnv :: TVar FailureBudget}++-- | A budget with no failure recorded yet.+newFailureBudget :: (MonadIO m) => FailureBudgetSettings -> m FailureBudgetEnv+newFailureBudget settings = FailureBudgetEnv <$> newTVarIO (emptyFailureBudget settings)++-- | Record a failure now.+recordFailureNow :: (MonadIO m) => FailureBudgetEnv -> m ()+recordFailureNow env = do+  now <- liftIO getMonotonicTimeNSec+  atomically $ modifyTVar' (unFailureBudgetEnv env) (recordFailure now)++-- | What the budget has to say now.+peekFailureBudget :: (MonadIO m) => FailureBudgetEnv -> m FailureBudgetReport+peekFailureBudget env = do+  now <- liftIO getMonotonicTimeNSec+  failureBudgetReport now <$> readTVarIO (unFailureBudgetEnv env)
+ src/Network/HTTP/Env/HttpClient.hs view
@@ -0,0 +1,149 @@+{-# LANGUAGE LambdaCase #-}++-- | The manager and the layers every outgoing HTTP call goes through.+module Network.HTTP.Env.HttpClient+  ( HttpEnv (..),+    httpEnvResetTimeout,+    withRequestLimiter,+    httpCall,+    httpCallWith,+    unlessRejecting,+    HttpEnvError (..),+    httpEnvError,+    httpEnvErrorCircuitBreakerError,+    HttpEnvReport (..),+    peekHttpEnv,+  )+where++import Control.Monad (forM_)+import Control.Monad.IO.Class+import Control.Monad.Logger.CallStack+import Control.Retry (RetryPolicyM)+import qualified Data.ByteString.Lazy as LB+import Data.Time (NominalDiffTime, UTCTime, getCurrentTime)+import Network.HTTP.Client (HttpException, Manager, Request, Response)+import Network.HTTP.Env.CircuitBreaker+import Network.HTTP.Env.CircuitBreaker.Retry (liftRetryPolicy)+import Network.HTTP.Env.FailureBudget (FailureBudgetEnv, FailureBudgetReport, peekFailureBudget)+import Network.HTTP.Env.HttpClient.Retry (Repeatable (..), httpLbsWithRetry, responseAsHttpException)+import Network.HTTP.Env.LogPolicy (LogPolicy)+import Network.HTTP.Env.Pacing (RequestLimiter, waitForRequest)+import Network.HTTP.Env.RateLimit (RateLimitHeaders, httpExceptionRateLimitWait, responseRateLimitWait)+import UnliftIO++-- | The manager and the layers that every HTTP call goes through.+data HttpEnv = HttpEnv+  { httpEnvManager :: !Manager,+    httpEnvRetryPolicy :: !(RetryPolicyM IO),+    httpEnvCircuitBreaker :: !(Maybe CircuitBreakerEnv),+    httpEnvFailureBudget :: !(Maybe FailureBudgetEnv),+    httpEnvRequestLimiter :: !(Maybe RequestLimiter),+    httpEnvLogPolicy :: !LogPolicy,+    -- | How the dependency says a quota is spent, if it does.+    httpEnvRateLimitHeaders :: !(Maybe RateLimitHeaders)+  }++-- | The env, pacing every call through the given limiter.+withRequestLimiter :: RequestLimiter -> HttpEnv -> HttpEnv+withRequestLimiter limiter env = env {httpEnvRequestLimiter = Just limiter}++-- | The reset timeout of this env's breaker, if it has one.+httpEnvResetTimeout :: HttpEnv -> Maybe NominalDiffTime+httpEnvResetTimeout = fmap circuitBreakerResetTimeout . httpEnvCircuitBreaker++-- | Perform an HTTP request through the env's layers and read the whole body.+-- A request is sent again only if its method is idempotent, it carries an+-- idempotency key, or it never left.+httpCall ::+  (MonadLogger m, MonadUnliftIO m) =>+  HttpEnv ->+  Request ->+  m (Either (HttpEnvError HttpException) (Response LB.ByteString))+httpCall = httpCallWith RepeatableIfIdempotent++-- | 'httpCall', saying whether the request may be sent again after a fault.+-- A spent quota is told apart whether the request throws on a refusal, as+-- with 'Network.HTTP.Client.parseUrlThrow', or not.+-- The request limiter is debited once per call, not per attempt.+httpCallWith ::+  (MonadLogger m, MonadUnliftIO m) =>+  Repeatable ->+  HttpEnv ->+  Request ->+  m (Either (HttpEnvError HttpException) (Response LB.ByteString))+httpCallWith repeatable env request = unlessRejecting (httpEnvCircuitBreaker env) $ do+  forM_ (httpEnvRequestLimiter env) waitForRequest+  let policy = liftRetryPolicy (httpEnvRetryPolicy env)+  result <- httpLbsWithRetry (httpEnvLogPolicy env) (httpEnvCircuitBreaker env) (httpEnvFailureBudget env) policy repeatable request (httpEnvManager env)+  now <- liftIO getCurrentTime+  pure $ case result of+    Left err -> Left (httpEnvError (fmap httpExceptionRateLimitWait (httpEnvRateLimitHeaders env)) now err)+    Right response ->+      case httpEnvRateLimitHeaders env >>= \convention -> responseRateLimitWait convention now response of+        Just quotaWait -> Left (HttpEnvErrorRateLimited quotaWait (responseAsHttpException (httpEnvLogPolicy env) request response))+        Nothing -> Right response++-- | Answer at once while the breaker rejects, rather than wait on a limiter+-- for a call it would reject.+unlessRejecting ::+  (MonadIO m) =>+  Maybe CircuitBreakerEnv ->+  m (Either (HttpEnvError e) a) ->+  m (Either (HttpEnvError e) a)+unlessRejecting mBreaker call = do+  circuit <- traverse peekCircuitBreaker mBreaker+  case circuit of+    Just CircuitReportRejecting -> pure (Left HttpEnvErrorCircuitOpen)+    Just CircuitReportProbing -> call+    Just CircuitReportClosed -> call+    Nothing -> call++-- | How a call through an env failed.+data HttpEnvError e+  = -- | The breaker is open, so nothing was sent.+    HttpEnvErrorCircuitOpen+  | -- | The dependency said a quota is spent; try again after the wait.+    -- It counts as an answer, so it resets the breaker's count of+    -- consecutive failures and closes a probing breaker.+    HttpEnvErrorRateLimited !NominalDiffTime !e+  | -- | Any other failure, with the dependency's own error.+    HttpEnvErrorFailed !e+  deriving (Show, Eq)++-- | Forget whether a failure was a spent quota, for a caller that treats a+-- spent quota like any other failure.+httpEnvErrorCircuitBreakerError :: HttpEnvError e -> CircuitBreakerError e+httpEnvErrorCircuitBreakerError = \case+  HttpEnvErrorCircuitOpen -> CircuitBreakerErrorOpen+  HttpEnvErrorRateLimited _ e -> CircuitBreakerErrorUnderlying e+  HttpEnvErrorFailed e -> CircuitBreakerErrorUnderlying e++-- | Tell a spent quota apart from any other failure, given how to read one.+httpEnvError :: Maybe (UTCTime -> e -> Maybe NominalDiffTime) -> UTCTime -> CircuitBreakerError e -> HttpEnvError e+httpEnvError mRateLimitWait now = \case+  CircuitBreakerErrorOpen -> HttpEnvErrorCircuitOpen+  CircuitBreakerErrorUnderlying e ->+    case mRateLimitWait >>= \rateLimitWait -> rateLimitWait now e of+      Just quotaWait -> HttpEnvErrorRateLimited quotaWait e+      Nothing -> HttpEnvErrorFailed e++-- | What an env's breaker and failure budget say, 'Nothing' for an absent one.+data HttpEnvReport = HttpEnvReport+  { -- | What the breaker is doing.+    httpEnvReportCircuit :: !(Maybe CircuitReport),+    -- | How much of the failure budget is spent.+    httpEnvReportFailureBudget :: !(Maybe FailureBudgetReport)+  }+  deriving (Show, Eq)++-- | What the env has to say right now, without counting as a call.+peekHttpEnv :: (MonadIO m) => HttpEnv -> m HttpEnvReport+peekHttpEnv env = do+  circuit <- traverse peekCircuitBreaker (httpEnvCircuitBreaker env)+  budget <- traverse peekFailureBudget (httpEnvFailureBudget env)+  pure+    HttpEnvReport+      { httpEnvReportCircuit = circuit,+        httpEnvReportFailureBudget = budget+      }
+ src/Network/HTTP/Env/HttpClient/Retry.hs view
@@ -0,0 +1,203 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE TypeApplications #-}++-- | Retrying HTTP requests, and where an 'HttpException' becomes a value.+--+-- [tag:NoUnscrubbedHttpException] Every 'HttpException' handed out of this+-- module has been through 'scrubHttpException', because showing one prints its+-- request's headers and http-client redacts only @Authorization@.+-- A new path out of this module must scrub too.+module Network.HTTP.Env.HttpClient.Retry+  ( httpLbsWithRetry,+    Repeatable (..),+    RepeatSafety (..),+    httpRepeatSafety,+    requestRepeatSafety,+    exceptionRepeatSafety,+    methodRepeatSafety,+    headersRepeatSafety,+    responseAsHttpException,+    catchAsHttpException,+    catchConnectionException,+    shouldRetryStatusCode,+    describeHttpFault,+    shouldRetryHttpResponse,+    shouldRetryHttpException,+  )+where++import Control.Monad+import Control.Monad.IO.Class+import Control.Monad.Logger.CallStack+import Control.Retry+import Data.Bifunctor (first)+import Data.ByteString (ByteString)+import qualified Data.ByteString.Lazy as LB+import qualified Data.Text as Text+import Network.HTTP.Client as HTTP+import Network.HTTP.Client.Internal as HTTP+import Network.HTTP.Env.CircuitBreaker+import Network.HTTP.Env.CircuitBreaker.Retry (RepeatSafety (..), anyRepeatSafe, retryingWithCircuitBreaker)+import Network.HTTP.Env.FailureBudget (FailureBudgetEnv)+import Network.HTTP.Env.LogPolicy (LogPolicy, hIdempotencyKey, renderHttpExceptionForLogging, renderResponseForLogging, scrubHttpException, scrubUriForLogging)+import Network.HTTP.Types as HTTP+import Network.URI (URI)+import UnliftIO++-- | Whether a call may be sent again after a fault.+data Repeatable+  = -- | Only when its method is idempotent, it carries an idempotency key, or+    -- it was never sent.+    RepeatableIfIdempotent+  | -- | Whatever its method, such as when the server deduplicates it.+    RepeatableAlways++-- | Whether a call may be sent again after this result.+httpRepeatSafety :: Repeatable -> Request -> Either HttpException a -> RepeatSafety+httpRepeatSafety repeatable request res = case repeatable of+  RepeatableAlways -> RepeatSafetySafe+  RepeatableIfIdempotent ->+    anyRepeatSafe+      [ requestRepeatSafety (method request) (requestHeaders request),+        case res of+          Left exception -> exceptionRepeatSafety exception+          Right _ -> RepeatSafetyUnsafe+      ]++-- | 'RepeatSafetySafe' for a request with an idempotent method or an idempotency key.+requestRepeatSafety :: Method -> [Header] -> RepeatSafety+requestRepeatSafety requestMethod headers =+  anyRepeatSafe [methodRepeatSafety requestMethod, headersRepeatSafety headers]++-- | 'RepeatSafetySafe' for a connection that never opened, so the request never left.+exceptionRepeatSafety :: HttpException -> RepeatSafety+exceptionRepeatSafety = \case+  InvalidUrlException _ _ -> RepeatSafetyUnsafe+  HttpExceptionRequest _ content -> case content of+    ConnectionFailure _ -> RepeatSafetySafe+    ConnectionTimeout -> RepeatSafetySafe+    ProxyConnectException _ _ _ -> RepeatSafetySafe+    _ -> RepeatSafetyUnsafe++-- | 'RepeatSafetySafe' for the methods RFC 9110 calls idempotent.+methodRepeatSafety :: Method -> RepeatSafety+methodRepeatSafety m =+  if m `elem` [methodGet, methodHead, methodOptions, methodTrace, methodPut, methodDelete]+    then RepeatSafetySafe+    else RepeatSafetyUnsafe++-- | 'RepeatSafetySafe' for headers with an 'hIdempotencyKey', which asks the server+-- to answer a resend as it answered the first.+headersRepeatSafety :: [Header] -> RepeatSafety+headersRepeatSafety headers =+  if any ((== hIdempotencyKey) . fst) headers then RepeatSafetySafe else RepeatSafetyUnsafe++-- | Perform an HTTP request, running each attempt through the breaker.+httpLbsWithRetry ::+  (MonadLogger m, MonadUnliftIO m) =>+  LogPolicy ->+  Maybe CircuitBreakerEnv ->+  Maybe FailureBudgetEnv ->+  RetryPolicyM m ->+  Repeatable ->+  HTTP.Request ->+  HTTP.Manager ->+  m (Either (CircuitBreakerError HttpException) (HTTP.Response LB.ByteString))+httpLbsWithRetry logPolicy mBreaker mBudget policy repeatable request man =+  retryingWithCircuitBreaker mBreaker mBudget policy (describeHttpFault logPolicy) (httpRepeatSafety repeatable request) $ \_ ->+    catchAsHttpException logPolicy request (tryHttpOnce logPolicy request man)++-- | Fold what an HTTP request can throw into a scrubbed 'HttpException'.+-- An 'Control.Exception.ErrorCall' propagates: it is a bug, not evidence that the server is down.+-- [ref:NoUnscrubbedHttpException]+catchAsHttpException :: (MonadUnliftIO m) => LogPolicy -> Request -> m a -> m (Either HttpException a)+catchAsHttpException logPolicy request action =+  fmap (first (scrubHttpException logPolicy)) $+    (Right <$> action)+      `catches` [ Handler $ \e ->+                    pure+                      ( Left+                          ( HttpExceptionRequest+                              request+                              (InternalException (SomeException (e :: IOError)))+                          )+                      ),+                  Handler $ \e -> pure (Left (toHttpException request e)),+                  Handler $ \e -> pure (Left (e :: HttpException))+                ]++-- | The scrubbed exception 'Network.HTTP.Client.parseUrlThrow' would have+-- thrown for this response.+-- [ref:NoUnscrubbedHttpException]+responseAsHttpException :: LogPolicy -> Request -> Response LB.ByteString -> HttpException+responseAsHttpException logPolicy request response =+  scrubHttpException logPolicy $+    HttpExceptionRequest request $+      StatusCodeException (void response) (LB.toStrict (LB.take 1024 (responseBody response)))++-- | Catch a scrubbed 'HttpException' or an 'IOException', and nothing else.+-- [ref:NoUnscrubbedHttpException]+catchConnectionException :: (MonadUnliftIO m) => LogPolicy -> m a -> m (Either SomeException a)+catchConnectionException logPolicy action =+  (Right <$> action)+    `catches` [ Handler $ \e -> pure (Left (toException (scrubHttpException logPolicy (e :: HttpException)))),+                Handler $ \e -> pure (Left (toException (e :: IOException)))+              ]++tryHttpOnce ::+  (MonadLogger m, MonadIO m) =>+  LogPolicy ->+  HTTP.Request ->+  HTTP.Manager ->+  m (HTTP.Response LB.ByteString)+tryHttpOnce logPolicy request man = do+  -- Never the raw 'getUri': OAuth2 token endpoints take secrets in the query.+  let loggedUri = scrubUriForLogging logPolicy (getUri request)+  logInfo $ Text.pack $ unwords [concat [show @ByteString (method request), "-ing"], show @URI loggedUri]+  response <- liftIO $ httpLbs request man+  let c = HTTP.statusCode (responseStatus response)+  when (c >= 400 && not (shouldRetryHttpResponse response)) $+    logWarn $+      Text.pack $+        unwords [show @Int c, "status code while fetching", show @URI loggedUri]+  pure response++-- | Describe a connection failure or a 5xx; a 2xx or 4xx is no fault.+describeHttpFault :: LogPolicy -> Either HttpException (Response LB.ByteString) -> Maybe String+describeHttpFault logPolicy = \case+  Left exception+    | shouldRetryHttpException exception -> Just (renderHttpExceptionForLogging logPolicy exception)+    | otherwise -> Nothing+  Right response+    | shouldRetryHttpResponse response -> Just (renderResponseForLogging logPolicy response)+    | otherwise -> Nothing++-- | A response with a 5xx.+shouldRetryHttpResponse :: Response LB.ByteString -> Bool+shouldRetryHttpResponse response =+  shouldRetryStatusCode $ responseStatus response++-- | A 5xx.+shouldRetryStatusCode :: Status -> Bool+shouldRetryStatusCode status =+  let c = HTTP.statusCode status+   in c >= 500 && c < 600++-- | A connection failure, a timeout, or a 5xx.+shouldRetryHttpException :: HttpException -> Bool+shouldRetryHttpException = \case+  InvalidUrlException _ _ -> False+  HttpExceptionRequest _ exceptionContent -> case exceptionContent of+    StatusCodeException response _ -> shouldRetryStatusCode (responseStatus response)+    ResponseTimeout -> True+    ConnectionTimeout -> True+    ConnectionFailure _ -> True+    InternalException _ -> True+    ProxyConnectException _ _ _ -> True+    NoResponseDataReceived -> True+    ResponseBodyTooShort _ _ -> True+    InvalidChunkHeaders -> True+    IncompleteHeaders -> True+    HttpZlibException _ -> True+    ConnectionClosed -> True+    _ -> False
+ src/Network/HTTP/Env/LogPolicy.hs view
@@ -0,0 +1,337 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeApplications #-}++-- | What may be written to a log about an HTTP request.+-- Opt-in: an unvouched header is dropped, an unvouched query parameter redacted.+module Network.HTTP.Env.LogPolicy+  ( LogPolicy (..),+    defaultLogPolicy,+    defaultHeadersToRedact,+    defaultHeadersToLog,+    quotaHeaders,+    hIdempotencyKey,+    defaultParamsToRedact,+    defaultParamsToLog,+    HeaderLogPolicy (..),+    headerLogPolicy,+    scrubHeadersForLogging,+    scrubHttpException,+    scrubHttpResponse,+    redactedHeaderValue,+    redactedParamValue,+    QueryParamLogPolicy (..),+    queryParamLogPolicy,+    scrubQueryForLogging,+    scrubUriForLogging,+    renderHttpExceptionForLogging,+    renderResponseForLogging,+    loggedResponseBodyBytes,+    renderBodyForLogging,+    withheldResponseBody,+  )+where++import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as LB+import Data.Int (Int64)+import Data.Set (Set)+import qualified Data.Set as Set+import qualified Data.Text as Text+import qualified Data.Text.Encoding as TE+import qualified Network.HTTP.Client as HTTP+import qualified Network.HTTP.Client.Internal as HTTP (Response (responseOriginalRequest))+import Network.HTTP.Env.Numeric (int64ToInt)+import Network.HTTP.Types (Query, parseQuery, renderQuery)+import Network.HTTP.Types.Header+import Network.URI (URI (..))+import Text.Show.Pretty (ppShow)++-- | The names a log may show, and the names it must redact.+-- The redaction sets win over the logging sets.+data LogPolicy = LogPolicy+  { -- | Headers logged with 'redactedHeaderValue'.+    logPolicyHeadersToRedact :: !(Set HeaderName),+    -- | Headers logged as they are.+    logPolicyHeadersToLog :: !(Set HeaderName),+    -- | Query parameters known to carry a credential, even if vouched for.+    logPolicyParamsToRedact :: !(Set ByteString),+    -- | Query parameters logged with their values.+    logPolicyParamsToLog :: !(Set ByteString)+  }++-- | The standard names only.+defaultLogPolicy :: LogPolicy+defaultLogPolicy =+  LogPolicy+    { logPolicyHeadersToRedact = defaultHeadersToRedact,+      logPolicyHeadersToLog = defaultHeadersToLog,+      logPolicyParamsToRedact = defaultParamsToRedact,+      logPolicyParamsToLog = defaultParamsToLog+    }++-- | The standard headers that carry credentials.+defaultHeadersToRedact :: Set HeaderName+defaultHeadersToRedact =+  Set.fromList+    [ hAuthorization,+      hCookie,+      hSetCookie,+      hProxyAuthorization+    ]++-- | The standard headers that carry no credential.+defaultHeadersToLog :: Set HeaderName+defaultHeadersToLog =+  Set.fromList+    [ hAccept,+      hAcceptCharset,+      hAcceptEncoding,+      hAcceptLanguage,+      hAcceptRanges,+      hAge,+      hAllow,+      hCacheControl,+      hConnection,+      hContentEncoding,+      hContentLanguage,+      hContentLength,+      hContentLocation,+      hContentMD5,+      hContentRange,+      hContentType,+      hDate,+      hETag,+      hExpect,+      hExpires,+      hFrom,+      hHost,+      hIfMatch,+      hIfModifiedSince,+      hIfNoneMatch,+      hIfRange,+      hIfUnmodifiedSince,+      hLastModified,+      hLocation,+      hMaxForwards,+      hPragma,+      hProxyAuthenticate,+      hRange,+      hReferer,+      hRetryAfter,+      hServer,+      hTE,+      hTrailer,+      hTransferEncoding,+      hUpgrade,+      hUserAgent,+      hVary,+      hVia,+      hWWWAuthenticate,+      hWarning,+      hContentDisposition,+      hMIMEVersion,+      hOrigin,+      hPrefer,+      hPreferenceApplied,+      "X-Request-ID",+      "X-Real-IP",+      "X-Forwarded-For",+      "X-Forwarded-Proto",+      "X-Forwarded-Host",+      "X-Forwarded-Server"+    ]++-- | The headers 'Network.HTTP.Env.RateLimit' reads a spent quota from.+-- Every policy logs them, because a spent quota is read from a scrubbed+-- failure.+quotaHeaders :: Set HeaderName+quotaHeaders =+  Set.fromList+    [ hRetryAfter,+      "X-RateLimit-Limit",+      "X-RateLimit-Remaining",+      "X-RateLimit-Reset",+      "X-RateLimit-Resource",+      "X-RateLimit-Used",+      "RateLimit",+      "RateLimit-Limit",+      "RateLimit-Policy",+      "RateLimit-Remaining",+      "RateLimit-Reset"+    ]++-- | The OAuth2 query parameters that carry a credential (RFC 6749).+defaultParamsToRedact :: Set ByteString+defaultParamsToRedact =+  Set.fromList+    [ "client_secret",+      "refresh_token",+      "access_token",+      "code",+      "state"+    ]++-- | The OAuth2 query parameters that carry no credential (RFC 6749 and 9207).+defaultParamsToLog :: Set ByteString+defaultParamsToLog =+  Set.fromList+    [ "client_id",+      "grant_type",+      "response_type",+      "redirect_uri",+      "scope",+      "iss"+    ]++-- | The header that asks a server to answer a resend as it answered the first.+-- Every policy logs it, because whether a call may be sent again is read from+-- a scrubbed failure.+hIdempotencyKey :: HeaderName+hIdempotencyKey = "Idempotency-Key"++-- | What to do with one header before it reaches a log sink.+data HeaderLogPolicy+  = HeaderLogPolicyLogValue+  | HeaderLogPolicyRedactValue+  | HeaderLogPolicyDrop+  deriving (Show, Eq)++-- | Whether a policy redacts, logs or drops a header.+headerLogPolicy :: LogPolicy -> HeaderName -> HeaderLogPolicy+headerLogPolicy policy name+  | name `Set.member` logPolicyHeadersToRedact policy = HeaderLogPolicyRedactValue+  | name `Set.member` logPolicyHeadersToLog policy = HeaderLogPolicyLogValue+  | name `Set.member` quotaHeaders = HeaderLogPolicyLogValue+  | name == hIdempotencyKey = HeaderLogPolicyLogValue+  | otherwise = HeaderLogPolicyDrop++-- | Apply 'headerLogPolicy' to a whole header list.+scrubHeadersForLogging :: LogPolicy -> [Header] -> [Header]+scrubHeadersForLogging policy headers = do+  (name, value) <- headers+  case headerLogPolicy policy name of+    HeaderLogPolicyLogValue -> pure (name, value)+    HeaderLogPolicyRedactValue -> pure (name, redactedHeaderValue)+    HeaderLogPolicyDrop -> []++-- | What a redacted header's value is logged as.+redactedHeaderValue :: ByteString+redactedHeaderValue = "<REDACTED>"++-- | The stand-in for a redacted query parameter value.+-- Tildes because it goes through URL encoding, which would mangle @<@ and @>@.+redactedParamValue :: ByteString+redactedParamValue = "~REDACTED~"++-- | What to do with one query parameter before it reaches a log sink.+-- Never dropped, because the URI must still match the request it logs.+data QueryParamLogPolicy+  = QueryParamLogPolicyLogValue+  | QueryParamLogPolicyRedactValue+  deriving (Show, Eq)++-- | The deny list is consulted first.+queryParamLogPolicy :: LogPolicy -> ByteString -> QueryParamLogPolicy+queryParamLogPolicy policy name+  | name `Set.member` logPolicyParamsToRedact policy = QueryParamLogPolicyRedactValue+  | name `Set.member` logPolicyParamsToLog policy = QueryParamLogPolicyLogValue+  | otherwise = QueryParamLogPolicyRedactValue++-- | Apply 'queryParamLogPolicy' to a whole query string.+scrubQueryForLogging :: LogPolicy -> Query -> Query+scrubQueryForLogging policy query = do+  (name, mValue) <- query+  case queryParamLogPolicy policy name of+    QueryParamLogPolicyLogValue -> pure (name, mValue)+    QueryParamLogPolicyRedactValue -> pure (name, redactedParamValue <$ mValue)++-- | A URI with its query string put through 'queryParamLogPolicy'.+-- Render it with 'show', which redacts the userinfo that this leaves alone.+scrubUriForLogging :: LogPolicy -> URI -> URI+scrubUriForLogging policy uri =+  let query :: Query+      query = parseQuery (TE.encodeUtf8 (Text.pack (uriQuery uri)))+   in uri {uriQuery = Text.unpack (TE.decodeUtf8Lenient (renderQuery True (scrubQueryForLogging policy query)))}++-- | An 'HTTP.HttpException' with its request and response scrubbed.+-- http-client's own 'Show' redacts only @Authorization@ by default.+scrubHttpException :: LogPolicy -> HTTP.HttpException -> HTTP.HttpException+scrubHttpException policy = \case+  HTTP.HttpExceptionRequest request content ->+    HTTP.HttpExceptionRequest (scrubHttpRequest policy request) (scrubHttpExceptionContent policy content)+  e@(HTTP.InvalidUrlException _ _) -> e++-- | A request with its headers and query string put through the policy.+scrubHttpRequest :: LogPolicy -> HTTP.Request -> HTTP.Request+scrubHttpRequest policy request =+  let query :: Query+      query = parseQuery (HTTP.queryString request)+   in request+        { HTTP.requestHeaders = scrubHeadersForLogging policy (HTTP.requestHeaders request),+          HTTP.queryString = renderQuery True (scrubQueryForLogging policy query)+        }++-- | The responses an exception carries, put through the policy.+-- A catch-all because 'HTTP.HttpExceptionContent' is http-client's type.+scrubHttpExceptionContent :: LogPolicy -> HTTP.HttpExceptionContent -> HTTP.HttpExceptionContent+scrubHttpExceptionContent policy = \case+  HTTP.StatusCodeException response body ->+    HTTP.StatusCodeException (scrubHttpResponse policy response) body+  HTTP.TooManyRedirects responses ->+    HTTP.TooManyRedirects (map (scrubHttpResponse policy) responses)+  content -> content++-- | A response with its headers and the request it answered put through the+-- policy, because http-client's 'Show' prints that request, and with no cookie+-- jar, which holds the cookies its headers set.+-- The body is left alone.+scrubHttpResponse :: LogPolicy -> HTTP.Response body -> HTTP.Response body+scrubHttpResponse policy response =+  response+    { HTTP.responseHeaders = scrubHeadersForLogging policy (HTTP.responseHeaders response),+      HTTP.responseCookieJar = mempty,+      HTTP.responseOriginalRequest = scrubHttpRequest policy (HTTP.getOriginalRequest response)+    }++-- | An 'HTTP.HttpException' scrubbed and rendered for a log line, with the+-- response body cut to 'loggedResponseBodyBytes'.+renderHttpExceptionForLogging :: LogPolicy -> HTTP.HttpException -> String+renderHttpExceptionForLogging policy =+  ppShow @HTTP.HttpException . cutExceptionBody . scrubHttpException policy++-- | Cut the response body an exception carries to 'loggedResponseBodyBytes'.+-- A catch-all because 'HTTP.HttpExceptionContent' is http-client's type.+cutExceptionBody :: HTTP.HttpException -> HTTP.HttpException+cutExceptionBody = \case+  HTTP.HttpExceptionRequest request (HTTP.StatusCodeException response body) ->+    HTTP.HttpExceptionRequest+      request+      (HTTP.StatusCodeException response (ByteString.take loggedResponseBodyInt body))+  e -> e++-- | 'loggedResponseBodyBytes' as an 'Int'.+loggedResponseBodyInt :: Int+loggedResponseBodyInt = int64ToInt loggedResponseBodyBytes++-- | A response scrubbed and rendered for a log line, with its body cut to+-- 'loggedResponseBodyBytes'.+renderResponseForLogging :: LogPolicy -> HTTP.Response LB.ByteString -> String+renderResponseForLogging policy response =+  ppShow @(HTTP.Response LB.ByteString) $+    LB.take loggedResponseBodyBytes <$> scrubHttpResponse policy response++-- | A body cut to 'loggedResponseBodyBytes' and rendered.+renderBodyForLogging :: LB.ByteString -> String+renderBodyForLogging = show @LB.ByteString . LB.take loggedResponseBodyBytes++-- | How much of a response body a log line may carry.+-- The same as http-client keeps in a 'HTTP.StatusCodeException'.+loggedResponseBodyBytes :: Int64+loggedResponseBodyBytes = 1024++-- | Stands in for a response body that must not be logged at all.+-- A token endpoint's 200 starts with the credential, so cutting is not enough.+withheldResponseBody :: String+withheldResponseBody = "<WITHHELD: may contain a credential>"
+ src/Network/HTTP/Env/Manager.hs view
@@ -0,0 +1,31 @@+{-# LANGUAGE OverloadedStrings #-}++-- | Building blocks for the 'ManagerSettings' of a TLS manager.+module Network.HTTP.Env.Manager+  ( tlsManagerSettingsWithMaxHeaderLength,+    withUserAgent,+  )+where++import Data.ByteString (ByteString)+import Network.HTTP.Client (ManagerSettings (..), managerSetMaxHeaderLength, requestHeaders)+import Network.HTTP.Client.TLS (tlsManagerSettings)++-- | 'tlsManagerSettings', reading header fields of up to this many bytes.+tlsManagerSettingsWithMaxHeaderLength :: Int -> ManagerSettings+tlsManagerSettingsWithMaxHeaderLength maxHeaderLengthBytes =+  managerSetMaxHeaderLength maxHeaderLengthBytes tlsManagerSettings++-- | The given settings, replacing every request's User-Agent.+withUserAgent :: ByteString -> ManagerSettings -> ManagerSettings+withUserAgent userAgent settings =+  settings+    { managerModifyRequest = \request ->+        managerModifyRequest+          settings+          request+            { requestHeaders =+                ("User-Agent", userAgent)+                  : filter ((/= "User-Agent") . fst) (requestHeaders request)+            }+    }
+ src/Network/HTTP/Env/Metrics.hs view
@@ -0,0 +1,45 @@+{-# LANGUAGE LambdaCase #-}++-- | How the calls to a service's dependencies are going, for Prometheus.+module Network.HTTP.Env.Metrics+  ( httpEnvReportValue,+    httpEnvSample,+  )+where++import Network.HTTP.Env.CircuitBreaker (CircuitReport (..))+import Network.HTTP.Env.FailureBudget (FailureBudgetReport (..), FailureBudgetStatus (..))+import Network.HTTP.Env.HttpClient (HttpEnvReport (..))+import System.Metrics.Prometheus.Metric (MetricSample (..))+import System.Metrics.Prometheus.Metric.Gauge (GaugeSample (..))+import System.Metrics.Prometheus.MetricId (Labels, MetricId (MetricId), Name)++-- | The worse of what the breaker and the budget say, from 0 to 1 (healthy).+-- Probing ranks below an exhausted budget, because under probing every call but+-- the probe fails fast.+httpEnvReportValue :: HttpEnvReport -> Double+httpEnvReportValue report =+  foldr+    min+    1+    ( maybe [] (pure . circuitValue) (httpEnvReportCircuit report)+        ++ maybe [] (pure . budgetValue . failureBudgetReportStatus) (httpEnvReportFailureBudget report)+    )+  where+    circuitValue :: CircuitReport -> Double+    circuitValue = \case+      CircuitReportClosed -> 1+      CircuitReportProbing -> 0.5+      CircuitReportRejecting -> 0+    budgetValue :: FailureBudgetStatus -> Double+    budgetValue = \case+      FailureBudgetStatusWithin -> 1+      FailureBudgetStatusExhausted -> 0.75++-- | A gauge of a report, as 'httpEnvReportValue', under the given name and labels.+-- Give each env its own labels, or two envs collapse into one series.+httpEnvSample :: Name -> Labels -> HttpEnvReport -> (MetricId, MetricSample)+httpEnvSample metricName reportLabels report =+  ( MetricId metricName reportLabels,+    GaugeMetricSample (GaugeSample (httpEnvReportValue report))+  )
+ src/Network/HTTP/Env/Numeric.hs view
@@ -0,0 +1,77 @@+{-# LANGUAGE NumericUnderscores #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Monomorphic numeric conversions.+-- Assumes a 64-bit platform, where an 'Int' holds every 'Word' and 'Int64'.+module Network.HTTP.Env.Numeric+  ( wordToInt,+    wordToIntSaturating,+    integerToCount,+    intToWord,+    int64ToInt,+    intToNominalDiffTime,+    nanosToNominalDiffTime,+    nominalDiffTimeToNanos,+    nominalDiffTimeToMicros,+    rationalToNominalDiffTime,+    scientificToRational,+  )+where++import Data.Int (Int64)+import Data.Scientific (Scientific)+import Data.Time (NominalDiffTime)+import Data.Word (Word64)++-- | Assumes a 64-bit platform.+wordToInt :: Word -> Int+wordToInt = fromIntegral++-- | Held at the largest 'Int'.+wordToIntSaturating :: Word -> Int+wordToIntSaturating w = fromIntegral (min w (fromIntegral (maxBound :: Int)))++-- | A count no larger than an 'Int' can hold, so that it can be used as one.+integerToCount :: Integer -> Maybe Word+integerToCount n =+  if n >= 0 && n <= toInteger (maxBound :: Int)+    then Just (fromInteger n)+    else Nothing++-- | Wraps a negative 'Int'.+intToWord :: Int -> Word+intToWord = fromIntegral++-- | Assumes a 64-bit platform.+int64ToInt :: Int64 -> Int+int64ToInt = fromIntegral++-- | A whole number of seconds.+intToNominalDiffTime :: Int -> NominalDiffTime+intToNominalDiffTime = fromIntegral++-- | A whole number of nanoseconds, as a duration.+nanosToNominalDiffTime :: Word64 -> NominalDiffTime+nanosToNominalDiffTime nanos = fromIntegral nanos / 1_000_000_000++-- | Rounded to the nearest nanosecond, and held between zero and 'maxBound'.+nominalDiffTimeToNanos :: NominalDiffTime -> Word64+nominalDiffTimeToNanos = saturatingRound 1_000_000_000++-- | Rounded to the nearest microsecond, and held between zero and 'maxBound'.+nominalDiffTimeToMicros :: NominalDiffTime -> Int+nominalDiffTimeToMicros = saturatingRound 1_000_000++saturatingRound :: forall a. (Bounded a, Integral a) => Rational -> NominalDiffTime -> a+saturatingRound perSecond d =+  let rounded :: Integer+      rounded = round (toRational d * perSecond)+   in fromInteger (max 0 (min (toInteger (maxBound :: a)) rounded))++-- | Seconds, as a 'Rational'.+rationalToNominalDiffTime :: Rational -> NominalDiffTime+rationalToNominalDiffTime = fromRational++-- | Exactly.+scientificToRational :: Scientific -> Rational+scientificToRational = toRational
+ src/Network/HTTP/Env/OptParse.hs view
@@ -0,0 +1,489 @@+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE LambdaCase #-}++-- | Configuration for 'Network.HTTP.Env.HttpClient.HttpEnv'.+-- Overrides are applied after parsing, because opt-env-conf cannot use one+-- parsed value as another's default.+module Network.HTTP.Env.OptParse+  ( HttpEnvSettings (..),+    defaultHttpEnvSettings,+    BackoffSettings (..),+    defaultBackoffSettings,+    backoffPolicy,+    BackoffOverrides (..),+    HttpEnvOverrides (..),+    CircuitBreakerOverrides (..),+    FailureBudgetOverrides (..),+    noHttpEnvOverrides,+    applyHttpEnvOverrides,+    resolveHttpEnvSettings,+    httpEnvOverridesParser,+    fullHttpEnvOverrides,+    HttpEnvName (..),+    newHttpEnv,+  )+where++import Autodocodec (bimapCodec, codec)+import Control.Monad.IO.Class (MonadIO)+import Control.Monad.Logger.CallStack (MonadLoggerIO)+import Control.Retry (RetryPolicyM, capDelay, fullJitterBackoff, limitRetriesByCumulativeDelay)+import Data.Bifunctor (first)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Data.Time (NominalDiffTime)+import Data.Validity+import Data.Validity.Time ()+import GHC.Generics (Generic)+import Network.HTTP.Client (Manager)+import Network.HTTP.Env.CircuitBreaker+import Network.HTTP.Env.CircuitBreaker.Retry (Attempts (..), defaultAttempts, limitAttempts)+import Network.HTTP.Env.FailureBudget+import Network.HTTP.Env.HttpClient (HttpEnv (..))+import Network.HTTP.Env.LogPolicy (LogPolicy)+import Network.HTTP.Env.Numeric (integerToCount, nominalDiffTimeToMicros)+import Network.HTTP.Env.OptParse.Duration (Duration (..), parseDuration, renderDurationParseError)+import Network.HTTP.Env.RateLimit (RateLimitHeaders, parseRateLimitHeaders, renderRateLimitHeaders)+import OptEnvConf+import Text.Read (readMaybe)++-- | Everything about how one dependency is called that an operator may tune.+data HttpEnvSettings = HttpEnvSettings+  { -- | How many requests one call may make, retries included.+    httpEnvSettingsAttemptsPerRequest :: !Attempts,+    -- | How long to wait between the attempts of one call.+    httpEnvSettingsBackoff :: !BackoffSettings,+    -- | When to stop sending requests.+    httpEnvSettingsCircuitBreaker :: !CircuitBreakerSettings,+    -- | When to report the dependency as unwell.+    httpEnvSettingsFailureBudget :: !FailureBudgetSettings,+    -- | Off unless chosen, because which headers a dependency sends is its own.+    httpEnvSettingsRateLimitHeaders :: !(Maybe RateLimitHeaders)+  }+  deriving (Show, Eq, Generic)++instance Validity HttpEnvSettings++-- | What a dependency is called with when the application chooses nothing:+--+-- * 4 attempts per request, with 'defaultBackoffSettings' between them;+-- * a circuit breaker that opens after 5 consecutive failed requests and+--   probes after 30s;+-- * a failure budget of 10 failed requests an hour;+-- * no rate-limit headers.+defaultHttpEnvSettings :: HttpEnvSettings+defaultHttpEnvSettings =+  HttpEnvSettings+    { httpEnvSettingsAttemptsPerRequest = defaultAttempts,+      httpEnvSettingsBackoff = defaultBackoffSettings,+      httpEnvSettingsCircuitBreaker = defaultCircuitBreakerSettings,+      httpEnvSettingsFailureBudget = defaultFailureBudgetSettings,+      httpEnvSettingsRateLimitHeaders = Nothing+    }++-- | How long to wait between the attempts of one call.+data BackoffSettings = BackoffSettings+  { -- | A full-jitter wait: a random time between half and all of the base+    -- doubled once per attempt so far.+    backoffSettingsBase :: !NominalDiffTime,+    -- | The longest any one wait may be.+    backoffSettingsMaxDelay :: !NominalDiffTime,+    -- | The most one call may wait in all; no attempt is made past it.+    backoffSettingsMaxTotalDelay :: !NominalDiffTime+  }+  deriving (Show, Eq, Generic)++instance Validity BackoffSettings where+  validate = validateBackoffSettings++-- Equivalent: genericValidate of durations is always valid.+validateBackoffSettings :: BackoffSettings -> Validation+validateBackoffSettings backoff@(BackoffSettings base maxDelay maxTotalDelay) =+  mconcat+    [ genericValidate backoff,+      declare "the base of the backoff is positive" $ base > 0,+      declare "the longest wait is positive" $ maxDelay > 0,+      declare "the longest total wait is positive" $ maxTotalDelay > 0+    ]+{-# ANN validateBackoffSettings ("DisableMutation: ListLit" :: String) #-}++-- | Waits based on 1s, none longer than 30s and no more than 60s in all.+defaultBackoffSettings :: BackoffSettings+defaultBackoffSettings =+  BackoffSettings+    { backoffSettingsBase = 1,+      backoffSettingsMaxDelay = 30,+      backoffSettingsMaxTotalDelay = 60+    }++-- | The retry policy that waits as the backoff says, with no limit on+-- attempts of its own.+backoffPolicy :: (MonadIO m) => BackoffSettings -> RetryPolicyM m+backoffPolicy (BackoffSettings base maxDelay maxTotalDelay) =+  limitRetriesByCumulativeDelay+    (nominalDiffTimeToMicros maxTotalDelay)+    (capDelay (nominalDiffTimeToMicros maxDelay) (fullJitterBackoff (nominalDiffTimeToMicros base)))++-- | What an operator set of a t'HttpEnvSettings'; 'Nothing' leaves a field be.+data HttpEnvOverrides = HttpEnvOverrides+  { -- | @attempts-per-request@+    httpEnvOverridesAttemptsPerRequest :: !(Maybe Attempts),+    -- | @backoff.*@+    httpEnvOverridesBackoff :: !BackoffOverrides,+    -- | @circuit-breaker.*@+    httpEnvOverridesCircuitBreaker :: !CircuitBreakerOverrides,+    -- | @failure-budget.*@+    httpEnvOverridesFailureBudget :: !FailureBudgetOverrides,+    -- | @rate-limit-headers@; @Just Nothing@ turns it off.+    httpEnvOverridesRateLimitHeaders :: !(Maybe (Maybe RateLimitHeaders))+  }+  deriving (Show, Eq, Generic)++instance Validity HttpEnvOverrides++-- | What an operator set of a t'BackoffSettings'.+data BackoffOverrides = BackoffOverrides+  { -- | @base@+    backoffOverridesBase :: !(Maybe NominalDiffTime),+    -- | @max-delay@+    backoffOverridesMaxDelay :: !(Maybe NominalDiffTime),+    -- | @max-total-delay@+    backoffOverridesMaxTotalDelay :: !(Maybe NominalDiffTime)+  }+  deriving (Show, Eq, Generic)++instance Validity BackoffOverrides where+  validate = validateBackoffOverrides++-- Equivalent: genericValidate of durations is always valid.+validateBackoffOverrides :: BackoffOverrides -> Validation+validateBackoffOverrides overrides@(BackoffOverrides base maxDelay maxTotalDelay) =+  mconcat+    [ genericValidate overrides,+      declare "a backoff base it sets is positive" $ all (> 0) base,+      declare "a longest wait it sets is positive" $ all (> 0) maxDelay,+      declare "a longest total wait it sets is positive" $ all (> 0) maxTotalDelay+    ]+{-# ANN validateBackoffOverrides ("DisableMutation: ListLit" :: String) #-}++-- | What an operator set of a t'CircuitBreakerSettings'.+data CircuitBreakerOverrides = CircuitBreakerOverrides+  { -- | @failure-threshold@+    circuitBreakerOverridesFailureThreshold :: !(Maybe Word),+    -- | @reset-timeout@+    circuitBreakerOverridesResetTimeout :: !(Maybe NominalDiffTime)+  }+  deriving (Show, Eq, Generic)++instance Validity CircuitBreakerOverrides where+  validate = validateCircuitBreakerOverrides++-- Equivalent: genericValidate of a count and a duration is always valid.+validateCircuitBreakerOverrides :: CircuitBreakerOverrides -> Validation+validateCircuitBreakerOverrides overrides@(CircuitBreakerOverrides threshold resetTimeout) =+  mconcat+    [ genericValidate overrides,+      declare "a failure threshold it sets is at least 1" $ all (>= 1) threshold,+      declare "a reset timeout it sets is positive" $ all (> 0) resetTimeout+    ]+{-# ANN validateCircuitBreakerOverrides ("DisableMutation: ListLit" :: String) #-}++-- | What an operator set of a t'FailureBudgetSettings'.+data FailureBudgetOverrides = FailureBudgetOverrides+  { -- | @failures@+    failureBudgetOverridesFailures :: !(Maybe Word),+    -- | @window@+    failureBudgetOverridesWindow :: !(Maybe NominalDiffTime)+  }+  deriving (Show, Eq, Generic)++instance Validity FailureBudgetOverrides where+  validate = validateFailureBudgetOverrides++-- Equivalent: genericValidate of a count and a duration is always valid.+validateFailureBudgetOverrides :: FailureBudgetOverrides -> Validation+validateFailureBudgetOverrides overrides@(FailureBudgetOverrides failures window) =+  mconcat+    [ genericValidate overrides,+      declare "a failure budget it sets allows at least one failure" $ all (>= 1) failures,+      declare "a failure budget window it sets is positive" $ all (> 0) window+    ]+{-# ANN validateFailureBudgetOverrides ("DisableMutation: ListLit" :: String) #-}++-- | Overrides that override nothing.+noHttpEnvOverrides :: HttpEnvOverrides+noHttpEnvOverrides =+  HttpEnvOverrides+    { httpEnvOverridesAttemptsPerRequest = Nothing,+      httpEnvOverridesBackoff =+        BackoffOverrides+          { backoffOverridesBase = Nothing,+            backoffOverridesMaxDelay = Nothing,+            backoffOverridesMaxTotalDelay = Nothing+          },+      httpEnvOverridesCircuitBreaker =+        CircuitBreakerOverrides+          { circuitBreakerOverridesFailureThreshold = Nothing,+            circuitBreakerOverridesResetTimeout = Nothing+          },+      httpEnvOverridesFailureBudget =+        FailureBudgetOverrides+          { failureBudgetOverridesFailures = Nothing,+            failureBudgetOverridesWindow = Nothing+          },+      httpEnvOverridesRateLimitHeaders = Nothing+    }++-- | Set every field the overrides set, and leave the others.+applyHttpEnvOverrides :: HttpEnvOverrides -> HttpEnvSettings -> HttpEnvSettings+-- Matched positionally so that a new field fails to compile here.+applyHttpEnvOverrides+  ( HttpEnvOverrides+      attempts+      (BackoffOverrides base maxDelay maxTotalDelay)+      (CircuitBreakerOverrides threshold resetTimeout)+      (FailureBudgetOverrides failures window)+      rateLimitHeaders+    )+  settings =+    let orElse :: Maybe a -> a -> a+        orElse = flip fromMaybe+        backoff = httpEnvSettingsBackoff settings+        breaker = httpEnvSettingsCircuitBreaker settings+        budget = httpEnvSettingsFailureBudget settings+     in HttpEnvSettings+          { httpEnvSettingsAttemptsPerRequest =+              attempts `orElse` httpEnvSettingsAttemptsPerRequest settings,+            httpEnvSettingsBackoff =+              BackoffSettings+                { backoffSettingsBase = base `orElse` backoffSettingsBase backoff,+                  backoffSettingsMaxDelay = maxDelay `orElse` backoffSettingsMaxDelay backoff,+                  backoffSettingsMaxTotalDelay = maxTotalDelay `orElse` backoffSettingsMaxTotalDelay backoff+                },+            httpEnvSettingsCircuitBreaker =+              CircuitBreakerSettings+                { circuitBreakerSettingsFailureThreshold =+                    threshold `orElse` circuitBreakerSettingsFailureThreshold breaker,+                  circuitBreakerSettingsResetTimeout =+                    resetTimeout `orElse` circuitBreakerSettingsResetTimeout breaker+                },+            httpEnvSettingsFailureBudget =+              FailureBudgetSettings+                { failureBudgetSettingsFailures =+                    failures `orElse` failureBudgetSettingsFailures budget,+                  failureBudgetSettingsWindow =+                    window `orElse` failureBudgetSettingsWindow budget+                },+            httpEnvSettingsRateLimitHeaders =+              rateLimitHeaders `orElse` httpEnvSettingsRateLimitHeaders settings+          }++-- | What one dependency is called with: its own block wins over the global one.+resolveHttpEnvSettings ::+  HttpEnvSettings ->+  HttpEnvOverrides ->+  HttpEnvSettings+resolveHttpEnvSettings global own = applyHttpEnvOverrides own global++-- | Overrides that set every field to what the settings hold.+fullHttpEnvOverrides :: HttpEnvSettings -> HttpEnvOverrides+fullHttpEnvOverrides (HttpEnvSettings attempts backoff breaker budget rateLimitHeaders) =+  HttpEnvOverrides+    { httpEnvOverridesAttemptsPerRequest = Just attempts,+      httpEnvOverridesBackoff =+        BackoffOverrides+          { backoffOverridesBase = Just (backoffSettingsBase backoff),+            backoffOverridesMaxDelay = Just (backoffSettingsMaxDelay backoff),+            backoffOverridesMaxTotalDelay = Just (backoffSettingsMaxTotalDelay backoff)+          },+      httpEnvOverridesCircuitBreaker =+        CircuitBreakerOverrides+          { circuitBreakerOverridesFailureThreshold = Just (circuitBreakerSettingsFailureThreshold breaker),+            circuitBreakerOverridesResetTimeout = Just (circuitBreakerSettingsResetTimeout breaker)+          },+      httpEnvOverridesFailureBudget =+        FailureBudgetOverrides+          { failureBudgetOverridesFailures = Just (failureBudgetSettingsFailures budget),+            failureBudgetOverridesWindow = Just (failureBudgetSettingsWindow budget)+          },+      httpEnvOverridesRateLimitHeaders = Just rateLimitHeaders+    }++-- | The global settings, every field defaulting to 'defaultHttpEnvSettings'.+instance HasParser HttpEnvSettings where+  settingsParser =+    (`applyHttpEnvOverrides` defaultHttpEnvSettings)+      <$> httpEnvOverridesParser (fullHttpEnvOverrides defaultHttpEnvSettings)++-- | A dependency's block, defaulting to the application's choice for it.+httpEnvOverridesParser :: HttpEnvOverrides -> Parser HttpEnvOverrides+httpEnvOverridesParser+  ( HttpEnvOverrides+      attempts+      (BackoffOverrides base maxDelay maxTotalDelay)+      (CircuitBreakerOverrides threshold resetTimeout)+      (FailureBudgetOverrides failures window)+      rateLimitHeaders+    ) =+    -- Checked after reading rather than in the reader, so that the check also+    -- holds for a configuration file, which a reader is never given.+    let field :: (Show a) => Maybe a -> (a -> Either HttpEnvOverridesError b) -> [Builder a] -> Parser (Maybe b)+        field mDefault validateField builders =+          let checked = checkMapEither (first renderHttpEnvOverridesError . validateField)+           in case mDefault of+                Nothing -> optional (checked (setting builders))+                Just d -> Just <$> checked (setting (builders ++ [value d]))+        durationField :: Maybe NominalDiffTime -> HttpEnvOverridesError -> String -> String -> Parser (Maybe NominalDiffTime)+        durationField mDefault err helpText key =+          fmap unDuration+            <$> field+              (Duration <$> mDefault)+              (\d -> if unDuration d > 0 then Right d else Left err)+              [ help helpText,+                reader $ eitherReader (first renderDurationParseError . parseDuration),+                name key,+                metavar "DURATION"+              ]+     in HttpEnvOverrides+          <$> field+            (unAttempts <$> attempts)+            (\n -> if n >= 1 then Right (Attempts n) else Left HttpEnvOverridesErrorNoAttempts)+            [ help "Requests per call, retries included",+              reader countReader,+              name "attempts-per-request",+              metavar "COUNT"+            ]+          <*> subAll+            "backoff"+            ( BackoffOverrides+                <$> durationField+                  base+                  HttpEnvOverridesErrorBackoffBaseNotPositive+                  "Base of the random wait between attempts, doubled once per attempt"+                  "base"+                <*> durationField+                  maxDelay+                  HttpEnvOverridesErrorBackoffMaxDelayNotPositive+                  "Longest wait between two attempts"+                  "max-delay"+                <*> durationField+                  maxTotalDelay+                  HttpEnvOverridesErrorBackoffMaxTotalDelayNotPositive+                  "Most one call waits between its attempts in all"+                  "max-total-delay"+            )+          <*> subAll+            "circuit-breaker"+            ( CircuitBreakerOverrides+                <$> field+                  threshold+                  (\n -> if n >= 1 then Right n else Left HttpEnvOverridesErrorNoFailureThreshold)+                  [ help "Consecutive failed requests that open the circuit breaker",+                    reader countReader,+                    name "failure-threshold",+                    metavar "COUNT"+                  ]+                <*> durationField+                  resetTimeout+                  HttpEnvOverridesErrorResetTimeoutNotPositive+                  "How long the circuit breaker stays open before a probe"+                  "reset-timeout"+            )+          <*> subAll+            "failure-budget"+            ( FailureBudgetOverrides+                <$> field+                  failures+                  (\n -> if n >= 1 then Right n else Left HttpEnvOverridesErrorNoFailures)+                  [ help "Failed requests within the window that report a dependency as unwell",+                    reader countReader,+                    name "failures",+                    metavar "COUNT"+                  ]+                <*> durationField+                  window+                  HttpEnvOverridesErrorWindowNotPositive+                  "How long a failed request counts towards the failure budget"+                  "window"+            )+          <*> rateLimitHeadersField rateLimitHeaders++-- | A whole number that fits in an 'Int'.+countReader :: Reader Word+countReader = eitherReader $ \s ->+  case readMaybe s >>= integerToCount of+    Just n -> Right n+    Nothing -> Left (unwords ["not a count:", show s])++-- | @rate-limit-headers@: @none@ or one of 'renderRateLimitHeaders'.+rateLimitHeadersField :: Maybe (Maybe RateLimitHeaders) -> Parser (Maybe (Maybe RateLimitHeaders))+rateLimitHeadersField mDefault =+  let parseChoice :: String -> Either HttpEnvOverridesError (Maybe RateLimitHeaders)+      parseChoice s =+        maybe (Left (HttpEnvOverridesErrorUnknownRateLimitHeaders s)) Right (parseRateLimitHeadersChoice s)+      builders :: [Builder (Maybe RateLimitHeaders)]+      builders =+        [ help "Headers the dependency reports a spent quota in: none, x-ratelimit, ratelimit-reset or ratelimit",+          reader (eitherReader (first renderHttpEnvOverridesError . parseChoice)),+          option,+          long "rate-limit-headers",+          env "RATE_LIMIT_HEADERS",+          confWith "rate-limit-headers" (bimapCodec (first renderHttpEnvOverridesError . parseChoice) renderRateLimitHeadersChoice codec),+          metavar "HEADERS"+        ]+   in case mDefault of+        Nothing -> optional (setting builders)+        Just d -> Just <$> setting (builders ++ [valueWithShown renderRateLimitHeadersChoice d])++parseRateLimitHeadersChoice :: String -> Maybe (Maybe RateLimitHeaders)+parseRateLimitHeadersChoice = \case+  "none" -> Just Nothing+  s -> Just <$> parseRateLimitHeaders s++renderRateLimitHeadersChoice :: Maybe RateLimitHeaders -> String+renderRateLimitHeadersChoice = maybe "none" renderRateLimitHeaders++-- | A value an operator gave that no dependency can be called with.+data HttpEnvOverridesError+  = HttpEnvOverridesErrorNoAttempts+  | HttpEnvOverridesErrorBackoffBaseNotPositive+  | HttpEnvOverridesErrorBackoffMaxDelayNotPositive+  | HttpEnvOverridesErrorBackoffMaxTotalDelayNotPositive+  | HttpEnvOverridesErrorNoFailureThreshold+  | HttpEnvOverridesErrorResetTimeoutNotPositive+  | HttpEnvOverridesErrorNoFailures+  | HttpEnvOverridesErrorWindowNotPositive+  | HttpEnvOverridesErrorUnknownRateLimitHeaders !String++renderHttpEnvOverridesError :: HttpEnvOverridesError -> String+renderHttpEnvOverridesError = \case+  HttpEnvOverridesErrorNoAttempts -> "a call must be allowed at least one request"+  HttpEnvOverridesErrorBackoffBaseNotPositive -> "the backoff base must be positive"+  HttpEnvOverridesErrorBackoffMaxDelayNotPositive -> "the longest wait must be positive"+  HttpEnvOverridesErrorBackoffMaxTotalDelayNotPositive -> "the longest total wait must be positive"+  HttpEnvOverridesErrorNoFailureThreshold -> "the circuit-breaker failure threshold must be at least 1"+  HttpEnvOverridesErrorResetTimeoutNotPositive -> "the circuit-breaker reset timeout must be positive"+  HttpEnvOverridesErrorNoFailures -> "the failure budget must allow at least one failure"+  HttpEnvOverridesErrorWindowNotPositive -> "the failure budget window must be positive"+  HttpEnvOverridesErrorUnknownRateLimitHeaders s -> unwords ["unknown rate-limit headers:", show s]++-- | Which dependency an env is for, as its breaker's log lines name it.+newtype HttpEnvName = HttpEnvName {unHttpEnvName :: Text}++-- | A live t'HttpEnv' with a fresh circuit breaker and failure budget.+newHttpEnv :: (MonadLoggerIO m) => HttpEnvName -> HttpEnvSettings -> LogPolicy -> Manager -> m HttpEnv+newHttpEnv envName settings logPolicy manager = do+  breaker <- newCircuitBreaker (unHttpEnvName envName) (httpEnvSettingsCircuitBreaker settings)+  budget <- newFailureBudget (httpEnvSettingsFailureBudget settings)+  pure+    HttpEnv+      { httpEnvManager = manager,+        httpEnvRetryPolicy =+          backoffPolicy (httpEnvSettingsBackoff settings)+            <> limitAttempts (httpEnvSettingsAttemptsPerRequest settings),+        httpEnvCircuitBreaker = Just breaker,+        httpEnvFailureBudget = Just budget,+        httpEnvRequestLimiter = Nothing,+        httpEnvLogPolicy = logPolicy,+        httpEnvRateLimitHeaders = httpEnvSettingsRateLimitHeaders settings+      }
+ src/Network/HTTP/Env/OptParse/Duration.hs view
@@ -0,0 +1,112 @@+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}++-- | A human-readable duration such as @30s@ or @1h@, for a setting.+module Network.HTTP.Env.OptParse.Duration+  ( Duration (..),+    DurationParseError (..),+    renderDurationParseError,+    formatDuration,+    parseDuration,+  )+where++import Autodocodec+import Control.Arrow (left)+import qualified Data.Char as Char+import Data.Maybe (fromMaybe, listToMaybe, mapMaybe)+import Data.Ratio (denominator, numerator)+import Data.Scientific (Scientific)+import qualified Data.Text as Text+import Data.Time (NominalDiffTime)+import Network.HTTP.Env.Numeric (intToNominalDiffTime, rationalToNominalDiffTime, scientificToRational)+import Text.Read (readMaybe)++-- | Shown as its 'NominalDiffTime', so a documented default reads as seconds.+newtype Duration = Duration {unDuration :: NominalDiffTime}+  deriving (Eq)+  deriving newtype (Show)++-- | Either a duration with a unit, or a whole number of seconds.+instance HasCodec Duration where+  codec =+    dimapCodec+      (\case Left d -> d; Right d -> d)+      Left+      $ eitherCodec+        (bimapCodec (left renderDurationParseError . parseDuration) formatDuration codec)+        (dimapCodec (Duration . intToNominalDiffTime) (round . unDuration) codec)++-- | In the largest unit that divides the duration exactly, or in seconds.+formatDuration :: Duration -> String+formatDuration (Duration d) =+  let units :: [(Rational, String)]+      units =+        [ (30 * 24 * 60 * 60, "M"),+          (7 * 24 * 60 * 60, "w"),+          (24 * 60 * 60, "d"),+          (60 * 60, "h"),+          (60, "m")+        ]+      seconds :: Rational+      seconds = toRational d+      inUnit :: (Rational, String) -> Maybe String+      inUnit (size, unit) =+        let count = seconds / size+         in if seconds /= 0 && denominator count == 1+              then Just (concat [show @Integer (numerator count), unit])+              else Nothing+   in fromMaybe (show @NominalDiffTime d) (listToMaybe (mapMaybe inUnit units))++-- | Why a duration could not be read.+data DurationParseError+  = DurationParseErrorMustStartWithNumber+  | DurationParseErrorInvalidNumber+  | DurationParseErrorUnknownUnit !String+  deriving (Show, Eq)++-- | For a person.+renderDurationParseError :: DurationParseError -> String+renderDurationParseError = \case+  DurationParseErrorMustStartWithNumber -> "Duration must start with a number"+  DurationParseErrorInvalidNumber -> "Invalid number"+  DurationParseErrorUnknownUnit unit ->+    concat+      [ "Unknown duration unit: ",+        unit,+        ". Valid units: s, m, h, d, w, M, seconds, minutes, hours, days, weeks, months"+      ]++-- | A number followed by a unit, which defaults to seconds.+-- Multiplied as a 'Rational' rather than a 'Double', so that a large count of a+-- large unit lands exactly on a multiple of that unit.+parseDuration :: String -> Either DurationParseError Duration+parseDuration s = do+  (num, unit) <- case span (\c -> Char.isDigit c || c == '.') s of+    ([], _) -> Left DurationParseErrorMustStartWithNumber+    (n, u) -> case readMaybe n :: Maybe Scientific of+      Nothing -> Left DurationParseErrorInvalidNumber+      Just num' -> Right (num', u)+  let stripped = Text.strip (Text.pack unit)+  factor :: Rational <- case stripped of+    -- Single letters are case-sensitive, because M is months and m minutes.+    "" -> Right 1+    "s" -> Right 1+    "m" -> Right 60+    "h" -> Right (60 * 60)+    "d" -> Right (24 * 60 * 60)+    "w" -> Right (7 * 24 * 60 * 60)+    "M" -> Right (30 * 24 * 60 * 60)+    _ -> case Text.toLower stripped of+      "seconds" -> Right 1+      "minutes" -> Right 60+      "hours" -> Right (60 * 60)+      "days" -> Right (24 * 60 * 60)+      "weeks" -> Right (7 * 24 * 60 * 60)+      "months" -> Right (30 * 24 * 60 * 60)+      _ -> Left $ DurationParseErrorUnknownUnit unit+  pure $ Duration $ rationalToNominalDiffTime $ scientificToRational num * factor
+ src/Network/HTTP/Env/Pacing.hs view
@@ -0,0 +1,122 @@+-- | Pacing requests per key, such as per account of a dependency that meters+-- each account separately, at a rate the dependency's answers can correct.+module Network.HTTP.Env.Pacing+  ( RequestLimiter,+    newRequestLimiter,+    waitForRequest,+    requestLimiterTokenLimiter,+    repaceRequestLimiter,+    KeyedLimiters,+    newKeyedLimiters,+    keyedLimiter,+    observeRequestsPerHour,+    requestsPerHourConfig,+    requestTokenCost,+  )+where++import Control.Concurrent.TokenLimiter.Concurrent+  ( Count,+    MonotonicDiffNanos,+    TokenLimitConfig (..),+    TokenLimiter (..),+    makeTokenLimiter,+    waitDebit,+  )+import Control.Monad (when)+import Data.Hashable (Hashable)+import qualified StmContainers.Map as StmMap+import UnliftIO++-- | A token limiter that one request debits a request's worth of tokens+-- from, so that its rate is in requests per hour.+-- Repacing it repaces every holder, such as an env it was handed to.+newtype RequestLimiter = RequestLimiter (TVar TokenLimiter)+  deriving (Eq)++-- | A full limiter that refills at the given number of requests per hour.+newRequestLimiter :: (MonadIO m) => Count -> m RequestLimiter+newRequestLimiter requestsPerHour = liftIO $ do+  limiter <- makeTokenLimiter (requestsPerHourConfig requestsPerHour)+  RequestLimiter <$> newTVarIO limiter++-- | Wait until one more request may go; how long it waited, if at all.+waitForRequest :: (MonadIO m) => RequestLimiter -> m (Maybe MonotonicDiffNanos)+waitForRequest (RequestLimiter var) = liftIO $ do+  limiter <- readTVarIO var+  waitDebit limiter requestTokenCost++-- | The token limiter underneath now, to inspect.+requestLimiterTokenLimiter :: (MonadIO m) => RequestLimiter -> m TokenLimiter+requestLimiterTokenLimiter (RequestLimiter var) = readTVarIO var++-- | Pace at a new number of requests per hour, starting full.+-- Nothing changes when the rate is the one already paced at, so that+-- repeating it does not refill the bucket.+repaceRequestLimiter :: (MonadIO m) => RequestLimiter -> Count -> m ()+repaceRequestLimiter (RequestLimiter var) requestsPerHour = liftIO $ do+  fresh <- makeTokenLimiter (requestsPerHourConfig requestsPerHour)+  let pacedAt :: TokenLimiter -> Count+      pacedAt = tokenLimitConfigTokensPerSecond . tokenLimiterConfig+  atomically $ do+    current <- readTVar var+    when (pacedAt current /= pacedAt fresh) $ writeTVar var fresh++-- | A token limiter per key, made on first use.+data KeyedLimiters k = KeyedLimiters+  { -- | The rate a key is paced at until the dependency says otherwise.+    keyedLimitersRequestsPerHour :: !Count,+    keyedLimitersMap :: !(StmMap.Map k RequestLimiter)+  }++-- | Limiters that pace a new key at the given rate until told otherwise.+newKeyedLimiters :: (MonadIO m) => Count -> m (KeyedLimiters k)+newKeyedLimiters requestsPerHour = do+  limiterMap <- liftIO StmMap.newIO+  pure+    KeyedLimiters+      { keyedLimitersRequestsPerHour = requestsPerHour,+        keyedLimitersMap = limiterMap+      }++-- | The limiter of a key, the same one every time for the same key.+keyedLimiter :: (MonadIO m, Hashable k) => KeyedLimiters k -> k -> m RequestLimiter+keyedLimiter limiters key = liftIO $ do+  let limiterMap = keyedLimitersMap limiters+  fresh <- newRequestLimiter (keyedLimitersRequestsPerHour limiters)+  atomically $ do+    existing <- StmMap.lookup key limiterMap+    case existing of+      Just limiter -> pure limiter+      Nothing -> do+        StmMap.insert fresh key limiterMap+        pure fresh++-- | Take the dependency's word for what a key is allowed, such as+-- 'Network.HTTP.Env.RateLimit.rateLimitLimit', with 'repaceRequestLimiter'.+observeRequestsPerHour :: (MonadIO m, Hashable k) => KeyedLimiters k -> k -> Count -> m ()+observeRequestsPerHour limiters key requestsPerHour = do+  limiter <- keyedLimiter limiters key+  repaceRequestLimiter limiter requestsPerHour++-- | A limiter that refills at the given number of requests per hour, starting+-- full with a burst of fifty.+requestsPerHourConfig :: Count -> TokenLimitConfig+requestsPerHourConfig requestsPerHour =+  let burst :: Count+      burst = requestBurst * requestTokenCost+   in TokenLimitConfig+        { tokenLimitConfigInitialTokens = burst,+          tokenLimitConfigMaxTokens = burst,+          -- At least one, because a rate of zero never refills.+          tokenLimitConfigTokensPerSecond = max 1 requestsPerHour+        }++-- | What one request costs: an hour's worth of seconds, so that the rate in+-- tokens per second is the rate in requests per hour.+requestTokenCost :: Count+requestTokenCost = 3600++-- | How many requests may go back to back.+requestBurst :: Count+requestBurst = 50
+ src/Network/HTTP/Env/RateLimit.hs view
@@ -0,0 +1,224 @@+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Reading a dependency's answer that a request quota is spent, and how long+-- to wait.+--+-- The headers are conventions rather than a standard, and they disagree on+-- the unit of the reset, so the convention a dependency uses is chosen+-- explicitly.+module Network.HTTP.Env.RateLimit+  ( RateLimitHeaders (..),+    renderRateLimitHeaders,+    parseRateLimitHeaders,+    isRateLimited,+    rateLimitWait,+    rateLimitLimit,+    structuredParameter,+    httpExceptionRateLimitWait,+    responseRateLimitWait,+    rateLimitMinimumWait,+    rateLimitMaximumWait,+    rateLimitRetryMargin,+  )+where++import Control.Applicative ((<|>))+import Data.ByteString (ByteString)+import qualified Data.ByteString as SB+import Data.Foldable (asum)+import Data.Maybe (isJust, listToMaybe, mapMaybe)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as TE+import qualified Data.Text.Read as Text.Read+import Data.Time (NominalDiffTime, UTCTime, defaultTimeLocale, diffUTCTime, parseTimeM)+import Data.Time.Clock.POSIX (posixSecondsToUTCTime)+import Data.Validity (Validity)+import Data.Word (Word8)+import GHC.Generics (Generic)+import Network.HTTP.Client+  ( HttpException (..),+    HttpExceptionContent (..),+    Response,+    responseHeaders,+    responseStatus,+  )+import Network.HTTP.Env.Numeric (intToNominalDiffTime)+import qualified Network.HTTP.Types as HTTP (statusCode)+import Network.HTTP.Types.Header (Header, hRetryAfter)+import qualified Network.HTTP.Types.Header as Header++-- | Which headers a dependency says its quota in.+data RateLimitHeaders+  = -- | @X-RateLimit-*@, with the reset as a Unix time, as GitHub sends them.+    -- A 403 counts only when the headers corroborate it.+    RateLimitHeadersXRateLimit+  | -- | @RateLimit-Reset@ as a Unix time, as GitLab sends it.+    RateLimitHeadersRateLimitReset+  | -- | A structured @RateLimit@ header whose @t@ is seconds from now, as+    -- Forgejo sends it.+    RateLimitHeadersStructured+  deriving (Show, Eq, Generic, Enum, Bounded)++instance Validity RateLimitHeaders++-- | The name a setting spells a convention with.+renderRateLimitHeaders :: RateLimitHeaders -> String+renderRateLimitHeaders = \case+  RateLimitHeadersXRateLimit -> "x-ratelimit"+  RateLimitHeadersRateLimitReset -> "ratelimit-reset"+  RateLimitHeadersStructured -> "ratelimit"++-- | The inverse of 'renderRateLimitHeaders'.+parseRateLimitHeaders :: String -> Maybe RateLimitHeaders+parseRateLimitHeaders s =+  lookup s (map (\headers -> (renderRateLimitHeaders headers, headers)) [minBound .. maxBound])++-- | Does a response with this status and these headers say the quota is spent?+--+-- Decided from the status and the headers, never from the body.+isRateLimited :: RateLimitHeaders -> Int -> [Header] -> Bool+isRateLimited convention code headers =+  code == 429+    || case convention of+      RateLimitHeadersXRateLimit ->+        code == 403+          && ( lookup "X-RateLimit-Remaining" headers == Just "0"+                 || retryAfterIsReadable headers+             )+      RateLimitHeadersRateLimitReset -> False+      RateLimitHeadersStructured -> False++-- | How long to wait before trying again, given when the refusal arrived.+--+-- @Retry-After@ first, then the convention's reset, then the floor, all+-- clamped between 'rateLimitMinimumWait' and 'rateLimitMaximumWait'.+rateLimitWait :: RateLimitHeaders -> UTCTime -> [Header] -> NominalDiffTime+rateLimitWait convention now headers =+  let asked :: Maybe NominalDiffTime+      asked = retryAfterWait now headers <|> resetWait convention now headers+   in max rateLimitMinimumWait . min rateLimitMaximumWait $ case asked of+        Nothing -> rateLimitMinimumWait+        Just wait -> wait + rateLimitRetryMargin++-- | @Retry-After@, in seconds or as an HTTP date.+retryAfterWait :: UTCTime -> [Header] -> Maybe NominalDiffTime+retryAfterWait now headers = do+  value <- lookup hRetryAfter headers+  (intToNominalDiffTime <$> readWholeInt value)+    <|> ((`diffUTCTime` now) <$> parseHttpDate value)++-- | Whether @Retry-After@ is there and reads as seconds or an HTTP date.+retryAfterIsReadable :: [Header] -> Bool+retryAfterIsReadable headers = case lookup hRetryAfter headers of+  Nothing -> False+  Just value -> isJust (readWholeInt value) || isJust (parseHttpDate value)++-- | The three formats RFC 9110 asks a recipient to accept.+parseHttpDate :: ByteString -> Maybe UTCTime+parseHttpDate value =+  let parseAs :: String -> Maybe UTCTime+      parseAs format = parseTimeM True defaultTimeLocale format (Text.unpack (TE.decodeLatin1 value))+   in asum+        ( map+            parseAs+            [ "%a, %d %b %Y %H:%M:%S GMT",+              "%A, %d-%b-%y %H:%M:%S GMT",+              "%a %b %e %H:%M:%S %Y"+            ]+        )++-- | How far off the convention's reset is; negative once it has passed.+resetWait :: RateLimitHeaders -> UTCTime -> [Header] -> Maybe NominalDiffTime+resetWait convention now headers =+  let epochResetWait :: Header.HeaderName -> Maybe NominalDiffTime+      epochResetWait name = do+        value <- lookup name headers+        epochSeconds <- readWholeInt value+        pure $ diffUTCTime (posixSecondsToUTCTime (intToNominalDiffTime epochSeconds)) now+   in case convention of+        RateLimitHeadersXRateLimit -> epochResetWait "X-RateLimit-Reset"+        RateLimitHeadersRateLimitReset -> epochResetWait "RateLimit-Reset"+        RateLimitHeadersStructured -> intToNominalDiffTime <$> structuredParameter "t" headers++-- | How many requests an hour the dependency says the caller is allowed, if+-- the convention says so.+--+-- Only @X-RateLimit-Limit@ of the @core@ resource, or of no named resource,+-- because other resources are metered on other scales. Zero and below are+-- refused: a rate of zero would stop a limiter.+rateLimitLimit :: RateLimitHeaders -> [Header] -> Maybe Int+rateLimitLimit convention headers = case convention of+  RateLimitHeadersXRateLimit ->+    case lookup "X-RateLimit-Resource" headers of+      Just resource | resource /= "core" -> Nothing+      _ -> do+        value <- lookup "X-RateLimit-Limit" headers+        limit <- readWholeInt value+        if limit > 0 then Just limit else Nothing+  RateLimitHeadersRateLimitReset -> Nothing+  RateLimitHeadersStructured -> Nothing++-- | The wait, if this exception is a refusal for a spent quota.+httpExceptionRateLimitWait :: RateLimitHeaders -> UTCTime -> HttpException -> Maybe NominalDiffTime+httpExceptionRateLimitWait convention now = \case+  HttpExceptionRequest _ (StatusCodeException response _) -> responseRateLimitWait convention now response+  _ -> Nothing++-- | The wait, if this response is a refusal for a spent quota.+responseRateLimitWait :: RateLimitHeaders -> UTCTime -> Response body -> Maybe NominalDiffTime+responseRateLimitWait convention now response =+  if isRateLimited convention (HTTP.statusCode (responseStatus response)) (responseHeaders response)+    then Just (rateLimitWait convention now (responseHeaders response))+    else Nothing++-- | A parameter of the structured header, such as @t@ in+-- @RateLimit: "default";r=0;t=42@.+structuredParameter :: ByteString -> [Header] -> Maybe Int+structuredParameter name headers = do+  value <- lookup "RateLimit" headers+  let parameters = drop 1 (SB.split semicolonByte value)+  parameter <- listToMaybe (mapMaybe (namedParameterValue name) parameters)+  readWholeInt parameter++namedParameterValue :: ByteString -> ByteString -> Maybe ByteString+namedParameterValue name parameter =+  let (key, rest) = SB.break (== equalsByte) parameter+   in if trimAsciiSpace key == name+        then Just (trimAsciiSpace (SB.drop 1 rest))+        else Nothing++trimAsciiSpace :: ByteString -> ByteString+trimAsciiSpace = SB.dropWhile (== spaceByte) . SB.dropWhileEnd (== spaceByte)++semicolonByte :: Word8+semicolonByte = 0x3b++equalsByte :: Word8+equalsByte = 0x3d++spaceByte :: Word8+spaceByte = 0x20++-- | A whole number and nothing besides; a leading minus is unreadable.+-- A value too large for an 'Int' wraps, which the clamp deals with.+readWholeInt :: ByteString -> Maybe Int+readWholeInt value = case TE.decodeUtf8' value of+  Left _ -> Nothing+  Right text -> case Text.Read.decimal text of+    Right (n, rest) | Text.null rest -> Just n+    _ -> Nothing++-- | Never sooner than this: a retry inside the same window is refused again.+rateLimitMinimumWait :: NominalDiffTime+rateLimitMinimumWait = 60++-- | Never longer than an hour's window plus the floor: a longer value is a+-- misread header.+rateLimitMaximumWait :: NominalDiffTime+rateLimitMaximumWait = 3600 + rateLimitMinimumWait++-- | Added to what was asked for, because the reset is the dependency's clock.+rateLimitRetryMargin :: NominalDiffTime+rateLimitRetryMargin = 5
+ src/Network/HTTP/Env/Servant.hs view
@@ -0,0 +1,34 @@+-- | Call an HTTP dependency with servant-client, through the same env as+-- "Network.HTTP.Env", which this module re-exports.+--+-- = Usage+--+-- Make the t'HttpEnv' as in "Network.HTTP.Env", then a t'ClientEnv' that+-- shares its layers, so that servant calls and plain calls to one+-- dependency share one breaker and one budget:+--+-- > clientEnv = servantClientEnv httpEnv baseUrl (const LevelError)+-- >+-- > result <- callClient clientEnv someClientM+-- > case result of+-- >   Right a -> ...+-- >   Left HttpEnvErrorCircuitOpen -> ...+-- >   Left (HttpEnvErrorRateLimited wait _) -> ...+-- >   Left (HttpEnvErrorFailed clientError) -> ...+module Network.HTTP.Env.Servant+  ( -- * Servant+    ClientEnv,+    servantClientEnv,+    callClient,+    callClientWith,+    callStreamingClient,+    callStreamingClientWith,+    peekClientEnv,++    -- * Everything in "Network.HTTP.Env"+    module Network.HTTP.Env,+  )+where++import Network.HTTP.Env+import Network.HTTP.Env.Servant.Client (ClientEnv, callClient, callClientWith, callStreamingClient, callStreamingClientWith, peekClientEnv, servantClientEnv)
+ src/Network/HTTP/Env/Servant/Client.hs view
@@ -0,0 +1,141 @@+{-# LANGUAGE LambdaCase #-}++-- | The servant analogue of 'Network.HTTP.Env.HttpClient'.+module Network.HTTP.Env.Servant.Client+  ( ClientEnv (..),+    servantClientEnv,+    peekClientEnv,+    callClient,+    callClientWith,+    callStreamingClient,+    callStreamingClientWith,+    clientErrorRateLimitWait,+  )+where++import Control.DeepSeq (NFData)+import Control.Monad (forM_)+import Control.Monad.IO.Class+import Control.Monad.Logger.CallStack+import Control.Retry (RetryPolicyM)+import Data.Foldable (toList)+import Data.Time (NominalDiffTime, UTCTime, getCurrentTime)+import Network.HTTP.Env.CircuitBreaker+import Network.HTTP.Env.CircuitBreaker.Retry (liftRetryPolicy)+import Network.HTTP.Env.FailureBudget (FailureBudgetEnv, peekFailureBudget)+import Network.HTTP.Env.HttpClient (HttpEnv (..), HttpEnvError, HttpEnvReport (..), httpEnvError, unlessRejecting)+import Network.HTTP.Env.HttpClient.Retry (Repeatable (..))+import Network.HTTP.Env.LogPolicy (LogPolicy)+import Network.HTTP.Env.Pacing (RequestLimiter, waitForRequest)+import Network.HTTP.Env.RateLimit (RateLimitHeaders, isRateLimited, rateLimitWait)+import Network.HTTP.Env.Servant.Retry+  ( runClientMWithRetries,+    runStreamingClientMWithRetries,+  )+import qualified Network.HTTP.Types as HTTP (statusCode)+import qualified Servant.Client as Servant+import qualified Servant.Client.Streaming as Streaming++-- | Servant's 'Servant.ClientEnv' plus the layers every call goes through.+data ClientEnv = ClientEnv+  { clientEnvBase :: !Servant.ClientEnv,+    clientEnvRetryPolicy :: !(RetryPolicyM IO),+    clientEnvCircuitBreaker :: !(Maybe CircuitBreakerEnv),+    clientEnvFailureBudget :: !(Maybe FailureBudgetEnv),+    clientEnvRequestLimiter :: !(Maybe RequestLimiter),+    -- | The log level of a call's final error.+    clientEnvErrorLogLevel :: !(Servant.ClientError -> LogLevel),+    clientEnvLogPolicy :: !LogPolicy,+    -- | How the dependency says a quota is spent, if it does.+    clientEnvRateLimitHeaders :: !(Maybe RateLimitHeaders)+  }++-- | A t'ClientEnv' for a base URL, sharing every layer of the given t'HttpEnv'.+servantClientEnv :: HttpEnv -> Servant.BaseUrl -> (Servant.ClientError -> LogLevel) -> ClientEnv+-- Matched positionally so that a new field fails to compile here.+servantClientEnv (HttpEnv manager policy breaker budget limiter logPolicy rateLimitHeaders) baseUrl errorLogLevel =+  ClientEnv+    { clientEnvBase = Servant.mkClientEnv manager baseUrl,+      clientEnvRetryPolicy = policy,+      clientEnvCircuitBreaker = breaker,+      clientEnvFailureBudget = budget,+      clientEnvRequestLimiter = limiter,+      clientEnvErrorLogLevel = errorLogLevel,+      clientEnvLogPolicy = logPolicy,+      clientEnvRateLimitHeaders = rateLimitHeaders+    }++-- | Run a one-shot servant request through the env's layers.+-- A request is sent again only if its method is idempotent, it carries an+-- idempotency key, or it never left.+callClient ::+  (MonadIO m, MonadLogger m) =>+  ClientEnv ->+  Servant.ClientM a ->+  m (Either (HttpEnvError Servant.ClientError) a)+callClient = callClientWith RepeatableIfIdempotent++-- | 'callClient', saying whether the request may be sent again after a fault.+callClientWith ::+  (MonadIO m, MonadLogger m) =>+  Repeatable ->+  ClientEnv ->+  Servant.ClientM a ->+  m (Either (HttpEnvError Servant.ClientError) a)+callClientWith repeatable env func = unlessRejecting (clientEnvCircuitBreaker env) $ do+  forM_ (clientEnvRequestLimiter env) waitForRequest+  let policy = liftRetryPolicy (clientEnvRetryPolicy env)+  result <- runClientMWithRetries (clientEnvLogPolicy env) (clientEnvCircuitBreaker env) (clientEnvFailureBudget env) (clientEnvErrorLogLevel env) policy repeatable func (clientEnvBase env)+  classifyCallError env result++-- | Streaming counterpart of 'callClient'.+callStreamingClient ::+  (MonadIO m, MonadLogger m, NFData a) =>+  ClientEnv ->+  Streaming.ClientM a ->+  m (Either (HttpEnvError Servant.ClientError) a)+callStreamingClient = callStreamingClientWith RepeatableIfIdempotent++-- | Streaming counterpart of 'callClientWith'.+callStreamingClientWith ::+  (MonadIO m, MonadLogger m, NFData a) =>+  Repeatable ->+  ClientEnv ->+  Streaming.ClientM a ->+  m (Either (HttpEnvError Servant.ClientError) a)+callStreamingClientWith repeatable env func = unlessRejecting (clientEnvCircuitBreaker env) $ do+  forM_ (clientEnvRequestLimiter env) waitForRequest+  let policy = liftRetryPolicy (clientEnvRetryPolicy env)+  result <- runStreamingClientMWithRetries (clientEnvLogPolicy env) (clientEnvCircuitBreaker env) (clientEnvFailureBudget env) (clientEnvErrorLogLevel env) policy repeatable func (clientEnvBase env)+  classifyCallError env result++-- | Tell a spent quota apart from any other failure of a call.+classifyCallError :: (MonadIO m) => ClientEnv -> Either (CircuitBreakerError Servant.ClientError) a -> m (Either (HttpEnvError Servant.ClientError) a)+classifyCallError env result = do+  now <- liftIO getCurrentTime+  pure $ case result of+    Left err -> Left (httpEnvError (fmap clientErrorRateLimitWait (clientEnvRateLimitHeaders env)) now err)+    Right a -> Right a++-- | The wait, if this error is a refusal for a spent quota.+clientErrorRateLimitWait :: RateLimitHeaders -> UTCTime -> Servant.ClientError -> Maybe NominalDiffTime+clientErrorRateLimitWait convention now = \case+  Servant.FailureResponse _ response+    | isRateLimited convention (HTTP.statusCode (Servant.responseStatusCode response)) (toList (Servant.responseHeaders response)) ->+        Just $ rateLimitWait convention now (toList (Servant.responseHeaders response))+  Servant.FailureResponse _ _ -> Nothing+  Servant.DecodeFailure _ _ -> Nothing+  Servant.UnsupportedContentType _ _ -> Nothing+  Servant.InvalidContentTypeHeader _ -> Nothing+  Servant.ConnectionError _ -> Nothing++-- | As 'Network.HTTP.Env.HttpClient.peekHttpEnv'.+peekClientEnv :: (MonadIO m) => ClientEnv -> m HttpEnvReport+peekClientEnv env = do+  circuit <- traverse peekCircuitBreaker (clientEnvCircuitBreaker env)+  budget <- traverse peekFailureBudget (clientEnvFailureBudget env)+  pure+    HttpEnvReport+      { httpEnvReportCircuit = circuit,+        httpEnvReportFailureBudget = budget+      }
+ src/Network/HTTP/Env/Servant/Retry.hs view
@@ -0,0 +1,165 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE TypeApplications #-}++-- | Retrying servant client calls, and where a 'Servant.Client.ClientError' becomes a value.+--+-- [tag:NoUnscrubbedClientError] Every 'Servant.Client.ClientError' handed out of this module+-- has been through 'scrubClientError', for the same reason as+-- [ref:NoUnscrubbedHttpException]: it carries the request we sent.+module Network.HTTP.Env.Servant.Retry+  ( runClientMWithRetries,+    runStreamingClientMWithRetries,+    runClientMWithRetries',+    shouldRetryClientError,+    describeClientFault,+    clientRepeatSafety,+    clientErrorRepeatSafety,+    scrubClientError,+    renderClientErrorForLogging,+  )+where++import Control.DeepSeq (NFData)+import Control.Exception (SomeException, fromException, toException)+import Control.Monad+import Control.Monad.IO.Class+import Control.Monad.Logger.CallStack+import Control.Retry+import qualified Data.ByteString.Lazy as LB+import Data.Foldable (toList)+import Data.Sequence (Seq)+import qualified Data.Sequence as Seq+import qualified Data.Text as Text+import qualified Data.Text.Encoding as TE+import Network.HTTP.Client (HttpException (..))+import Network.HTTP.Env.CircuitBreaker+import Network.HTTP.Env.CircuitBreaker.Retry (retryingWithCircuitBreaker)+import Network.HTTP.Env.FailureBudget (FailureBudgetEnv)+import Network.HTTP.Env.HttpClient.Retry+import Network.HTTP.Env.LogPolicy (LogPolicy, loggedResponseBodyBytes, scrubHeadersForLogging, scrubHttpException, scrubQueryForLogging, withheldResponseBody)+import Network.HTTP.Types.Header (Header)+import qualified Servant.Client as Oneshot+import qualified Servant.Client.Core as Core+import qualified Servant.Client.Streaming as Streaming+import Text.Show.Pretty++-- | Run a servant request, running each attempt through the breaker.+-- The final error is logged at the level the given function assigns it.+runClientMWithRetries :: (MonadIO m, MonadLogger m) => LogPolicy -> Maybe CircuitBreakerEnv -> Maybe FailureBudgetEnv -> (Oneshot.ClientError -> LogLevel) -> RetryPolicyM m -> Repeatable -> Oneshot.ClientM a -> Oneshot.ClientEnv -> m (Either (CircuitBreakerError Oneshot.ClientError) a)+runClientMWithRetries logPolicy mBreaker mBudget errorLogLevel = runClientMWithRetries' logPolicy mBreaker mBudget errorLogLevel Oneshot.runClientM++-- | Streaming counterpart of 'runClientMWithRetries'.+runStreamingClientMWithRetries :: (MonadIO m, MonadLogger m, NFData a) => LogPolicy -> Maybe CircuitBreakerEnv -> Maybe FailureBudgetEnv -> (Oneshot.ClientError -> LogLevel) -> RetryPolicyM m -> Repeatable -> Streaming.ClientM a -> Streaming.ClientEnv -> m (Either (CircuitBreakerError Oneshot.ClientError) a)+runStreamingClientMWithRetries logPolicy mBreaker mBudget errorLogLevel = runClientMWithRetries' logPolicy mBreaker mBudget errorLogLevel Streaming.runClientM++-- | 'runClientMWithRetries' over any runner.+runClientMWithRetries' :: (MonadIO m, MonadLogger m) => LogPolicy -> Maybe CircuitBreakerEnv -> Maybe FailureBudgetEnv -> (Oneshot.ClientError -> LogLevel) -> (cm a -> env -> IO (Either Oneshot.ClientError a)) -> RetryPolicyM m -> Repeatable -> cm a -> env -> m (Either (CircuitBreakerError Oneshot.ClientError) a)+runClientMWithRetries' logPolicy mBreaker mBudget errorLogLevel runner policy repeatable func clientEnv = do+  result <-+    retryingWithCircuitBreaker mBreaker mBudget policy (describeClientFault logPolicy) (clientRepeatSafety repeatable) $ \rs -> do+      let num = succ $ rsIterNumber rs+      when (num > 1) $ logDebug $ Text.pack $ unwords ["Attempt", show @Int num]+      -- The runner can throw a connection failure rather than return one,+      -- for example when streaming.+      liftIO $ do+        errOrThrow <- catchConnectionException logPolicy (runner func clientEnv)+        pure $ case errOrThrow of+          Left someException -> Left (Oneshot.ConnectionError someException)+          Right res -> res+  case result of+    Left CircuitBreakerErrorOpen -> pure (Left CircuitBreakerErrorOpen)+    Left (CircuitBreakerErrorUnderlying err) -> do+      -- [ref:NoUnscrubbedClientError]+      let scrubbed = scrubClientError logPolicy err+      logOther (errorLogLevel scrubbed) $ Text.pack $ unwords ["Servant request failed:", renderClientErrorForLogging logPolicy scrubbed]+      pure $ Left $ CircuitBreakerErrorUnderlying scrubbed+    Right a -> pure $ Right a++-- | A 'Oneshot.ClientError' scrubbed and rendered for a log line.+-- A body that failed is cut to 'loggedResponseBodyBytes'; one that could not+-- be read is withheld, since it may be a success that carries a credential.+renderClientErrorForLogging :: LogPolicy -> Oneshot.ClientError -> String+renderClientErrorForLogging policy err =+  let withheld :: Core.ResponseF LB.ByteString -> Core.ResponseF LB.ByteString+      withheld response = response {Core.responseBody = LB.fromStrict (TE.encodeUtf8 (Text.pack withheldResponseBody))}+   in ppShow @Oneshot.ClientError $ case scrubClientError policy err of+        Oneshot.FailureResponse request response ->+          Oneshot.FailureResponse request (LB.take loggedResponseBodyBytes <$> response)+        Oneshot.DecodeFailure msg response -> Oneshot.DecodeFailure msg (withheld response)+        Oneshot.UnsupportedContentType mediaType response -> Oneshot.UnsupportedContentType mediaType (withheld response)+        Oneshot.InvalidContentTypeHeader response -> Oneshot.InvalidContentTypeHeader (withheld response)+        Oneshot.ConnectionError e -> Oneshot.ConnectionError e++-- | A 'Oneshot.ClientError' with every request and response in it scrubbed.+-- A connection failure carries a second copy of the request.+scrubClientError :: LogPolicy -> Oneshot.ClientError -> Oneshot.ClientError+scrubClientError policy = \case+  Oneshot.FailureResponse request response ->+    Oneshot.FailureResponse (scrubRequest policy request) (scrubResponse policy response)+  Oneshot.DecodeFailure msg response ->+    Oneshot.DecodeFailure msg (scrubResponse policy response)+  Oneshot.UnsupportedContentType mediaType response ->+    Oneshot.UnsupportedContentType mediaType (scrubResponse policy response)+  Oneshot.InvalidContentTypeHeader response ->+    Oneshot.InvalidContentTypeHeader (scrubResponse policy response)+  Oneshot.ConnectionError e -> Oneshot.ConnectionError (scrubConnectionException policy e)++scrubRequest :: LogPolicy -> Core.RequestF body path -> Core.RequestF body path+scrubRequest policy request =+  request+    { Core.requestHeaders = scrubHeaderSeq policy (Core.requestHeaders request),+      Core.requestQueryString = Seq.fromList (scrubQueryForLogging policy (toList (Core.requestQueryString request)))+    }++scrubResponse :: LogPolicy -> Core.ResponseF body -> Core.ResponseF body+scrubResponse policy response =+  response {Core.responseHeaders = scrubHeaderSeq policy (Core.responseHeaders response)}++scrubHeaderSeq :: LogPolicy -> Seq Header -> Seq Header+scrubHeaderSeq policy = Seq.fromList . scrubHeadersForLogging policy . toList++-- | The exception behind a connection failure, put through the policy.+scrubConnectionException :: LogPolicy -> SomeException -> SomeException+scrubConnectionException policy e = case fromException e of+  Just httpException -> toException (scrubHttpException policy httpException)+  Nothing -> e++-- | Describe a connection error or a 5xx; anything else is no fault.+describeClientFault :: LogPolicy -> Either Oneshot.ClientError a -> Maybe String+describeClientFault logPolicy = \case+  Left err+    | shouldRetryClientError err -> Just (renderClientErrorForLogging logPolicy err)+    | otherwise -> Nothing+  Right _ -> Nothing++-- | Whether a call may be sent again after this result.+clientRepeatSafety :: Repeatable -> Either Oneshot.ClientError a -> RepeatSafety+clientRepeatSafety repeatable res = case repeatable of+  RepeatableAlways -> RepeatSafetySafe+  RepeatableIfIdempotent -> case res of+    Left err -> clientErrorRepeatSafety err+    Right _ -> RepeatSafetyUnsafe++-- | 'httpRepeatSafety' of the request behind an error.+-- A request the error does not carry is taken as unsafe to send again.+clientErrorRepeatSafety :: Oneshot.ClientError -> RepeatSafety+clientErrorRepeatSafety = \case+  Oneshot.FailureResponse request _ ->+    requestRepeatSafety (Core.requestMethod request) (toList (Core.requestHeaders request))+  Oneshot.ConnectionError e -> case fromException e of+    Just exception@(HttpExceptionRequest request _) ->+      httpRepeatSafety RepeatableIfIdempotent request (Left exception :: Either HttpException ())+    Just (InvalidUrlException _ _) -> RepeatSafetyUnsafe+    Nothing -> RepeatSafetyUnsafe+  Oneshot.DecodeFailure _ _ -> RepeatSafetyUnsafe+  Oneshot.UnsupportedContentType _ _ -> RepeatSafetyUnsafe+  Oneshot.InvalidContentTypeHeader _ -> RepeatSafetyUnsafe++-- | A connection failure or a 5xx.+shouldRetryClientError :: Oneshot.ClientError -> Bool+shouldRetryClientError = \case+  Oneshot.FailureResponse _ response -> shouldRetryStatusCode $ Oneshot.responseStatusCode response+  Oneshot.DecodeFailure _ _ -> False+  Oneshot.UnsupportedContentType _ _ -> False+  Oneshot.InvalidContentTypeHeader _ -> False+  Oneshot.ConnectionError _ -> True