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

{- | Native requests pass the edge check and admission, run under the serve-path cap, and bound
actual upstream chunks and examined source documents independently.
-}
module Ecluse.Core.Registry.RubyGems.Handlers.Budget (
    withNativeRequest,
    newNativeReadBudget,
    newNativeDocumentBudget,
) where

import Network.HTTP.Types (ResponseHeaders)
import Network.Wai (Request, ResponseReceived)
import UnliftIO (withRunInIO)
import UnliftIO.Exception (throwIO)

import Ecluse.Core.Registry.Exchange (withinServeCapOr)
import Ecluse.Core.Registry.Exchange.Types (ExchangeClient (ecDeadlines))
import Ecluse.Core.Registry.RubyGems.Route.Response (RubyResponse, rubyReplies)
import Ecluse.Core.Security (BodyLimit (MetadataBodyLimit), LimitError (BodyTooLarge), Limits (progressFloor))
import Ecluse.Core.Server.Admission.Meter (MemoryTicket)
import Ecluse.Core.Server.Context (Handler, MountBinding (bindingPackumentDeps), PackumentDeps (pdInboundToken, pdLimits), ServeRuntime (srPublicClient), ctxMount, ctxRuntime)
import Ecluse.Core.Server.Pipeline.Origin (ObservedReadBoundExceeded (ObservedReadBoundExceeded))
import Ecluse.Core.Server.Pipeline.Packument (PackumentReplies (packumentUnauthorised, packumentUnavailable))
import Ecluse.Core.Server.Pipeline.Shared (edgeTokenMatches, forwardedCredential, shedMessage, unauthorisedMessage)
import Ecluse.Core.Server.Response (mkRefusal)

{- | Refuse a caller the edge does not authorise, then run @action@ under @admit@ and the serve-path
cap, answering @expired@ once the cap passes and handing the result to @continue@.
-}
withNativeRequest ::
    (ServeRuntime -> (ResponseHeaders -> Handler ResponseReceived) -> (MemoryTicket -> Handler a) -> (a -> Handler ResponseReceived) -> Handler ResponseReceived) ->
    Request ->
    (RubyResponse -> Handler ResponseReceived) ->
    (PackumentDeps -> a) ->
    (MemoryTicket -> PackumentDeps -> Handler a) ->
    (a -> Handler ResponseReceived) ->
    Handler ResponseReceived
withNativeRequest :: forall a.
(ServeRuntime
 -> (ResponseHeaders -> Handler ResponseReceived)
 -> (MemoryTicket -> Handler a)
 -> (a -> Handler ResponseReceived)
 -> Handler ResponseReceived)
-> Request
-> (RubyResponse -> Handler ResponseReceived)
-> (PackumentDeps -> a)
-> (MemoryTicket -> PackumentDeps -> Handler a)
-> (a -> Handler ResponseReceived)
-> Handler ResponseReceived
withNativeRequest ServeRuntime
-> (ResponseHeaders -> Handler ResponseReceived)
-> (MemoryTicket -> Handler a)
-> (a -> Handler ResponseReceived)
-> Handler ResponseReceived
admit Request
request RubyResponse -> Handler ResponseReceived
refuse PackumentDeps -> a
expired MemoryTicket -> PackumentDeps -> Handler a
action a -> Handler ResponseReceived
continue = do
    mount <- (RequestCtx -> MountBinding) -> Handler MountBinding
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
asks RequestCtx -> MountBinding
ctxMount
    runtime <- asks ctxRuntime
    let deps = MountBinding -> PackumentDeps
bindingPackumentDeps MountBinding
mount
    if not (edgeTokenMatches (pdInboundToken deps) (forwardedCredential mount request))
        then refuse (packumentUnauthorised rubyReplies [] (mkRefusal Nothing unauthorisedMessage))
        else
            admit
                runtime
                (\ResponseHeaders
headers -> RubyResponse -> Handler ResponseReceived
refuse (PackumentReplies RubyResponse
-> ResponseHeaders -> Refusal -> RubyResponse
forall response.
PackumentReplies response -> ResponseHeaders -> Refusal -> response
packumentUnavailable PackumentReplies RubyResponse
rubyReplies ResponseHeaders
headers (Maybe HelpMessage -> Text -> Refusal
mkRefusal Maybe HelpMessage
forall a. Maybe a
Nothing Text
shedMessage)))
                (\MemoryTicket
ticket -> ((forall a. Handler a -> IO a) -> IO a) -> Handler a
forall b. ((forall a. Handler a -> IO a) -> IO b) -> Handler b
forall (m :: * -> *) b.
MonadUnliftIO m =>
((forall a. m a -> IO a) -> IO b) -> m b
withRunInIO (((forall a. Handler a -> IO a) -> IO a) -> Handler a)
-> ((forall a. Handler a -> IO a) -> IO a) -> Handler a
forall a b. (a -> b) -> a -> b
$ \forall a. Handler a -> IO a
run -> Deadlines -> ProgressFloor -> a -> IO a -> IO a
forall a. Deadlines -> ProgressFloor -> a -> IO a -> IO a
withinServeCapOr (ExchangeClient -> Deadlines
ecDeadlines (ServeRuntime -> ExchangeClient
srPublicClient ServeRuntime
runtime)) (Limits -> ProgressFloor
progressFloor (PackumentDeps -> Limits
pdLimits PackumentDeps
deps)) (PackumentDeps -> a
expired PackumentDeps
deps) (Handler a -> IO a
forall a. Handler a -> IO a
run (MemoryTicket -> PackumentDeps -> Handler a
action MemoryTicket
ticket PackumentDeps
deps)))
                continue

-- | Refuse before another source chunk reaches its parser when cumulative input exceeds the cap.
newNativeReadBudget :: Int -> IO (Int -> IO ())
newNativeReadBudget :: Int -> IO (Int -> IO ())
newNativeReadBudget Int
cap = do
    count <- Int -> IO (Int -> IO Bool)
newNativeByteCounter Int
cap
    pure $ \Int
bytes -> do
        exceeded <- Int -> IO Bool
count Int
bytes
        when exceeded (throwIO (ObservedReadBoundExceeded (BodyTooLarge (MetadataBodyLimit cap))))

-- | Refuse before admission when examined source documents, including cache hits, exceed the cap.
newNativeDocumentBudget :: Int -> response -> IO (Int -> IO (Either response ()))
newNativeDocumentBudget :: forall response.
Int -> response -> IO (Int -> IO (Either response ()))
newNativeDocumentBudget Int
cap response
refusal = do
    count <- Int -> IO (Int -> IO Bool)
newNativeByteCounter Int
cap
    pure $ \Int
bytes -> do
        exceeded <- Int -> IO Bool
count Int
bytes
        pure (if exceeded then Left refusal else Right ())

newNativeByteCounter :: Int -> IO (Int -> IO Bool)
newNativeByteCounter :: Int -> IO (Int -> IO Bool)
newNativeByteCounter Int
cap = do
    total <- Integer -> IO (IORef Integer)
forall (m :: * -> *) a. MonadIO m => a -> m (IORef a)
newIORef (Integer
0 :: Integer)
    pure $ \Int
bytes ->
        IORef Integer -> (Integer -> (Integer, Bool)) -> IO Bool
forall (m :: * -> *) a b.
MonadIO m =>
IORef a -> (a -> (a, b)) -> m b
atomicModifyIORef' IORef Integer
total (\Integer
seen -> let next :: Integer
next = Integer
seen Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 Int
bytes) in (Integer
next, Integer
next Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Int -> Integer
forall a. Integral a => a -> Integer
toInteger Int
cap))