"""Точка входа HTTP-приложения lab2.""" import logging import uuid from contextlib import asynccontextmanager from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from starlette.middleware.base import BaseHTTPMiddleware from app.api import router from app.db import Database from app.errors import AppError, error_body from app.sessions import SessionStore logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s", ) logger = logging.getLogger("messenger") db = Database() sessions = SessionStore() @asynccontextmanager async def lifespan(_app: FastAPI): logger.info("server starting; connecting to postgres/redis") db.open() sessions.open() _app.state.db = db _app.state.sessions = sessions logger.info("dependencies ready") yield db.begin_shutdown() sessions.close() db.close() logger.info("SIGTERM/shutdown: stop accepting, ready=false") app = FastAPI(title="MTUSI Messenger lab2", lifespan=lifespan) app.state.db = db app.state.sessions = sessions app.include_router(router) class RequestIdMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4()) request.state.request_id = request_id response = await call_next(request) response.headers["X-Request-Id"] = request_id logger.info( "%s %s -> %s request_id=%s", request.method, request.url.path, response.status_code, request_id, ) return response app.add_middleware(RequestIdMiddleware) @app.exception_handler(AppError) async def app_error_handler(request: Request, exc: AppError): request_id = getattr(request.state, "request_id", None) or str(uuid.uuid4()) headers = {"X-Request-Id": request_id} headers.update(exc.headers) return JSONResponse( status_code=exc.status, content=error_body(exc.code, exc.message, request_id), headers=headers, ) @app.exception_handler(RequestValidationError) async def validation_handler(request: Request, _exc: RequestValidationError): request_id = getattr(request.state, "request_id", None) or str(uuid.uuid4()) return JSONResponse( status_code=400, content=error_body("invalid_request", "Неверный запрос", request_id), headers={"X-Request-Id": request_id}, ) @app.exception_handler(Exception) async def internal_handler(request: Request, exc: Exception): request_id = getattr(request.state, "request_id", None) or str(uuid.uuid4()) logger.exception("unhandled error request_id=%s", request_id) return JSONResponse( status_code=500, content=error_body("internal_error", "Внутренняя ошибка", request_id), headers={"X-Request-Id": request_id}, ) def run() -> None: import uvicorn from app.config import settings uvicorn.run( "app.main:app", host=settings.host, port=settings.port, log_level="info", ) if __name__ == "__main__": run()