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

{- | Shared HTTP fault classification for registry, queue, and advisory adapters.
Client exceptions become "Ecluse.Core.Fault" values at the adapter boundary. Neither a value nor
its rendering carries the request or the response: a header, a query a redirect reached, or a
cookie can carry a credential. Every manager the roles build starts from 'typedTlsManagerSettings',
so a failed body read raises a client exception too.
-}
module Ecluse.Core.Fault.Http (
    classifyTransport,
    httpFault,
    isRetryableStatusCode,
    displayFaultT,
    isClientFault,
    hostPortLabel,

    -- * Managers
    typedBodyReads,
    typedTlsManagerSettings,
) where

import Data.List (lookup)
import Data.Text qualified as T
import GHC.IO.Exception (IOErrorType (ResourceVanished, TimeExpired))
import Network.Connection (HostCannotConnect, HostNotResolved)
import Network.HTTP.Client (
    BodyReader,
    HttpException (HttpExceptionRequest, InvalidUrlException),
    HttpExceptionContent (..),
    ManagerSettings (managerModifyResponse),
    Request (host, port),
    Response,
    getOriginalRequest,
    responseStatus,
 )
import Network.HTTP.Client.Internal (unHttpExceptionContentWrapper)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Network.HTTP.Types.Status (statusCode)
import Network.TLS qualified as TLS
import System.IO.Error (IOError, ioeGetErrorType)
import UnliftIO.Exception (catchJust, throwIO)

import Ecluse.Core.Fault (
    HttpFault (HttpStatus, HttpTransport),
    TransportCause (TransportProtocol, TransportTimeout, TransportTls, TransportUnreachable),
    TransportFault,
    renderHttpFault,
    transportFault,
 )
import Ecluse.Core.Security.Authority (dialledAuthorityLabel)
import Ecluse.Core.Text (displayExceptionT)

-- | Classify a client exception by type, reading text only for the socket error tls keeps as text. The detail is the dialled @host:port@ and the client's own reason.
classifyTransport :: HttpException -> TransportFault
classifyTransport :: HttpException -> TransportFault
classifyTransport HttpException
err = TransportCause -> Text -> TransportFault
transportFault (HttpException -> TransportCause
causeOf HttpException
err) (HttpException -> Text
dialledAuthority HttpException
err Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> HttpException -> Text
clientReason HttpException
err)
  where
    causeOf :: HttpException -> TransportCause
causeOf = \case
        HttpExceptionRequest Request
_ HttpExceptionContent
content -> case HttpExceptionContent
content of
            HttpExceptionContent
ConnectionTimeout -> TransportCause
TransportTimeout
            HttpExceptionContent
ResponseTimeout -> TransportCause
TransportTimeout
            ConnectionFailure SomeException
_ -> TransportCause
TransportUnreachable
            HttpExceptionContent
ConnectionClosed -> TransportCause
TransportUnreachable
            -- The peer hung up before the first response byte, so the request never
            -- reached a protocol exchange.
            HttpExceptionContent
NoResponseDataReceived -> TransportCause
TransportUnreachable
            InternalException SomeException
inner -> SomeException -> TransportCause
internalCause SomeException
inner
            HttpExceptionContent
_ -> TransportCause
TransportProtocol
        InvalidUrlException String
_ String
_ -> TransportCause
TransportProtocol

-- The TLS manager wraps its connector's refused connection or empty address list here, where plain HTTP raises ConnectionFailure.
-- A failed socket call classes by its error type on either scheme, inside the TLS handshake or outside it.
internalCause :: SomeException -> TransportCause
internalCause :: SomeException -> TransportCause
internalCause SomeException
inner
    | Just (TLS.HandshakeFailed TLSError
reason) <- SomeException -> Maybe TLSException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
inner, Just TransportCause
cause <- TLSError -> Maybe TransportCause
handshakeSocketCause TLSError
reason = TransportCause
cause
    | Just (TLSException
_ :: TLS.TLSException) <- SomeException -> Maybe TLSException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
inner = TransportCause
TransportTls
    | Just (HostCannotConnect
_ :: HostCannotConnect) <- SomeException -> Maybe HostCannotConnect
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
inner = TransportCause
TransportUnreachable
    | Just (HostNotResolved
_ :: HostNotResolved) <- SomeException -> Maybe HostNotResolved
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
inner = TransportCause
TransportUnreachable
    | Just IOError
ioe <- SomeException -> Maybe IOError
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
inner, Just TransportCause
cause <- IOErrorType
-> [(IOErrorType, TransportCause)] -> Maybe TransportCause
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup (IOError -> IOErrorType
ioeGetErrorType IOError
ioe) [(IOErrorType, TransportCause)]
socketCauses = TransportCause
cause
    | Bool
otherwise = TransportCause
TransportProtocol

-- A peer that closes or resets is unreachable, as NoResponseDataReceived is. A timed-out socket call is the kernel giving up on an unanswered peer.
socketCauses :: [(IOErrorType, TransportCause)]
socketCauses :: [(IOErrorType, TransportCause)]
socketCauses = [(IOErrorType
ResourceVanished, TransportCause
TransportUnreachable), (IOErrorType
TimeExpired, TransportCause
TransportTimeout)]

-- tls keeps a socket's IOException only as its shown text, "location: type (reason)", so the error type is
-- recognised as base renders it between those delimiters.
handshakeSocketCause :: TLS.TLSError -> Maybe TransportCause
handshakeSocketCause :: TLSError -> Maybe TransportCause
handshakeSocketCause = \case
    TLSError
TLS.Error_EOF -> TransportCause -> Maybe TransportCause
forall a. a -> Maybe a
Just TransportCause
TransportUnreachable
    TLS.Error_Misc String
shown -> [TransportCause] -> Maybe TransportCause
forall a. [a] -> Maybe a
listToMaybe [TransportCause
cause | (IOErrorType
errorType, TransportCause
cause) <- [(IOErrorType, TransportCause)]
socketCauses, (Text
": " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> IOErrorType -> Text
forall b a. (Show a, IsString b) => a -> b
show IOErrorType
errorType Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" (") Text -> Text -> Bool
`T.isInfixOf` String -> Text
forall a. ToText a => a -> Text
toText String
shown]
    TLSError
_ -> Maybe TransportCause
forall a. Maybe a
Nothing

-- | The answered status, or else the transport fault 'classifyTransport' assigns.
httpFault :: HttpException -> HttpFault
httpFault :: HttpException -> HttpFault
httpFault = \case
    HttpExceptionRequest Request
_ (StatusCodeException Response ()
response ByteString
_) -> Int -> HttpFault
HttpStatus (Status -> Int
statusCode (Response () -> Status
forall body. Response body -> Status
responseStatus Response ()
response))
    HttpException
other -> TransportFault -> HttpFault
HttpTransport (HttpException -> TransportFault
classifyTransport HttpException
other)

-- | Whether an HTTP status signals a temporary failure: server errors, timeout, or throttling.
isRetryableStatusCode :: Int -> Bool
isRetryableStatusCode :: Int -> Bool
isRetryableStatusCode Int
code = Int
code Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
500 Bool -> Bool -> Bool
|| Int
code Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
408 Bool -> Bool -> Bool
|| Int
code Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
429

-- | An exception for a log line, without GHC's context. A client exception renders through 'renderHttpFault' at the @host:port@ it dialled, or by its reason alone without a request.
displayFaultT :: SomeException -> Text
displayFaultT :: SomeException -> Text
displayFaultT SomeException
err
    | Just HttpException
http <- SomeException -> Maybe HttpException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
err = Text -> HttpFault -> Text
renderHttpFault (HttpException -> Text
dialledAuthority HttpException
http) (HttpException -> HttpFault
httpFault HttpException
http)
    | Just HttpExceptionContent
content <- SomeException -> Maybe HttpExceptionContent
outsideRequest SomeException
err = HttpExceptionContent -> Text
contentReason HttpExceptionContent
content
    | Bool
otherwise = SomeException -> Text
displayWithoutContext SomeException
err

-- | Whether 'displayFaultT' renders the exception as an http-client fault, with a request or without one.
isClientFault :: SomeException -> Bool
isClientFault :: SomeException -> Bool
isClientFault SomeException
err = Maybe HttpException -> Bool
forall a. Maybe a -> Bool
isJust (forall e. Exception e => SomeException -> Maybe e
fromException @HttpException SomeException
err) Bool -> Bool -> Bool
|| Maybe HttpExceptionContent -> Bool
forall a. Maybe a -> Bool
isJust (SomeException -> Maybe HttpExceptionContent
outsideRequest SomeException
err)

-- A fault http-client raises outside a request, such as a malformed proxy variable, carries no HttpException and no peer to name.
outsideRequest :: SomeException -> Maybe HttpExceptionContent
outsideRequest :: SomeException -> Maybe HttpExceptionContent
outsideRequest SomeException
err = HttpExceptionContentWrapper -> HttpExceptionContent
unHttpExceptionContentWrapper (HttpExceptionContentWrapper -> HttpExceptionContent)
-> Maybe HttpExceptionContentWrapper -> Maybe HttpExceptionContent
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SomeException -> Maybe HttpExceptionContentWrapper
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
err

-- | A dialled host and port as a log line names them, so an IPv6 host keeps its brackets.
hostPortLabel :: Text -> Int -> Text
hostPortLabel :: Text -> Int -> Text
hostPortLabel Text
dialledHost Int
dialledPort = Text -> Text
dialledAuthorityLabel (Text
dialledHost Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
":" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Int -> Text
forall b a. (Show a, IsString b) => a -> b
show Int
dialledPort)

-- | Raise a socket or TLS failure in a response body read as the 'HttpException' the client raises for one before the body.
typedBodyReads :: ManagerSettings -> ManagerSettings
typedBodyReads :: ManagerSettings -> ManagerSettings
typedBodyReads ManagerSettings
settings = ManagerSettings
settings{managerModifyResponse = fmap typedReads . managerModifyResponse settings}

-- | 'tlsManagerSettings' under 'typedBodyReads': every manager the roles build starts from this value.
typedTlsManagerSettings :: ManagerSettings
typedTlsManagerSettings :: ManagerSettings
typedTlsManagerSettings = ManagerSettings -> ManagerSettings
typedBodyReads ManagerSettings
tlsManagerSettings

-- http-client wraps an exception only until the response arrives, so a failure in the body reaches the reader bare.
typedReads :: Response BodyReader -> Response BodyReader
typedReads :: Response BodyReader -> Response BodyReader
typedReads Response BodyReader
response = BodyReader -> BodyReader
forall {m :: * -> *} {a}. MonadUnliftIO m => m a -> m a
rewrap (BodyReader -> BodyReader)
-> Response BodyReader -> Response BodyReader
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Response BodyReader
response
  where
    rewrap :: m a -> m a
rewrap m a
bodyRead = (SomeException -> Maybe SomeException)
-> m a -> (SomeException -> m a) -> m a
forall (m :: * -> *) e b a.
(MonadUnliftIO m, Exception e) =>
(e -> Maybe b) -> m a -> (b -> m a) -> m a
catchJust SomeException -> Maybe SomeException
bareFault m a
bodyRead (HttpException -> m a
forall (m :: * -> *) e a. (MonadIO m, Exception e) => e -> m a
throwIO (HttpException -> m a)
-> (SomeException -> HttpException) -> SomeException -> m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Request -> HttpExceptionContent -> HttpException
HttpExceptionRequest (Response BodyReader -> Request
forall a. Response a -> Request
getOriginalRequest Response BodyReader
response) (HttpExceptionContent -> HttpException)
-> (SomeException -> HttpExceptionContent)
-> SomeException
-> HttpException
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SomeException -> HttpExceptionContent
InternalException)

bareFault :: SomeException -> Maybe SomeException
bareFault :: SomeException -> Maybe SomeException
bareFault SomeException
err
    | Maybe IOError -> Bool
forall a. Maybe a -> Bool
isJust (forall e. Exception e => SomeException -> Maybe e
fromException @IOError SomeException
err) Bool -> Bool -> Bool
|| Maybe TLSException -> Bool
forall a. Maybe a -> Bool
isJust (forall e. Exception e => SomeException -> Maybe e
fromException @TLS.TLSException SomeException
err) = SomeException -> Maybe SomeException
forall a. a -> Maybe a
Just SomeException
err
    | Bool
otherwise = Maybe SomeException
forall a. Maybe a
Nothing

-- A status and a socket or TLS failure in a body read carry the request a redirect reached. Any other fault carries the request first sent.
dialledAuthority :: HttpException -> Text
dialledAuthority :: HttpException -> Text
dialledAuthority = \case
    HttpExceptionRequest Request
request HttpExceptionContent
_ -> Text -> Int -> Text
hostPortLabel (ByteString -> Text
forall a b. ConvertUtf8 a b => b -> a
decodeUtf8 (Request -> ByteString
host Request
request)) (Request -> Int
port Request
request)
    InvalidUrlException String
url String
_ -> Text -> Text
dialledAuthorityLabel (String -> Text
forall a. ToText a => a -> Text
toText String
url)

clientReason :: HttpException -> Text
clientReason :: HttpException -> Text
clientReason = \case
    HttpExceptionRequest Request
_ HttpExceptionContent
content -> HttpExceptionContent -> Text
contentReason HttpExceptionContent
content
    InvalidUrlException String
_ String
reason -> Text
"InvalidUrlException: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> String -> Text
forall a. ToText a => a -> Text
toText String
reason

-- Every constructor by name, so a new one fails the build until judged. Byte strings (headers, status
-- lines, proxy values) are never rendered, and an inner exception renders without GHC's context.
contentReason :: HttpExceptionContent -> Text
contentReason :: HttpExceptionContent -> Text
contentReason = \case
    StatusCodeException Response ()
response ByteString
_ -> Text
"StatusCodeException: HTTP " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Int -> Text
forall b a. (Show a, IsString b) => a -> b
show (Status -> Int
statusCode (Response () -> Status
forall body. Response body -> Status
responseStatus Response ()
response))
    TooManyRedirects [Response ByteString]
_ -> Text
"TooManyRedirects"
    HttpExceptionContent
OverlongHeaders -> Text
"OverlongHeaders"
    HttpExceptionContent
TooManyHeaderFields -> Text
"TooManyHeaderFields"
    HttpExceptionContent
ResponseTimeout -> Text
"ResponseTimeout"
    HttpExceptionContent
ConnectionTimeout -> Text
"ConnectionTimeout"
    ConnectionFailure SomeException
inner -> Text
"ConnectionFailure: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> SomeException -> Text
displayWithoutContext SomeException
inner
    InvalidStatusLine ByteString
_ -> Text
"InvalidStatusLine"
    InvalidHeader ByteString
_ -> Text
"InvalidHeader"
    InvalidRequestHeader ByteString
_ -> Text
"InvalidRequestHeader"
    InternalException SomeException
inner -> Text
"InternalException: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> SomeException -> Text
displayWithoutContext SomeException
inner
    ProxyConnectException{} -> Text
"ProxyConnectException"
    HttpExceptionContent
NoResponseDataReceived -> Text
"NoResponseDataReceived"
    HttpExceptionContent
TlsNotSupported -> Text
"TlsNotSupported"
    WrongRequestBodyStreamSize{} -> Text
"WrongRequestBodyStreamSize"
    ResponseBodyTooShort{} -> Text
"ResponseBodyTooShort"
    HttpExceptionContent
InvalidChunkHeaders -> Text
"InvalidChunkHeaders"
    HttpExceptionContent
IncompleteHeaders -> Text
"IncompleteHeaders"
    InvalidDestinationHost ByteString
_ -> Text
"InvalidDestinationHost"
    HttpZlibException ZlibException
_ -> Text
"HttpZlibException"
    InvalidProxyEnvironmentVariable Text
name Text
_ -> Text
"InvalidProxyEnvironmentVariable: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
name
    HttpExceptionContent
ConnectionClosed -> Text
"ConnectionClosed"
    InvalidProxySettings Text
_ -> Text
"InvalidProxySettings"

-- GHC 9.10 appends the exception context, a backtrace, to a SomeException's display. The exception inside renders without it.
displayWithoutContext :: SomeException -> Text
displayWithoutContext :: SomeException -> Text
displayWithoutContext (SomeException e
inner) = e -> Text
forall e. Exception e => e -> Text
displayExceptionT e
inner