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

{- | Unit-slot admission over the shared weighted controller, and the overflow queue that both
metadata gates' refusals share. The composition root builds both with the process's sweeper. A
runtime built without the queue refuses a full room at once.
-}
module Ecluse.Core.Server.Admission.Internal (
    ServeAdmission (..),
    newServeAdmission,
    withServeAdmission,
    serveAdmissionLine,
    serveAdmissionOverflow,

    -- * Internals exported for testing
    newServeAdmissionTuned,
    withOverflow,
) where

import Control.Exception (ErrorCall (ErrorCall))
import UnliftIO (MonadUnliftIO, throwIO)

import Ecluse.Core.Deadline (Deadlines)
import Ecluse.Core.Server.Admission.Overflow (Line, Overflow, newOverflow)
import Ecluse.Core.Server.Admission.Types (Shed)
import Ecluse.Core.Server.Admission.Weighted (
    AdmissionObservers (..),
    WeightedAdmission,
    admissionWaitMicros,
    newWeightedAdmission,
    weightedAdmissionLine,
    withWeightedAdmission,
 )
import Ecluse.Core.Telemetry.Record (MetricsPort (..))

-- | Process-wide serve capacity and its bounded waiting room, and the overflow queue when it is on.
data ServeAdmission = ServeAdmission
    { ServeAdmission -> WeightedAdmission
saSlots :: WeightedAdmission
    , ServeAdmission -> Maybe Overflow
saOverflow :: Maybe Overflow
    }

{- | Allocate positive capacity, a waiting room of the same size, and an overflow queue for it. The
deadlines must be swept, as the composition root's are, or a queued request never times out.
-}

-- The configuration parser guarantees capacity > 0. This bounds check is defence in depth.
newServeAdmission :: Deadlines -> Int -> IO ServeAdmission
newServeAdmission :: Deadlines -> Int -> IO ServeAdmission
newServeAdmission Deadlines
deadlines Int
capacity
    | Int
capacity Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = ErrorCall -> IO ServeAdmission
forall (m :: * -> *) e a. (MonadIO m, Exception e) => e -> m a
throwIO (String -> ErrorCall
ErrorCall String
"ServeAdmission capacity must be positive")
    | Bool
otherwise = do
        slots <- Deadlines -> Int -> Int -> Int -> IO ServeAdmission
newServeAdmissionTuned Deadlines
deadlines Int
capacity Int
capacity Int
admissionWaitMicros
        withOverflow slots <$> newOverflow deadlines capacity

-- | Set the waiting-room bound and microsecond wait budget explicitly, with no overflow queue.
newServeAdmissionTuned :: Deadlines -> Int -> Int -> Int -> IO ServeAdmission
newServeAdmissionTuned :: Deadlines -> Int -> Int -> Int -> IO ServeAdmission
newServeAdmissionTuned Deadlines
deadlines Int
capacity Int
room Int
waitMicros = do
    slots <- Deadlines -> Int -> Int -> Int -> IO WeightedAdmission
newWeightedAdmission Deadlines
deadlines Int
capacity Int
room Int
waitMicros
    pure ServeAdmission{saSlots = slots, saOverflow = Nothing}

-- | Put an overflow queue in front of the gates.
withOverflow :: ServeAdmission -> Overflow -> ServeAdmission
withOverflow :: ServeAdmission -> Overflow -> ServeAdmission
withOverflow ServeAdmission
admission Overflow
overflow = ServeAdmission
admission{saOverflow = Just overflow}

-- | The line of requests the serve slots' full room turned away.
serveAdmissionLine :: ServeAdmission -> Line
serveAdmissionLine :: ServeAdmission -> Line
serveAdmissionLine = WeightedAdmission -> Line
weightedAdmissionLine (WeightedAdmission -> Line)
-> (ServeAdmission -> WeightedAdmission) -> ServeAdmission -> Line
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ServeAdmission -> WeightedAdmission
saSlots

-- | The overflow queue in front of the gates, when it is on.
serveAdmissionOverflow :: ServeAdmission -> Maybe Overflow
serveAdmissionOverflow :: ServeAdmission -> Maybe Overflow
serveAdmissionOverflow = ServeAdmission -> Maybe Overflow
saOverflow

-- | Hold one slot for the action, or say why the gate turned the request away.
{-# INLINE withServeAdmission #-}
withServeAdmission :: (MonadUnliftIO m) => MetricsPort -> ServeAdmission -> m a -> m (Either Shed a)
withServeAdmission :: forall (m :: * -> *) a.
MonadUnliftIO m =>
MetricsPort -> ServeAdmission -> m a -> m (Either Shed a)
withServeAdmission MetricsPort
metrics ServeAdmission
admission =
    AdmissionObservers
-> WeightedAdmission -> Int -> m a -> m (Either Shed a)
forall (m :: * -> *) a.
MonadUnliftIO m =>
AdmissionObservers
-> WeightedAdmission -> Int -> m a -> m (Either Shed a)
withWeightedAdmission AdmissionObservers
observers (ServeAdmission -> WeightedAdmission
saSlots ServeAdmission
admission) Int
1
  where
    observers :: AdmissionObservers
observers =
        AdmissionObservers
            { onQueued :: IO ()
onQueued = MetricsPort -> IO ()
mpServeAdmissionQueued MetricsPort
metrics
            , onShed :: IO ()
onShed = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
            , onInFlightDelta :: Int -> IO ()
onInFlightDelta = MetricsPort -> Int -> IO ()
mpServeAdmissionInFlight MetricsPort
metrics
            }