from fastapi import FastAPI, Request, HTTPException from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse import os from src.utils import generate_id, create_error_response from src.api.routes.health import health from src.api.routes.users import user from src.api.routes.chats import chat from src.api.routes.messages import message from src.api.routes.auth import auth from src.lifespan import lifespan from sqlalchemy.exc import OperationalError as SAOperationalError from redis.exceptions import RedisError application = FastAPI(title="MTUSI Messenger", version="1.0.0", lifespan=lifespan) @application.middleware("http") async def add_request_id(request: Request, call_next): request_id = str(generate_id()) request.state.request_id = request_id response = await call_next(request) response.headers["X-Request-Id"] = request_id return response @application.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): messages = [] for err in exc.errors(): loc = '.'.join(str(p) for p in err["loc"] if p not in ('body',)) msg = err.get("msg", "invalid") if msg.startswith("Value error, "): msg = msg[len("Value error, "):] messages.append(f"{loc}: {msg}" if loc else msg) detail = "; ".join(messages) or "invalid request" request_id = getattr(request.state, "request_id", "") return JSONResponse( status_code=400, content={"error": { "code": "invalid_request", "message": detail, "request_id": request_id } }, headers={"X-Request-Id": request_id}, ) @application.exception_handler(SAOperationalError) async def db_unavailable_handler(request: Request, exc: SAOperationalError): request_id = getattr(request.state, "request_id", str(generate_id())) return JSONResponse( status_code=503, content={ "error": { "code": "unavailable", "message": "database unavailable", "request_id": request_id, } }, headers={"X-Request-Id": request_id}, ) @application.exception_handler(HTTPException) async def http_exception_handler(request: Request, exc: HTTPException): request_id = getattr(request.state, "request_id", None) if request_id is None: request_id = str(generate_id()) code_map = { 400: "invalid_request", 401: "unauthorized", 404: "not_found", 409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type", 429: "rate_limited", 503: "unavailable" } code = code_map.get(exc.status_code, "internal_error") response_headers = {"X-Request-Id": request_id} if exc.headers: response_headers.update(exc.headers) return JSONResponse( status_code=exc.status_code, content={"error": { "code": code, "message": str(exc.detail), "request_id": request_id} }, headers=response_headers) @application.exception_handler(Exception) async def global_exception_handler(request: Request, exc: Exception): request_id = getattr(request.state, "request_id", None) if request_id is None: request_id = str(generate_id()) print(f'Internal Error: {exc}') return create_error_response(message="Internal Server Error", code="internal_error", status_code=500, request_id=request_id) application.include_router(health.router, prefix="/health", tags=["Health"]) application.include_router(user.router, prefix="/api", tags=["Users"]) application.include_router(chat.router, prefix="/api", tags=["Chats"]) application.include_router(message.router, prefix="/api", tags=["Messages"]) application.include_router(auth.router, prefix="/api", tags=["Auth"])