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

{- | Shared weighted admission for serve slots and publish bytes.
A bounded waiting room prevents newcomers from bypassing queued requests. Wake order is not FIFO.
The room's wait runs on the deadline sweeper, and each freed place wakes the gate's overflow line.
-}
module Ecluse.Core.Server.Admission.Weighted (
    WeightedAdmission,
    weightedAdmissionWaiting,
    weightedAdmissionLine,
    newWeightedAdmission,
    withWeightedAdmission,
    AdmissionObservers (..),
    admissionWaitMicros,
) where

import Control.Concurrent.STM (retry)
import UnliftIO (MonadUnliftIO)
import UnliftIO.Exception qualified as UE

import Ecluse.Core.Deadline (Deadlines, withDeadlineFlag)
import Ecluse.Core.Server.Admission.Overflow (Line, newLine, signalLine)
import Ecluse.Core.Server.Admission.Types (Shed (..))

-- | Capacity and waiting-room state. Only the controller can mutate these fields.
data WeightedAdmission = WeightedAdmission
    { WeightedAdmission -> TVar Int
waAvailable :: TVar Int
    , WeightedAdmission -> TVar Int
waWaiting :: TVar Int
    , WeightedAdmission -> Int
waWaitingRoom :: Int
    , WeightedAdmission -> Int
waWaitMicros :: Int
    , WeightedAdmission -> Deadlines
waDeadlines :: Deadlines
    , WeightedAdmission -> Line
waLine :: Line
    -- ^ Requests this gate turned away at a full room, woken as places free.
    }

-- | Admission observers, independent of the telemetry vocabulary.
data AdmissionObservers = AdmissionObservers
    { AdmissionObservers -> IO ()
onQueued :: IO ()
    -- ^ Runs after a queued request acquires capacity, not when it registers.
    , AdmissionObservers -> IO ()
onShed :: IO ()
    -- ^ Records a refusal at the door or an expired wait.
    , AdmissionObservers -> Int -> IO ()
onInFlightDelta :: Int -> IO ()
    -- ^ Records signed weight under the acquisition mask.
    }

-- | Wait one second, matching the shed response Retry-After hint.
admissionWaitMicros :: Int
admissionWaitMicros :: Int
admissionWaitMicros = Int
1_000_000

{- | Keep capacity verbatim and clamp the room and microsecond wait budget at zero. A positive wait
ends on a sweep of the deadlines, so a fixture that never waits one out may leave them unswept.
-}
newWeightedAdmission :: Deadlines -> Int -> Int -> Int -> IO WeightedAdmission
newWeightedAdmission :: Deadlines -> Int -> Int -> Int -> IO WeightedAdmission
newWeightedAdmission Deadlines
deadlines Int
capacity Int
room Int
waitMicros = do
    available <- Int -> IO (TVar Int)
forall (m :: * -> *) a. MonadIO m => a -> m (TVar a)
newTVarIO Int
capacity
    waiting <- newTVarIO 0
    line <- newLine
    pure
        WeightedAdmission
            { waAvailable = available
            , waWaiting = waiting
            , waWaitingRoom = max 0 room
            , waWaitMicros = max 0 waitMicros
            , waDeadlines = deadlines
            , waLine = line
            }

-- The outcome of the door transaction: the weight taken directly, a place taken in the
-- waiting room, or a refusal (the room was full).
data Gate = Admitted | Queued | Refused

-- The door transaction: decide a 'Gate' in one STM step. The weight is taken directly
-- only when no one is waiting, so a newcomer never jumps a non-empty waiting room.
doorDecision :: WeightedAdmission -> Int -> STM Gate
doorDecision :: WeightedAdmission -> Int -> STM Gate
doorDecision WeightedAdmission
wa Int
weight = do
    available <- TVar Int -> STM Int
forall a. TVar a -> STM a
readTVar (WeightedAdmission -> TVar Int
waAvailable WeightedAdmission
wa)
    waiting <- weightedAdmissionWaiting wa
    if available >= weight && waiting == 0
        then writeTVar (waAvailable wa) (available - weight) $> Admitted
        else
            if waiting >= waWaitingRoom wa
                then pure Refused
                else writeTVar (waWaiting wa) (waiting + 1) $> Queued

-- Take the weight the moment it fits, or report expiry. One transaction, so a
-- timeout can never race a committed acquire into leaked weight.
acquireOrExpire :: WeightedAdmission -> Int -> TVar Bool -> STM Bool
acquireOrExpire :: WeightedAdmission -> Int -> TVar Bool -> STM Bool
acquireOrExpire WeightedAdmission
wa Int
weight TVar Bool
deadline = do
    available <- TVar Int -> STM Int
forall a. TVar a -> STM a
readTVar (WeightedAdmission -> TVar Int
waAvailable WeightedAdmission
wa)
    if available >= weight
        then writeTVar (waAvailable wa) (available - weight) $> True
        else do
            expired <- readTVar deadline
            if expired then pure False else retry

-- | Hold the supplied weight through the action, or say why the gate turned the request away.

-- Inlined with its arm helpers so each wrapper's literal observers vanish at the call site.
{-# INLINE withWeightedAdmission #-}
withWeightedAdmission ::
    (MonadUnliftIO m) =>
    AdmissionObservers ->
    WeightedAdmission ->
    Int ->
    m a ->
    m (Either Shed a)
withWeightedAdmission :: forall (m :: * -> *) a.
MonadUnliftIO m =>
AdmissionObservers
-> WeightedAdmission -> Int -> m a -> m (Either Shed a)
withWeightedAdmission AdmissionObservers
obs WeightedAdmission
wa Int
weight m a
action =
    ((forall a. m a -> m a) -> m (Either Shed a)) -> m (Either Shed a)
forall (m :: * -> *) b.
MonadUnliftIO m =>
((forall a. m a -> m a) -> m b) -> m b
UE.mask (((forall a. m a -> m a) -> m (Either Shed a))
 -> m (Either Shed a))
-> ((forall a. m a -> m a) -> m (Either Shed a))
-> m (Either Shed a)
forall a b. (a -> b) -> a -> b
$ \forall a. m a -> m a
restore -> do
        gate <- STM Gate -> m Gate
forall (m :: * -> *) a. MonadIO m => STM a -> m a
atomically (WeightedAdmission -> Int -> STM Gate
doorDecision WeightedAdmission
wa Int
weight)
        case gate of
            Gate
Refused -> AdmissionObservers -> Shed -> m (Either Shed a)
forall (m :: * -> *) a.
MonadIO m =>
AdmissionObservers -> Shed -> m (Either Shed a)
shedRecording AdmissionObservers
obs Shed
RoomFull
            Gate
Admitted -> AdmissionObservers
-> WeightedAdmission
-> Int
-> IO ()
-> (m a -> m a)
-> m a
-> m (Either Shed a)
forall (m :: * -> *) a.
MonadUnliftIO m =>
AdmissionObservers
-> WeightedAdmission
-> Int
-> IO ()
-> (m a -> m a)
-> m a
-> m (Either Shed a)
admittedRun AdmissionObservers
obs WeightedAdmission
wa Int
weight (() -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()) m a -> m a
forall a. m a -> m a
restore m a
action
            Gate
Queued -> AdmissionObservers
-> WeightedAdmission
-> Int
-> (m a -> m a)
-> m a
-> m (Either Shed a)
forall (m :: * -> *) a.
MonadUnliftIO m =>
AdmissionObservers
-> WeightedAdmission
-> Int
-> (m a -> m a)
-> m a
-> m (Either Shed a)
queuedWait AdmissionObservers
obs WeightedAdmission
wa Int
weight m a -> m a
forall a. m a -> m a
restore m a
action

-- Record the shed and refuse. A room place taken on the queued path is already
-- surrendered before this runs.
{-# INLINE shedRecording #-}
shedRecording :: (MonadIO m) => AdmissionObservers -> Shed -> m (Either Shed a)
shedRecording :: forall (m :: * -> *) a.
MonadIO m =>
AdmissionObservers -> Shed -> m (Either Shed a)
shedRecording AdmissionObservers
obs Shed
why = IO () -> m ()
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (AdmissionObservers -> IO ()
onShed AdmissionObservers
obs) m () -> Either Shed a -> m (Either Shed a)
forall (f :: * -> *) a b. Functor f => f a -> b -> f b
$> Shed -> Either Shed a
forall a b. a -> Either a b
Left Shed
why

-- A blocked STM retry stays interruptible under the mask, so a cancellation aborts it taking
-- nothing while a committed acquire returns with the weight held and exceptions still masked.
{-# INLINE queuedWait #-}
queuedWait ::
    (MonadUnliftIO m) =>
    AdmissionObservers ->
    WeightedAdmission ->
    Int ->
    (m a -> m a) ->
    m a ->
    m (Either Shed a)
queuedWait :: forall (m :: * -> *) a.
MonadUnliftIO m =>
AdmissionObservers
-> WeightedAdmission
-> Int
-> (m a -> m a)
-> m a
-> m (Either Shed a)
queuedWait AdmissionObservers
obs WeightedAdmission
wa Int
weight m a -> m a
restore m a
action = do
    acquired <-
        IO Bool -> m Bool
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Deadlines -> Int -> (TVar Bool -> IO Bool) -> IO Bool
forall a. Deadlines -> Int -> (TVar Bool -> IO a) -> IO a
withDeadlineFlag (WeightedAdmission -> Deadlines
waDeadlines WeightedAdmission
wa) (WeightedAdmission -> Int
waWaitMicros WeightedAdmission
wa) (STM Bool -> IO Bool
forall (m :: * -> *) a. MonadIO m => STM a -> m a
atomically (STM Bool -> IO Bool)
-> (TVar Bool -> STM Bool) -> TVar Bool -> IO Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. WeightedAdmission -> Int -> TVar Bool -> STM Bool
acquireOrExpire WeightedAdmission
wa Int
weight))
            m Bool -> m () -> m Bool
forall (m :: * -> *) a b. MonadUnliftIO m => m a -> m b -> m a
`UE.finally` STM () -> m ()
forall (m :: * -> *) a. MonadIO m => STM a -> m a
atomically (WeightedAdmission -> STM ()
leaveRoom WeightedAdmission
wa)
    if acquired
        then admittedRun obs wa weight (onQueued obs) restore action
        else shedRecording obs WaitExpired

-- A room place freed, so the oldest request this gate turned away may take it.
leaveRoom :: WeightedAdmission -> STM ()
leaveRoom :: WeightedAdmission -> STM ()
leaveRoom WeightedAdmission
wa = TVar Int -> (Int -> Int) -> STM ()
forall a. TVar a -> (a -> a) -> STM ()
modifyTVar' (WeightedAdmission -> TVar Int
waWaiting WeightedAdmission
wa) (Int -> Int -> Int
forall a. Num a => a -> a -> a
subtract Int
1) STM () -> STM () -> STM ()
forall a b. STM a -> STM b -> STM b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Line -> STM ()
signalLine (WeightedAdmission -> Line
waLine WeightedAdmission
wa)

-- The gauge increment runs under the enclosing mask, before 'restore', and 'afterArm' with it, so a
-- cancellation or a throwing observer cannot fire the finaliser's decrement without the increment.
{-# INLINE admittedRun #-}
admittedRun ::
    (MonadUnliftIO m) =>
    AdmissionObservers ->
    WeightedAdmission ->
    Int ->
    IO () ->
    (m a -> m a) ->
    m a ->
    m (Either Shed a)
admittedRun :: forall (m :: * -> *) a.
MonadUnliftIO m =>
AdmissionObservers
-> WeightedAdmission
-> Int
-> IO ()
-> (m a -> m a)
-> m a
-> m (Either Shed a)
admittedRun AdmissionObservers
obs WeightedAdmission
wa Int
weight IO ()
afterArm m a -> m a
restore m a
action =
    a -> Either Shed a
forall a b. b -> Either a b
Right
        (a -> Either Shed a) -> m a -> m (Either Shed a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ( (IO () -> m ()
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (AdmissionObservers -> Int -> IO ()
onInFlightDelta AdmissionObservers
obs Int
weight 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 ()
afterArm) m () -> m a -> m a
forall a b. m a -> m b -> m b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> m a -> m a
restore m a
action)
                m a -> m () -> m a
forall (m :: * -> *) a b. MonadUnliftIO m => m a -> m b -> m a
`UE.finally` AdmissionObservers -> WeightedAdmission -> Int -> m ()
forall (m :: * -> *).
MonadUnliftIO m =>
AdmissionObservers -> WeightedAdmission -> Int -> m ()
releaseWeight AdmissionObservers
obs WeightedAdmission
wa Int
weight
            )

-- Publish the gauge decrement before returning capacity, or a woken waiter increments while the departing
-- holder is still observable. The STM release is the finaliser, so a throwing observer cannot leak capacity.
{-# INLINE releaseWeight #-}
releaseWeight :: (MonadUnliftIO m) => AdmissionObservers -> WeightedAdmission -> Int -> m ()
releaseWeight :: forall (m :: * -> *).
MonadUnliftIO m =>
AdmissionObservers -> WeightedAdmission -> Int -> m ()
releaseWeight AdmissionObservers
obs WeightedAdmission
wa Int
weight =
    IO () -> m ()
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (AdmissionObservers -> Int -> IO ()
onInFlightDelta AdmissionObservers
obs (Int -> Int
forall a. Num a => a -> a
negate Int
weight))
        m () -> m () -> m ()
forall (m :: * -> *) a b. MonadUnliftIO m => m a -> m b -> m a
`UE.finally` STM () -> m ()
forall (m :: * -> *) a. MonadIO m => STM a -> m a
atomically (WeightedAdmission -> Int -> STM ()
returnWeight WeightedAdmission
wa Int
weight)

-- With a request in the room the freed weight is its, and its departure wakes the line. Otherwise the weight is the place.
returnWeight :: WeightedAdmission -> Int -> STM ()
returnWeight :: WeightedAdmission -> Int -> STM ()
returnWeight WeightedAdmission
wa Int
weight = do
    TVar Int -> (Int -> Int) -> STM ()
forall a. TVar a -> (a -> a) -> STM ()
modifyTVar' (WeightedAdmission -> TVar Int
waAvailable WeightedAdmission
wa) (Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
weight)
    waiting <- TVar Int -> STM Int
forall a. TVar a -> STM a
readTVar (WeightedAdmission -> TVar Int
waWaiting WeightedAdmission
wa)
    when (waiting == 0) (signalLine (waLine wa))

-- | The line of requests this gate turned away at a full room.
weightedAdmissionLine :: WeightedAdmission -> Line
weightedAdmissionLine :: WeightedAdmission -> Line
weightedAdmissionLine = WeightedAdmission -> Line
waLine

-- | Observe committed waiting-room occupancy without changing admission state.
weightedAdmissionWaiting :: WeightedAdmission -> STM Int
weightedAdmissionWaiting :: WeightedAdmission -> STM Int
weightedAdmissionWaiting = TVar Int -> STM Int
forall a. TVar a -> STM a
readTVar (TVar Int -> STM Int)
-> (WeightedAdmission -> TVar Int) -> WeightedAdmission -> STM Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. WeightedAdmission -> TVar Int
waWaiting