158 lines
5.4 KiB
Python
158 lines
5.4 KiB
Python
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 uvicorn
|
|
from .api import auth, chats, health, messages, users
|
|
from .storage.db import init_schema
|
|
|
|
|
|
# --- Логирование: структурированный stdout, без содержимого сообщений ---
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
|
stream=sys.stdout,
|
|
)
|
|
logger = logging.getLogger("app")
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
init_schema() # создать таблицы в БД если их ещё нет
|
|
logger.info("event=startup app_env=%s", os.environ.get("APP_ENV", "lab"))
|
|
yield
|
|
logger.info("event=shutdown_complete")
|
|
|
|
|
|
app = FastAPI(
|
|
title="MTUCI Messenger — lab2",
|
|
version="1.2.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 во всех ответах + структурный лог без тела сообщений."""
|
|
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
|
|
duration_ms = round((time.monotonic() - started) * 1000, 2)
|
|
# Логируем только метаданные: метод, путь без query, статус, длительность, request_id
|
|
path = request.url.path
|
|
logger.info(
|
|
"event=http method=%s path=%s status=%s duration_ms=%s request_id=%s",
|
|
request.method,
|
|
path,
|
|
response.status_code,
|
|
duration_ms,
|
|
request_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)
|
|
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(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.
|
|
|
|
server.should_exit=True заставляет uvicorn закрыть слушающий сокет
|
|
(healthcheck перестаёт отвечать) и корректно завершить процесс.
|
|
"""
|
|
logger.info("event=sigterm_received signal=%s", signum)
|
|
server.should_exit = True
|
|
|
|
signal.signal(signal.SIGTERM, _handle_sigterm)
|
|
server.run() |