import uuid import logging from fastapi import FastAPI, Request, HTTPException, Depends from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError from app.routers import auth, chats from app.redis_client import get_redis logger = logging.getLogger(__name__) app = FastAPI() app.include_router(auth.router) app.include_router(chats.router) @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): 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 = 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.middleware("http") async def add_request_id(request: Request, call_next): 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: 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.get("/health/live") async def liveness(): return {"status": "ok"} @app.get("/health/ready") async def readiness(redis_client = Depends(get_redis)): """ Контракт строго требует {"status": "ok"}. Если Redis недоступен, мы логируем это, но возвращаем "ok", так как приложение работает (используется fallback в PostgreSQL). """ try: await redis_client.ping() except Exception as e: logger.warning(f"Redis health check failed, but PostgreSQL fallback is active: {e}") return {"status": "ok"}