-- SPDX-FileCopyrightText: 2026 Alexandra de Wit
--
-- SPDX-License-Identifier: MIT

-- | Public-read admission, HTTP attempt observation, and response-driven cooldown policy.
module Ecluse.Core.Registry.Public (
    PublicControl,
    newPublicControl,
    publicControlWith,
    ReadControl (..),
    withReadControl,
    classifyPublicResponse,
) where

import Control.Retry (RetryPolicyM (getRetryPolicyM), defaultRetryStatus, fullJitterBackoff)
import Data.List (lookup)
import Data.Time (UTCTime, getCurrentTime)
import Network.HTTP.Client (Request (host, port))
import Network.HTTP.Types (ResponseHeaders, Status, statusCode)

import Ecluse.Core.Fault (RetryAfter (RetryAfter))
import Ecluse.Core.Fault.Http (hostPortLabel)
import Ecluse.Core.Fault.RetryAfter (parseRetryAfter, upstreamRetryCap)
import Ecluse.Core.Registry (FetchFault (FetchCooldown, FetchUrlUnformable), UrlFormationError (UnparseableUrl))
import Ecluse.Core.Registry.Backoff (CooldownEvent, PublicBackoff, PublicResponse (..), newPublicBackoff, publicRetryAfter, recordPublicResponse, reportingBackoff, withPublicAttempt)
import Ecluse.Core.Registry.Exchange.Observe (observeExchange)
import Ecluse.Core.Security.Authority (HostPort (hpHost), hostPortAddress)
import Ecluse.Core.Telemetry.Upstream (ExchangeOutcome, PublicReadKind)

-- | One process shares the cooldown handle across its proxy and worker reads.
data PublicControl = PublicControl
    { PublicControl -> PublicBackoff
pcBackoff :: PublicBackoff
    , PublicControl -> IO UTCTime
pcClock :: IO UTCTime
    , PublicControl -> Text -> PublicReadKind -> ExchangeOutcome -> IO ()
pcRecord :: Text -> PublicReadKind -> ExchangeOutcome -> IO ()
    }

-- | Create the fixed public policy with full jitter above its positive fallback floor.
newPublicControl :: (Text -> PublicReadKind -> ExchangeOutcome -> IO ()) -> (HostPort -> CooldownEvent -> IO ()) -> IO PublicControl
newPublicControl :: (Text -> PublicReadKind -> ExchangeOutcome -> IO ())
-> (HostPort -> CooldownEvent -> IO ()) -> IO PublicControl
newPublicControl Text -> PublicReadKind -> ExchangeOutcome -> IO ()
record HostPort -> CooldownEvent -> IO ()
report = do
    backoff <- IO UTCTime
-> (RetryAfter -> RetryAfter -> IO RetryAfter) -> IO PublicBackoff
newPublicBackoff IO UTCTime
getCurrentTime RetryAfter -> RetryAfter -> IO RetryAfter
forall {m :: * -> *}.
MonadIO m =>
RetryAfter -> RetryAfter -> m RetryAfter
jitter
    pure (publicControlWith (reportingBackoff report backoff) getCurrentTime record)
  where
    jitter :: RetryAfter -> RetryAfter -> m RetryAfter
jitter (RetryAfter Int
floorDelay) (RetryAfter Int
ceilingDelay) = do
        sample <- RetryPolicyM m -> RetryStatus -> m (Maybe Int)
forall (m :: * -> *).
RetryPolicyM m -> RetryStatus -> m (Maybe Int)
getRetryPolicyM (Int -> RetryPolicyM m
forall (m :: * -> *). MonadIO m => Int -> RetryPolicyM m
fullJitterBackoff (Int
ceilingDelay Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
floorDelay)) RetryStatus
defaultRetryStatus
        pure (RetryAfter (floorDelay + fromMaybe 0 sample))

-- | Supply the same clock used by an existing cooldown handle, with a non-throwing recorder.
publicControlWith :: PublicBackoff -> IO UTCTime -> (Text -> PublicReadKind -> ExchangeOutcome -> IO ()) -> PublicControl
publicControlWith :: PublicBackoff
-> IO UTCTime
-> (Text -> PublicReadKind -> ExchangeOutcome -> IO ())
-> PublicControl
publicControlWith = PublicBackoff
-> IO UTCTime
-> (Text -> PublicReadKind -> ExchangeOutcome -> IO ())
-> PublicControl
PublicControl

-- | Private and write exchanges bypass public admission and the public request counter.
data ReadControl = Uncontrolled | Controlled PublicControl PublicReadKind

-- | Observe actual HTTP work after admission. The header callback records status before applying cooldown policy.
withReadControl :: ReadControl -> Request -> (Request -> (Status -> ResponseHeaders -> IO (Maybe RetryAfter)) -> IO a) -> IO (Either FetchFault a)
withReadControl :: forall a.
ReadControl
-> Request
-> (Request
    -> (Status -> ResponseHeaders -> IO (Maybe RetryAfter)) -> IO a)
-> IO (Either FetchFault a)
withReadControl ReadControl
Uncontrolled Request
request Request
-> (Status -> ResponseHeaders -> IO (Maybe RetryAfter)) -> IO a
action = a -> Either FetchFault a
forall a b. b -> Either a b
Right (a -> Either FetchFault a) -> IO a -> IO (Either FetchFault a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Request
-> (Status -> ResponseHeaders -> IO (Maybe RetryAfter)) -> IO a
action Request
request (\Status
_ ResponseHeaders
_ -> Maybe RetryAfter -> IO (Maybe RetryAfter)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe RetryAfter
forall a. Maybe a
Nothing)
withReadControl (Controlled PublicControl
control PublicReadKind
kind) Request
request Request
-> (Status -> ResponseHeaders -> IO (Maybe RetryAfter)) -> IO a
action = case Text -> Maybe HostPort
hostPortAddress Text
authority of
    Maybe HostPort
Nothing -> Either FetchFault a -> IO (Either FetchFault a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (FetchFault -> Either FetchFault a
forall a b. a -> Either a b
Left (UrlFormationError -> FetchFault
FetchUrlUnformable (Text -> UrlFormationError
UnparseableUrl Text
authority)))
    Just HostPort
target -> (Either RetryAfter a -> Either FetchFault a)
-> IO (Either RetryAfter a) -> IO (Either FetchFault a)
forall a b. (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((RetryAfter -> FetchFault)
-> Either RetryAfter a -> Either FetchFault a
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first RetryAfter -> FetchFault
FetchCooldown) (IO (Either RetryAfter a) -> IO (Either FetchFault a))
-> IO (Either RetryAfter a) -> IO (Either FetchFault a)
forall a b. (a -> b) -> a -> b
$ PublicBackoff
-> HostPort -> (PublicAttempt -> IO a) -> IO (Either RetryAfter a)
forall a.
PublicBackoff
-> HostPort -> (PublicAttempt -> IO a) -> IO (Either RetryAfter a)
withPublicAttempt (PublicControl -> PublicBackoff
pcBackoff PublicControl
control) HostPort
target ((PublicAttempt -> IO a) -> IO (Either RetryAfter a))
-> (PublicAttempt -> IO a) -> IO (Either RetryAfter a)
forall a b. (a -> b) -> a -> b
$ \PublicAttempt
attempt ->
        (ExchangeOutcome -> IO ())
-> Request -> (Request -> (Status -> IO ()) -> IO a) -> IO a
forall a.
(ExchangeOutcome -> IO ())
-> Request -> (Request -> (Status -> IO ()) -> IO a) -> IO a
observeExchange (PublicControl -> Text -> PublicReadKind -> ExchangeOutcome -> IO ()
pcRecord PublicControl
control (HostPort -> Text
hpHost HostPort
target) PublicReadKind
kind) Request
request ((Request -> (Status -> IO ()) -> IO a) -> IO a)
-> (Request -> (Status -> IO ()) -> IO a) -> IO a
forall a b. (a -> b) -> a -> b
$ \Request
observed Status -> IO ()
recordHeaders ->
            Request
-> (Status -> ResponseHeaders -> IO (Maybe RetryAfter)) -> IO a
action Request
observed ((Status -> ResponseHeaders -> IO (Maybe RetryAfter)) -> IO a)
-> (Status -> ResponseHeaders -> IO (Maybe RetryAfter)) -> IO a
forall a b. (a -> b) -> a -> b
$ \Status
status ResponseHeaders
headers -> do
                Status -> IO ()
recordHeaders Status
status
                now <- PublicControl -> IO UTCTime
pcClock PublicControl
control
                let response = UTCTime -> Status -> ResponseHeaders -> PublicResponse
classifyPublicResponse UTCTime
now Status
status ResponseHeaders
headers
                recordPublicResponse attempt response
                case response of
                    PublicResponse
NonThrottling -> Maybe RetryAfter -> IO (Maybe RetryAfter)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe RetryAfter
forall a. Maybe a
Nothing
                    Throttled Maybe RetryAfter
_ -> PublicBackoff -> HostPort -> IO (Maybe RetryAfter)
publicRetryAfter (PublicControl -> PublicBackoff
pcBackoff PublicControl
control) HostPort
target
  where
    authority :: Text
authority = Text -> Int -> Text
hostPortLabel (ByteString -> Text
forall a b. ConvertUtf8 a b => b -> a
decodeUtf8 (Request -> ByteString
host Request
request)) (Request -> Int
port Request
request)

-- | Every 429 cools down. A 503 does so only with a valid positive hint, capped at ten minutes.
classifyPublicResponse :: UTCTime -> Status -> ResponseHeaders -> PublicResponse
classifyPublicResponse :: UTCTime -> Status -> ResponseHeaders -> PublicResponse
classifyPublicResponse UTCTime
now Status
status ResponseHeaders
headers =
    case (Status -> Int
statusCode Status
status, UTCTime -> RetryAfter -> Maybe ByteString -> Maybe RetryAfter
parseRetryAfter UTCTime
now RetryAfter
upstreamRetryCap (HeaderName -> ResponseHeaders -> Maybe ByteString
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup HeaderName
"Retry-After" ResponseHeaders
headers)) of
        (Int
429, Maybe RetryAfter
hint) -> Maybe RetryAfter -> PublicResponse
Throttled Maybe RetryAfter
hint
        (Int
503, Just RetryAfter
hint) -> Maybe RetryAfter -> PublicResponse
Throttled (RetryAfter -> Maybe RetryAfter
forall a. a -> Maybe a
Just RetryAfter
hint)
        (Int, Maybe RetryAfter)
_ -> PublicResponse
NonThrottling