forked from mtusi2026/mtusi2026lab2
+ добавила функционал на 4 + тесты
This commit is contained in:
+43
-3
@@ -10,9 +10,10 @@ 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_schema
|
||||
from .storage.db import init_schema, init_pool, close_pool
|
||||
|
||||
|
||||
# --- Логирование: структурированный stdout, без содержимого сообщений ---
|
||||
@@ -26,9 +27,15 @@ 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"))
|
||||
init_pool() # пул соединений PostgreSQL с таймаутами (уровень 4)
|
||||
init_schema() # создать таблицы в БД если их ещё нет
|
||||
logger.info(
|
||||
"event=startup app_env=%s session_store=%s",
|
||||
os.environ.get("APP_ENV", "lab"),
|
||||
os.environ.get("SESSION_STORE", "postgres"),
|
||||
)
|
||||
yield
|
||||
close_pool()
|
||||
logger.info("event=shutdown_complete")
|
||||
|
||||
|
||||
@@ -121,6 +128,39 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
|
||||
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 недоступен или конфигурация битая.
|
||||
|
||||
sessions.py поднимает RuntimeError("redis_unavailable") при ошибке Redis.
|
||||
Отдаём 503, чтобы смоук/resilience видели корректный unavailable,
|
||||
а не внутреннюю 500.
|
||||
"""
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user