{-# LANGUAGE CPP #-}{- |Module : PGQueuer.TracingDescription : OpenTelemetry distributed tracing and W3C trace context propagation.Copyright : (c) Tushar Adhatrao, 2026License : MITMaintainer : tusharadhatrao@gmail.comStability : experimentalProvides functions for injecting active OpenTelemetry contexts into job headersat enqueue time and extracting them to create linked spans during execution.Compiled conditionally with the @otel@ cabal flag.-}module PGQueuer.Tracing ( injectOtelContext , withJobSpan ) whereimport Data.Aeson (Value (..))import PGQueuer.Types (Entrypoint (..), JobId (..))#ifdef OTELimport qualified Data.Aeson.Key as Kimport qualified Data.Aeson.KeyMap as KMimport qualified Data.CaseInsensitive as CIimport qualified Data.HashMap.Strict as HMimport qualified Data.Text as Timport qualified Data.Text.Encoding as TEimport qualified OpenTelemetry.Context as Contextimport qualified OpenTelemetry.Context.ThreadLocal as ThreadLocalimport qualified OpenTelemetry.Propagator as Propagatorimport qualified OpenTelemetry.Propagator.W3CTraceContext as W3Cimport qualified OpenTelemetry.Trace.Core as Traceimport UnliftIO.Exception (catchAny, throwIO, bracket)import Control.Monad (void)#endif-- | Serialize active OTel context to Aeson.ValueinjectOtelContext :: IO (Maybe Value)#ifdef OTELinjectOtelContext = do mCtx <- ThreadLocal.lookupContext case mCtx of Nothing -> return Nothing Just ctx -> do let prop = W3C.w3cTraceContextPropagator headers <- Propagator.inject prop ctx [] let obj = KM.fromList $ map (\(k, v) -> (K.fromText $ TE.decodeUtf8 $ CI.original k, String $ TE.decodeUtf8 v)) headers return $ Just (Object obj)#elseinjectOtelContext = return Nothing#endif-- | Wrap user execution in a new span, linking the parent contextwithJobSpan :: Entrypoint -> JobId -> Maybe Value -> IO a -> IO a#ifdef OTELwithJobSpan (Entrypoint ep) (JobId jid) mHeaders action = do tp <- Trace.getGlobalTracerProvider let tracer = Trace.makeTracer tp "pgqueuer-hs" Trace.tracerOptions prop = W3C.w3cTraceContextPropagator headers = case mHeaders of Just (Object obj) -> [ (CI.mk $ TE.encodeUtf8 $ K.toText k, TE.encodeUtf8 s) | (k, String s) <- KM.toList obj ] _ -> [] let emptyCtx = Context.empty ctx <- Propagator.extract prop headers emptyCtx let spanArgs = Trace.defaultSpanArguments { Trace.attributes = HM.fromList [ ("messaging.system", Trace.toAttribute ("pgqueuer" :: T.Text)) , ("messaging.destination.name", Trace.toAttribute ep) , ("messaging.message.id", Trace.toAttribute (T.pack $ show jid)) ] } let restore prev = case prev of Nothing -> void ThreadLocal.detachContext Just c -> void (ThreadLocal.attachContext c) bracket (ThreadLocal.attachContext ctx) restore $ \_ -> do Trace.inSpan' tracer ("process " <> ep) spanArgs $ \otelSpan -> do action `catchAny` \e -> do Trace.setStatus otelSpan (Trace.Error (T.pack $ show e)) Trace.recordException otelSpan HM.empty Nothing e throwIO e#elsewithJobSpan _ _ _ action = action#endif