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:
@@ -3,6 +3,7 @@ JSON-запроса (спек `unit-of-work`). S3 и кэш — фейки: ра
|
||||
PostgreSQL как сервера, не затрагивается."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from pathlib import Path
|
||||
@@ -13,10 +14,17 @@ import pytest
|
||||
from sqlalchemy import event
|
||||
|
||||
from builders import attachment_dto
|
||||
from conftest import BLOCK_SECONDS, admin, truncate_all
|
||||
from conftest import (
|
||||
BLOCK_SECONDS,
|
||||
DatabaseWarnings,
|
||||
TcpProxy,
|
||||
admin,
|
||||
truncate_all,
|
||||
)
|
||||
from fakes import FakeCache, FakeDatabase, FakeObjectStorage
|
||||
from src.api import dependencies
|
||||
from src.core.repos import chat_cache
|
||||
from src.core.services import ChatService
|
||||
from src.core.services import session as session_module
|
||||
from src.infra.db import create_engine, create_session_factory
|
||||
from src.infra.db.session import engine, session_factory
|
||||
@@ -24,6 +32,7 @@ from src.infra.db.uow import SqlAlchemyUnitOfWork
|
||||
from src.main import app
|
||||
from src.schemas.dataclasses import ChatFullDTO
|
||||
from src.schemas.enums import AttachmentStatus
|
||||
from src.utils.constants import DB_CLOSE_TIMEOUT_SECONDS
|
||||
from src.utils.utc import utcnow
|
||||
|
||||
pytestmark = pytest.mark.anyio
|
||||
@@ -268,6 +277,65 @@ async def test_hash_queue_gets_deadline(client: httpx.AsyncClient) -> None:
|
||||
assert max(elapsed for _, elapsed in results) < BLOCK_SECONDS + MARGIN
|
||||
|
||||
|
||||
class _PoolRecords(logging.Handler):
|
||||
"""Записи пула: только текст, `exc_info` с кадрами не хранится."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(level=logging.WARNING)
|
||||
self.messages: list[str] = []
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
self.messages.append(record.getMessage())
|
||||
|
||||
|
||||
async def test_deadline_in_second_block_single_record(
|
||||
client: httpx.AsyncClient,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
proxy_target: tuple[str, int],
|
||||
warnings: DatabaseWarnings,
|
||||
) -> None:
|
||||
"""Сценарий «Срок запроса истёк во втором блоке: одна запись, без ERROR
|
||||
пула»: заморозка между входом и операцией, зазор сроков — настоящая
|
||||
длительность блока входа."""
|
||||
headers, _ = await _register_login(client)
|
||||
records = _PoolRecords()
|
||||
pool_logger = logging.getLogger("sqlalchemy.pool")
|
||||
pool_logger.addHandler(records)
|
||||
async with TcpProxy(*proxy_target) as proxy:
|
||||
proxied = create_engine(
|
||||
dependencies.settings.database.model_copy(
|
||||
update={"host": "127.0.0.1", "port": proxy.port},
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dependencies,
|
||||
"session_factory",
|
||||
create_session_factory(proxied),
|
||||
)
|
||||
real_list = ChatService.list_user_chats
|
||||
|
||||
async def frozen_list(self, **kwargs):
|
||||
proxy.freeze()
|
||||
return await real_list(self, **kwargs)
|
||||
|
||||
monkeypatch.setattr(ChatService, "list_user_chats", frozen_list)
|
||||
try:
|
||||
started = time.monotonic()
|
||||
response = await client.get("/chats", headers=headers)
|
||||
elapsed = time.monotonic() - started
|
||||
checked_out = proxied.pool.checkedout()
|
||||
finally:
|
||||
pool_logger.removeHandler(records)
|
||||
proxy.thaw()
|
||||
await proxied.dispose()
|
||||
assert response.status_code == 503
|
||||
assert response.json()["error"]["code"] == "unavailable"
|
||||
assert elapsed < BLOCK_SECONDS + DB_CLOSE_TIMEOUT_SECONDS + MARGIN
|
||||
assert warnings.events == ["Database is unavailable"]
|
||||
assert records.messages == []
|
||||
assert checked_out == 0
|
||||
|
||||
|
||||
async def test_upload_longer_than_block(
|
||||
client: httpx.AsyncClient,
|
||||
fake_clients,
|
||||
|
||||
Reference in New Issue
Block a user