From 4a52a71956a8d46fcb7294ac71734504bb09bcc2 Mon Sep 17 00:00:00 2001 From: S. Solomon Darnell Date: Fri, 28 Mar 2025 21:52:21 -0500 Subject: two version of R2R are here --- .../prometheus_client/context_managers.py | 82 ++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 .venv/lib/python3.12/site-packages/prometheus_client/context_managers.py (limited to '.venv/lib/python3.12/site-packages/prometheus_client/context_managers.py') diff --git a/.venv/lib/python3.12/site-packages/prometheus_client/context_managers.py b/.venv/lib/python3.12/site-packages/prometheus_client/context_managers.py new file mode 100644 index 00000000..3988ec22 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/prometheus_client/context_managers.py @@ -0,0 +1,82 @@ +from timeit import default_timer +from types import TracebackType +from typing import ( + Any, Callable, Literal, Optional, Tuple, Type, TYPE_CHECKING, TypeVar, + Union, +) + +from .decorator import decorate + +if TYPE_CHECKING: + from . import Counter + F = TypeVar("F", bound=Callable[..., Any]) + + +class ExceptionCounter: + def __init__(self, counter: "Counter", exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]]) -> None: + self._counter = counter + self._exception = exception + + def __enter__(self) -> None: + pass + + def __exit__(self, typ: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType]) -> Literal[False]: + if isinstance(value, self._exception): + self._counter.inc() + return False + + def __call__(self, f: "F") -> "F": + def wrapped(func, *args, **kwargs): + with self: + return func(*args, **kwargs) + + return decorate(f, wrapped) + + +class InprogressTracker: + def __init__(self, gauge): + self._gauge = gauge + + def __enter__(self): + self._gauge.inc() + + def __exit__(self, typ, value, traceback): + self._gauge.dec() + + def __call__(self, f: "F") -> "F": + def wrapped(func, *args, **kwargs): + with self: + return func(*args, **kwargs) + + return decorate(f, wrapped) + + +class Timer: + def __init__(self, metric, callback_name): + self._metric = metric + self._callback_name = callback_name + + def _new_timer(self): + return self.__class__(self._metric, self._callback_name) + + def __enter__(self): + self._start = default_timer() + return self + + def __exit__(self, typ, value, traceback): + # Time can go backwards. + duration = max(default_timer() - self._start, 0) + callback = getattr(self._metric, self._callback_name) + callback(duration) + + def labels(self, *args, **kw): + self._metric = self._metric.labels(*args, **kw) + + def __call__(self, f: "F") -> "F": + def wrapped(func, *args, **kwargs): + # Obtaining new instance of timer every time + # ensures thread safety and reentrancy. + with self._new_timer(): + return func(*args, **kwargs) + + return decorate(f, wrapped) -- cgit v1.2.3