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

{- | The wait "Ecluse.Core.Registry.ResponseWait" keeps for each exchange, its pure transitions, and
the opener under any length of wait. Importing this module opts out of the public surface's
stability promises. It exists so a spec can test the transitions directly and open responses under a
wait of a second or two.
-}
module Ecluse.Core.Registry.ResponseWait.Internal (
    ResponseWait (..),
    connectedAt,
    uploadingAt,
    uploadedAt,
    waitFault,
    openResponseAfter,
    WaitExpired (..),
) where

import Control.Exception (asyncExceptionFromException, asyncExceptionToException, handleJust)
import Data.ByteString qualified as BS
import GHC.Clock (getMonotonicTimeNSec)
import Network.HTTP.Client (
    BodyReader,
    GivesPopper,
    HttpException (HttpExceptionRequest),
    HttpExceptionContent (ConnectionTimeout, ResponseTimeout),
    Request (checkResponse, requestBody, responseTimeout),
    RequestBody (..),
    Response,
    responseOpen,
    responseTimeoutNone,
 )
import Network.HTTP.Client.Internal (throwHttp)
import Text.Show (showParen, showString, shows, showsPrec)
import UnliftIO.Exception (throwIO)

import Ecluse.Core.Deadline (withEndableDeadline)
import Ecluse.Core.Registry.Exchange.Types (ExchangeClient (..))

{- | Where an exchange stands, each with the monotonic nanoseconds that bound it: the connection's
deadline, the wait an upload leaves for the headers, or the headers' deadline.
-}
data ResponseWait
    = Connecting {-# UNPACK #-} !Word64
    | Uploading {-# UNPACK #-} !Word64
    | Answering {-# UNPACK #-} !Word64
    deriving stock (ResponseWait -> ResponseWait -> Bool
(ResponseWait -> ResponseWait -> Bool)
-> (ResponseWait -> ResponseWait -> Bool) -> Eq ResponseWait
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ResponseWait -> ResponseWait -> Bool
== :: ResponseWait -> ResponseWait -> Bool
$c/= :: ResponseWait -> ResponseWait -> Bool
/= :: ResponseWait -> ResponseWait -> Bool
Eq, Int -> ResponseWait -> ShowS
[ResponseWait] -> ShowS
ResponseWait -> String
(Int -> ResponseWait -> ShowS)
-> (ResponseWait -> String)
-> ([ResponseWait] -> ShowS)
-> Show ResponseWait
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ResponseWait -> ShowS
showsPrec :: Int -> ResponseWait -> ShowS
$cshow :: ResponseWait -> String
show :: ResponseWait -> String
$cshowList :: [ResponseWait] -> ShowS
showList :: [ResponseWait] -> ShowS
Show)

{- | The wait the headers have left once a connection is in hand: what the connection left of the
whole wait, or on http-client's retry of a stale connection, what the attempt before it left.
-}
connectedAt :: Word64 -> ResponseWait -> Either HttpExceptionContent Word64
connectedAt :: Word64 -> ResponseWait -> Either HttpExceptionContent Word64
connectedAt Word64
now = \case
    Connecting Word64
deadline -> HttpExceptionContent
-> Word64 -> Either HttpExceptionContent Word64
forall {a}. a -> Word64 -> Either a Word64
leftBefore HttpExceptionContent
ConnectionTimeout Word64
deadline
    Uploading Word64
left -> Word64 -> Either HttpExceptionContent Word64
forall a b. b -> Either a b
Right Word64
left
    Answering Word64
deadline -> HttpExceptionContent
-> Word64 -> Either HttpExceptionContent Word64
forall {a}. a -> Word64 -> Either a Word64
leftBefore HttpExceptionContent
ResponseTimeout Word64
deadline
  where
    leftBefore :: a -> Word64 -> Either a Word64
leftBefore a
fault Word64
deadline = if Word64
now Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word64
deadline then a -> Either a Word64
forall a b. a -> Either a b
Left a
fault else Word64 -> Either a Word64
forall a b. b -> Either a b
Right (Word64
deadline Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
now)

-- | Pause the headers' deadline while a streamed body is written. A deadline already due stays due.
uploadingAt :: Word64 -> ResponseWait -> ResponseWait
uploadingAt :: Word64 -> ResponseWait -> ResponseWait
uploadingAt Word64
now = \case
    Answering Word64
deadline | Word64
now Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
< Word64
deadline -> Word64 -> ResponseWait
Uploading (Word64
deadline Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
now)
    ResponseWait
other -> ResponseWait
other

-- | Start the headers' deadline again once the request body is written.
uploadedAt :: Word64 -> ResponseWait -> ResponseWait
uploadedAt :: Word64 -> ResponseWait -> ResponseWait
uploadedAt Word64
now = \case
    Uploading Word64
left -> Word64 -> ResponseWait
Answering (Word64
now Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
+ Word64
left)
    ResponseWait
other -> ResponseWait
other

-- | The timeout an exchange takes at a monotonic time, if its wait ran out.
waitFault :: Word64 -> ResponseWait -> Maybe HttpExceptionContent
waitFault :: Word64 -> ResponseWait -> Maybe HttpExceptionContent
waitFault Word64
now = \case
    Connecting Word64
deadline | Word64
now Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word64
deadline -> HttpExceptionContent -> Maybe HttpExceptionContent
forall a. a -> Maybe a
Just HttpExceptionContent
ConnectionTimeout
    Answering Word64
deadline | Word64
now Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word64
deadline -> HttpExceptionContent -> Maybe HttpExceptionContent
forall a. a -> Maybe a
Just HttpExceptionContent
ResponseTimeout
    ResponseWait
_ -> Maybe HttpExceptionContent
forall a. Maybe a
Nothing

{- | 'responseOpen' with a wait of this many nanoseconds in place of http-client's response timeout.
The wait ends once the headers are in, before the caller sees the response.
-}
openResponseAfter :: Word64 -> ExchangeClient -> Request -> IO (Response BodyReader)
openResponseAfter :: Word64 -> ExchangeClient -> Request -> IO (Response BodyReader)
openResponseAfter Word64
whole ExchangeClient{Manager
ecManager :: Manager
ecManager :: ExchangeClient -> Manager
ecManager, Deadlines
ecDeadlines :: Deadlines
ecDeadlines :: ExchangeClient -> Deadlines
ecDeadlines} Request
request = do
    started <- IO Word64
getMonotonicTimeNSec
    wait <- newIORef $! Connecting (started + whole)
    scope <- newIORef ()
    let expired Word64
now = (HttpExceptionContent -> SomeException)
-> Maybe HttpExceptionContent -> Maybe SomeException
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (WaitExpired -> SomeException
forall e. Exception e => e -> SomeException
toException (WaitExpired -> SomeException)
-> (HttpExceptionContent -> WaitExpired)
-> HttpExceptionContent
-> SomeException
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IORef () -> HttpExceptionContent -> WaitExpired
WaitExpired IORef ()
scope) (Maybe HttpExceptionContent -> Maybe SomeException)
-> (ResponseWait -> Maybe HttpExceptionContent)
-> ResponseWait
-> Maybe SomeException
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Word64 -> ResponseWait -> Maybe HttpExceptionContent
waitFault Word64
now (ResponseWait -> Maybe SomeException)
-> f ResponseWait -> f (Maybe SomeException)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IORef ResponseWait -> f ResponseWait
forall (m :: * -> *) a. MonadIO m => IORef a -> m a
readIORef IORef ResponseWait
wait
        ours (WaitExpired IORef ()
raised HttpExceptionContent
content) = if IORef ()
raised IORef () -> IORef () -> Bool
forall a. Eq a => a -> a -> Bool
== IORef ()
scope then HttpExceptionContent -> Maybe HttpExceptionContent
forall a. a -> Maybe a
Just HttpExceptionContent
content else Maybe HttpExceptionContent
forall a. Maybe a
Nothing
        timed IO a
answered =
            Request
request
                { requestBody = RequestBodyIO (sending wait (requestBody request))
                , responseTimeout = responseTimeoutNone
                , checkResponse = \Request
sent Response BodyReader
response -> IO a
answered IO a -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Request -> Request -> Response BodyReader -> IO ()
checkResponse Request
request Request
sent Response BodyReader
response
                }
    handleJust ours (throwIO . HttpExceptionRequest request) $
        withEndableDeadline ecDeadlines expired (\IO ()
answered -> Request -> Manager -> IO (Response BodyReader)
responseOpen (IO () -> Request
forall {a}. IO a -> Request
timed IO ()
answered) Manager
ecManager)

{- http-client builds the body on a connection, just before the head, which goes out under the headers'
deadline so a retry after a failed head keeps one. Only a streamed body, as a metered one is, pauses it. -}
sending :: IORef ResponseWait -> RequestBody -> IO RequestBody
sending :: IORef ResponseWait -> RequestBody -> IO RequestBody
sending IORef ResponseWait
wait RequestBody
body = do
    now <- IO Word64
getMonotonicTimeNSec
    -- Thrown as http-client throws its own, which tags it with the request and closes the connection.
    left <- either throwHttp pure . connectedAt now =<< readIORef wait
    built <- resolved body
    -- The sweeper reads the wait from another thread, so it only ever holds an evaluated state.
    writeIORef wait $! Answering (now + left)
    pure $ case built of
        RequestBodyStream Int64
size GivesPopper ()
gives -> Int64 -> GivesPopper () -> RequestBody
RequestBodyStream Int64
size (IORef ResponseWait -> GivesPopper () -> GivesPopper ()
timedUpload IORef ResponseWait
wait GivesPopper ()
gives)
        RequestBodyStreamChunked GivesPopper ()
gives -> GivesPopper () -> RequestBody
RequestBodyStreamChunked (IORef ResponseWait -> GivesPopper () -> GivesPopper ()
timedUpload IORef ResponseWait
wait GivesPopper ()
gives)
        RequestBody
other -> RequestBody
other

resolved :: RequestBody -> IO RequestBody
resolved :: RequestBody -> IO RequestBody
resolved = \case
    RequestBodyIO IO RequestBody
build -> IO RequestBody
build IO RequestBody -> (RequestBody -> IO RequestBody) -> IO RequestBody
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= RequestBody -> IO RequestBody
resolved
    RequestBody
other -> RequestBody -> IO RequestBody
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure RequestBody
other

-- The connection pulls until a slice comes back empty.
timedUpload :: IORef ResponseWait -> GivesPopper () -> GivesPopper ()
timedUpload :: IORef ResponseWait -> GivesPopper () -> GivesPopper ()
timedUpload IORef ResponseWait
wait GivesPopper ()
gives NeedsPopper ()
needsPopper = GivesPopper ()
gives GivesPopper () -> GivesPopper ()
forall a b. (a -> b) -> a -> b
$ \BodyReader
popper -> NeedsPopper ()
needsPopper NeedsPopper () -> NeedsPopper ()
forall a b. (a -> b) -> a -> b
$ do
    (Word64 -> ResponseWait -> ResponseWait) -> IO ()
stamp Word64 -> ResponseWait -> ResponseWait
uploadingAt
    slice <- BodyReader
popper
    slice <$ when (BS.null slice) (stamp uploadedAt)
  where
    stamp :: (Word64 -> ResponseWait -> ResponseWait) -> IO ()
stamp Word64 -> ResponseWait -> ResponseWait
transition = IO Word64
getMonotonicTimeNSec IO Word64 -> (Word64 -> IO ()) -> IO ()
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \Word64
now -> IORef ResponseWait -> (ResponseWait -> ResponseWait) -> IO ()
forall (m :: * -> *) a. MonadIO m => IORef a -> (a -> a) -> m ()
modifyIORef' IORef ResponseWait
wait (Word64 -> ResponseWait -> ResponseWait
transition Word64
now)

{- | Raised asynchronously, as http-client's own timer is, so a TLS handshake that wraps synchronous
faults passes it on. 'openResponseAfter' turns it back into the client's fault.
-}
data WaitExpired = WaitExpired (IORef ()) HttpExceptionContent

-- Shown as http-client's unexported wrapper shows its own timeout, because the client span records the text.
instance Show WaitExpired where
    showsPrec :: Int -> WaitExpired -> ShowS
showsPrec Int
precedence (WaitExpired IORef ()
_ HttpExceptionContent
content) =
        Bool -> ShowS -> ShowS
showParen (Int
precedence Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
11) (String -> ShowS
showString String
"HttpExceptionContentWrapper {unHttpExceptionContentWrapper = " ShowS -> ShowS -> ShowS
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HttpExceptionContent -> ShowS
forall a. Show a => a -> ShowS
shows HttpExceptionContent
content ShowS -> ShowS -> ShowS
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> ShowS
showString String
"}")

instance Exception WaitExpired where
    toException :: WaitExpired -> SomeException
toException = WaitExpired -> SomeException
forall e. Exception e => e -> SomeException
asyncExceptionToException
    fromException :: SomeException -> Maybe WaitExpired
fromException = SomeException -> Maybe WaitExpired
forall e. Exception e => SomeException -> Maybe e
asyncExceptionFromException