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

{- | What a span records when an exception escapes it. @hs-opentelemetry@ records an escaping
exception's 'displayException'. For an HTTP client or @amazonka@ exception, that text holds the
request, header and query included, or a proxy variable's value. 'withEscapeHandler' tells the
library to ignore those, and 'recordEscape' records a typed cause and the error status in their place.
-}
module Ecluse.Runtime.Telemetry.Escape (
    escapedRequestCause,
    withEscapeHandler,
    recordEscape,
    escapeRecordingMiddleware,
) where

import Data.HashMap.Strict qualified as HashMap
import Data.Typeable (typeOf)
import Network.Wai (Middleware)
import OpenTelemetry.Attributes (toAttribute)
import OpenTelemetry.Trace.Core (
    ExceptionClassification (IgnoredException),
    ExceptionHandler,
    ExceptionResponse (ExceptionResponse),
    NewEvent (NewEvent, newEventAttributes, newEventName, newEventTimestamp),
    Span,
    SpanStatus (Error),
    TracerProviderOptions (tracerProviderOptionsExceptionHandlers),
    addEvent,
    getActiveSpan,
    setStatus,
 )
import UnliftIO.Exception (withException)

import Ecluse.Core.Fault (renderTransportFault)
import Ecluse.Core.Fault.Http (displayFaultT, isClientFault)
import Ecluse.Runtime.Aws.Fault (classifyEscapedTransport)

-- | The typed cause of an exception whose own rendering can print a request or a proxy credential, or 'Nothing' for any other.
escapedRequestCause :: SomeException -> Maybe Text
escapedRequestCause :: SomeException -> Maybe Text
escapedRequestCause SomeException
err
    | SomeException -> Bool
isClientFault SomeException
err = Text -> Maybe Text
forall a. a -> Maybe a
Just (SomeException -> Text
displayFaultT SomeException
err)
    | Bool
otherwise = TransportFault -> Text
renderTransportFault (TransportFault -> Text) -> Maybe TransportFault -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SomeException -> Maybe TransportFault
classifyEscapedTransport SomeException
err

-- | Make the library ignore an exception 'escapedRequestCause' knows, so only 'recordEscape' records it.
withEscapeHandler :: TracerProviderOptions -> TracerProviderOptions
withEscapeHandler :: TracerProviderOptions -> TracerProviderOptions
withEscapeHandler TracerProviderOptions
options =
    TracerProviderOptions
options{tracerProviderOptionsExceptionHandlers = ignoreRequestFaults : tracerProviderOptionsExceptionHandlers options}

ignoreRequestFaults :: ExceptionHandler
ignoreRequestFaults :: ExceptionHandler
ignoreRequestFaults SomeException
err = ExceptionClassification -> AttributeMap -> ExceptionResponse
ExceptionResponse ExceptionClassification
IgnoredException AttributeMap
forall a. Monoid a => a
mempty ExceptionResponse -> Maybe Text -> Maybe ExceptionResponse
forall a b. a -> Maybe b -> Maybe a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ SomeException -> Maybe Text
escapedRequestCause SomeException
err

-- | Record an escaping exception the library ignores: its typed cause as the error status, and as an @exception@ event.
recordEscape :: (MonadIO m) => Span -> SomeException -> m ()
recordEscape :: forall (m :: * -> *). MonadIO m => Span -> SomeException -> m ()
recordEscape Span
theSpan err :: SomeException
err@(SomeException e
inner) = Maybe Text -> (Text -> m ()) -> m ()
forall (f :: * -> *) a.
Applicative f =>
Maybe a -> (a -> f ()) -> f ()
whenJust (SomeException -> Maybe Text
escapedRequestCause SomeException
err) ((Text -> m ()) -> m ()) -> (Text -> m ()) -> m ()
forall a b. (a -> b) -> a -> b
$ \Text
cause -> do
    Span -> SpanStatus -> m ()
forall (m :: * -> *). MonadIO m => Span -> SpanStatus -> m ()
setStatus Span
theSpan (Text -> SpanStatus
Error Text
cause)
    Span -> NewEvent -> m ()
forall (m :: * -> *). MonadIO m => Span -> NewEvent -> m ()
addEvent
        Span
theSpan
        NewEvent
            { newEventName :: Text
newEventName = Text
"exception"
            , newEventAttributes :: AttributeMap
newEventAttributes =
                [(Text, Attribute)] -> AttributeMap
forall k v. (Eq k, Hashable k) => [(k, v)] -> HashMap k v
HashMap.fromList
                    [ (Text
"exception.type", Text -> Attribute
forall a. ToAttribute a => a -> Attribute
toAttribute (TypeRep -> Text
forall b a. (Show a, IsString b) => a -> b
show (e -> TypeRep
forall a. Typeable a => a -> TypeRep
typeOf e
inner) :: Text))
                    , (Text
"exception.message", Text -> Attribute
forall a. ToAttribute a => a -> Attribute
toAttribute Text
cause)
                    , (Text
"exception.escaped", Bool -> Attribute
forall a. ToAttribute a => a -> Attribute
toAttribute Bool
True)
                    ]
            , newEventTimestamp :: Maybe Timestamp
newEventTimestamp = Maybe Timestamp
forall a. Maybe a
Nothing
            }

-- | Record an exception escaping the application on the active span, the WAI server span when this runs inside its middleware.
escapeRecordingMiddleware :: Middleware
escapeRecordingMiddleware :: Middleware
escapeRecordingMiddleware Application
app Request
request Response -> IO ResponseReceived
respond =
    Application
app Request
request Response -> IO ResponseReceived
respond IO ResponseReceived
-> (SomeException -> IO ()) -> IO ResponseReceived
forall (m :: * -> *) e a b.
(MonadUnliftIO m, Exception e) =>
m a -> (e -> m b) -> m a
`withException` \SomeException
err -> IO (Maybe Span)
forall (m :: * -> *). MonadIO m => m (Maybe Span)
getActiveSpan IO (Maybe Span) -> (Maybe Span -> 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
>>= (Span -> IO ()) -> Maybe Span -> IO ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ (Span -> SomeException -> IO ()
forall (m :: * -> *). MonadIO m => Span -> SomeException -> m ()
`recordEscape` SomeException
err)