import logging import os import socket from uuid import uuid4 from starlette.datastructures import MutableHeaders 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 started = False async def send_wrapper(message) -> None: nonlocal started if message['type'] == 'http.response.start': started = True 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(f'unhandled error request_id={request_id} path={scope.get("path")}') if started: raise response = error_response(500, 'внутренняя ошибка', request_id) await response(scope, receive, send_wrapper)