Spaces:
Sleeping
Sleeping
Download app/middleware/correlation.py from yabeskn/briga-core-api: direct link, hf CLI and curl.
- Browser
- Download file 2.52 kB
-
https://huggingface.co/spaces/yabeskn/briga-core-api/resolve/main/app/middleware/correlation.py
- Command line
-
hf download hf://spaces/yabeskn/briga-core-api/app/middleware/correlation.py
-
curl -L -o correlation.py https://huggingface.co/spaces/yabeskn/briga-core-api/resolve/main/app/middleware/correlation.py
2.52 kB
| """Correlation ID middleware for request tracking. | |
| Adds a unique X-Request-ID to all requests for debugging across separated services: | |
| - Main API <-> AI Router | |
| - Frontend <-> Main API | |
| - Any inter-service communication | |
| """ | |
| import uuid | |
| import time | |
| from typing import Callable | |
| from starlette.middleware.base import BaseHTTPMiddleware | |
| from starlette.requests import Request | |
| from starlette.responses import Response | |
| from loguru import logger | |
| class CorrelationIDMiddleware(BaseHTTPMiddleware): | |
| """Middleware that adds correlation IDs to all requests. | |
| Features: | |
| - Generates unique X-Request-ID if not provided | |
| - Passes X-Request-ID to downstream services (AI Router) | |
| - Logs request timing for performance monitoring | |
| - Supports X-Correlation-ID for cross-service tracing | |
| """ | |
| async def dispatch(self, request: Request, call_next: Callable) -> Response: | |
| # Get or generate correlation ID | |
| request_id = request.headers.get("X-Request-ID") or str(uuid.uuid4())[:8] | |
| correlation_id = request.headers.get("X-Correlation-ID") or request_id | |
| # Store in request state for downstream use | |
| request.state.request_id = request_id | |
| request.state.correlation_id = correlation_id | |
| # Add timing | |
| start_time = time.time() | |
| # Add to logs context | |
| logger.bind(request_id=request_id, correlation_id=correlation_id) | |
| # Log incoming request | |
| logger.info(f"[{request_id}] {request.method} {request.url.path}") | |
| # Process request | |
| response = await call_next(request) | |
| # Calculate duration | |
| duration_ms = (time.time() - start_time) * 1000 | |
| # Add headers to response | |
| response.headers["X-Request-ID"] = request_id | |
| response.headers["X-Correlation-ID"] = correlation_id | |
| response.headers["X-Response-Time"] = f"{duration_ms:.1f}ms" | |
| # Log completed request | |
| logger.info(f"[{request_id}] {request.method} {request.url.path} -> {response.status_code} ({duration_ms:.1f}ms)") | |
| return response | |
| def get_request_id(request: Request) -> str: | |
| """Extract request ID from request state (for use in route handlers).""" | |
| return getattr(request.state, "request_id", "unknown") | |
| def get_correlation_id(request: Request) -> str: | |
| """Extract correlation ID from request state (for downstream calls).""" | |
| return getattr(request.state, "correlation_id", "unknown") | |