import logging import os import signal import sys import time import uuid from contextlib import asynccontextmanager from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.openapi.utils import get_openapi from fastapi.responses import JSONResponse from starlette.exceptions import HTTPException as StarletteHTTPException import psycopg import uvicorn from .api import auth, chats, health, messages, users from .storage.db import init_pool, close_pool # --- Логирование: структурированный stdout, без содержимого сообщений --- logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s", stream=sys.stdout, ) logger = logging.getLogger("app") # X-Instance-Id: стабильный в пределах жизни процесса. Значение приходит # из env INSTANCE_ID (задаётся Dockerfile/Compose) либо генерируется один раз. INSTANCE_ID = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex[:12] @asynccontextmanager async def lifespan(app: FastAPI): init_pool() # пул соединений PostgreSQL с таймаутами (уровень 4) # Схему готовит отдельный сервис migrate (service_completed_successfully) logger.info( "event=startup app_env=%s session_store=%s instance_id=%s", os.environ.get("APP_ENV", "lab"), os.environ.get("SESSION_STORE", "postgres"), INSTANCE_ID, ) yield close_pool() logger.info("event=shutdown_complete instance_id=%s", INSTANCE_ID) app = FastAPI( title="MTUCI Messenger — lab3", version="1.3.0", lifespan=lifespan, swagger_ui_parameters={"persistAuthorization": True}, ) def custom_openapi(): if app.openapi_schema: return app.openapi_schema schema = get_openapi(title=app.title, version=app.version, routes=app.routes) app.openapi_schema = schema return schema app.openapi = custom_openapi @app.middleware("http") async def observability_middleware(request: Request, call_next): """X-Request-Id и X-Instance-Id во всех ответах + структурный лог.""" request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex request.state.request_id = request_id started = time.monotonic() response = await call_next(request) response.headers["X-Request-Id"] = request_id response.headers["X-Instance-Id"] = INSTANCE_ID duration_ms = round((time.monotonic() - started) * 1000, 2) path = request.url.path logger.info( "event=http method=%s path=%s status=%s duration_ms=%s request_id=%s instance_id=%s", request.method, path, response.status_code, duration_ms, request_id, INSTANCE_ID, ) return response # Словарь HTTP-кодов → кодов ошибок из контракта _ERROR_CODES = { 400: "invalid_request", 401: "unauthorized", 404: "not_found", 409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type", 429: "rate_limited", 503: "unavailable", 500: "internal_error", } def _unauthorized_challenge(path: str) -> str: """Basic — только для POST /api/v1/auth/sessions; остальное — Bearer.""" if path == "/api/v1/auth/sessions": return 'Basic realm="messenger", charset="UTF-8"' return 'Bearer realm="messenger"' def _error_response( status_code: int, message: str, request_id: str, path: str = "" ) -> JSONResponse: code = _ERROR_CODES.get(status_code, "internal_error") headers = {} if status_code == 401: headers["WWW-Authenticate"] = _unauthorized_challenge(path) # X-Instance-Id может не быть при ошибке до middleware — но middleware # оборачивает всё, так что заголовок будет добавлен в middleware. return JSONResponse( status_code=status_code, content={"error": {"code": code, "message": message, "request_id": request_id}}, headers=headers, ) @app.exception_handler(StarletteHTTPException) async def http_exception_handler(request: Request, exc: StarletteHTTPException): request_id = getattr(request.state, "request_id", uuid.uuid4().hex) message = exc.detail if isinstance(exc.detail, str) else "Ошибка" return _error_response(exc.status_code, message, request_id, request.url.path) @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): request_id = getattr(request.state, "request_id", uuid.uuid4().hex) return _error_response(400, "Неверный запрос", request_id, request.url.path) @app.exception_handler(psycopg.OperationalError) async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError): """PostgreSQL недоступен → 503 unavailable, без внутренних деталей.""" request_id = getattr(request.state, "request_id", uuid.uuid4().hex) logger.error( "event=db_unavailable type=%s request_id=%s", type(exc).__name__, request_id, ) return _error_response(503, "Зависимость недоступна", request_id, request.url.path) @app.exception_handler(RuntimeError) async def runtime_error_handler(request: Request, exc: RuntimeError): """Redis недоступен или конфигурация битая.""" request_id = getattr(request.state, "request_id", uuid.uuid4().hex) text = str(exc) if "redis_unavailable" in text: logger.error("event=redis_unavailable request_id=%s", request_id) return _error_response(503, "Зависимость недоступна", request_id, request.url.path) logger.error( "event=runtime_error type=%s request_id=%s", type(exc).__name__, request_id, ) return _error_response(500, "Внутренняя ошибка", request_id, request.url.path) @app.exception_handler(Exception) async def unhandled_exception_handler(request: Request, exc: Exception): request_id = getattr(request.state, "request_id", uuid.uuid4().hex) logger.error("event=unhandled_exception type=%s request_id=%s", type(exc).__name__, request_id) return _error_response(500, "Внутренняя ошибка", request_id, request.url.path) app.include_router(health.router) app.include_router(auth.router) app.include_router(users.router) app.include_router(chats.router) app.include_router(messages.router) if __name__ == "__main__": config = uvicorn.Config( "app.main:app", host="0.0.0.0", port=8080, log_level="info", ) server = uvicorn.Server(config) def _handle_sigterm(signum, frame): """SIGTERM: логируем и инициируем graceful shutdown uvicorn.""" logger.info("event=sigterm_received signal=%s", signum) server.should_exit = True signal.signal(signal.SIGTERM, _handle_sigterm) server.run()