http-env-0.0.0.0: src/Network/HTTP/Env/FailureBudget.hs
{-# 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)