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

{- | The implementation behind "Ecluse.Core.Credential.Refresh", which documents the policy
and re-exports the curated surface. Importing this module opts out of that stability promise,
the convention @text@ and @bytestring@ use, so production code imports the public one.
-}
module Ecluse.Core.Credential.Refresh.Internal (
    -- * Configuration
    RefreshConfig (..),
    defaultRefreshConfig,

    -- * The refreshing provider
    refreshingProvider,
    refreshingProviderWith,

    -- * Telemetry reporters
    RefreshReporter (..),
    noRefreshReporter,
    CredentialReporters (..),
    noCredentialReporters,

    -- * Failure
    CredentialError (..),

    -- * State and pure\/transition helpers (exposed for direct testing)
    CacheState (..),
    MintClaim,
    ServeAction (..),
    decide,
    refreshDueAt,
    onMintSuccess,
    onMintFailure,
    releaseSingleFlight,
) where

import Control.Concurrent.STM (retry)
import Data.Ord (clamp)
import Data.Time (NominalDiffTime, UTCTime, addUTCTime, diffUTCTime)
import UnliftIO (asyncWithUnmask, throwIO, try)
import UnliftIO.Exception (mask, onException)

import Ecluse.Core.Breaker (
    Attempt,
    Breaker,
    BreakerPhase (HalfOpen),
    BreakerReporter,
    admit,
    breakerPhase,
    initialBreaker,
    noBreakerReporter,
    recordFailure,
    recordSuccess,
    release,
    reportBreakerChange,
 )
import Ecluse.Core.Credential (AuthToken (..), CredentialProvider (..))
import Ecluse.Core.InFlight (guardInFlight)

-- | A failure from credential minting or refresh policy.
data CredentialError
    = -- | The token expired with the mint breaker open, so no mint was attempted.
      BreakerOpen
    | -- | An effectful leaf still holds its 'defaultRefreshConfig' placeholder.
      Unconfigured Text
    | -- | An already-expired mint is treated as a mint failure.
      MintedTokenAlreadyExpired
    deriving stock (CredentialError -> CredentialError -> Bool
(CredentialError -> CredentialError -> Bool)
-> (CredentialError -> CredentialError -> Bool)
-> Eq CredentialError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: CredentialError -> CredentialError -> Bool
== :: CredentialError -> CredentialError -> Bool
$c/= :: CredentialError -> CredentialError -> Bool
/= :: CredentialError -> CredentialError -> Bool
Eq, Int -> CredentialError -> ShowS
[CredentialError] -> ShowS
CredentialError -> String
(Int -> CredentialError -> ShowS)
-> (CredentialError -> String)
-> ([CredentialError] -> ShowS)
-> Show CredentialError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CredentialError -> ShowS
showsPrec :: Int -> CredentialError -> ShowS
$cshow :: CredentialError -> String
show :: CredentialError -> String
$cshowList :: [CredentialError] -> ShowS
showList :: [CredentialError] -> ShowS
Show)

instance Exception CredentialError

-- | Observe refresh outcomes with the active token's absolute expiry, absent for non-expiring tokens.
data RefreshReporter = RefreshReporter
    { RefreshReporter -> Maybe UTCTime -> IO ()
onRefreshSucceeded :: Maybe UTCTime -> IO ()
    -- ^ A mint succeeded, with the new token's absolute expiry.
    , RefreshReporter -> Maybe UTCTime -> IO ()
onRefreshFailed :: Maybe UTCTime -> IO ()
    -- ^ A mint failed, with the still-cached token's absolute expiry.
    }

-- | The inert refresh reporter: records nothing on either outcome.
noRefreshReporter :: RefreshReporter
noRefreshReporter :: RefreshReporter
noRefreshReporter = (Maybe UTCTime -> IO ())
-> (Maybe UTCTime -> IO ()) -> RefreshReporter
RefreshReporter (IO () -> Maybe UTCTime -> IO ()
forall a b. a -> b -> a
const IO ()
forall (f :: * -> *). Applicative f => f ()
pass) (IO () -> Maybe UTCTime -> IO ()
forall a b. a -> b -> a
const IO ()
forall (f :: * -> *). Applicative f => f ()
pass)

-- | The telemetry observers a refreshing provider records through, bundled into one value.
data CredentialReporters = CredentialReporters
    { CredentialReporters -> BreakerReporter
crBreakerReporter :: BreakerReporter
    -- ^ Observes the mint breaker's state transitions (@ecluse.rule.breaker.state@).
    , CredentialReporters -> RefreshReporter
crRefreshReporter :: RefreshReporter
    -- ^ Observes each refresh outcome (@ecluse.credential.refresh@ \/ @.token.ttl@).
    }

-- | The inert pair: a provider built with it records nothing on either signal.
noCredentialReporters :: CredentialReporters
noCredentialReporters :: CredentialReporters
noCredentialReporters = BreakerReporter -> RefreshReporter -> CredentialReporters
CredentialReporters BreakerReporter
noBreakerReporter RefreshReporter
noRefreshReporter

-- | Refresh policy with injected mint, clock, jitter and observers.
data RefreshConfig = RefreshConfig
    { RefreshConfig -> IO AuthToken
rcMint :: IO AuthToken
    -- ^ The per-cloud token mint, the __only__ part that touches a network.
    , RefreshConfig -> IO UTCTime
rcClock :: IO UTCTime
    -- ^ Injected so a test drives refresh timing without real time passing.
    , RefreshConfig -> IO Double
rcJitter :: IO Double
    -- ^ A fraction in @[0, 1)@, sampled per token to advance refresh.
    , RefreshConfig -> Double
rcRefreshAt :: Double
    -- ^ The fraction of a token's lifetime to refresh at, before jitter. Clamped to @[0, 1]@.
    , RefreshConfig -> NominalDiffTime
rcRefreshFloor :: NominalDiffTime
    -- ^ Seconds before expiry that bound the latest refresh instant.
    , RefreshConfig -> Int
rcBreakerThreshold :: Int
    -- ^ Consecutive mint failures that trip the circuit breaker.
    , RefreshConfig -> NominalDiffTime
rcBreakerCooldown :: NominalDiffTime
    -- ^ Cooldown in seconds before one owned recovery mint.
    , RefreshConfig -> CredentialReporters
rcReporters :: CredentialReporters
    -- ^ Inert by default. The composition root installs the live pair.
    }

-- | Default policy knobs. Unwired 'rcMint' and 'rcClock' throw 'Unconfigured'.
defaultRefreshConfig :: RefreshConfig
defaultRefreshConfig :: RefreshConfig
defaultRefreshConfig =
    RefreshConfig
        { rcMint :: IO AuthToken
rcMint = Text -> IO AuthToken
forall a. Text -> IO a
unconfigured Text
"rcMint"
        , rcClock :: IO UTCTime
rcClock = Text -> IO UTCTime
forall a. Text -> IO a
unconfigured Text
"rcClock"
        , rcJitter :: IO Double
rcJitter = Double -> IO Double
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Double
0
        , rcRefreshAt :: Double
rcRefreshAt = Double
0.8
        , rcRefreshFloor :: NominalDiffTime
rcRefreshFloor = NominalDiffTime
30
        , rcBreakerThreshold :: Int
rcBreakerThreshold = Int
5
        , rcBreakerCooldown :: NominalDiffTime
rcBreakerCooldown = NominalDiffTime
60
        , rcReporters :: CredentialReporters
rcReporters = CredentialReporters
noCredentialReporters
        }
  where
    unconfigured :: Text -> IO a
    unconfigured :: forall a. Text -> IO a
unconfigured Text
field = CredentialError -> IO a
forall (m :: * -> *) e a. (MonadIO m, Exception e) => e -> m a
throwIO (Text -> CredentialError
Unconfigured Text
field)

-- | The mutable state of a refreshing provider.
data CacheState = CacheState
    { CacheState -> AuthToken
csToken :: AuthToken
    -- ^ The token currently served.
    , CacheState -> Maybe UTCTime
csRefreshDue :: Maybe UTCTime
    -- ^ When the background refresh fires. 'Nothing' for a token with no expiry.
    , CacheState -> Maybe MintClaim
csMintClaim :: Maybe MintClaim
    -- ^ The current mint owner, absent when idle.
    , CacheState -> Integer
csClaimCounter :: Integer
    -- ^ Retained across cleanup to fence older mint owners.
    , CacheState -> Breaker
csBreaker :: Breaker
    -- ^ The circuit-breaker state.
    }

-- | Build a cached provider, minting eagerly so an initial mint failure aborts construction.
refreshingProvider :: RefreshConfig -> IO CredentialProvider
refreshingProvider :: RefreshConfig -> IO CredentialProvider
refreshingProvider = IO () -> RefreshConfig -> IO CredentialProvider
refreshingProviderWith (() -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ())

-- | Add a test hook between the single-flight claim and the mint runner.
refreshingProviderWith :: IO () -> RefreshConfig -> IO CredentialProvider
refreshingProviderWith :: IO () -> RefreshConfig -> IO CredentialProvider
refreshingProviderWith IO ()
afterClaim RefreshConfig
cfg = do
    now <- RefreshConfig -> IO UTCTime
rcClock RefreshConfig
cfg
    token <- rcMint cfg
    due <- refreshDueAt cfg now token
    stateVar <- newTVarIO (CacheState token due Nothing 0 initialBreaker)
    pure CredentialProvider{currentToken = serve afterClaim cfg stateVar}

-- | A mint identity and its atomically admitted breaker ticket.
data MintClaim = MintClaim Integer Attempt Breaker Breaker
    deriving stock (MintClaim -> MintClaim -> Bool
(MintClaim -> MintClaim -> Bool)
-> (MintClaim -> MintClaim -> Bool) -> Eq MintClaim
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: MintClaim -> MintClaim -> Bool
== :: MintClaim -> MintClaim -> Bool
$c/= :: MintClaim -> MintClaim -> Bool
/= :: MintClaim -> MintClaim -> Bool
Eq, Int -> MintClaim -> ShowS
[MintClaim] -> ShowS
MintClaim -> String
(Int -> MintClaim -> ShowS)
-> (MintClaim -> String)
-> ([MintClaim] -> ShowS)
-> Show MintClaim
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> MintClaim -> ShowS
showsPrec :: Int -> MintClaim -> ShowS
$cshow :: MintClaim -> String
show :: MintClaim -> String
$cshowList :: [MintClaim] -> ShowS
showList :: [MintClaim] -> ShowS
Show)

-- | Whether a caller serves the cache, owns a mint, or receives a breaker refusal.
data ServeAction
    = -- | Serve a valid cached token.
      ServeCached AuthToken
    | -- | Serve the token and transfer the claim to a background worker.
      ServeAndRefresh AuthToken MintClaim
    | -- | Run the claimed mint synchronously for an expired token.
      MintNow MintClaim
    | -- | Refuse an expired caller during cooldown or owned recovery.
      RefuseMint
    deriving stock (ServeAction -> ServeAction -> Bool
(ServeAction -> ServeAction -> Bool)
-> (ServeAction -> ServeAction -> Bool) -> Eq ServeAction
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ServeAction -> ServeAction -> Bool
== :: ServeAction -> ServeAction -> Bool
$c/= :: ServeAction -> ServeAction -> Bool
/= :: ServeAction -> ServeAction -> Bool
Eq, Int -> ServeAction -> ShowS
[ServeAction] -> ShowS
ServeAction -> String
(Int -> ServeAction -> ShowS)
-> (ServeAction -> String)
-> ([ServeAction] -> ShowS)
-> Show ServeAction
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ServeAction -> ShowS
showsPrec :: Int -> ServeAction -> ShowS
$cshow :: ServeAction -> String
show :: ServeAction -> String
$cshowList :: [ServeAction] -> ShowS
showList :: [ServeAction] -> ShowS
Show)

serve :: IO () -> RefreshConfig -> TVar CacheState -> IO AuthToken
serve :: IO () -> RefreshConfig -> TVar CacheState -> IO AuthToken
serve IO ()
afterClaim RefreshConfig
cfg TVar CacheState
stateVar = ((forall a. IO a -> IO a) -> IO AuthToken) -> IO AuthToken
forall (m :: * -> *) b.
MonadUnliftIO m =>
((forall a. m a -> m a) -> m b) -> m b
mask (((forall a. IO a -> IO a) -> IO AuthToken) -> IO AuthToken)
-> ((forall a. IO a -> IO a) -> IO AuthToken) -> IO AuthToken
forall a b. (a -> b) -> a -> b
$ \forall a. IO a -> IO a
restore -> do
    now <- RefreshConfig -> IO UTCTime
rcClock RefreshConfig
cfg
    atomically (decide stateVar now) >>= \case
        ServeCached AuthToken
token -> AuthToken -> IO AuthToken
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure AuthToken
token
        ServeAndRefresh AuthToken
token MintClaim
claim -> AuthToken
token AuthToken -> IO () -> IO AuthToken
forall a b. a -> IO b -> IO a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ IO () -> RefreshConfig -> TVar CacheState -> MintClaim -> IO ()
forkRefresh IO ()
afterClaim RefreshConfig
cfg TVar CacheState
stateVar MintClaim
claim
        MintNow MintClaim
claim ->
            (IO AuthToken -> IO AuthToken)
-> (SomeException -> IO ())
-> IO ()
-> IO AuthToken
-> IO AuthToken
forall a.
(IO a -> IO a) -> (SomeException -> IO ()) -> IO () -> IO a -> IO a
guardInFlight IO AuthToken -> IO AuthToken
forall a. IO a -> IO a
restore (IO () -> SomeException -> IO ()
forall a b. a -> b -> a
const IO ()
forall (f :: * -> *). Applicative f => f ()
pass) (TVar CacheState -> MintClaim -> IO ()
releaseSingleFlight TVar CacheState
stateVar MintClaim
claim) (IO AuthToken -> IO AuthToken) -> IO AuthToken -> IO AuthToken
forall a b. (a -> b) -> a -> b
$
                IO () -> RefreshConfig -> MintClaim -> IO ()
startMint IO ()
afterClaim RefreshConfig
cfg MintClaim
claim IO () -> IO AuthToken -> IO AuthToken
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> RefreshConfig -> TVar CacheState -> MintClaim -> IO AuthToken
mintSynchronously RefreshConfig
cfg TVar CacheState
stateVar MintClaim
claim
        ServeAction
RefuseMint -> CredentialError -> IO AuthToken
forall (m :: * -> *) e a. (MonadIO m, Exception e) => e -> m a
throwIO CredentialError
BreakerOpen

forkRefresh :: IO () -> RefreshConfig -> TVar CacheState -> MintClaim -> IO ()
forkRefresh :: IO () -> RefreshConfig -> TVar CacheState -> MintClaim -> IO ()
forkRefresh IO ()
afterClaim RefreshConfig
cfg TVar CacheState
stateVar MintClaim
claim =
    IO (Async ()) -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void
        ( ((forall a. IO a -> IO a) -> IO ()) -> IO (Async ())
forall (m :: * -> *) a.
MonadUnliftIO m =>
((forall b. m b -> m b) -> m a) -> m (Async a)
asyncWithUnmask (((forall a. IO a -> IO a) -> IO ()) -> IO (Async ()))
-> ((forall a. IO a -> IO a) -> IO ()) -> IO (Async ())
forall a b. (a -> b) -> a -> b
$ \forall a. IO a -> IO a
unmask ->
            (IO () -> IO ())
-> (SomeException -> IO ()) -> IO () -> IO () -> IO ()
forall a.
(IO a -> IO a) -> (SomeException -> IO ()) -> IO () -> IO a -> IO a
guardInFlight IO () -> IO ()
forall a. IO a -> IO a
unmask (IO () -> SomeException -> IO ()
forall a b. a -> b -> a
const IO ()
forall (f :: * -> *). Applicative f => f ()
pass) (TVar CacheState -> MintClaim -> IO ()
releaseSingleFlight TVar CacheState
stateVar MintClaim
claim) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
                IO () -> RefreshConfig -> MintClaim -> IO ()
startMint IO ()
afterClaim RefreshConfig
cfg MintClaim
claim IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> IO MintOutcome -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (RefreshConfig -> TVar CacheState -> MintClaim -> IO MintOutcome
attemptMint RefreshConfig
cfg TVar CacheState
stateVar MintClaim
claim)
        )
        IO () -> IO () -> IO ()
forall (m :: * -> *) a b. MonadUnliftIO m => m a -> m b -> m a
`onException` TVar CacheState -> MintClaim -> IO ()
releaseSingleFlight TVar CacheState
stateVar MintClaim
claim

startMint :: IO () -> RefreshConfig -> MintClaim -> IO ()
startMint :: IO () -> RefreshConfig -> MintClaim -> IO ()
startMint IO ()
afterClaim RefreshConfig
cfg (MintClaim Integer
_ Attempt
_ Breaker
old Breaker
new) = do
    IO ()
afterClaim
    BreakerReporter -> Breaker -> Breaker -> IO ()
reportBreakerChange (CredentialReporters -> BreakerReporter
crBreakerReporter (RefreshConfig -> CredentialReporters
rcReporters RefreshConfig
cfg)) Breaker
old Breaker
new

-- | Claim mint and breaker ownership together. Healthy expired followers wait, recovery followers refuse.
decide :: TVar CacheState -> UTCTime -> STM ServeAction
decide :: TVar CacheState -> UTCTime -> STM ServeAction
decide TVar CacheState
stateVar UTCTime
now = do
    st <- TVar CacheState -> STM CacheState
forall a. TVar a -> STM a
readTVar TVar CacheState
stateVar
    if not (tokenValid now (csToken st))
        then case csMintClaim st of
            Just MintClaim
_ | Breaker -> BreakerPhase
breakerPhase (CacheState -> Breaker
csBreaker CacheState
st) BreakerPhase -> BreakerPhase -> Bool
forall a. Eq a => a -> a -> Bool
== BreakerPhase
HalfOpen -> ServeAction -> STM ServeAction
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ServeAction
RefuseMint
            Just MintClaim
_ -> STM ServeAction
forall a. STM a
retry
            Maybe MintClaim
Nothing -> TVar CacheState
-> UTCTime
-> CacheState
-> (MintClaim -> ServeAction)
-> ServeAction
-> STM ServeAction
claimMint TVar CacheState
stateVar UTCTime
now CacheState
st MintClaim -> ServeAction
MintNow ServeAction
RefuseMint
        else
            if refreshNeeded now st && isNothing (csMintClaim st)
                then claimMint stateVar now st (ServeAndRefresh (csToken st)) (ServeCached (csToken st))
                else pure (ServeCached (csToken st))

claimMint :: TVar CacheState -> UTCTime -> CacheState -> (MintClaim -> ServeAction) -> ServeAction -> STM ServeAction
claimMint :: TVar CacheState
-> UTCTime
-> CacheState
-> (MintClaim -> ServeAction)
-> ServeAction
-> STM ServeAction
claimMint TVar CacheState
stateVar UTCTime
now CacheState
st MintClaim -> ServeAction
claimed ServeAction
refused = case UTCTime -> Breaker -> (Maybe Attempt, Breaker)
admit UTCTime
now (CacheState -> Breaker
csBreaker CacheState
st) of
    (Maybe Attempt
Nothing, Breaker
_) -> ServeAction -> STM ServeAction
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ServeAction
refused
    (Just Attempt
ticket, Breaker
breaker) -> do
        let next :: Integer
next = CacheState -> Integer
csClaimCounter CacheState
st Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
1
            claim :: MintClaim
claim = Integer -> Attempt -> Breaker -> Breaker -> MintClaim
MintClaim Integer
next Attempt
ticket (CacheState -> Breaker
csBreaker CacheState
st) Breaker
breaker
        TVar CacheState -> CacheState -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar TVar CacheState
stateVar CacheState
st{csMintClaim = Just claim, csClaimCounter = next, csBreaker = breaker}
        ServeAction -> STM ServeAction
forall a. a -> STM a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (MintClaim -> ServeAction
claimed MintClaim
claim)

data MintOutcome
    = Minted AuthToken
    | MintedExpired
    | MintThrew SomeException

attemptMint :: RefreshConfig -> TVar CacheState -> MintClaim -> IO MintOutcome
attemptMint :: RefreshConfig -> TVar CacheState -> MintClaim -> IO MintOutcome
attemptMint RefreshConfig
cfg TVar CacheState
stateVar MintClaim
claim = do
    result <- IO AuthToken -> IO (Either SomeException AuthToken)
forall (m :: * -> *) e a.
(MonadUnliftIO m, Exception e) =>
m a -> m (Either e a)
try (RefreshConfig -> IO AuthToken
rcMint RefreshConfig
cfg)
    now <- rcClock cfg
    case result of
        Right AuthToken
token | UTCTime -> AuthToken -> Bool
tokenValid UTCTime
now AuthToken
token -> do
            due <- RefreshConfig -> UTCTime -> AuthToken -> IO (Maybe UTCTime)
refreshDueAt RefreshConfig
cfg UTCTime
now AuthToken
token
            committed <- commitBreakerFold cfg stateVar claim (onMintSuccess claim token due)
            when committed (onRefreshSucceeded (crRefreshReporter (rcReporters cfg)) (authExpiresAt token))
            pure (Minted token)
        Right AuthToken
_ -> do
            RefreshConfig -> TVar CacheState -> MintClaim -> UTCTime -> IO ()
recordMintFailure RefreshConfig
cfg TVar CacheState
stateVar MintClaim
claim UTCTime
now
            MintOutcome -> IO MintOutcome
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure MintOutcome
MintedExpired
        Left (SomeException
e :: SomeException) -> do
            RefreshConfig -> TVar CacheState -> MintClaim -> UTCTime -> IO ()
recordMintFailure RefreshConfig
cfg TVar CacheState
stateVar MintClaim
claim UTCTime
now
            MintOutcome -> IO MintOutcome
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (SomeException -> MintOutcome
MintThrew SomeException
e)

mintSynchronously :: RefreshConfig -> TVar CacheState -> MintClaim -> IO AuthToken
mintSynchronously :: RefreshConfig -> TVar CacheState -> MintClaim -> IO AuthToken
mintSynchronously RefreshConfig
cfg TVar CacheState
stateVar MintClaim
claim =
    RefreshConfig -> TVar CacheState -> MintClaim -> IO MintOutcome
attemptMint RefreshConfig
cfg TVar CacheState
stateVar MintClaim
claim IO MintOutcome -> (MintOutcome -> IO AuthToken) -> IO AuthToken
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
        Minted AuthToken
token -> AuthToken -> IO AuthToken
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure AuthToken
token
        MintOutcome
MintedExpired -> CredentialError -> IO AuthToken
forall (m :: * -> *) e a. (MonadIO m, Exception e) => e -> m a
throwIO CredentialError
MintedTokenAlreadyExpired
        MintThrew SomeException
e -> SomeException -> IO AuthToken
forall (m :: * -> *) e a. (MonadIO m, Exception e) => e -> m a
throwIO SomeException
e

-- | Release only this mint's ownership and its unsettled recovery ticket, on every exit.
releaseSingleFlight :: TVar CacheState -> MintClaim -> IO ()
releaseSingleFlight :: TVar CacheState -> MintClaim -> IO ()
releaseSingleFlight TVar CacheState
stateVar claim :: MintClaim
claim@(MintClaim Integer
_ Attempt
ticket Breaker
_ Breaker
_) = STM () -> IO ()
forall (m :: * -> *) a. MonadIO m => STM a -> m a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$
    TVar CacheState -> (CacheState -> CacheState) -> STM ()
forall a. TVar a -> (a -> a) -> STM ()
modifyTVar' TVar CacheState
stateVar ((CacheState -> CacheState) -> STM ())
-> (CacheState -> CacheState) -> STM ()
forall a b. (a -> b) -> a -> b
$ \CacheState
st ->
        if CacheState -> Maybe MintClaim
csMintClaim CacheState
st Maybe MintClaim -> Maybe MintClaim -> Bool
forall a. Eq a => a -> a -> Bool
== MintClaim -> Maybe MintClaim
forall a. a -> Maybe a
Just MintClaim
claim
            then CacheState
st{csMintClaim = Nothing, csBreaker = release ticket (csBreaker st)}
            else CacheState
st

recordMintFailure :: RefreshConfig -> TVar CacheState -> MintClaim -> UTCTime -> IO ()
recordMintFailure :: RefreshConfig -> TVar CacheState -> MintClaim -> UTCTime -> IO ()
recordMintFailure RefreshConfig
cfg TVar CacheState
stateVar MintClaim
claim UTCTime
now = do
    cached <- CacheState -> AuthToken
csToken (CacheState -> AuthToken) -> IO CacheState -> IO AuthToken
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TVar CacheState -> IO CacheState
forall (m :: * -> *) a. MonadIO m => TVar a -> m a
readTVarIO TVar CacheState
stateVar
    committed <- commitBreakerFold cfg stateVar claim (onMintFailure claim cfg now)
    when committed (onRefreshFailed (crRefreshReporter (rcReporters cfg)) (authExpiresAt cached))

commitBreakerFold :: RefreshConfig -> TVar CacheState -> MintClaim -> (CacheState -> CacheState) -> IO Bool
commitBreakerFold :: RefreshConfig
-> TVar CacheState
-> MintClaim
-> (CacheState -> CacheState)
-> IO Bool
commitBreakerFold RefreshConfig
cfg TVar CacheState
stateVar MintClaim
claim CacheState -> CacheState
step = do
    (committed, old, new) <- STM (Bool, Breaker, Breaker) -> IO (Bool, Breaker, Breaker)
forall (m :: * -> *) a. MonadIO m => STM a -> m a
atomically (STM (Bool, Breaker, Breaker) -> IO (Bool, Breaker, Breaker))
-> STM (Bool, Breaker, Breaker) -> IO (Bool, Breaker, Breaker)
forall a b. (a -> b) -> a -> b
$ do
        st <- TVar CacheState -> STM CacheState
forall a. TVar a -> STM a
readTVar TVar CacheState
stateVar
        let matches = CacheState -> Maybe MintClaim
csMintClaim CacheState
st Maybe MintClaim -> Maybe MintClaim -> Bool
forall a. Eq a => a -> a -> Bool
== MintClaim -> Maybe MintClaim
forall a. a -> Maybe a
Just MintClaim
claim
            st' = if Bool
matches then CacheState -> CacheState
step CacheState
st else CacheState
st
        writeTVar stateVar st'
        pure (matches, csBreaker st, csBreaker st')
    reportBreakerChange (crBreakerReporter (rcReporters cfg)) old new
    pure committed

-- | Install a matching owner's token and settle its breaker. Cleanup releases the mint claim.
onMintSuccess :: MintClaim -> AuthToken -> Maybe UTCTime -> CacheState -> CacheState
onMintSuccess :: MintClaim -> AuthToken -> Maybe UTCTime -> CacheState -> CacheState
onMintSuccess claim :: MintClaim
claim@(MintClaim Integer
_ Attempt
ticket Breaker
_ Breaker
_) AuthToken
token Maybe UTCTime
due CacheState
st
    | CacheState -> Maybe MintClaim
csMintClaim CacheState
st Maybe MintClaim -> Maybe MintClaim -> Bool
forall a. Eq a => a -> a -> Bool
== MintClaim -> Maybe MintClaim
forall a. a -> Maybe a
Just MintClaim
claim =
        CacheState
st{csToken = token, csRefreshDue = due, csBreaker = recordSuccess ticket (csBreaker st)}
    | Bool
otherwise = CacheState
st

-- | Count a matching owner's genuine failure without replacing the cached token.
onMintFailure :: MintClaim -> RefreshConfig -> UTCTime -> CacheState -> CacheState
onMintFailure :: MintClaim -> RefreshConfig -> UTCTime -> CacheState -> CacheState
onMintFailure claim :: MintClaim
claim@(MintClaim Integer
_ Attempt
ticket Breaker
_ Breaker
_) RefreshConfig
cfg UTCTime
now CacheState
st
    | CacheState -> Maybe MintClaim
csMintClaim CacheState
st Maybe MintClaim -> Maybe MintClaim -> Bool
forall a. Eq a => a -> a -> Bool
== MintClaim -> Maybe MintClaim
forall a. a -> Maybe a
Just MintClaim
claim =
        CacheState
st{csBreaker = recordFailure (rcBreakerThreshold cfg) (rcBreakerCooldown cfg) now ticket (csBreaker st)}
    | Bool
otherwise = CacheState
st

tokenValid :: UTCTime -> AuthToken -> Bool
tokenValid :: UTCTime -> AuthToken -> Bool
tokenValid UTCTime
now AuthToken
token = case AuthToken -> Maybe UTCTime
authExpiresAt AuthToken
token of
    Maybe UTCTime
Nothing -> Bool
True
    Just UTCTime
expiry -> UTCTime
now UTCTime -> UTCTime -> Bool
forall a. Ord a => a -> a -> Bool
< UTCTime
expiry

refreshNeeded :: UTCTime -> CacheState -> Bool
refreshNeeded :: UTCTime -> CacheState -> Bool
refreshNeeded UTCTime
now CacheState
st = case CacheState -> Maybe UTCTime
csRefreshDue CacheState
st of
    Maybe UTCTime
Nothing -> Bool
False
    Just UTCTime
due -> UTCTime
now UTCTime -> UTCTime -> Bool
forall a. Ord a => a -> a -> Bool
>= UTCTime
due

-- | Jitter advances the refresh fraction. The floor bounds the latest instant before expiry.
refreshDueAt :: RefreshConfig -> UTCTime -> AuthToken -> IO (Maybe UTCTime)
refreshDueAt :: RefreshConfig -> UTCTime -> AuthToken -> IO (Maybe UTCTime)
refreshDueAt RefreshConfig
cfg UTCTime
issuedAt AuthToken
token = case AuthToken -> Maybe UTCTime
authExpiresAt AuthToken
token of
    Maybe UTCTime
Nothing -> Maybe UTCTime -> IO (Maybe UTCTime)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe UTCTime
forall a. Maybe a
Nothing
    Just UTCTime
expiry -> do
        jitter <- RefreshConfig -> IO Double
rcJitter RefreshConfig
cfg
        let lifetime = NominalDiffTime -> Double
forall a b. (Real a, Fractional b) => a -> b
realToFrac (UTCTime -> UTCTime -> NominalDiffTime
diffUTCTime UTCTime
expiry UTCTime
issuedAt) :: Double
            frac = Double -> Double
clamp01 (RefreshConfig -> Double
rcRefreshAt RefreshConfig
cfg Double -> Double -> Double
forall a. Num a => a -> a -> a
- Double -> Double
clamp01 Double
jitter)
            byFraction = NominalDiffTime -> UTCTime -> UTCTime
addUTCTime (Double -> NominalDiffTime
forall a b. (Real a, Fractional b) => a -> b
realToFrac (Double
frac Double -> Double -> Double
forall a. Num a => a -> a -> a
* Double
lifetime)) UTCTime
issuedAt
            floorInstant = NominalDiffTime -> UTCTime -> UTCTime
addUTCTime (NominalDiffTime -> NominalDiffTime
forall a. Num a => a -> a
negate (RefreshConfig -> NominalDiffTime
rcRefreshFloor RefreshConfig
cfg)) UTCTime
expiry
            -- Never later than the floor before expiry, never before issue.
            due = UTCTime -> UTCTime -> UTCTime
forall a. Ord a => a -> a -> a
max UTCTime
issuedAt (UTCTime -> UTCTime -> UTCTime
forall a. Ord a => a -> a -> a
min UTCTime
byFraction UTCTime
floorInstant)
        pure (Just due)
  where
    clamp01 :: Double -> Double
    clamp01 :: Double -> Double
clamp01 = (Double, Double) -> Double -> Double
forall a. Ord a => (a, a) -> a -> a
clamp (Double
0, Double
1)