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

{- | Observe HTTP attempts without taking ownership of their responses.
Callers admit local work first and report headers before consuming the body.
Attempt notification precedes header writes and does not prove remote receipt.
Connection failures can occur before that notification.
The injected recorder must not throw.
-}
module Ecluse.Core.Registry.Exchange.Observe (
    ExchangeOutcome (..),
    observeExchange,
) where

import Control.Exception qualified as Exception
import Network.HTTP.Client (HttpException, Request (requestBody), RequestBody (RequestBodyIO))
import Network.HTTP.Types (Status, statusCode)

import Ecluse.Core.Registry.Progress (isProgressFloorFailure)
import Ecluse.Core.Telemetry.Upstream (ExchangeOutcome (..))

data Attempt = Unstarted | Pending | Answered
    deriving stock (Attempt -> Attempt -> Bool
(Attempt -> Attempt -> Bool)
-> (Attempt -> Attempt -> Bool) -> Eq Attempt
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Attempt -> Attempt -> Bool
== :: Attempt -> Attempt -> Bool
$c/= :: Attempt -> Attempt -> Bool
/= :: Attempt -> Attempt -> Bool
Eq)

-- | Keep response ownership in the continuation. Report its headers before reading its body.
observeExchange :: (ExchangeOutcome -> IO ()) -> Request -> (Request -> (Status -> IO ()) -> IO a) -> IO a
observeExchange :: forall a.
(ExchangeOutcome -> IO ())
-> Request -> (Request -> (Status -> IO ()) -> IO a) -> IO a
observeExchange ExchangeOutcome -> IO ()
record Request
request Request -> (Status -> IO ()) -> IO a
action = ((forall a. IO a -> IO a) -> IO a) -> IO a
forall b. ((forall a. IO a -> IO a) -> IO b) -> IO b
Exception.mask (((forall a. IO a -> IO a) -> IO a) -> IO a)
-> ((forall a. IO a -> IO a) -> IO a) -> IO a
forall a b. (a -> b) -> a -> b
$ \forall a. IO a -> IO a
restore -> do
    attemptPhase <- Attempt -> IO (IORef Attempt)
forall (m :: * -> *) a. MonadIO m => a -> m (IORef a)
newIORef Attempt
Unstarted
    let settle ExchangeOutcome
outcome = IO () -> IO ()
forall a. IO a -> IO a
Exception.mask_ (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
            previous <- IORef Attempt -> (Attempt -> (Attempt, Attempt)) -> IO Attempt
forall (m :: * -> *) a b.
MonadIO m =>
IORef a -> (a -> (a, b)) -> m b
atomicModifyIORef' IORef Attempt
attemptPhase (Attempt
Answered,)
            unless (previous == Answered) (record outcome)
        starting = IO () -> IO ()
forall a. IO a -> IO a
Exception.mask_ (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
            previous <- IORef Attempt -> (Attempt -> (Attempt, Attempt)) -> IO Attempt
forall (m :: * -> *) a b.
MonadIO m =>
IORef a -> (a -> (a, b)) -> m b
atomicModifyIORef' IORef Attempt
attemptPhase (Attempt
Pending,)
            when (previous == Pending) (record TransportFailure)
        observed = Request
request{requestBody = RequestBodyIO (starting $> requestBody request)}
        headers = ExchangeOutcome -> IO ()
settle (ExchangeOutcome -> IO ())
-> (Status -> ExchangeOutcome) -> Status -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> ExchangeOutcome
ResponseStatus (Int -> ExchangeOutcome)
-> (Status -> Int) -> Status -> ExchangeOutcome
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Status -> Int
statusCode
        failed (SomeException
fault :: Exception.SomeException) = do
            current <- IORef Attempt -> IO Attempt
forall (m :: * -> *) a. MonadIO m => IORef a -> m a
readIORef IORef Attempt
attemptPhase
            case (Exception.fromException fault :: Maybe Exception.SomeAsyncException, Exception.fromException fault :: Maybe HttpException) of
                (Just SomeAsyncException
_, Maybe HttpException
_) -> Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Attempt
current Attempt -> Attempt -> Bool
forall a. Eq a => a -> a -> Bool
== Attempt
Pending) (ExchangeOutcome -> IO ()
settle ExchangeOutcome
Cancelled)
                (Maybe SomeAsyncException
_, Just HttpException
_) -> ExchangeOutcome -> IO ()
settle ExchangeOutcome
TransportFailure
                (Maybe SomeAsyncException, Maybe HttpException)
_ | SomeException -> Bool
isProgressFloorFailure SomeException
fault -> ExchangeOutcome -> IO ()
settle ExchangeOutcome
TransportFailure
                (Maybe SomeAsyncException, Maybe HttpException)
_ -> IO ()
forall (f :: * -> *). Applicative f => f ()
pass
            Exception.throwIO fault
    outcome <- Exception.try (restore (action observed headers))
    either failed pure outcome