import uuid from fastapi import FastAPI, Request, HTTPException from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError from app.routers import auth, chats app = FastAPI() app.include_router(auth.router) app.include_router(chats.router) @app.middleware("http") async def add_request_id(request: Request, call_next): # Генерируем или берем request_id один раз и сохраняем в state запроса request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4()) request.state.request_id = request_id try: response = await call_next(request) except Exception: # Fallback для совершенно необработанных исключений return JSONResponse( status_code=500, content={"error": {"code": "internal_error", "message": "Unexpected error", "request_id": request_id}}, headers={"X-Request-Id": request_id} ) # Гарантируем наличие заголовка в успешном ответе response.headers["X-Request-Id"] = request.state.request_id return response @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): # Берем тот же request_id, что был создан в middleware request_id = getattr(request.state, "request_id", str(uuid.uuid4())) first_error = exc.errors()[0] if exc.errors() else {"msg": "Invalid request"} return JSONResponse( status_code=400, content={ "error": { "code": "invalid_request", "message": first_error.get("msg", "Invalid request"), "request_id": request_id } }, headers={"X-Request-Id": request_id} ) @app.exception_handler(HTTPException) async def http_exception_handler(request: Request, exc: HTTPException): # Берем тот же request_id, что был создан в middleware request_id = getattr(request.state, "request_id", str(uuid.uuid4())) detail = exc.detail if isinstance(exc.detail, dict) else {"code": "internal_error", "message": str(exc.detail)} clean_error = { "code": detail.get("code", "internal_error"), "message": detail.get("message", "Unknown error"), "request_id": request_id } headers = {"X-Request-Id": request_id} if exc.headers: headers.update(exc.headers) return JSONResponse( status_code=exc.status_code, content={"error": clean_error}, headers=headers ) @app.get("/health/live") async def liveness(): return {"status": "ok"} @app.get("/health/ready") async def readiness(): return {"status": "ok"}