authentik.lib.tracing.common

Shared tracer protocol and no-op fallback

 1"""Shared tracer protocol and no-op fallback"""
 2
 3from collections.abc import Callable
 4from contextlib import contextmanager
 5from functools import wraps
 6from typing import Any, Protocol
 7
 8# Set by lifecycle/gunicorn.conf.py before the app is preloaded, to tell
 9# AuthentikCoreConfig.ready() to defer setup_post_fork() to gunicorn's post_fork hook
10TRACER_DEFER_POSTFORK_ENV_VAR = "AUTHENTIK_TRACER_DEFER_POSTFORK"
11
12
13class Span(Protocol):
14    """Structural interface every tracer's span-like object satisfies"""
15
16    description: str | None
17
18    def set_data(self, key: str, value: Any) -> None:
19        pass
20
21
22class NoOpSpan:
23    """Span yielded by the no-op tracer"""
24
25    description: str | None = None
26
27    def set_data(self, key: str, value: Any) -> None:
28        pass
29
30
31class Tracer:
32    """Base tracer: the protocol every tracer follows, and the no-op fallback used
33    when no error-reporting backend is configured"""
34
35    def setup_pre_fork(self) -> None:
36        pass
37
38    def setup_post_fork(self) -> None:
39        pass
40
41    def record_exception(self, exc: Exception) -> None:
42        pass
43
44    def get_http_meta(self) -> dict[str, str]:
45        return {}
46
47    def set_tag(self, key: str, value: Any) -> None:
48        pass
49
50    @contextmanager
51    def start_span(self, op: str, name: str | None = None):
52        yield NoOpSpan()
53
54    def instrument(self, arg_annotate: list[str] | None = None):
55        """Decorator to trace a function"""
56
57        def wrapper_outer(func: Callable):
58
59            @wraps(func)
60            def wrapper(*args, **kwargs) -> Any:
61                with self.start_span(f"{func.__module__}.{func.__qualname__}") as span:
62                    if arg_annotate:
63                        for arg in arg_annotate:
64                            span.set_data(arg, kwargs.get(arg))
65                    return func(*args, **kwargs)
66
67            return wrapper
68
69        return wrapper_outer
TRACER_DEFER_POSTFORK_ENV_VAR = 'AUTHENTIK_TRACER_DEFER_POSTFORK'
class Span(typing.Protocol):
14class Span(Protocol):
15    """Structural interface every tracer's span-like object satisfies"""
16
17    description: str | None
18
19    def set_data(self, key: str, value: Any) -> None:
20        pass

Structural interface every tracer's span-like object satisfies

Span(*args, **kwargs)
1903def _no_init_or_replace_init(self, *args, **kwargs):
1904    cls = type(self)
1905
1906    if cls._is_protocol:
1907        raise TypeError('Protocols cannot be instantiated')
1908
1909    # Already using a custom `__init__`. No need to calculate correct
1910    # `__init__` to call. This can lead to RecursionError. See bpo-45121.
1911    if cls.__init__ is not _no_init_or_replace_init:
1912        return
1913
1914    # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`.
1915    # The first instantiation of the subclass will call `_no_init_or_replace_init` which
1916    # searches for a proper new `__init__` in the MRO. The new `__init__`
1917    # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent
1918    # instantiation of the protocol subclass will thus use the new
1919    # `__init__` and no longer call `_no_init_or_replace_init`.
1920    for base in cls.__mro__:
1921        init = base.__dict__.get('__init__', _no_init_or_replace_init)
1922        if init is not _no_init_or_replace_init:
1923            cls.__init__ = init
1924            break
1925    else:
1926        # should not happen
1927        cls.__init__ = object.__init__
1928
1929    cls.__init__(self, *args, **kwargs)
description: str | None
def set_data(self, key: str, value: Any) -> None:
19    def set_data(self, key: str, value: Any) -> None:
20        pass
class NoOpSpan:
23class NoOpSpan:
24    """Span yielded by the no-op tracer"""
25
26    description: str | None = None
27
28    def set_data(self, key: str, value: Any) -> None:
29        pass

Span yielded by the no-op tracer

description: str | None = None
def set_data(self, key: str, value: Any) -> None:
28    def set_data(self, key: str, value: Any) -> None:
29        pass
class Tracer:
32class Tracer:
33    """Base tracer: the protocol every tracer follows, and the no-op fallback used
34    when no error-reporting backend is configured"""
35
36    def setup_pre_fork(self) -> None:
37        pass
38
39    def setup_post_fork(self) -> None:
40        pass
41
42    def record_exception(self, exc: Exception) -> None:
43        pass
44
45    def get_http_meta(self) -> dict[str, str]:
46        return {}
47
48    def set_tag(self, key: str, value: Any) -> None:
49        pass
50
51    @contextmanager
52    def start_span(self, op: str, name: str | None = None):
53        yield NoOpSpan()
54
55    def instrument(self, arg_annotate: list[str] | None = None):
56        """Decorator to trace a function"""
57
58        def wrapper_outer(func: Callable):
59
60            @wraps(func)
61            def wrapper(*args, **kwargs) -> Any:
62                with self.start_span(f"{func.__module__}.{func.__qualname__}") as span:
63                    if arg_annotate:
64                        for arg in arg_annotate:
65                            span.set_data(arg, kwargs.get(arg))
66                    return func(*args, **kwargs)
67
68            return wrapper
69
70        return wrapper_outer

Base tracer: the protocol every tracer follows, and the no-op fallback used when no error-reporting backend is configured

def setup_pre_fork(self) -> None:
36    def setup_pre_fork(self) -> None:
37        pass
def setup_post_fork(self) -> None:
39    def setup_post_fork(self) -> None:
40        pass
def record_exception(self, exc: Exception) -> None:
42    def record_exception(self, exc: Exception) -> None:
43        pass
def get_http_meta(self) -> dict[str, str]:
45    def get_http_meta(self) -> dict[str, str]:
46        return {}
def set_tag(self, key: str, value: Any) -> None:
48    def set_tag(self, key: str, value: Any) -> None:
49        pass
@contextmanager
def start_span(self, op: str, name: str | None = None):
51    @contextmanager
52    def start_span(self, op: str, name: str | None = None):
53        yield NoOpSpan()
def instrument(self, arg_annotate: list[str] | None = None):
55    def instrument(self, arg_annotate: list[str] | None = None):
56        """Decorator to trace a function"""
57
58        def wrapper_outer(func: Callable):
59
60            @wraps(func)
61            def wrapper(*args, **kwargs) -> Any:
62                with self.start_span(f"{func.__module__}.{func.__qualname__}") as span:
63                    if arg_annotate:
64                        for arg in arg_annotate:
65                            span.set_data(arg, kwargs.get(arg))
66                    return func(*args, **kwargs)
67
68            return wrapper
69
70        return wrapper_outer

Decorator to trace a function