import uuid from contextlib import asynccontextmanager from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError from app.db import db from app.migrations import apply_migrations from app.storage import Storage from app.session_store import make_session_store from app.cache import make_cache from app.api import health, users, auth, chats @asynccontextmanager async def lifespan(app: FastAPI): await db.connect() await apply_migrations(db.pool) app.state.cache = make_cache() app.state.storage = Storage(db.pool, app.state.cache) app.state.session_store = make_session_store(db.pool) await app.state.session_store.delete_expired() yield await app.state.cache.close() await app.state.session_store.close() await db.close() app = FastAPI(title="MTUSI Messenger", version="1.3.0", lifespan=lifespan) @app.middleware("http") async def request_context(request: Request, call_next): rid = request.headers.get("X-Request-Id") or uuid.uuid4().hex request.state.request_id = rid response = await call_next(request) response.headers["X-Request-Id"] = rid return response @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): rid = getattr(request.state, "request_id", uuid.uuid4().hex) return JSONResponse( status_code=400, content={ "error": { "code": "invalid_request", "message": "validation error", "request_id": rid, } }, headers={"X-Request-Id": rid}, ) @app.exception_handler(Exception) async def generic_exception_handler(request: Request, exc: Exception): rid = getattr(request.state, "request_id", uuid.uuid4().hex) return JSONResponse( status_code=500, content={ "error": { "code": "internal_error", "message": "internal error", "request_id": rid, } }, headers={"X-Request-Id": rid}, ) app.include_router(health.router) app.include_router(users.router, prefix="/api/v1") app.include_router(auth.router, prefix="/api/v1") app.include_router(chats.router, prefix="/api/v1")