authentik.lib.tracing.otel_django_middleware

 1from functools import wraps
 2from inspect import iscoroutinefunction
 3
 4from opentelemetry import trace
 5
 6tracer = trace.get_tracer("authentik")
 7
 8
 9class TracedMiddleware:
10    """Base class for Django middleware opting into tracing: each call is wrapped in a
11    span named after the middleware's dotted path, so the spans of nested middleware and
12    the view nest inside it."""
13
14    def __init_subclass__(cls, **kwargs):
15        super().__init_subclass__(**kwargs)
16        call = cls.__call__
17        if getattr(call, "_traced", False):
18            return
19
20        @wraps(call)
21        async def acall(self, request):
22            with tracer.start_as_current_span(f"{type(self).__module__}.{type(self).__qualname__}"):
23                return await call(self, request)
24
25        @wraps(call)
26        def traced_call(self, request):
27            # MiddlewareMixin marks the instance and returns a coroutine from __call__
28            if iscoroutinefunction(self):
29                return acall(self, request)
30            with tracer.start_as_current_span(f"{type(self).__module__}.{type(self).__qualname__}"):
31                return call(self, request)
32
33        if iscoroutinefunction(call):
34            traced_call = acall
35        traced_call._traced = True  # type: ignore[attr-defined]
36        cls.__call__ = traced_call  # type: ignore[method-assign]
tracer = <opentelemetry.trace.ProxyTracer object>
class TracedMiddleware:
10class TracedMiddleware:
11    """Base class for Django middleware opting into tracing: each call is wrapped in a
12    span named after the middleware's dotted path, so the spans of nested middleware and
13    the view nest inside it."""
14
15    def __init_subclass__(cls, **kwargs):
16        super().__init_subclass__(**kwargs)
17        call = cls.__call__
18        if getattr(call, "_traced", False):
19            return
20
21        @wraps(call)
22        async def acall(self, request):
23            with tracer.start_as_current_span(f"{type(self).__module__}.{type(self).__qualname__}"):
24                return await call(self, request)
25
26        @wraps(call)
27        def traced_call(self, request):
28            # MiddlewareMixin marks the instance and returns a coroutine from __call__
29            if iscoroutinefunction(self):
30                return acall(self, request)
31            with tracer.start_as_current_span(f"{type(self).__module__}.{type(self).__qualname__}"):
32                return call(self, request)
33
34        if iscoroutinefunction(call):
35            traced_call = acall
36        traced_call._traced = True  # type: ignore[attr-defined]
37        cls.__call__ = traced_call  # type: ignore[method-assign]

Base class for Django middleware opting into tracing: each call is wrapped in a span named after the middleware's dotted path, so the spans of nested middleware and the view nest inside it.