|
| 1 | +import time |
| 2 | +from collections.abc import Awaitable, Callable |
| 3 | +from dataclasses import dataclass |
| 4 | +from functools import cache |
| 5 | + |
| 6 | +from fastapi import Request, Response |
| 7 | +from prometheus_client import Counter, Gauge, Histogram |
| 8 | +from starlette.middleware.base import BaseHTTPMiddleware |
| 9 | + |
| 10 | +from core.config import settings |
| 11 | + |
| 12 | + |
| 13 | +@dataclass |
| 14 | +class Metrics: |
| 15 | + request_count: Counter |
| 16 | + request_latency: Histogram |
| 17 | + inprogress_requests: Gauge |
| 18 | + |
| 19 | + |
| 20 | +@cache |
| 21 | +def get_metrics() -> Metrics: |
| 22 | + prefix = settings.APP_NAME.replace("-", "_") |
| 23 | + # Use a didicated registry via default REGISTRY, okay for most setups. |
| 24 | + return Metrics( |
| 25 | + request_count=Counter( |
| 26 | + f"{prefix}_http_requests_total", |
| 27 | + "Total number of HTTP requests", |
| 28 | + ["method", "endpoint", "status_code"], |
| 29 | + ), |
| 30 | + request_latency=Histogram( |
| 31 | + f"{prefix}_http_request_duration_seconds", |
| 32 | + "HTTP request latency (seconds)", |
| 33 | + ["method", "endpoint", "status_code"], |
| 34 | + buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0), |
| 35 | + ), |
| 36 | + inprogress_requests=Gauge( |
| 37 | + f"{prefix}_inprogress_requests", |
| 38 | + "Number of in-progress requests", |
| 39 | + ["endpoint"], |
| 40 | + ), |
| 41 | + ) |
| 42 | + |
| 43 | + |
| 44 | +def _get_route_path(request: Request) -> str: |
| 45 | + """ |
| 46 | + Return the route template path if available (e.g. "/api/users/{user_id}"), |
| 47 | + otherwise fallback to raw path (but avoid querystring). |
| 48 | + """ |
| 49 | + route = request.scope.get("route") |
| 50 | + try: |
| 51 | + # Starlette/fastapi Route has .path attribute |
| 52 | + if hasattr(route, "path"): |
| 53 | + return route.path # type: ignore |
| 54 | + except Exception: |
| 55 | + pass |
| 56 | + # Fallback: use the raw path but strip any high-cardinality parts carefully |
| 57 | + return request.url.path |
| 58 | + |
| 59 | + |
| 60 | +class MetricsMiddleware(BaseHTTPMiddleware): |
| 61 | + async def dispatch( |
| 62 | + self, |
| 63 | + request: Request, |
| 64 | + call_next: Callable[[Request], Awaitable[Response]], |
| 65 | + ) -> Response: |
| 66 | + |
| 67 | + # Do not collect for non-api or static endpoints (configurable) |
| 68 | + path = request.url.path |
| 69 | + if not path.startswith("/api"): |
| 70 | + return await call_next(request) |
| 71 | + |
| 72 | + metrics = get_metrics() |
| 73 | + endpoint = _get_route_path(request) |
| 74 | + |
| 75 | + # inprogress gauge |
| 76 | + metrics.inprogress_requests.labels(endpoint=endpoint).inc() |
| 77 | + start_time = time.time() |
| 78 | + |
| 79 | + try: |
| 80 | + response = await call_next(request) |
| 81 | + finally: |
| 82 | + # always decrement even on exceptions |
| 83 | + metrics.inprogress_requests.labels(endpoint=endpoint).dec() |
| 84 | + |
| 85 | + process_time = time.time() - start_time |
| 86 | + status = getattr(response, "status_code", 500) |
| 87 | + |
| 88 | + labels = { |
| 89 | + "method": request.method, |
| 90 | + "endpoint": endpoint, |
| 91 | + "status_code": str(status), |
| 92 | + } |
| 93 | + metrics.request_count.labels(**labels).inc() |
| 94 | + metrics.request_latency.labels(**labels).observe(process_time) |
| 95 | + |
| 96 | + return response |
0 commit comments