import logging import sys import time from contextlib import asynccontextmanager from uuid import uuid4 from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError import uvicorn from starlette.responses import JSONResponse, Response from .errors import ApiError from .models import ErrorDetails, ErrorResponse from .config import load_settings from .routes import router from .storage.history_cache import HistoryCache from .storage.postgres import PostgresStore access_logger = logging.getLogger("messenger.access") if not access_logger.handlers: handler = logging.StreamHandler(sys.stdout) handler.setFormatter( logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s") ) access_logger.addHandler(handler) access_logger.setLevel(logging.INFO) access_logger.propagate = False @asynccontextmanager async def lifespan(application: FastAPI): settings = load_settings() store = PostgresStore(settings.database_url) await store.connect() await store.migrate() application.state.store = store application.state.settings = settings cache = HistoryCache(settings.cache_url, settings.cache_ttl_seconds) await cache.connect() application.state.history_cache = cache try: yield finally: await cache.close() await store.close() app = FastAPI( title="MTUSI Messenger", version="1.1.0", redoc_url=None, lifespan=lifespan, ) @app.middleware("http") async def add_request_id(request: Request, call_next) -> Response: """Добавляет ID запроса и пишет безопасную строку access-лога.""" request.state.request_id = str(uuid4()) started_at = time.monotonic() status_code = 500 try: response = await call_next(request) status_code = response.status_code response.headers["X-Request-Id"] = request.state.request_id return response finally: access_logger.info( "request_id=%s method=%s path=%s status=%s elapsed_ms=%.3f", request.state.request_id, request.method, request.url.path, status_code, (time.monotonic() - started_at) * 1000, ) def error_response( request: Request, status_code: int, code: str, message: str, headers: dict[str, str] | None = None ) -> JSONResponse: request_id = request.state.request_id body = ErrorResponse( error=ErrorDetails(code=code, message=message, request_id=request_id) ) # Неожиданная ошибка обрабатывается за пределами HTTP-middleware. # Поэтому её ответ тоже должен сам получить заголовок из контракта. return JSONResponse( status_code=status_code, content=body.model_dump(), headers={"X-Request-Id": request_id, **(headers or {})}, ) @app.exception_handler(ApiError) async def handle_api_error(request: Request, error: ApiError) -> JSONResponse: """Преобразует контролируемую ошибку API в стандартный JSON-ответ.""" return error_response(request, error.status_code, error.code, error.message, error.headers) @app.exception_handler(RequestValidationError) async def handle_validation_error( request: Request, error: RequestValidationError ) -> JSONResponse: """Преобразует ошибки JSON и Pydantic в обязательный ответ 400.""" return error_response(request, 400, "invalid_request", "Некорректный запрос") @app.exception_handler(Exception) async def handle_unexpected_error(request: Request, error: Exception) -> JSONResponse: """Не раскрывает внутренние детали при непредвиденной ошибке приложения.""" return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера") app.include_router(router) def main() -> None: settings = load_settings() uvicorn.run( app, host=settings.host, port=settings.port, access_log=False, timeout_graceful_shutdown=8, ) if __name__ == "__main__": main()