fast-telemetry 0.0.2__py3-none-any.whl → 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -28,7 +28,7 @@ version_tuple: VERSION_TUPLE
28
28
  commit_id: COMMIT_ID
29
29
  __commit_id__: COMMIT_ID
30
30
 
31
- __version__ = version = '0.0.2'
32
- __version_tuple__ = version_tuple = (0, 0, 2)
31
+ __version__ = version = '0.2.0'
32
+ __version_tuple__ = version_tuple = (0, 2, 0)
33
33
 
34
34
  __commit_id__ = commit_id = None
fast_telemetry/core.py CHANGED
@@ -2,6 +2,7 @@ import os
2
2
  import functools
3
3
  import inspect
4
4
  from abc import abstractmethod, ABC
5
+ from types import TracebackType
5
6
  from typing import (
6
7
  Callable,
7
8
  Any,
@@ -98,13 +99,82 @@ class MetricsCollector(ABC):
98
99
 
99
100
  return sync_wrapper
100
101
 
102
+ @overload
103
+ def track_exception(self, func: Callable[P, R]) -> Callable[P, R]:
104
+ pass
105
+
106
+ @overload
107
+ def track_exception(self, *, exclude: list[Type[BaseException]] | None = None) -> "_ExceptionTracker":
108
+ pass
109
+
101
110
  @abstractmethod
102
111
  def track_exception(
103
- self, *, exclude: list[Type[BaseException]] | None = None
104
- ) -> Callable[[Callable[P, R]], Callable[P, R]]:
112
+ self, arg: Callable[P, R] | None = None, *, exclude: list[Type[BaseException]] | None = None
113
+ ) -> Any:
105
114
  pass
106
115
 
107
116
 
117
+ class _ExceptionTracker:
118
+ """
119
+ Гибридный класс: Context Manager + Decorator.
120
+ Используется внутри track_exception.
121
+ """
122
+
123
+ def __init__(
124
+ self,
125
+ metrics: MetricsCollector,
126
+ exclude: list[Type[BaseException]] | None = None,
127
+ ):
128
+ self.metrics = metrics
129
+ self.exclude = tuple(exclude) if exclude else ()
130
+
131
+ def _handle_exception(self, exc_val: BaseException) -> None:
132
+ if not isinstance(exc_val, self.exclude):
133
+ self.metrics.inc_error(exc_val)
134
+
135
+ def __enter__(self) -> "_ExceptionTracker":
136
+ return self
137
+
138
+ def __exit__(
139
+ self,
140
+ exc_type: Type[BaseException] | None,
141
+ exc_val: BaseException | None,
142
+ exc_tb: TracebackType | None,
143
+ ) -> None:
144
+ if exc_val:
145
+ self._handle_exception(exc_val)
146
+
147
+ async def __aenter__(self) -> "_ExceptionTracker":
148
+ return self
149
+
150
+ async def __aexit__(
151
+ self,
152
+ exc_type: Type[BaseException] | None,
153
+ exc_val: BaseException | None,
154
+ exc_tb: TracebackType | None,
155
+ ) -> None:
156
+ if exc_val:
157
+ self._handle_exception(exc_val)
158
+
159
+ def __call__(self, func: Callable[P, R]) -> Callable[P, R]:
160
+ if inspect.iscoroutinefunction(func):
161
+
162
+ @functools.wraps(func)
163
+ async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
164
+ async with self:
165
+ return await func(*args, **kwargs)
166
+
167
+ return async_wrapper # type: ignore
168
+ else:
169
+
170
+ @functools.wraps(func)
171
+ def sync_wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
172
+ with self:
173
+ return func(*args, **kwargs)
174
+
175
+ return sync_wrapper
176
+
177
+
108
178
  class PrometheusMetrics(MetricsCollector, MetricsExporter):
109
179
  """
110
180
  Реализация метрик на базе prometheus-client.
@@ -186,39 +256,14 @@ class PrometheusMetrics(MetricsCollector, MetricsExporter):
186
256
  self, arg: Callable[P, R] | None = None, *, exclude: list[Type[BaseException]] | None = None
187
257
  ) -> Any:
188
258
  """
189
- Декоратор для подсчета исключений.
190
- Использует имя класса исключения как метку error_type.
259
+ Декоратор и контекстный менеджер для подсчета исключений.
191
260
  """
192
-
193
- def decorator(func: Callable[P, R]) -> Callable[P, R]:
194
- if inspect.iscoroutinefunction(func):
195
-
196
- @functools.wraps(func)
197
- async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
198
- try:
199
- return await func(*args, **kwargs) # type: ignore
200
- except Exception as e:
201
- if not exclude or not isinstance(e, tuple(exclude)):
202
- self.inc_error(e)
203
- raise
204
-
205
- return async_wrapper # type: ignore
206
- else:
207
-
208
- @functools.wraps(func)
209
- def sync_wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
210
- try:
211
- return func(*args, **kwargs)
212
- except Exception as e:
213
- if not exclude or not isinstance(e, tuple(exclude)):
214
- self.inc_error(e)
215
- raise
216
-
217
- return sync_wrapper
261
+ tracker = _ExceptionTracker(self, exclude=exclude)
218
262
 
219
263
  if callable(arg):
220
- return decorator(arg)
221
- return decorator
264
+ return tracker(arg)
265
+
266
+ return tracker
222
267
 
223
268
  def timer(self, task_type: str, long_task: bool = False) -> ContextManager[Any]:
224
269
  if long_task:
@@ -4,12 +4,9 @@ from fastapi import FastAPI
4
4
  from prometheus_fastapi_instrumentator import Instrumentator
5
5
 
6
6
  from .. import MetricsExporter
7
- from ..core import PrometheusMetrics
8
7
 
9
8
 
10
- def setup_fastapi_metrics(
11
- app: FastAPI, metrics: MetricsExporter, excluded_routes: Iterable[str] | None = None
12
- ) -> None:
9
+ def setup_fastapi_metrics(app: FastAPI, metrics: MetricsExporter, excluded_routes: Iterable[str] | None = None) -> None:
13
10
  """
14
11
  Настраивает автоматический мониторинг HTTP запросов
15
12
  и добавляет эндпоинт /metrics.
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fast-telemetry
3
- Version: 0.0.2
3
+ Version: 0.2.0
4
4
  Summary: Internal standardized metrics library
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
7
- Requires-Dist: prometheus-client~=0.21.0
7
+ Requires-Dist: prometheus-client<1.0.0,>=0.21.0
8
8
  Provides-Extra: web
9
- Requires-Dist: fastapi~=0.115.0; extra == "web"
10
- Requires-Dist: prometheus-fastapi-instrumentator~=7.1.0; extra == "web"
9
+ Requires-Dist: fastapi<1.0.0,>=0.115.0; extra == "web"
10
+ Requires-Dist: prometheus-fastapi-instrumentator<8.0.0,>=7.1.0; extra == "web"
11
11
  Provides-Extra: stream
12
12
  Requires-Dist: faststream~=0.6.0; extra == "stream"
13
13
 
@@ -0,0 +1,12 @@
1
+ __init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ fast_telemetry/__init__.py,sha256=maomIZLdB92E2j9kW1caPUa-_B799ZTGEi24NY-ERZI,191
3
+ fast_telemetry/_version.py,sha256=Dg8AmJomLVpjKL6prJylOONZAPRtB86LOce7dorQS_A,704
4
+ fast_telemetry/core.py,sha256=je27wPE2rvpNGjW76Z562PL-tHG2_KEuMm3N1lLceMQ,9424
5
+ fast_telemetry/integrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ fast_telemetry/integrations/fastapi.py,sha256=PtnPUJeW4QTwo89jEfBLGDvzlLB6c3V-qtBU3ynoEts,1039
7
+ fast_telemetry/integrations/faststream.py,sha256=1ncNXCHk9nv1SyV_fKqwo2LpOh8rV1n8wxpLBtb7KGY,3389
8
+ fast_telemetry/integrations/worker.py,sha256=BQCLdjxTB3PluD7Bxv-rPzOjWTkBde6ssg4KOxQENeQ,4713
9
+ fast_telemetry-0.2.0.dist-info/METADATA,sha256=1MhNHhHJ0mzR61vEmRnBujO6c_ibf3mbj2kOEWJR-Kw,8896
10
+ fast_telemetry-0.2.0.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
11
+ fast_telemetry-0.2.0.dist-info/top_level.txt,sha256=OvY6pUtFsIZyuDZiiIF6RFF-mfjMuvXDpUbz4XXXop0,24
12
+ fast_telemetry-0.2.0.dist-info/RECORD,,
@@ -1,12 +0,0 @@
1
- __init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- fast_telemetry/__init__.py,sha256=maomIZLdB92E2j9kW1caPUa-_B799ZTGEi24NY-ERZI,191
3
- fast_telemetry/_version.py,sha256=huLsL1iGeXWQKZ8bjwDdIWC7JOkj3wnzBh-HFMZl1PY,704
4
- fast_telemetry/core.py,sha256=T39rEQuM2W95S9_9ww05a6RSIRFgvo7XFagqKBXGqCk,8431
5
- fast_telemetry/integrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
- fast_telemetry/integrations/fastapi.py,sha256=l2MQaKz8lAdwOBQPFbvzsHlS7I7SYuaHNelCLKu83I0,1082
7
- fast_telemetry/integrations/faststream.py,sha256=1ncNXCHk9nv1SyV_fKqwo2LpOh8rV1n8wxpLBtb7KGY,3389
8
- fast_telemetry/integrations/worker.py,sha256=BQCLdjxTB3PluD7Bxv-rPzOjWTkBde6ssg4KOxQENeQ,4713
9
- fast_telemetry-0.0.2.dist-info/METADATA,sha256=IM_4_-Rlv53La2l4vw15zBWSvmw4N4kFMKdQS6A8zEs,8875
10
- fast_telemetry-0.0.2.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
11
- fast_telemetry-0.0.2.dist-info/top_level.txt,sha256=OvY6pUtFsIZyuDZiiIF6RFF-mfjMuvXDpUbz4XXXop0,24
12
- fast_telemetry-0.0.2.dist-info/RECORD,,