Coverage for mindsdb / metrics / metrics.py: 55%

29 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-21 00:36 +0000

1from http import HTTPStatus 

2import functools 

3import time 

4import os 

5 

6from prometheus_client import Histogram, Summary 

7 

8 

9INTEGRATION_HANDLER_QUERY_TIME = Summary( 

10 'mindsdb_integration_handler_query_seconds', 

11 'How long integration handlers take to answer queries', 

12 ('integration', 'response_type') 

13) 

14 

15INTEGRATION_HANDLER_RESPONSE_SIZE = Summary( 

16 'mindsdb_integration_handler_response_size', 

17 'How many rows are returned by an integration handler query', 

18 ('integration', 'response_type') 

19) 

20 

21_REST_API_LATENCY = Histogram( 

22 'mindsdb_rest_api_latency_seconds', 

23 'How long REST API requests take to complete, grouped by method, endpoint, and status', 

24 ('method', 'endpoint', 'status') 

25) 

26 

27 

28def api_endpoint_metrics(method: str, uri: str): 

29 def decorator_metrics(endpoint_func): 

30 @functools.wraps(endpoint_func) 

31 def wrapper_metrics(*args, **kwargs): 

32 if os.environ.get('PROMETHEUS_MULTIPROC_DIR', None) is None: 32 ↛ 34line 32 didn't jump to line 34 because the condition on line 32 was always true

33 return endpoint_func(*args, **kwargs) 

34 time_before_query = time.perf_counter() 

35 try: 

36 response = endpoint_func(*args, **kwargs) 

37 except Exception as e: 

38 # Still record metrics for unexpected exceptions. 

39 elapsed_seconds = time.perf_counter() - time_before_query 

40 api_latency_with_labels = _REST_API_LATENCY.labels( 

41 method, uri, HTTPStatus.INTERNAL_SERVER_ERROR.value) 

42 api_latency_with_labels.observe(elapsed_seconds) 

43 raise e 

44 elapsed_seconds = time.perf_counter() - time_before_query 

45 status = response.status_code if hasattr(response, 'status_code') else HTTPStatus.OK.value 

46 api_latency_with_labels = _REST_API_LATENCY.labels(method, uri, status) 

47 api_latency_with_labels.observe(elapsed_seconds) 

48 return response 

49 return wrapper_metrics 

50 return decorator_metrics