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

-- | Bounded registry exchanges under the progress floor, the response wait, and optional public authority control.
module Ecluse.Core.Registry.Exchange (
    -- * The bounded exchange
    boundedExchange,
    runExchange,
    runExchangeUsing,
    singleAttemptSettings,
    newSingleAttemptManager,
    withSuccessBody,
    withSuccessBodyUsing,
    boundedRelay,

    -- * The serve-path cap
    withinServeCap,
    withinServeCapOr,

    -- * Source digests
    digestingRead,

    -- * Metered reads
    chargedRead,
    chargedReadWith,
    accumulatingCharge,
    accumulatingChargeFrom,
    boundedChargedRead,
    boundedIncrementalRead,

    -- * Request formation
    formThen,
) where

import Crypto.Hash.IO (hashMutableInit, hashMutableUpdate)
import Data.ByteString qualified as BS
import Data.ByteString.Lazy qualified as LBS
import Network.HTTP.Client (
    BodyReader,
    Manager,
    ManagerSettings (managerRetryableException),
    Request (requestBody),
    Response (responseStatus),
    brRead,
    newManager,
    responseBody,
    responseHeaders,
 )
import Network.HTTP.Types.Status (statusCode)
import UnliftIO (try)

import Ecluse.Core.Deadline (Deadlines, timeout)
import Ecluse.Core.Fault (TransportCause (TransportTimeout), transportFault)
import Ecluse.Core.Fault.Http (classifyTransport, typedTlsManagerSettings)
import Ecluse.Core.Fault.RetryAfter (responseRetryAfter)
import Ecluse.Core.Registry (
    BodyOutcome (SuccessBody, UnreadStatus),
    FetchFault (FetchBoundExceeded, FetchCooldown, FetchTransport),
    PublishRelayResponse (..),
    UrlFormationError,
    isSuccessStatus,
 )
import Ecluse.Core.Registry.Exchange.Types (ExchangeClient (ecDeadlines))
import Ecluse.Core.Registry.Progress (meteredReader, meteredUpload, watched)
import Ecluse.Core.Registry.Public (ReadControl (Uncontrolled), withReadControl)
import Ecluse.Core.Registry.ResponseWait (withResponse)
import Ecluse.Core.Security (
    BodyLimit,
    LimitError,
    ProgressFloor,
    boundedRead,
    floorMinBytes,
    floorServeCapMicros,
    floorWindowMicros,
 )
import Ecluse.Core.Server.MemoryModel (bufferedChunkCharge)
import Ecluse.Core.Snapshot (ContentDigest, digestFromMutableContext)

-- | Destructive clients must return uncertain transport failures for reassessment before retry.
singleAttemptSettings :: ManagerSettings -> ManagerSettings
singleAttemptSettings :: ManagerSettings -> ManagerSettings
singleAttemptSettings ManagerSettings
settings = ManagerSettings
settings{managerRetryableException = const False}

-- | A 'typedTlsManagerSettings' manager under 'singleAttemptSettings'. @newTlsManagerWith@ would replace its retry check and restore the replay on a reused connection.
newSingleAttemptManager :: IO Manager
newSingleAttemptManager :: IO Manager
newSingleAttemptManager = ManagerSettings -> IO Manager
newManager (ManagerSettings -> ManagerSettings
singleAttemptSettings ManagerSettings
typedTlsManagerSettings)

-- | Project status, decompressed byte count, and body. Transport failures retain their typed cause.
boundedExchange :: (Int -> Int -> ByteString -> a) -> ExchangeClient -> ProgressFloor -> BodyLimit -> Request -> IO (Either FetchFault a)
boundedExchange :: forall a.
(Int -> Int -> ByteString -> a)
-> ExchangeClient
-> ProgressFloor
-> BodyLimit
-> Request
-> IO (Either FetchFault a)
boundedExchange Int -> Int -> ByteString -> a
project ExchangeClient
client ProgressFloor
progress BodyLimit
limits Request
request =
    ExchangeClient
-> ProgressFloor
-> Request
-> (Response BodyReader -> IO (Either LimitError a))
-> IO (Either FetchFault a)
forall a.
ExchangeClient
-> ProgressFloor
-> Request
-> (Response BodyReader -> IO (Either LimitError a))
-> IO (Either FetchFault a)
runExchange ExchangeClient
client ProgressFloor
progress Request
request ((Int -> Int -> ByteString -> a)
-> BodyLimit -> Response BodyReader -> IO (Either LimitError a)
forall a.
(Int -> Int -> ByteString -> a)
-> BodyLimit -> Response BodyReader -> IO (Either LimitError a)
readBounded Int -> Int -> ByteString -> a
project BodyLimit
limits)

readBounded :: (Int -> Int -> ByteString -> a) -> BodyLimit -> Response BodyReader -> IO (Either LimitError a)
readBounded :: forall a.
(Int -> Int -> ByteString -> a)
-> BodyLimit -> Response BodyReader -> IO (Either LimitError a)
readBounded Int -> Int -> ByteString -> a
project BodyLimit
limits Response BodyReader
response =
    ((Int, ByteString) -> a)
-> Either LimitError (Int, ByteString) -> Either LimitError a
forall a b. (a -> b) -> Either LimitError a -> Either LimitError b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((Int -> ByteString -> a) -> (Int, ByteString) -> a
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry (Int -> Int -> ByteString -> a
project (Status -> Int
statusCode (Response BodyReader -> Status
forall body. Response body -> Status
responseStatus Response BodyReader
response))))
        (Either LimitError (Int, ByteString) -> Either LimitError a)
-> IO (Either LimitError (Int, ByteString))
-> IO (Either LimitError a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> BodyLimit -> BodyReader -> IO (Either LimitError (Int, ByteString))
forall (m :: * -> *).
Monad m =>
BodyLimit
-> m ByteString -> m (Either LimitError (Int, ByteString))
boundedRead BodyLimit
limits (BodyReader -> BodyReader
brRead (Response BodyReader -> BodyReader
forall body. Response body -> body
responseBody Response BodyReader
response))

-- | The exchange keeping the answered status alongside the body, for the first-party relay.
boundedRelay :: ExchangeClient -> ProgressFloor -> BodyLimit -> Request -> IO (Either FetchFault PublishRelayResponse)
boundedRelay :: ExchangeClient
-> ProgressFloor
-> BodyLimit
-> Request
-> IO (Either FetchFault PublishRelayResponse)
boundedRelay =
    (Int -> Int -> ByteString -> PublishRelayResponse)
-> ExchangeClient
-> ProgressFloor
-> BodyLimit
-> Request
-> IO (Either FetchFault PublishRelayResponse)
forall a.
(Int -> Int -> ByteString -> a)
-> ExchangeClient
-> ProgressFloor
-> BodyLimit
-> Request
-> IO (Either FetchFault a)
boundedExchange ((Int -> Int -> ByteString -> PublishRelayResponse)
 -> ExchangeClient
 -> ProgressFloor
 -> BodyLimit
 -> Request
 -> IO (Either FetchFault PublishRelayResponse))
-> (Int -> Int -> ByteString -> PublishRelayResponse)
-> ExchangeClient
-> ProgressFloor
-> BodyLimit
-> Request
-> IO (Either FetchFault PublishRelayResponse)
forall a b. (a -> b) -> a -> b
$ \Int
status Int
_ ByteString
body ->
        PublishRelayResponse{relayStatus :: Int
relayStatus = Int
status, relayBody :: LByteString
relayBody = ByteString -> LByteString
LBS.fromStrict ByteString
body}

-- | Consume a response under the progress floor and the response wait, classifying transport and body-limit failures.
runExchange :: ExchangeClient -> ProgressFloor -> Request -> (Response BodyReader -> IO (Either LimitError a)) -> IO (Either FetchFault a)
runExchange :: forall a.
ExchangeClient
-> ProgressFloor
-> Request
-> (Response BodyReader -> IO (Either LimitError a))
-> IO (Either FetchFault a)
runExchange = ReadControl
-> ExchangeClient
-> ProgressFloor
-> Request
-> (Response BodyReader -> IO (Either LimitError a))
-> IO (Either FetchFault a)
forall a.
ReadControl
-> ExchangeClient
-> ProgressFloor
-> Request
-> (Response BodyReader -> IO (Either LimitError a))
-> IO (Either FetchFault a)
runExchangeUsing ReadControl
Uncontrolled

-- | Retain the controlled response lifetime for header-aware bounded consumers.
runExchangeUsing :: ReadControl -> ExchangeClient -> ProgressFloor -> Request -> (Response BodyReader -> IO (Either LimitError a)) -> IO (Either FetchFault a)
runExchangeUsing :: forall a.
ReadControl
-> ExchangeClient
-> ProgressFloor
-> Request
-> (Response BodyReader -> IO (Either LimitError a))
-> IO (Either FetchFault a)
runExchangeUsing ReadControl
control ExchangeClient
client ProgressFloor
progress Request
request Response BodyReader -> IO (Either LimitError a)
readResponse =
    Deadlines
-> ProgressFloor
-> (Watch
    -> IO
         (Either HttpException (Either FetchFault (Either FetchFault a))))
-> IO
     (Maybe
        (Either HttpException (Either FetchFault (Either FetchFault a))))
forall a.
Deadlines -> ProgressFloor -> (Watch -> IO a) -> IO (Maybe a)
watched
        (ExchangeClient -> Deadlines
ecDeadlines ExchangeClient
client)
        ProgressFloor
progress
        ( \Watch
watch ->
            IO (Either FetchFault (Either FetchFault a))
-> IO
     (Either HttpException (Either FetchFault (Either FetchFault a)))
forall (m :: * -> *) e a.
(MonadUnliftIO m, Exception e) =>
m a -> m (Either e a)
try
                ( ReadControl
-> Request
-> (Request
    -> (Status -> ResponseHeaders -> IO (Maybe RetryAfter))
    -> IO (Either FetchFault a))
-> IO (Either FetchFault (Either FetchFault a))
forall a.
ReadControl
-> Request
-> (Request
    -> (Status -> ResponseHeaders -> IO (Maybe RetryAfter)) -> IO a)
-> IO (Either FetchFault a)
withReadControl ReadControl
control (Watch -> Request
metered Watch
watch) ((Request
  -> (Status -> ResponseHeaders -> IO (Maybe RetryAfter))
  -> IO (Either FetchFault a))
 -> IO (Either FetchFault (Either FetchFault a)))
-> (Request
    -> (Status -> ResponseHeaders -> IO (Maybe RetryAfter))
    -> IO (Either FetchFault a))
-> IO (Either FetchFault (Either FetchFault a))
forall a b. (a -> b) -> a -> b
$ \Request
observed Status -> ResponseHeaders -> IO (Maybe RetryAfter)
recordHeaders ->
                    ExchangeClient
-> Request
-> (Response BodyReader -> IO (Either FetchFault a))
-> IO (Either FetchFault a)
forall a.
ExchangeClient -> Request -> (Response BodyReader -> IO a) -> IO a
withResponse ExchangeClient
client Request
observed ((Response BodyReader -> IO (Either FetchFault a))
 -> IO (Either FetchFault a))
-> (Response BodyReader -> IO (Either FetchFault a))
-> IO (Either FetchFault a)
forall a b. (a -> b) -> a -> b
$ \Response BodyReader
response -> do
                        cooldown <- Status -> ResponseHeaders -> IO (Maybe RetryAfter)
recordHeaders (Response BodyReader -> Status
forall body. Response body -> Status
responseStatus Response BodyReader
response) (Response BodyReader -> ResponseHeaders
forall body. Response body -> ResponseHeaders
responseHeaders Response BodyReader
response)
                        case cooldown of
                            Just RetryAfter
retry -> 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 (RetryAfter -> FetchFault
FetchCooldown RetryAfter
retry))
                            Maybe RetryAfter
Nothing -> (LimitError -> FetchFault)
-> Either LimitError 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 LimitError -> FetchFault
FetchBoundExceeded (Either LimitError a -> Either FetchFault a)
-> IO (Either LimitError a) -> IO (Either FetchFault a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Response BodyReader -> IO (Either LimitError a)
readResponse (Watch -> BodyReader -> BodyReader
meteredReader Watch
watch (BodyReader -> BodyReader)
-> Response BodyReader -> Response BodyReader
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Response BodyReader
response)
                )
        )
        IO
  (Maybe
     (Either HttpException (Either FetchFault (Either FetchFault a))))
-> (Maybe
      (Either HttpException (Either FetchFault (Either FetchFault a)))
    -> Either FetchFault a)
-> IO (Either FetchFault a)
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \case
            Maybe
  (Either HttpException (Either FetchFault (Either FetchFault a)))
Nothing -> FetchFault -> Either FetchFault a
forall a b. a -> Either a b
Left (ProgressFloor -> FetchFault
belowFloor ProgressFloor
progress)
            Just (Left HttpException
httpErr) -> FetchFault -> Either FetchFault a
forall a b. a -> Either a b
Left (TransportFault -> FetchFault
FetchTransport (HttpException -> TransportFault
classifyTransport HttpException
httpErr))
            Just (Right Either FetchFault (Either FetchFault a)
result) -> Either FetchFault (Either FetchFault a) -> Either FetchFault a
forall (m :: * -> *) a. Monad m => m (m a) -> m a
join Either FetchFault (Either FetchFault a)
result
  where
    metered :: Watch -> Request
metered Watch
watch = Request
request{requestBody = meteredUpload watch (requestBody request)}

-- | Fail an action that outlives the floor's serve-path cap with the transport timeout, about one sweep late.
withinServeCap :: Deadlines -> ProgressFloor -> (FetchFault -> e) -> IO (Either e a) -> IO (Either e a)
withinServeCap :: forall e a.
Deadlines
-> ProgressFloor
-> (FetchFault -> e)
-> IO (Either e a)
-> IO (Either e a)
withinServeCap Deadlines
deadlines ProgressFloor
progress FetchFault -> e
inject = Deadlines
-> ProgressFloor
-> Either e a
-> IO (Either e a)
-> IO (Either e a)
forall a. Deadlines -> ProgressFloor -> a -> IO a -> IO a
withinServeCapOr Deadlines
deadlines ProgressFloor
progress (e -> Either e a
forall a b. a -> Either a b
Left (FetchFault -> e
inject FetchFault
capExceeded))
  where
    capExceeded :: FetchFault
capExceeded = TransportFault -> FetchFault
FetchTransport (TransportCause -> Text -> TransportFault
transportFault TransportCause
TransportTimeout (Text
"the upstream exchange outlived its " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Int -> Text
seconds (ProgressFloor -> Int
floorServeCapMicros ProgressFloor
progress) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"-second serve-path cap"))

-- | Answer @expired@ once an action outlives the floor's serve-path cap, about one sweep late.
withinServeCapOr :: Deadlines -> ProgressFloor -> a -> IO a -> IO a
withinServeCapOr :: forall a. Deadlines -> ProgressFloor -> a -> IO a -> IO a
withinServeCapOr Deadlines
deadlines ProgressFloor
progress a
expired IO a
action =
    a -> Maybe a -> a
forall a. a -> Maybe a -> a
fromMaybe a
expired (Maybe a -> a) -> IO (Maybe a) -> IO a
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Deadlines -> Int -> IO a -> IO (Maybe a)
forall a. Deadlines -> Int -> IO a -> IO (Maybe a)
timeout Deadlines
deadlines (ProgressFloor -> Int
floorServeCapMicros ProgressFloor
progress) IO a
action

belowFloor :: ProgressFloor -> FetchFault
belowFloor :: ProgressFloor -> FetchFault
belowFloor ProgressFloor
progress =
    TransportFault -> FetchFault
FetchTransport (TransportFault -> FetchFault)
-> (Text -> TransportFault) -> Text -> FetchFault
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TransportCause -> Text -> TransportFault
transportFault TransportCause
TransportTimeout (Text -> FetchFault) -> Text -> FetchFault
forall a b. (a -> b) -> a -> b
$
        Text
"the exchange moved fewer than "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Int -> Text
forall b a. (Show a, IsString b) => a -> b
show (ProgressFloor -> Int
floorMinBytes ProgressFloor
progress)
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" body bytes, counting both directions together, in a "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Int -> Text
seconds (ProgressFloor -> Int
floorWindowMicros ProgressFloor
progress)
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"-second progress window"

-- Whole seconds as an operator wrote them, and a fraction only where one exists.
seconds :: Int -> Text
seconds :: Int -> Text
seconds Int
micros = case Int
micros Int -> Int -> (Int, Int)
forall a. Integral a => a -> a -> (a, a)
`divMod` Int
1_000_000 of
    (Int
whole, Int
0) -> Int -> Text
forall b a. (Show a, IsString b) => a -> b
show Int
whole
    (Int, Int)
_ -> Double -> Text
forall b a. (Show a, IsString b) => a -> b
show (Int -> Double
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
micros Double -> Double -> Double
forall a. Fractional a => a -> a -> a
/ Double
1_000_000 :: Double)

-- | Consume a 2xx body within the response lifetime. A status outside 2xx never reaches the consumer.
withSuccessBody :: ExchangeClient -> ProgressFloor -> (IO ByteString -> IO (Either LimitError a)) -> Request -> IO (Either FetchFault (BodyOutcome a))
withSuccessBody :: forall a.
ExchangeClient
-> ProgressFloor
-> (BodyReader -> IO (Either LimitError a))
-> Request
-> IO (Either FetchFault (BodyOutcome a))
withSuccessBody = ReadControl
-> ExchangeClient
-> ProgressFloor
-> (BodyReader -> IO (Either LimitError a))
-> Request
-> IO (Either FetchFault (BodyOutcome a))
forall a.
ReadControl
-> ExchangeClient
-> ProgressFloor
-> (BodyReader -> IO (Either LimitError a))
-> Request
-> IO (Either FetchFault (BodyOutcome a))
withSuccessBodyUsing ReadControl
Uncontrolled

-- | Apply public control only to the HTTP exchange that supplies this body.
withSuccessBodyUsing :: ReadControl -> ExchangeClient -> ProgressFloor -> (IO ByteString -> IO (Either LimitError a)) -> Request -> IO (Either FetchFault (BodyOutcome a))
withSuccessBodyUsing :: forall a.
ReadControl
-> ExchangeClient
-> ProgressFloor
-> (BodyReader -> IO (Either LimitError a))
-> Request
-> IO (Either FetchFault (BodyOutcome a))
withSuccessBodyUsing ReadControl
control ExchangeClient
client ProgressFloor
progress BodyReader -> IO (Either LimitError a)
consume Request
request = ReadControl
-> ExchangeClient
-> ProgressFloor
-> Request
-> (Response BodyReader -> IO (Either LimitError (BodyOutcome a)))
-> IO (Either FetchFault (BodyOutcome a))
forall a.
ReadControl
-> ExchangeClient
-> ProgressFloor
-> Request
-> (Response BodyReader -> IO (Either LimitError a))
-> IO (Either FetchFault a)
runExchangeUsing ReadControl
control ExchangeClient
client ProgressFloor
progress Request
request ((Response BodyReader -> IO (Either LimitError (BodyOutcome a)))
 -> IO (Either FetchFault (BodyOutcome a)))
-> (Response BodyReader -> IO (Either LimitError (BodyOutcome a)))
-> IO (Either FetchFault (BodyOutcome a))
forall a b. (a -> b) -> a -> b
$ \Response BodyReader
response -> do
    let code :: Int
code = Status -> Int
statusCode (Response BodyReader -> Status
forall body. Response body -> Status
responseStatus Response BodyReader
response)
    if Int -> Bool
isSuccessStatus Int
code
        then (a -> BodyOutcome a)
-> Either LimitError a -> Either LimitError (BodyOutcome a)
forall a b. (a -> b) -> Either LimitError a -> Either LimitError b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Int -> a -> BodyOutcome a
forall a. Int -> a -> BodyOutcome a
SuccessBody Int
code) (Either LimitError a -> Either LimitError (BodyOutcome a))
-> IO (Either LimitError a)
-> IO (Either LimitError (BodyOutcome a))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> BodyReader -> IO (Either LimitError a)
consume (BodyReader -> BodyReader
brRead (Response BodyReader -> BodyReader
forall body. Response body -> body
responseBody Response BodyReader
response))
        else BodyOutcome a -> Either LimitError (BodyOutcome a)
forall a b. b -> Either a b
Right (BodyOutcome a -> Either LimitError (BodyOutcome a))
-> (Maybe RetryAfter -> BodyOutcome a)
-> Maybe RetryAfter
-> Either LimitError (BodyOutcome a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Maybe RetryAfter -> BodyOutcome a
forall a. Int -> Maybe RetryAfter -> BodyOutcome a
UnreadStatus Int
code (Maybe RetryAfter -> Either LimitError (BodyOutcome a))
-> IO (Maybe RetryAfter) -> IO (Either LimitError (BodyOutcome a))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ResponseHeaders -> IO (Maybe RetryAfter)
responseRetryAfter (Response BodyReader -> ResponseHeaders
forall body. Response body -> ResponseHeaders
responseHeaders Response BodyReader
response)

-- | Run a consumer over a source that hashes each chunk it passes on. A success carries the digest of every chunk read.
digestingRead :: (IO ByteString -> IO (Either e a)) -> IO ByteString -> IO (Either e (a, ContentDigest))
digestingRead :: forall e a.
(BodyReader -> IO (Either e a))
-> BodyReader -> IO (Either e (a, ContentDigest))
digestingRead BodyReader -> IO (Either e a)
consume BodyReader
readChunk = do
    context <- IO (MutableContext SHA256)
forall alg. HashAlgorithm alg => IO (MutableContext alg)
hashMutableInit
    let next = do
            chunk <- BodyReader
readChunk
            hashMutableUpdate context chunk
            pure chunk
    consume next >>= traverse (\a
result -> (a
result,) (ContentDigest -> (a, ContentDigest))
-> IO ContentDigest -> IO (a, ContentDigest)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> MutableContext SHA256 -> IO ContentDigest
digestFromMutableContext MutableContext SHA256
context)

-- | Pay for each chunk's length before the consumer sees it.
chargedRead :: (Int -> IO ()) -> IO ByteString -> IO ByteString
chargedRead :: (Int -> IO ()) -> BodyReader -> BodyReader
chargedRead Int -> IO ()
charge = (ByteString -> IO ()) -> BodyReader -> BodyReader
chargedReadWith (Int -> IO ()
charge (Int -> IO ()) -> (ByteString -> Int) -> ByteString -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Int
BS.length)

-- | Pay for the observed chunk before a parser or buffer retains it.
chargedReadWith :: (ByteString -> IO ()) -> IO ByteString -> IO ByteString
chargedReadWith :: (ByteString -> IO ()) -> BodyReader -> BodyReader
chargedReadWith ByteString -> IO ()
charge BodyReader
readChunk = do
    chunk <- BodyReader
readChunk
    charge chunk
    pure chunk

-- | Convert per-chunk costs to an absolute requirement within one read operation.
accumulatingCharge :: (Int -> IO ()) -> IO (Int -> IO ())
accumulatingCharge :: (Int -> IO ()) -> IO (Int -> IO ())
accumulatingCharge Int -> IO ()
charge = do
    (add, _) <- Integer -> (Int -> IO ()) -> IO (Int -> IO (), IO Int)
accumulatingChargeFrom Integer
0 Int -> IO ()
charge
    pure $ \Int
bytes -> Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
bytes Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0) (Int -> IO ()
add Int
bytes)

-- | Report the saturated reservation, including after callback failure. Zero additions charge too, but construction does not charge the seed.
accumulatingChargeFrom :: Integer -> (Int -> IO ()) -> IO (Int -> IO (), IO Int)
accumulatingChargeFrom :: Integer -> (Int -> IO ()) -> IO (Int -> IO (), IO Int)
accumulatingChargeFrom Integer
initial Int -> IO ()
charge = do
    held <- Integer -> IO (IORef Integer)
forall (m :: * -> *) a. MonadIO m => a -> m (IORef a)
newIORef Integer
initial
    let total = Integer -> Int
forall a. Num a => Integer -> a
fromInteger (Integer -> Int) -> (Integer -> Integer) -> Integer -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Integer -> Integer -> Integer
forall a. Ord a => a -> a -> a
min (Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Int
forall a. Bounded a => a
maxBound :: Int))
        add p
bytes = do
            required <- IORef Integer -> (Integer -> (Integer, Integer)) -> IO Integer
forall (m :: * -> *) a b.
MonadIO m =>
IORef a -> (a -> (a, b)) -> m b
atomicModifyIORef' IORef Integer
held (\Integer
previous -> let next :: Integer
next = Integer
previous Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ p -> Integer
forall a. Integral a => a -> Integer
toInteger p
bytes in (Integer
next, Integer
next))
            charge (total required)
    pure (add, total <$> readIORef held)

-- | Pay the running total of buffered chunks and their final strict copy before the bounded reader retains them.
boundedChargedRead :: (Int -> IO ()) -> BodyLimit -> IO ByteString -> IO (Either LimitError (Int, ByteString))
boundedChargedRead :: (Int -> IO ())
-> BodyLimit
-> BodyReader
-> IO (Either LimitError (Int, ByteString))
boundedChargedRead Int -> IO ()
charge BodyLimit
limits BodyReader
readChunk = (Int -> IO ()) -> IO (Int -> IO ())
accumulatingCharge Int -> IO ()
charge IO (Int -> IO ())
-> ((Int -> IO ()) -> IO (Either LimitError (Int, ByteString)))
-> IO (Either LimitError (Int, ByteString))
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \Int -> IO ()
retain -> (Int -> IO ())
-> BodyLimit
-> BodyReader
-> IO (Either LimitError (Int, ByteString))
boundedIncrementalRead Int -> IO ()
retain BodyLimit
limits BodyReader
readChunk

-- | Pay each buffered chunk's own charge, never a running total, before the bounded reader retains it.
boundedIncrementalRead :: (Int -> IO ()) -> BodyLimit -> IO ByteString -> IO (Either LimitError (Int, ByteString))
boundedIncrementalRead :: (Int -> IO ())
-> BodyLimit
-> BodyReader
-> IO (Either LimitError (Int, ByteString))
boundedIncrementalRead Int -> IO ()
charge BodyLimit
limits = BodyLimit -> BodyReader -> IO (Either LimitError (Int, ByteString))
forall (m :: * -> *).
Monad m =>
BodyLimit
-> m ByteString -> m (Either LimitError (Int, ByteString))
boundedRead BodyLimit
limits (BodyReader -> IO (Either LimitError (Int, ByteString)))
-> (BodyReader -> BodyReader)
-> BodyReader
-> IO (Either LimitError (Int, ByteString))
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Int -> IO ()) -> BodyReader -> BodyReader
chargedRead (\Int
bytes -> let cost :: Int
cost = Int -> Int
bufferedChunkCharge Int
bytes in Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
cost Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0) (Int -> IO ()
charge Int
cost))

-- | Report request-formation and exchange failures through the same error channel.
formThen ::
    (UrlFormationError -> fault) ->
    (Request -> IO (Either fault a)) ->
    Either UrlFormationError Request ->
    IO (Either fault a)
formThen :: forall fault a.
(UrlFormationError -> fault)
-> (Request -> IO (Either fault a))
-> Either UrlFormationError Request
-> IO (Either fault a)
formThen UrlFormationError -> fault
unformable = (UrlFormationError -> IO (Either fault a))
-> (Request -> IO (Either fault a))
-> Either UrlFormationError Request
-> IO (Either fault a)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Either fault a -> IO (Either fault a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either fault a -> IO (Either fault a))
-> (UrlFormationError -> Either fault a)
-> UrlFormationError
-> IO (Either fault a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. fault -> Either fault a
forall a b. a -> Either a b
Left (fault -> Either fault a)
-> (UrlFormationError -> fault)
-> UrlFormationError
-> Either fault a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. UrlFormationError -> fault
unformable)