forked from prometheus/client_python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext_managers.py
More file actions
77 lines (55 loc) · 2.03 KB
/
context_managers.py
File metadata and controls
77 lines (55 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import sys
from timeit import default_timer
from types import TracebackType
from typing import Any, Callable, Optional, Type, TYPE_CHECKING, TypeVar
if sys.version_info >= (3, 8, 0):
from typing import Literal
from .decorator import decorate
if TYPE_CHECKING:
from . import Counter
F = TypeVar("F", bound=Callable[..., Any])
class ExceptionCounter:
def __init__(self, counter: "Counter", exception: 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):
def wrapped(func, *args, **kwargs):
with self:
return func(*args, **kwargs)
return decorate(f, wrapped)
class Timer:
def __init__(self, callback):
self._callback = callback
def _new_timer(self):
return self.__class__(self._callback)
def __enter__(self):
self._start = default_timer()
def __exit__(self, typ, value, traceback):
# Time can go backwards.
duration = max(default_timer() - self._start, 0)
self._callback(duration)
def __call__(self, 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)