chore: port lab 5 solution into the lab 6 skeleton

Source: mtusi2026lab5-safronov, solution/bvt2301-safronov, 046ec9e.
Contracts, public tests and evidence of lab 5 are not carried over.
The compose project, image and CI prefix are renamed to lab6; the first
broker start defect is recorded in KNOWN_ISSUES.md; PLAN.md outlines the
OpenSpec changes of lab 6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 04:46:56 +03:00
co-authored by Claude Opus 5.5
parent 470d9d6f1e
commit 9cc6c0c7a6
621 changed files with 151446 additions and 29 deletions
+257
View File
@@ -0,0 +1,257 @@
"""`make service_test_db`: временная база `test_uow_<db>` в PostgreSQL стенда.
Имя проверяется шаблоном до любых действий (иначе код 2). База создаётся и
мигрирует в начале, удаляется при любом исходе (`pytest_unconfigure`); рабочая база
не затрагивается. Настройки «тесного» API — окружением до импорта `src`, как у
четвёртого API стенда отказов: срок 2 с, пул 1, ожидание пула 1 с, один хэш
одновременно. Единицы работы со своими сроками и пулами тесты собирают сами
(`make_engine`). Design change `unit-of-work`, решение 13.
"""
import asyncio
import os
import re
import subprocess
import sys
from pathlib import Path
import pytest
from dotenv import dotenv_values
ROOT = Path(__file__).resolve().parents[2]
TEST_DB_PATTERN = re.compile(r"^test_uow_[a-z0-9_]+$")
BLOCK_SECONDS = 2.0
# больше любой границы времени в тестах заморозки
FREEZE_LIMIT_SECONDS = 8.0
def _test_db_name() -> str:
override = os.environ.get("SERVICE_TEST_DB")
if override is not None:
return override
env = dotenv_values(ROOT / ".env")
return f"test_uow_{env.get('POSTGRES_DB') or 'messenger'}"
TEST_DB = _test_db_name()
if TEST_DB_PATTERN.fullmatch(TEST_DB) is None:
print(f"service_test_db: bad database name {TEST_DB!r}", file=sys.stderr)
# до импорта src и до любых действий с PostgreSQL
os._exit(2)
os.environ.update(
{
"APP__RUN_MODE": "console",
"DATABASE__NAME": TEST_DB,
"DATABASE__POOL_SIZE": "1",
"DATABASE__MAX_OVERFLOW": "0",
"DATABASE__POOL_TIMEOUT_SECONDS": "1",
"DATABASE__REQUEST_TIMEOUT_SECONDS": str(BLOCK_SECONDS),
"AUTH__KDF_CONCURRENCY": "1",
},
)
import asyncpg # noqa: E402
from sqlalchemy.ext.asyncio import ( # noqa: E402
AsyncEngine,
AsyncSession,
async_sessionmaker, # noqa: E402
)
from src.config import settings # noqa: E402
from src.infra.db import ( # noqa: E402
create_engine,
create_session_factory,
scope,
)
from src.infra.db.models.base import Base # noqa: E402
from src.infra.db.uow import SqlAlchemyUnitOfWork # noqa: E402
_created = False
class DatabaseWarnings:
"""Записи логгера `database`: сколько раз назван отказ."""
def __init__(self) -> None:
self.events: list[str] = []
def warning(self, event_name: str, **_: object) -> None:
self.events.append(event_name)
@pytest.fixture
def warnings(monkeypatch: pytest.MonkeyPatch) -> DatabaseWarnings:
recorder = DatabaseWarnings()
monkeypatch.setattr(scope, "logger", recorder)
return recorder
async def _admin_connection(database: str = "postgres") -> asyncpg.Connection:
source = settings.database
return await asyncpg.connect(
host=source.host,
port=source.port,
user=source.user,
password=source.password.get_secret_value(),
database=database,
timeout=source.connect_timeout_seconds,
)
async def _recreate(*, create: bool) -> None:
connection = await _admin_connection()
try:
await connection.execute(
f'DROP DATABASE IF EXISTS "{TEST_DB}" WITH (FORCE)',
)
if create:
await connection.execute(f'CREATE DATABASE "{TEST_DB}"')
finally:
await connection.close()
def pytest_sessionstart(session: pytest.Session) -> None:
global _created
_created = True
asyncio.run(_recreate(create=True))
subprocess.run(
[sys.executable, "-m", "alembic", "upgrade", "head"],
cwd=ROOT,
check=True,
capture_output=True,
)
def pytest_unconfigure(config: pytest.Config) -> None:
if _created:
asyncio.run(_recreate(create=False))
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
def make_engine(**overrides: object) -> AsyncEngine:
"""Свой engine к временной базе: тот же `create_engine`, что у процессов."""
return create_engine(settings.database.model_copy(update=overrides))
def make_uow(
factory: async_sessionmaker[AsyncSession],
*,
timeout_seconds: float = 5,
) -> SqlAlchemyUnitOfWork:
return SqlAlchemyUnitOfWork(factory, timeout_seconds=timeout_seconds)
def make_factory(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]:
return create_session_factory(engine)
async def admin() -> asyncpg.Connection:
"""Соединение с временной базой мимо приложения: блокировки, обрыв, чистка."""
return await _admin_connection(TEST_DB)
async def truncate_all() -> None:
tables = ", ".join(
f'"{table.name}"' for table in Base.metadata.sorted_tables
)
connection = await admin()
try:
await connection.execute(f"TRUNCATE {tables} CASCADE")
finally:
await connection.close()
class TcpProxy:
"""TCP-прокси до PostgreSQL: замороженный сервер без `docker pause` рабочего
PostgreSQL. `freeze` — байты перестают идти в обе стороны, соединения живы;
`drop` — все соединения оборваны; `client_writes` — порции от клиента."""
def __init__(self, host: str, port: int) -> None:
self._target = (host, port)
self._server: asyncio.Server | None = None
self._gate = asyncio.Event()
self._gate.set()
self._writers: set[asyncio.StreamWriter] = set()
self._tasks: set[asyncio.Task[None]] = set()
self.port = 0
self.accepted = 0
self.client_writes = 0
async def __aenter__(self) -> "TcpProxy":
self._server = await asyncio.start_server(
self._handle,
"127.0.0.1",
0,
)
self.port = self._server.sockets[0].getsockname()[1]
return self
async def __aexit__(self, *exc_info: object) -> None:
self.thaw()
self.drop()
if self._server is not None:
self._server.close()
for task in list(self._tasks):
task.cancel()
await asyncio.gather(*self._tasks, return_exceptions=True)
def freeze(self) -> None:
"""Разморозка по сторожу: регрессия (откат вне срока) иначе висела бы
вечно, а так тест доходит до проверки времени и падает."""
self._gate.clear()
asyncio.get_running_loop().call_later(FREEZE_LIMIT_SECONDS, self.thaw)
def thaw(self) -> None:
self._gate.set()
def drop(self) -> None:
for writer in list(self._writers):
writer.transport.abort()
self._writers.clear()
async def _handle(
self,
reader: asyncio.StreamReader,
writer: asyncio.StreamWriter,
) -> None:
self.accepted += 1
upstream_reader, upstream_writer = await asyncio.open_connection(
*self._target,
)
self._writers.update({writer, upstream_writer})
for task in (
self._pump(reader, upstream_writer, counted=True),
self._pump(upstream_reader, writer, counted=False),
):
pump = asyncio.ensure_future(task)
self._tasks.add(pump)
pump.add_done_callback(self._tasks.discard)
async def _pump(
self,
reader: asyncio.StreamReader,
writer: asyncio.StreamWriter,
*,
counted: bool,
) -> None:
try:
while data := await reader.read(65536):
await self._gate.wait()
if counted:
self.client_writes += 1
writer.write(data)
await writer.drain()
except (ConnectionError, OSError):
pass
finally:
writer.transport.abort()
@pytest.fixture
def proxy_target() -> tuple[str, int]:
return settings.database.host, settings.database.port
@@ -0,0 +1,23 @@
"""Набор `repo_contract.py` на настоящем SQL; число проверок то же, что на фейке."""
import pytest
from conftest import make_engine, make_factory, make_uow, truncate_all
from repo_contract import CHECKS
pytestmark = pytest.mark.anyio
@pytest.mark.parametrize(
"check",
CHECKS,
ids=[check.__name__ for check in CHECKS],
)
async def test_repo_contract_sql(check) -> None:
await truncate_all()
engine = make_engine(pool_size=2)
factory = make_factory(engine)
try:
await check(lambda: make_uow(factory))
finally:
await engine.dispose()
+457
View File
@@ -0,0 +1,457 @@
"""Приложение в процессе на «тесном» API: соединение на шаг и общий срок
JSON-запроса (спек `unit-of-work`). S3 и кэш — фейки: рабочий стенд, кроме его
PostgreSQL как сервера, не затрагивается."""
import asyncio
import logging
import time
from collections.abc import AsyncIterator
from pathlib import Path
from uuid import uuid4
import httpx
import pytest
from sqlalchemy import event
from builders import attachment_dto
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
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
ROOT = Path(__file__).resolve().parents[2]
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
# запас на планировщик: срок проверяется сверху, не точно
MARGIN = 0.6
PASSWORD = "password-1234"
class _Recording:
"""Обёртка ASGI: сколько соединений занято в начале ответа."""
def __init__(self) -> None:
self.at_response_start: list[int] = []
async def __call__(self, scope, receive, send) -> None:
async def recording_send(message) -> None:
if message["type"] == "http.response.start":
self.at_response_start.append(engine.pool.checkedout())
await send(message)
await app(scope, receive, recording_send)
@pytest.fixture
def fake_clients(monkeypatch: pytest.MonkeyPatch) -> tuple[FakeCache, object]:
journal = FakeDatabase()
cache = FakeCache(journal)
storage = FakeObjectStorage(journal)
monkeypatch.setattr(dependencies, "cache", cache)
monkeypatch.setattr(dependencies, "object_storage", storage)
return cache, storage
@pytest.fixture
async def recording(fake_clients) -> AsyncIterator[_Recording]:
await truncate_all()
await engine.dispose()
yield _Recording()
await engine.dispose()
@pytest.fixture
async def client(recording: _Recording) -> AsyncIterator[httpx.AsyncClient]:
transport = httpx.ASGITransport(
app=recording,
raise_app_exceptions=False,
)
async with httpx.AsyncClient(
transport=transport,
base_url="http://test/api/v1",
timeout=30,
) as created:
yield created
class _Checkouts:
def __init__(self) -> None:
self.count = 0
def __call__(self, *_: object) -> None:
self.count += 1
def __enter__(self) -> "_Checkouts":
event.listen(engine.sync_engine, "checkout", self)
return self
def __exit__(self, *_: object) -> None:
event.remove(engine.sync_engine, "checkout", self)
async def _register_login(
client: httpx.AsyncClient,
) -> tuple[dict[str, str], str]:
username = f"u{uuid4().hex[:12]}"
response = await client.post(
"/users",
json={
"username": username,
"display_name": "User",
"password": PASSWORD,
},
)
assert response.status_code == 201, response.text
user_id = response.json()["id"]
response = await client.post("/auth/sessions", auth=(username, PASSWORD))
assert response.status_code == 201, response.text
token = response.json()["token"]
return {"Authorization": f"Bearer {token}"}, user_id
async def _chat(
client: httpx.AsyncClient,
headers: dict[str, str],
user_id: str,
) -> str:
response = await client.post(
"/chats",
headers=headers,
json={"title": "T", "member_ids": [user_id]},
)
assert response.status_code == 201, response.text
return response.json()["id"]
async def test_response_without_held_connection(
client: httpx.AsyncClient,
recording: _Recording,
) -> None:
"""Сценарий «Ответ без занятого соединения»."""
headers, user_id = await _register_login(client)
chat_id = await _chat(client, headers, user_id)
recording.at_response_start.clear()
with _Checkouts() as checkouts:
response = await client.get(
f"/chats/{chat_id}/messages",
headers=headers,
)
assert response.status_code == 200
assert checkouts.count == 2
assert recording.at_response_start == [0]
async def test_pool_of_one_connection(client: httpx.AsyncClient) -> None:
"""Сценарий «Пул из одного соединения»."""
headers, user_id = await _register_login(client)
chat_id = await _chat(client, headers, user_id)
assert engine.pool.size() == 1
responses = await asyncio.gather(
*(
client.get(f"/chats/{chat_id}/messages", headers=headers)
for _ in range(2)
),
)
assert [item.status_code for item in responses] == [200, 200]
async def test_login_does_not_hold_connection_on_hash(
client: httpx.AsyncClient,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Сценарий «Вход не держит соединение на хэш»."""
headers, _ = await _register_login(client)
username = (await client.get("/users/me", headers=headers)).json()[
"username"
]
verifying = asyncio.Event()
release = asyncio.Event()
async def verify_password(*, password: str, password_hash: str | None):
verifying.set()
await release.wait()
return True
monkeypatch.setattr(session_module, "verify_password", verify_password)
login = asyncio.create_task(
client.post("/auth/sessions", auth=(username, PASSWORD)),
)
await verifying.wait()
assert engine.pool.checkedout() == 0
other = await client.get("/users/me", headers=headers)
assert other.status_code == 200
release.set()
assert (await login).status_code == 201
async def test_block_without_postgres_takes_no_connection(
client: httpx.AsyncClient,
fake_clients,
) -> None:
"""Сценарий «Блок без обращения к PostgreSQL»: только вход выдаёт."""
cache, _ = fake_clients
headers, user_id = await _register_login(client)
chat_id = await _chat(client, headers, user_id)
# карточка уже в кэше после создания
found = await chat_cache.get_chat(cache, chat_id=chat_id)
assert isinstance(found, ChatFullDTO)
with _Checkouts() as checkouts:
response = await client.get(f"/chats/{chat_id}", headers=headers)
assert response.status_code == 200
assert checkouts.count == 1
async def test_two_slow_steps_fit_single_deadline(
client: httpx.AsyncClient,
) -> None:
"""Сценарий «Два медленных шага»: 503 через ~T, а не через сумму сроков."""
headers, user_id = await _register_login(client)
chat_id = await _chat(client, headers, user_id)
sessions_lock = await admin()
messages_lock = await admin()
sessions_tx = sessions_lock.transaction()
messages_tx = messages_lock.transaction()
await sessions_tx.start()
await messages_tx.start()
try:
await sessions_lock.execute(
"LOCK TABLE sessions IN ACCESS EXCLUSIVE MODE",
)
await messages_lock.execute(
"LOCK TABLE messages IN ACCESS EXCLUSIVE MODE",
)
started = time.monotonic()
request = asyncio.create_task(
client.get(f"/chats/{chat_id}/messages", headers=headers),
)
# проверка токена занимает больше половины срока
await asyncio.sleep(BLOCK_SECONDS * 0.6)
await sessions_tx.rollback()
response = await request
elapsed = time.monotonic() - started
finally:
await messages_tx.rollback()
await sessions_lock.close()
await messages_lock.close()
assert response.status_code == 503
assert response.json()["error"]["code"] == "unavailable"
assert elapsed < BLOCK_SECONDS + MARGIN
async def test_hash_queue_gets_deadline(client: httpx.AsyncClient) -> None:
"""Сценарий «Очередь хэшей»: не успевшие — 503 через ~T."""
headers, _ = await _register_login(client)
username = (await client.get("/users/me", headers=headers)).json()[
"username"
]
async def login() -> tuple[int, float]:
started = time.monotonic()
response = await client.post(
"/auth/sessions",
auth=(username, PASSWORD),
)
return response.status_code, time.monotonic() - started
results = await asyncio.gather(*(login() for _ in range(200)))
statuses = {status for status, _ in results}
assert 503 in statuses
assert statuses <= {201, 503}
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,
) -> None:
"""Сценарий «Вложение дольше срока блока»: загрузка."""
_, storage = fake_clients
headers, user_id = await _register_login(client)
chat_id = await _chat(client, headers, user_id)
async def slow_body() -> AsyncIterator[bytes]:
yield SAMPLE[:100]
await asyncio.sleep(BLOCK_SECONDS + 0.3)
yield SAMPLE[100:]
started = time.monotonic()
response = await client.post(
f"/chats/{chat_id}/attachments",
params={"filename": "a.png"},
headers={**headers, "Content-Type": "image/png"},
content=slow_body(),
)
assert response.status_code == 202, response.text
assert time.monotonic() - started > BLOCK_SECONDS
assert storage.objects
async def test_download_longer_than_block(
client: httpx.AsyncClient,
fake_clients,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Тот же сценарий: скачивание потоком."""
_, storage = fake_clients
headers, user_id = await _register_login(client)
chat_id = await _chat(client, headers, user_id)
row = attachment_dto(
chat_id=chat_id,
owner_id=user_id,
status=AttachmentStatus.READY,
created_at=utcnow(),
namespace=storage.namespace,
)
async with SqlAlchemyUnitOfWork(
session_factory,
timeout_seconds=BLOCK_SECONDS,
) as uow:
await uow.attachments.insert_attachment(attachment=row)
await uow.commit()
storage.seed(row.object_key, b"content", content_type="image/png")
real_open = storage.open
class _Slow:
def __init__(self, inner) -> None:
self.inner = inner
async def __aenter__(self):
stored = await self.inner.__aenter__()
real_chunks = stored.iter_chunks
async def iter_chunks(chunk_bytes: int = 1024):
await asyncio.sleep(BLOCK_SECONDS + 0.3)
async for chunk in real_chunks(chunk_bytes):
yield chunk
stored.iter_chunks = iter_chunks
return stored
async def __aexit__(self, *exc_info: object):
return await self.inner.__aexit__(*exc_info)
monkeypatch.setattr(storage, "open", lambda key: _Slow(real_open(key)))
started = time.monotonic()
response = await client.get(
f"/attachments/{row.id}/content",
headers=headers,
)
assert response.status_code == 200
assert response.content == b"content"
assert time.monotonic() - started > BLOCK_SECONDS
async def test_code_order_with_postgres_down(
client: httpx.AsyncClient,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Вход идёт раньше валидации, битый JSON — раньше входа; отказ БД на входе —
503 до 400 (design, Context, п. 8)."""
headers, user_id = await _register_login(client)
chat_id = await _chat(client, headers, user_id)
down_settings = dependencies.settings.database.model_copy(
update={"port": 1, "connect_timeout_seconds": 1},
)
down = create_engine(down_settings)
monkeypatch.setattr(
dependencies,
"session_factory",
create_session_factory(down),
)
url = f"/chats/{chat_id}/messages"
try:
no_token = await client.post(url, json={"text": "x"})
assert no_token.status_code == 401
broken = await client.post(
url,
headers={**headers, "Content-Type": "application/json"},
content=b"{not json",
)
assert broken.status_code == 400
extra = await client.post(
url,
headers={**headers, "Idempotency-Key": "k"},
json={"text": "x", "extra": 1},
)
assert extra.status_code == 503
assert extra.json()["error"]["code"] == "unavailable"
history = await client.get(url, headers=headers)
assert history.status_code == 503
finally:
await down.dispose()
+514
View File
@@ -0,0 +1,514 @@
"""Настоящая единица работы: граница транзакции, соединение на шаг, срок блока,
отказ PostgreSQL и обрыв соединения с дешёвой проверкой при выдаче (спек
`unit-of-work`, design, решения 2, 4, 7)."""
import asyncio
import time
import pytest
from sqlalchemy import event, exc, text
from builders import NOW, PASSWORD_HASH, attachment_dto, user_dto
from conftest import (
DatabaseWarnings,
TcpProxy,
admin,
make_engine,
make_factory,
make_uow,
truncate_all,
)
from src.core import exceptions
from src.core.ports.uow import UnitOfWorkError
from src.infra.db import scope
from src.infra.db.engine import _ping_once
from src.infra.db.uow import SqlAlchemyUnitOfWork
from src.schemas.enums import AttachmentStatus
from src.utils.constants import (
DB_APPLICATION_NAME,
DB_CLOSE_TIMEOUT_SECONDS,
)
pytestmark = pytest.mark.anyio
SECONDS_MARGIN = 0.7
# сервер замечает закрытый сокет не сразу
SESSIONS_SETTLE_SECONDS = 3.0
@pytest.fixture
async def engine():
await truncate_all()
created = make_engine(pool_size=1)
yield created
await created.dispose()
@pytest.fixture
def uow(engine) -> SqlAlchemyUnitOfWork:
return make_uow(make_factory(engine))
def _other(engine) -> SqlAlchemyUnitOfWork:
return make_uow(make_factory(engine))
async def _pid(uow: SqlAlchemyUnitOfWork) -> int:
result = await uow._current_session().execute(
text("SELECT pg_backend_pid()"),
)
return result.scalar_one()
async def _user_visible(engine, username: str) -> bool:
async with _other(engine) as other:
found = await other.users.get_user_credentials(username=username)
return found is not None
async def test_exit_without_commit(uow, engine) -> None:
"""Сценарий «Выход без фиксации»."""
user = user_dto()
async with uow:
await uow.users.insert_user(user=user, password_hash=PASSWORD_HASH)
assert not await _user_visible(engine, user.username)
async def test_exception_inside_block(uow, engine) -> None:
"""Сценарий «Исключение внутри блока»: то же исключение, запись откачена."""
user = user_dto()
with pytest.raises(exceptions.UsernameTaken):
async with uow:
await uow.users.insert_user(user=user, password_hash=PASSWORD_HASH)
raise exceptions.UsernameTaken
assert not await _user_visible(engine, user.username)
async def test_commit_visible_to_other_connection(uow, engine) -> None:
"""Сценарий «Фиксация»."""
user = user_dto()
async with uow:
await uow.users.insert_user(user=user, password_hash=PASSWORD_HASH)
await uow.commit()
assert await _user_visible(engine, user.username)
async def test_work_after_commit_is_an_error(uow) -> None:
"""Сценарий «Работа после фиксации»: не молчаливая вторая транзакция."""
async with uow:
await uow.commit()
with pytest.raises(UnitOfWorkError):
_ = uow.users
with pytest.raises(UnitOfWorkError):
await uow.commit()
async def test_nested_block_without_second_connection(uow, engine) -> None:
"""Сценарий «Вложенный блок»."""
async with uow:
await uow.users.get_user_credentials(username="nobody")
with pytest.raises(UnitOfWorkError):
await uow.__aenter__()
assert engine.pool.checkedout() == 1
async def test_repo_outside_block_no_query(uow, engine) -> None:
"""Сценарий «Repo вне блока»: запроса нет."""
with pytest.raises(UnitOfWorkError):
_ = uow.users
assert engine.pool.checkedout() == 0
async def test_blocks_opened(uow) -> None:
for _ in range(3):
async with uow:
pass
assert uow.blocks_opened == 3
async def test_connection_taken_only_inside_block(uow, engine) -> None:
pool = engine.pool
assert pool.checkedout() == 0
async with uow:
# выдача ленивая: сессия без выражения соединения не берёт
assert pool.checkedout() == 0
await uow.users.get_user_credentials(username="nobody")
assert pool.checkedout() == 1
assert pool.checkedout() == 0
async def test_commit_returns_connection_after_exit(uow, engine) -> None:
async with uow:
await uow.users.get_user_credentials(username="nobody")
await uow.commit()
assert engine.pool.checkedout() == 0
async def test_statement_longer_than_block(
engine,
warnings: DatabaseWarnings,
) -> None:
"""Сценарий «Запрос дольше срока»."""
uow = make_uow(make_factory(engine), timeout_seconds=0.3)
async with uow:
first_pid = await _pid(uow)
started = time.monotonic()
with pytest.raises(exceptions.ServiceUnavailable):
async with uow:
await uow._current_session().execute(
text("SELECT pg_sleep(4)"),
)
assert time.monotonic() - started < 0.3 + DB_CLOSE_TIMEOUT_SECONDS
assert warnings.events == ["Database is unavailable"]
assert engine.pool.checkedout() == 0
# следующий блок — рабочее соединение, а не прежнее
async with uow:
assert await _pid(uow) != first_pid
async def test_frozen_on_rollback(
proxy_target,
warnings: DatabaseWarnings,
) -> None:
"""Сценарий «PostgreSQL заморожен при откате»."""
async with TcpProxy(*proxy_target) as proxy:
engine = make_engine(host="127.0.0.1", port=proxy.port, pool_size=1)
uow = make_uow(make_factory(engine), timeout_seconds=0.5)
started = None
with pytest.raises(exceptions.ServiceUnavailable):
async with uow:
await uow.users.get_user_credentials(username="nobody")
proxy.freeze()
started = time.monotonic()
elapsed = time.monotonic() - started
assert elapsed < 0.5 + DB_CLOSE_TIMEOUT_SECONDS + SECONDS_MARGIN
assert warnings.events == ["Database is unavailable"]
assert engine.pool.checkedout() == 0
proxy.thaw()
await engine.dispose()
async def test_frozen_at_exception_in_block(proxy_target) -> None:
"""Исключение при замороженном сервере: откат под сроком блока, отказ БД
заменяет доменное исключение, а не висит до разморозки."""
async with TcpProxy(*proxy_target) as proxy:
engine = make_engine(host="127.0.0.1", port=proxy.port, pool_size=1)
uow = make_uow(make_factory(engine), timeout_seconds=0.5)
started = time.monotonic()
with pytest.raises(exceptions.ServiceUnavailable):
async with uow:
await uow.users.get_user_credentials(username="nobody")
proxy.freeze()
started = time.monotonic()
raise exceptions.ChatNotFound
elapsed = time.monotonic() - started
assert elapsed < 0.5 + DB_CLOSE_TIMEOUT_SECONDS + SECONDS_MARGIN
proxy.thaw()
await engine.dispose()
async def test_cancel_with_open_transaction(proxy_target) -> None:
"""Сценарий «Отмена при открытой транзакции»."""
async with TcpProxy(*proxy_target) as proxy:
engine = make_engine(host="127.0.0.1", port=proxy.port, pool_size=1)
uow = make_uow(make_factory(engine), timeout_seconds=30)
inside = asyncio.Event()
async def block() -> None:
async with uow:
await uow.users.get_user_credentials(username="nobody")
inside.set()
await asyncio.sleep(60)
task = asyncio.create_task(block())
await inside.wait()
accepted = proxy.accepted
proxy.freeze()
started = time.monotonic()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
elapsed = time.monotonic() - started
assert elapsed < DB_CLOSE_TIMEOUT_SECONDS + SECONDS_MARGIN
assert engine.pool.checkedout() == 0
proxy.thaw()
# соединение в пул не вернулось: следующий блок открывает новое
async with uow:
await uow.users.get_user_credentials(username="nobody")
assert proxy.accepted == accepted + 1
await engine.dispose()
async def test_child_task_under_deadline_keeps_block_timer(engine) -> None:
"""Общий срок снимает таймер только у своей задачи: дочернюю его отмена не
достанет, а копия контекста у неё та же."""
uow = make_uow(make_factory(engine), timeout_seconds=0.3)
async def slow_block() -> None:
async with uow:
await uow._current_session().execute(text("SELECT pg_sleep(4)"))
started = time.monotonic()
async with scope.deadline_scope(timeout_seconds=30):
with pytest.raises(exceptions.ServiceUnavailable):
await asyncio.create_task(slow_block())
assert time.monotonic() - started < 0.3 + DB_CLOSE_TIMEOUT_SECONDS
async def _app_sessions(connection) -> int:
"""Сессии приложения во временной базе; соединение теста — без его имени."""
return await connection.fetchval(
"SELECT count(*) FROM pg_stat_activity "
"WHERE datname = current_database() AND application_name = $1",
DB_APPLICATION_NAME,
)
async def _settled_sessions(connection, *, limit: int) -> int:
"""Сессии, когда их стало не больше `limit` или вышел срок ожидания."""
deadline = time.monotonic() + SESSIONS_SETTLE_SECONDS
while True:
sessions = await _app_sessions(connection)
if sessions <= limit or time.monotonic() > deadline:
return sessions
await asyncio.sleep(0.1)
async def test_no_sessions_over_pool_after_freeze(proxy_target) -> None:
"""Сценарий «После заморозки PostgreSQL сессий сверх пула нет»: заморозка на
проверке соединения при выдаче (транзакции нет, и срок простоя транзакции
сессию не снимет), три раза подряд."""
pool_size = 2
connection = await admin()
try:
baseline = await _app_sessions(connection)
async with TcpProxy(*proxy_target) as proxy:
engine = make_engine(
host="127.0.0.1",
port=proxy.port,
pool_size=pool_size,
)
factory = make_factory(engine)
async def step() -> None:
uow = make_uow(factory, timeout_seconds=0.3)
async with uow:
await uow._current_session().execute(
text("SELECT pg_sleep(0.05)"),
)
for _ in range(3):
# прогрев: открыты все соединения пула, запросы идут вместе
await asyncio.gather(*(step() for _ in range(pool_size)))
proxy.freeze()
results = await asyncio.gather(
*(step() for _ in range(pool_size)),
return_exceptions=True,
)
assert all(
isinstance(result, exceptions.ServiceUnavailable)
for result in results
), results
proxy.thaw()
# соединения этой пачки сброшены, в пуле их нет
assert engine.pool.checkedout() == 0
sessions = await _settled_sessions(connection, limit=baseline)
assert sessions <= baseline, f"{sessions} > {baseline}"
# пул рабочий: новые соединения вместо сброшенных
await step()
await engine.dispose()
finally:
await connection.close()
async def test_soft_close_is_graceful(proxy_target) -> None:
"""Мягкое закрытие без отказа: сервер получил Terminate и закрыл сессию сам,
обрыв транспорта после него ничего не меняет."""
connection = await admin()
try:
baseline = await _app_sessions(connection)
async with TcpProxy(*proxy_target) as proxy:
engine = make_engine(
host="127.0.0.1",
port=proxy.port,
pool_size=1,
)
async with engine.connect():
pass
assert await _app_sessions(connection) == baseline + 1
before = proxy.client_writes
await engine.dispose()
sessions = await _settled_sessions(connection, limit=baseline)
assert sessions == baseline
# единственная порция клиента после проверки — Terminate
assert proxy.client_writes == before + 1
finally:
await connection.close()
async def test_constraint_violation(
uow,
engine,
warnings: DatabaseWarnings,
) -> None:
"""Сценарий «Нарушение ограничения»."""
async with uow:
first_pid = await _pid(uow)
with pytest.raises(exc.IntegrityError):
async with uow:
# owner не участник: внешний ключ на chat_members
await uow.attachments.insert_attachment(
attachment=attachment_dto(
chat_id=user_dto().id,
owner_id=user_dto().id,
),
)
assert warnings.events == []
assert engine.pool.checkedout() == 0
async with uow:
assert await _pid(uow) == first_pid
async def test_terminated_connection_replaced(uow) -> None:
"""`pg_terminate_backend`: следующий блок получает новое без ошибки."""
async with uow:
pid = await _pid(uow)
connection = await admin()
try:
await connection.fetchval("SELECT pg_terminate_backend($1)", pid)
finally:
await connection.close()
async with uow:
assert await _pid(uow) != pid
async def test_ping_is_replaced(engine) -> None:
assert engine.dialect.do_ping is _ping_once
async def test_ping_detects_dropped_connection_through_proxy(
proxy_target,
) -> None:
"""Обрыв при подменённой проверке: `_connection`, `fetchrow` и
`_handle_exception` адаптера настоящие. Смена их имён ломает разбор обрыва, и
следующий блок падает ошибкой вместо нового соединения (design, решение 7)."""
async with TcpProxy(*proxy_target) as proxy:
engine = make_engine(host="127.0.0.1", port=proxy.port, pool_size=1)
pings: list[bool] = []
real_ping = engine.dialect.do_ping
def spy(connection) -> bool:
result = False
try:
result = real_ping(connection)
finally:
pings.append(result)
return result
engine.dialect.do_ping = spy
uow = make_uow(make_factory(engine))
async with uow:
first = await _pid(uow)
accepted = proxy.accepted
proxy.drop()
await asyncio.sleep(0)
async with uow:
second = await _pid(uow)
# проверка выполнялась и нашла обрыв; новое соединение через прокси
assert pings == [False]
assert second != first
assert proxy.accepted == accepted + 1
await engine.dispose()
async def test_ping_is_one_exchange(proxy_target) -> None:
"""Проверка при выдаче — один обмен, а не `BEGIN`, `;`, `ROLLBACK`."""
async with TcpProxy(*proxy_target) as proxy:
engine = make_engine(host="127.0.0.1", port=proxy.port, pool_size=1)
async with engine.connect():
pass
# первая проверка готовит выражение, вторая — повторная
async with engine.connect():
pass
before = proxy.client_writes
async with engine.connect():
pass
assert proxy.client_writes - before == 1
await engine.dispose()
async def test_ping_with_real_postgres_rejected_connection(engine) -> None:
"""Живое соединение: проверка не падает и возвращает пул в рабочий вид."""
async with engine.connect() as connection:
await connection.execute(text("SELECT 1"))
assert engine.pool.checkedout() == 0
async def _statements(engine, action) -> list[str]:
captured: list[str] = []
def before_cursor_execute(_c, _cursor, statement, _p, _ctx, _many) -> None:
captured.append(statement)
event.listen(
engine.sync_engine,
"before_cursor_execute",
before_cursor_execute,
)
try:
await action()
finally:
event.remove(
engine.sync_engine,
"before_cursor_execute",
before_cursor_execute,
)
return captured
@pytest.mark.parametrize(
("method", "constant"),
[
("lock_due_jobs", "'queued'"),
("count_published", "'queued'"),
("count_unfinished", "'processing'"),
("count_unfinished", "'queued'"),
("lock_stale_pending", "'pending'"),
("get_staging_candidates", "'ready'"),
],
)
async def test_status_is_a_constant_in_statement(
uow,
engine,
method: str,
constant: str,
) -> None:
async def action() -> None:
async with uow:
if method == "lock_due_jobs":
await uow.jobs.lock_due_jobs(now=NOW, limit=1)
elif method == "count_published":
await uow.jobs.count_published()
elif method == "count_unfinished":
await uow.jobs.count_unfinished(limit=1)
elif method == "lock_stale_pending":
await uow.attachments.lock_stale_pending(
attachment_id=user_dto().id,
older_than=NOW,
)
else:
await uow.attachments.get_staging_candidates(
status=AttachmentStatus.READY,
updated_before=None,
after=None,
limit=1,
)
statements = await _statements(engine, action)
relevant = [
item
for item in statements
if "attachment" in item.lower() and "select" in item.lower()
]
assert relevant
assert all(constant in item for item in relevant), relevant