import logging import os import socket import time from uuid import uuid4 from opentelemetry import trace from starlette.datastructures import MutableHeaders from ..observability import get_metrics from ..observability.logging import safe_extra from .errors import error_response logger = logging.getLogger('app') class RequestContext: def __init__(self, app) -> None: self.app = app self.instance_id = os.getenv('INSTANCE_ID') or socket.gethostname() async def __call__(self, scope, receive, send) -> None: if scope['type'] != 'http': await self.app(scope, receive, send) return request_id = uuid4().hex scope.setdefault('state', {})['request_id'] = request_id is_health = scope.get('path') in {'/health/live', '/health/ready'} started_at = time.perf_counter() started = False status_code = 500 async def send_wrapper(message) -> None: nonlocal started, status_code if message['type'] == 'http.response.start': started = True status_code = message['status'] headers = MutableHeaders(scope=message) headers['X-Request-Id'] = request_id headers['X-Instance-Id'] = self.instance_id await send(message) try: await self.app(scope, receive, send_wrapper) except Exception: logger.exception( 'unhandled HTTP error', extra=safe_extra('http.request.failed', request_id=request_id), ) if started: raise response = error_response(500, 'внутренняя ошибка', request_id) await response(scope, receive, send_wrapper) finally: duration = time.perf_counter() - started_at route = getattr(scope.get('route'), 'path', None) or 'unmatched' method = scope.get('method', 'UNKNOWN') status_class = f'{status_code // 100}xx' span = trace.get_current_span() if span.is_recording(): span.set_attribute('request.id', request_id) span.set_attribute('http.route', route) if not is_health: attributes = { 'http.request.method': method, 'http.route': route, 'http.response.status_class': status_class, } instruments = get_metrics() instruments.http_requests.add(1, attributes) instruments.http_duration.record(duration, attributes) logger.info( 'HTTP request completed', extra=safe_extra( 'http.request.completed', request_id=request_id, http_method=method, http_route=route, http_status_code=status_code, duration_seconds=round(duration, 6), ), )