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:
+13
-3
@@ -28,13 +28,23 @@ class BoundedCloseConnection(asyncpg.Connection):
|
||||
соединение для CancelRequest и в `close()` ждёт его без срока.
|
||||
SQLAlchemy при отмене задачи закрывает соединение мягко, поэтому
|
||||
замёрзший Postgres держал бы запрос до разморозки. Здесь всё
|
||||
закрытие ограничено: по истечении asyncpg обрывает соединение, а
|
||||
SQLAlchemy переходит к принудительному закрытию.
|
||||
закрытие ограничено, а транспорт обрывается в `finally`: прерванный
|
||||
`close()` asyncpg уже пометил протокол закрывающимся, и его `abort()`
|
||||
выходит сразу, не трогая сокет. Без этого сокет открыт до конца процесса,
|
||||
и после разморозки сессия PostgreSQL живёт сверх пула, а срок простоя
|
||||
транзакции её не снимет, если транзакции нет (проверка `_ping_once`).
|
||||
После штатного закрытия обрыв ничего не делает: Terminate отправлен, и
|
||||
транспорт asyncpg уже закрыл сам. `_transport` — внутреннее имя asyncpg,
|
||||
его смену ловит `test_no_sessions_over_pool_after_freeze`.
|
||||
"""
|
||||
|
||||
async def close(self, *, timeout: float | None = None) -> None:
|
||||
limit = timeout or DB_CLOSE_TIMEOUT_SECONDS
|
||||
await asyncio.wait_for(super().close(timeout=timeout), limit)
|
||||
transport = self._transport
|
||||
try:
|
||||
await asyncio.wait_for(super().close(timeout=timeout), limit)
|
||||
finally:
|
||||
transport.abort()
|
||||
|
||||
|
||||
def _ping_once(dbapi_connection: Any) -> bool:
|
||||
|
||||
+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:
|
||||
|
||||
+33
-15
@@ -28,6 +28,8 @@ import signal
|
||||
from collections.abc import Callable
|
||||
from contextlib import suppress
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from src.config import settings
|
||||
from src.core.services.attachment_processing import (
|
||||
AttachmentProcessingService,
|
||||
@@ -38,7 +40,7 @@ from src.infra.db import create_engine, create_session_factory
|
||||
from src.infra.db.uow import SqlAlchemyUnitOfWork
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.infra.render import ImageRenderer
|
||||
from src.infra.s3 import create_object_storage
|
||||
from src.infra.s3 import ObjectStorage, create_object_storage
|
||||
from src.schemas.enums import JobOutcome
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="worker")
|
||||
@@ -53,6 +55,30 @@ def main() -> int:
|
||||
return asyncio.run(run())
|
||||
|
||||
|
||||
def service_factory(
|
||||
session_factory: async_sessionmaker[AsyncSession],
|
||||
*,
|
||||
storage: ObjectStorage,
|
||||
renderer: ImageRenderer,
|
||||
stop: asyncio.Event,
|
||||
) -> Callable[[], AttachmentProcessingService]:
|
||||
"""Единица работы держит открытую сессию, а доставки идут одновременно:
|
||||
сервис на доставку (design change `unit-of-work`, решение 3)."""
|
||||
|
||||
def make_service() -> AttachmentProcessingService:
|
||||
return AttachmentProcessingService(
|
||||
uow=SqlAlchemyUnitOfWork(
|
||||
session_factory,
|
||||
timeout_seconds=settings.database.request_timeout_seconds,
|
||||
),
|
||||
storage=storage,
|
||||
renderer=renderer,
|
||||
stop=stop,
|
||||
)
|
||||
|
||||
return make_service
|
||||
|
||||
|
||||
async def run() -> int:
|
||||
stop = asyncio.Event()
|
||||
loop = asyncio.get_running_loop()
|
||||
@@ -67,20 +93,12 @@ async def run() -> int:
|
||||
session_factory = create_session_factory(engine)
|
||||
storage = create_object_storage(settings.s3, namespace=namespace)
|
||||
|
||||
renderer = ImageRenderer(worker)
|
||||
|
||||
def make_service() -> AttachmentProcessingService:
|
||||
# единица работы держит открытую сессию, а доставки идут одновременно:
|
||||
# сервис на доставку (design change unit-of-work, решение 3)
|
||||
return AttachmentProcessingService(
|
||||
uow=SqlAlchemyUnitOfWork(
|
||||
session_factory,
|
||||
timeout_seconds=settings.database.request_timeout_seconds,
|
||||
),
|
||||
storage=storage,
|
||||
renderer=renderer,
|
||||
stop=stop,
|
||||
)
|
||||
make_service = service_factory(
|
||||
session_factory,
|
||||
storage=storage,
|
||||
renderer=ImageRenderer(worker),
|
||||
stop=stop,
|
||||
)
|
||||
|
||||
try:
|
||||
if not (
|
||||
|
||||
Reference in New Issue
Block a user