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