forked from mtusi2026/mtusi2026lab5
chore: port lab 4 solution into the lab 5 skeleton
Source: mtusi2026lab4-safronov, solution/bvt2301-safronov, 2546deb. Contracts, public tests and evidence of lab 4 are not carried over. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
"""Короткая сессия БД на один шаг: срок и перевод отказа PostgreSQL в 503.
|
||||
|
||||
Общая для процесса API (`db_session_scope` и `get_db_session` в
|
||||
`src/api/dependencies.py`) и уборщика (`src/cleaner/main.py`): у каждого
|
||||
своя фабрика сессий (design change `upload-consistency`, решение 7).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from src.core.exceptions import ServiceUnavailable
|
||||
from src.infra.db.errors import is_db_unavailable
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="database")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def session_scope(
|
||||
session_factory: async_sessionmaker[AsyncSession],
|
||||
*,
|
||||
timeout_seconds: float,
|
||||
) -> AsyncIterator[AsyncSession]:
|
||||
"""Сессия БД на один шаг; commit делает сервис.
|
||||
|
||||
Незакоммиченное при выходе откатывается. Работа с БД внутри
|
||||
ограничена `timeout_seconds`: зависший Postgres не держит шаг
|
||||
бесконечно. Недоступность БД (`is_db_unavailable`) — `warning` и
|
||||
`ServiceUnavailable` (503), а соединение не возвращается в пул: его
|
||||
состояние неизвестно, а откат на зависшем сервере повис бы.
|
||||
"""
|
||||
async with session_factory() as db_session:
|
||||
try:
|
||||
async with asyncio.timeout(timeout_seconds):
|
||||
yield db_session
|
||||
except Exception as e:
|
||||
if not is_db_unavailable(e):
|
||||
raise
|
||||
await db_session.invalidate()
|
||||
logger.warning(
|
||||
"Database is unavailable",
|
||||
error_type=type(e).__name__,
|
||||
error=str(e),
|
||||
)
|
||||
raise ServiceUnavailable from e
|
||||
Reference in New Issue
Block a user