forked from mtusi2026/mtusi2026lab5
fix: address unit-of-work verify findings
Abort the transport when a bounded close ends, so a frozen server leaves no sessions over the pool once the ping has no transaction. Under the shared request deadline a block sets no timer of its own, so a single cancel closes the connection and the log has one record. Add a test that concurrent worker deliveries get separate units of work, and state the cost of the pattern against both baselines in the report. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+23
-1
@@ -9,6 +9,7 @@ JSON-запроса (design change `unit-of-work`, решения 4 и 6).
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from contextvars import ContextVar
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
@@ -18,6 +19,13 @@ from src.infra.logger import AbstractLogger, get_logger
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="database")
|
||||
|
||||
# задача, у которой идёт общий срок. Задача, а не флаг: дочерняя задача получает
|
||||
# копию контекста, но отмена общего срока до неё не доходит, и её блоку нужен свой
|
||||
_deadline_task: ContextVar[asyncio.Task[object] | None] = ContextVar(
|
||||
"deadline_task",
|
||||
default=None,
|
||||
)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def session_scope(
|
||||
@@ -36,10 +44,20 @@ async def session_scope(
|
||||
на зависшем сервере повис бы. По той же причине отмена задачи (остановка
|
||||
процесса, общий срок запроса) сбрасывает соединение: `close()` сессии послал
|
||||
бы ROLLBACK.
|
||||
|
||||
Внутри `deadline_scope` своего таймера нет: общий срок той же настройкой начат
|
||||
раньше и истекает первым. Таймер блока сработал бы через доли секунды, вторая
|
||||
отмена прервала бы закрытие соединения в пуле: ERROR в журнале, а запись пула
|
||||
вернул бы только сборщик мусора (change `unit-of-work`, уточнение 18).
|
||||
"""
|
||||
limit = (
|
||||
None
|
||||
if _deadline_task.get() is asyncio.current_task()
|
||||
else timeout_seconds
|
||||
)
|
||||
async with session_factory() as db_session:
|
||||
try:
|
||||
async with asyncio.timeout(timeout_seconds):
|
||||
async with asyncio.timeout(limit):
|
||||
try:
|
||||
yield db_session
|
||||
except Exception as e:
|
||||
@@ -65,13 +83,17 @@ async def deadline_scope(*, timeout_seconds: float) -> AsyncIterator[None]:
|
||||
|
||||
Истечение отменяет задачу: открытый блок сбрасывает своё соединение
|
||||
(`session_scope`), а здесь — та же запись и тот же отказ, что у срока блока.
|
||||
Срок вызывающий задаёт не меньше срока блока: блоки своего таймера не взводят.
|
||||
"""
|
||||
token = _deadline_task.set(asyncio.current_task())
|
||||
try:
|
||||
async with asyncio.timeout(timeout_seconds):
|
||||
yield
|
||||
except TimeoutError as e:
|
||||
_log_unavailable(e)
|
||||
raise ServiceUnavailable from e
|
||||
finally:
|
||||
_deadline_task.reset(token)
|
||||
|
||||
|
||||
def _log_unavailable(error: Exception) -> None:
|
||||
|
||||
Reference in New Issue
Block a user