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
+132
View File
@@ -0,0 +1,132 @@
"""DTO для тестов: явное время, ничего случайного, кроме id."""
from datetime import UTC, datetime, timedelta
from hashlib import sha256
from uuid import UUID, uuid4
from src.schemas import dataclasses
from src.schemas.enums import (
AttachmentJobState,
AttachmentStatus,
AttachmentVariantName,
ImageType,
)
NOW = datetime(2026, 3, 1, 12, 0, 0, tzinfo=UTC)
# вид значения держит CHECK ck_users_password_hash_argon2id
PASSWORD_HASH = "$argon2id$v=19$m=65536,t=3,p=4$c2FsdA$aGFzaA"
def at(seconds: float) -> datetime:
"""Момент относительно `NOW`."""
return NOW + timedelta(seconds=seconds)
def user_dto(*, username: str | None = None) -> dataclasses.UserFullDTO:
return dataclasses.UserFullDTO(
id=uuid4(),
username=username or f"u{uuid4().hex[:12]}",
display_name="User",
created_at=NOW,
)
def chat_dto(
*,
member_ids: tuple[UUID, ...],
created_at: datetime = NOW,
) -> dataclasses.ChatFullDTO:
return dataclasses.ChatFullDTO(
id=uuid4(),
title="Chat",
member_ids=member_ids,
created_at=created_at,
)
def message_dto(
*,
chat_id: UUID,
sender_id: UUID,
created_at: datetime = NOW,
attachment_ids: tuple[UUID, ...] = (),
) -> dataclasses.MessageFullDTO:
return dataclasses.MessageFullDTO(
id=uuid4(),
chat_id=chat_id,
sender_id=sender_id,
text="hello",
created_at=created_at,
attachment_ids=attachment_ids,
)
def attachment_dto(
*,
chat_id: UUID,
owner_id: UUID,
status: AttachmentStatus = AttachmentStatus.PENDING,
created_at: datetime = NOW,
updated_at: datetime | None = None,
staging: bool = True,
namespace: str = "testdb",
data: bytes = b"content",
object_key: str | None = None,
) -> dataclasses.AttachmentFullDTO:
attachment_id = uuid4()
return dataclasses.AttachmentFullDTO(
id=attachment_id,
chat_id=chat_id,
owner_id=owner_id,
filename="a.png",
content_type=ImageType.PNG,
size_bytes=len(data),
sha256=sha256(data).digest(),
object_key=object_key
or f"{namespace}/attachments/{attachment_id}/original",
staging_key=f"{namespace}/staging/{attachment_id}/original"
if staging
else None,
status=status,
created_at=created_at,
updated_at=updated_at or created_at,
)
def job_dto(
*,
attachment_id: UUID,
created_at: datetime = NOW,
pipeline_version: int = 1,
) -> dataclasses.AttachmentJobDTO:
return dataclasses.AttachmentJobDTO(
id=uuid4(),
attachment_id=attachment_id,
pipeline_version=pipeline_version,
state=AttachmentJobState.QUEUED,
attempt=0,
created_at=created_at,
updated_at=created_at,
)
def variant_dto(
*,
attachment_id: UUID,
name: AttachmentVariantName = AttachmentVariantName.THUMBNAIL,
pipeline_version: int = 1,
) -> dataclasses.AttachmentVariantDTO:
return dataclasses.AttachmentVariantDTO(
name=name,
pipeline_version=pipeline_version,
object_key=(
f"testdb/attachments/{attachment_id}/"
f"v{pipeline_version}-{name.value}"
),
content_type="image/jpeg",
size_bytes=3,
width=10,
height=10,
sha256=sha256(b"var").digest(),
created_at=NOW,
)
+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
+46
View File
@@ -0,0 +1,46 @@
"""Фейки единицы работы, repo и клиентов для быстрых тестов сервисов.
Метод фейка реализует контракт из докстринга порта (design change
`unit-of-work`, решение 11). Совпадение с SQL закрепляет
`service-tests/repo_contract.py`, сигнатуры — `unit/test_architecture.py`.
"""
from .clients import (
FakeCache,
FakeImageRenderer,
FakeJobPublisher,
FakeObjectStorage,
FakeStoredObject,
)
from .database import FakeDatabase
from .repos import (
FakeAttachmentJobReplayRepository,
FakeAttachmentJobRepository,
FakeAttachmentRepository,
FakeAttachmentVariantRepository,
FakeChatRepository,
FakeIdempotencyRepository,
FakeMessageRepository,
FakeSessionRepository,
FakeUserRepository,
)
from .uow import FakeUnitOfWork
__all__ = [
"FakeAttachmentJobReplayRepository",
"FakeAttachmentJobRepository",
"FakeAttachmentRepository",
"FakeAttachmentVariantRepository",
"FakeCache",
"FakeChatRepository",
"FakeDatabase",
"FakeIdempotencyRepository",
"FakeImageRenderer",
"FakeJobPublisher",
"FakeMessageRepository",
"FakeObjectStorage",
"FakeSessionRepository",
"FakeStoredObject",
"FakeUnitOfWork",
"FakeUserRepository",
]
+245
View File
@@ -0,0 +1,245 @@
"""Фейки клиентов: настоящие `chat_cache` и `attachment_object` работают поверх
них, ключи и формат значения не дублируются (design change `unit-of-work`,
решение 8). Журнал и заданные отказы — общие с `FakeDatabase`: порядок вызовов S3
и издателя виден рядом с блоками.
"""
from collections import Counter
from collections.abc import AsyncIterator, Sequence
from contextlib import asynccontextmanager
from datetime import UTC, datetime
from types import MappingProxyType
from typing import BinaryIO
from uuid import UUID
from src.core import exceptions
from src.infra.s3 import (
StorageStats,
StoredObjectInfo,
StoredObjectPage,
)
from src.schemas.dataclasses import RenderedVariantsDTO
from .database import FakeDatabase
_FAR_PAST = datetime(2000, 1, 1, tzinfo=UTC)
_CHUNK_BYTES = 1024
_CALL_NAMES = ("list", "head", "get", "delete", "put")
class FakeCache:
"""`failing` — Valkey недоступен: промах и пропуск, как у `Cache`."""
def __init__(
self,
database: FakeDatabase,
*,
namespace: str = "testdb",
) -> None:
self.namespace = namespace
self._db = database
self.values: dict[str, str] = {}
self.failing = False
async def get(self, key: str) -> str | None:
self._db.events.append("cache.get")
return None if self.failing else self.values.get(key)
async def set(self, key: str, value: str, *, ttl_seconds: int) -> bool:
self._db.events.append("cache.set")
if self.failing:
return False
self.values[key] = value
return True
async def aclose(self) -> None:
return None
class FakeStoredObject:
def __init__(self, info: StoredObjectInfo, data: bytes, storage) -> None:
self.info = info
self._data = data
self._storage = storage
@property
def size(self) -> int:
return self.info.size
@property
def content_type(self) -> str | None:
return self.info.content_type
async def iter_chunks(
self,
chunk_bytes: int = _CHUNK_BYTES,
) -> AsyncIterator[bytes]:
for start in range(0, len(self._data), chunk_bytes):
chunk = self._data[start : start + chunk_bytes]
self._storage.read_bytes += len(chunk)
yield chunk
async def read(self) -> bytes:
self._storage.read_bytes += len(self._data)
return self._data
class FakeObjectStorage:
"""Объекты в памяти. Событие — `storage.<операция>`, отказ — `fail_on` базы
(`storage.put`, `storage.list`, …): счётчик растёт до вызова, как у клиента.
`seed` кладёт объект мимо счётчиков и журнала."""
def __init__(
self,
database: FakeDatabase,
*,
namespace: str = "testdb",
) -> None:
self.namespace = namespace
self._db = database
self.objects: dict[str, tuple[bytes, str | None, datetime]] = {}
self.calls: Counter[str] = Counter()
self.listed_keys = 0
self.read_bytes = 0
def seed(
self,
key: str,
data: bytes = b"x",
*,
content_type: str | None = "image/png",
last_modified: datetime = _FAR_PAST,
) -> None:
self.objects[key] = (data, content_type, last_modified)
def _call(self, name: str) -> None:
self.calls[name] += 1
self._db.record(f"storage.{name}")
def _info(self, key: str) -> StoredObjectInfo:
data, content_type, last_modified = self.objects[key]
return StoredObjectInfo(
key=key,
size=len(data),
content_type=content_type,
last_modified=last_modified,
)
def stats(self) -> StorageStats:
return StorageStats(
calls=MappingProxyType(
{name: self.calls[name] for name in _CALL_NAMES},
),
listed_keys=self.listed_keys,
read_bytes=self.read_bytes,
)
async def start(self) -> None:
return None
async def aclose(self) -> None:
return None
async def put(
self,
key: str,
body: BinaryIO,
*,
size: int,
content_type: str,
) -> None:
self._call("put")
self.objects[key] = (
body.read(),
content_type,
datetime.now(tz=UTC),
)
async def head(self, key: str) -> StoredObjectInfo | None:
self._call("head")
return self._info(key) if key in self.objects else None
async def list_page(
self,
prefix: str,
*,
token: str | None,
max_keys: int,
) -> StoredObjectPage:
self._call("list")
keys = sorted(
key
for key in self.objects
if key.startswith(prefix) and (token is None or key > token)
)
page = keys[:max_keys]
self.listed_keys += len(page)
return StoredObjectPage(
objects=tuple(self._info(key) for key in page),
next_token=page[-1] if len(keys) > max_keys else None,
)
@asynccontextmanager
async def open(self, key: str) -> AsyncIterator[FakeStoredObject]:
self._call("get")
if key not in self.objects:
raise exceptions.StoredObjectMissing
yield FakeStoredObject(self._info(key), self.objects[key][0], self)
async def delete(self, key: str) -> None:
self._call("delete")
self.objects.pop(key, None)
class FakeJobPublisher:
"""Подтверждает всё или заданное подмножество (`unconfirmed`); журнал —
`publisher.publish_many`, `publisher.ready_messages`."""
def __init__(
self,
database: FakeDatabase,
*,
namespace: str = "testdb",
) -> None:
self.namespace = namespace
self.queue = f"{namespace}.attachment.process.v1"
self._db = database
self.unconfirmed: set[UUID] = set()
self.ready = 0
self.published: list[UUID] = []
async def publish_many(
self,
items: Sequence[tuple[UUID, bytes]],
) -> set[UUID]:
self._db.record("publisher.publish_many")
confirmed = {
job_id for job_id, _ in items if job_id not in self.unconfirmed
}
self.published.extend(job_id for job_id, _ in items)
return confirmed
async def ready_messages(self) -> int:
self._db.record("publisher.ready_messages")
return self.ready
async def aclose(self) -> None:
return None
class FakeImageRenderer:
"""`result` — итог, `fail_on["renderer.render"]` — отказ процесса обработки."""
def __init__(
self,
database: FakeDatabase,
result: RenderedVariantsDTO | None = None,
) -> None:
self._db = database
self.result = result
async def render(self, data: bytes) -> RenderedVariantsDTO:
self._db.record("renderer.render")
if self.result is None:
raise AssertionError("FakeImageRenderer has no result")
return self.result
+77
View File
@@ -0,0 +1,77 @@
"""Хранилище фейков: таблицы-словари замороженных DTO, общие для экземпляров
единицы работы, как PostgreSQL для процессов.
Нет плана запроса, блокировок и ожидания, индексов и внешних ключей: занятую
строку тест объявляет явно (`held`), отказ — тоже (`fail_on`, `fail_commit`).
Порядок действий виден в общем журнале `events`: вход, выражения, вызовы S3 и
издателя, фиксация, выход.
"""
from dataclasses import dataclass, field
from typing import Any
from uuid import UUID
_TABLES = (
"users",
"credentials",
"sessions",
"chats",
"messages",
"idempotency",
"attachments",
"jobs",
"variants",
"job_replays",
)
@dataclass
class FakeDatabase:
users: dict[UUID, Any] = field(default_factory=dict)
# username → UserCredentialsDTO
credentials: dict[str, Any] = field(default_factory=dict)
sessions: dict[UUID, Any] = field(default_factory=dict)
chats: dict[UUID, Any] = field(default_factory=dict)
messages: dict[UUID, Any] = field(default_factory=dict)
# (user_id, chat_id, key) → (request_hash, message_id, created_at)
idempotency: dict[tuple, tuple] = field(default_factory=dict)
attachments: dict[UUID, Any] = field(default_factory=dict)
jobs: dict[UUID, Any] = field(default_factory=dict)
# (attachment_id, pipeline_version, имя) → AttachmentVariantDTO
variants: dict[tuple, Any] = field(default_factory=dict)
job_replays: dict[UUID, Any] = field(default_factory=dict)
events: list[str] = field(default_factory=list)
# id строк, которые держит другой процесс: SKIP LOCKED их пропускает
held: set[UUID] = field(default_factory=set)
# имя события → исключение, которое бросит это действие
fail_on: dict[str, BaseException] = field(default_factory=dict)
# исключение фиксации и сколько фиксаций пропустить до него
fail_commit: BaseException | None = None
commits_before_fail: int = 0
def record(self, name: str) -> None:
"""Записать действие; заданный отказ — бросить."""
self.events.append(name)
failure = self.fail_on.get(name)
if failure is not None:
raise failure
def snapshot(self) -> dict[str, dict]:
return {name: dict(getattr(self, name)) for name in _TABLES}
def restore(self, snapshot: dict[str, dict]) -> None:
for name, table in snapshot.items():
setattr(self, name, dict(table))
def inside_block(self, name: str) -> bool:
"""Было ли действие `name` между входом в блок и выходом из него."""
depth = 0
for event in self.events:
if event == "enter":
depth += 1
elif event == "exit":
depth -= 1
elif event == name and depth > 0:
return True
return False
+991
View File
@@ -0,0 +1,991 @@
"""Фейки девяти repo по контракту портов (design change `unit-of-work`, решение
11): условия переходов, keyset по полям и порядок результата; без блокировок,
планов и внешних ключей. Каждый метод пишет событие `<repo>.<метод>` в журнал и
бросает заданный `fail_on`.
"""
import functools
import inspect
from collections.abc import Collection, Iterable
from dataclasses import replace
from datetime import datetime
from uuid import UUID
from src.core.ports.attachment import AbstractAttachmentRepository
from src.core.ports.attachment_job import AbstractAttachmentJobRepository
from src.core.ports.attachment_job_replay import (
AbstractAttachmentJobReplayRepository,
)
from src.core.ports.attachment_variant import (
AbstractAttachmentVariantRepository,
)
from src.core.ports.chat import AbstractChatRepository
from src.core.ports.idempotency import AbstractIdempotencyRepository
from src.core.ports.message import AbstractMessageRepository
from src.core.ports.session import AbstractSessionRepository
from src.core.ports.user import AbstractUserRepository
from src.schemas import dataclasses
from src.schemas.enums import (
AttachmentErrorCode,
AttachmentJobReason,
AttachmentJobState,
AttachmentStatus,
AttachmentVariantName,
)
from src.utils.cursor import CursorKey
from .database import FakeDatabase
def _recorded(method, event: str):
@functools.wraps(method)
async def wrapper(self, *args, **kwargs):
self._db.record(event)
return await method(self, *args, **kwargs)
return wrapper
class _FakeRepository:
"""Подкласс задаёт `event_prefix`; методы оборачиваются записью в журнал,
`functools.wraps` сохраняет сигнатуру для сверки с портом."""
event_prefix = ""
def __init__(self, database: FakeDatabase) -> None:
self._db = database
def __init_subclass__(cls, **kwargs) -> None:
super().__init_subclass__(**kwargs)
for name, member in list(vars(cls).items()):
if not name.startswith("_") and inspect.iscoroutinefunction(
member,
):
setattr(
cls,
name,
_recorded(member, f"{cls.event_prefix}.{name}"),
)
class FakeUserRepository(_FakeRepository, AbstractUserRepository):
event_prefix = "users"
async def insert_user(
self,
*,
user: dataclasses.UserFullDTO,
password_hash: str,
) -> dataclasses.UserFullDTO | None:
if user.username in self._db.credentials:
return None
self._db.users[user.id] = user
self._db.credentials[user.username] = dataclasses.UserCredentialsDTO(
user=user,
password_hash=password_hash,
)
return user
async def get_user_credentials(
self,
*,
username: str,
) -> dataclasses.UserCredentialsDTO | None:
return self._db.credentials.get(username)
async def get_existing_user_ids(
self,
*,
user_ids: Iterable[UUID],
) -> set[UUID]:
return {item for item in user_ids if item in self._db.users}
class FakeSessionRepository(_FakeRepository, AbstractSessionRepository):
event_prefix = "sessions"
async def insert_session(
self,
*,
session: dataclasses.SessionFullDTO,
) -> dataclasses.SessionFullDTO:
self._db.sessions[session.id] = session
return session
async def get_current_session(
self,
*,
token_hash: bytes,
now: datetime,
) -> dataclasses.CurrentSessionDTO | None:
for session in self._db.sessions.values():
if session.token_hash == token_hash and session.expires_at > now:
return dataclasses.CurrentSessionDTO(
id=session.id,
user=self._db.users[session.user_id],
)
return None
async def delete_session(self, *, session_id: UUID) -> bool:
return self._db.sessions.pop(session_id, None) is not None
def _after_key(item, after: CursorKey | None) -> bool:
return after is None or (item.created_at, item.id) > after
class FakeChatRepository(_FakeRepository, AbstractChatRepository):
event_prefix = "chats"
async def insert_chat(
self,
*,
chat: dataclasses.ChatFullDTO,
) -> dataclasses.ChatFullDTO:
self._db.chats[chat.id] = replace(chat, member_ids=())
return chat
async def insert_chat_members(
self,
*,
chat: dataclasses.ChatFullDTO,
) -> int:
self._db.chats[chat.id] = chat
return len(chat.member_ids)
async def get_chat(
self,
*,
chat_id: UUID,
) -> dataclasses.ChatFullDTO | None:
return self._db.chats.get(chat_id)
async def get_user_chats_page(
self,
*,
user_id: UUID,
after: CursorKey | None,
limit: int,
) -> list[dataclasses.ChatFullDTO]:
rows = sorted(
(
chat
for chat in self._db.chats.values()
if user_id in chat.member_ids and _after_key(chat, after)
),
key=lambda chat: (chat.created_at, chat.id),
)
return rows[: limit + 1]
class FakeMessageRepository(_FakeRepository, AbstractMessageRepository):
event_prefix = "messages"
async def insert_message(
self,
*,
message: dataclasses.MessageFullDTO,
instance_id: str,
) -> dataclasses.MessageFullDTO:
self._db.messages[message.id] = replace(message, attachment_ids=())
return message
async def insert_message_attachments(
self,
*,
message: dataclasses.MessageFullDTO,
) -> int:
self._db.messages[message.id] = message
return len(message.attachment_ids)
async def get_chat_messages_page(
self,
*,
chat_id: UUID,
after: CursorKey | None,
limit: int,
) -> list[dataclasses.MessageFullDTO]:
rows = sorted(
(
message
for message in self._db.messages.values()
if message.chat_id == chat_id and _after_key(message, after)
),
key=lambda message: (message.created_at, message.id),
)
return rows[: limit + 1]
class FakeIdempotencyRepository(
_FakeRepository,
AbstractIdempotencyRepository,
):
event_prefix = "idempotency"
async def claim_key(
self,
*,
user_id: UUID,
chat_id: UUID,
key: str,
request_hash: bytes,
message_id: UUID,
created_at: datetime,
expired_before: datetime,
) -> bool:
current = self._db.idempotency.get((user_id, chat_id, key))
if current is not None and current[2] >= expired_before:
return False
self._db.idempotency[(user_id, chat_id, key)] = (
request_hash,
message_id,
created_at,
)
return True
async def get_key_result(
self,
*,
user_id: UUID,
chat_id: UUID,
key: str,
) -> dataclasses.IdempotencyRecordDTO | None:
current = self._db.idempotency.get((user_id, chat_id, key))
if current is None:
return None
message = self._db.messages.get(current[1])
if message is None:
return None
return dataclasses.IdempotencyRecordDTO(
request_hash=current[0],
message=message,
)
_IN_WORK = (AttachmentStatus.QUEUED, AttachmentStatus.PROCESSING)
class FakeAttachmentRepository(_FakeRepository, AbstractAttachmentRepository):
event_prefix = "attachments"
def _set(self, row, updated_at: datetime | None = None, **fields):
if updated_at is not None:
fields["updated_at"] = max(updated_at, row.updated_at)
changed = replace(row, **fields)
self._db.attachments[row.id] = changed
return changed
def _staging_matches(
self,
row,
status: AttachmentStatus,
updated_before: datetime | None,
) -> bool:
return (
row.staging_key is not None
and row.status == status
and (updated_before is None or row.updated_at < updated_before)
)
@staticmethod
def _staging_dto(row) -> dataclasses.AttachmentInListDTO:
return dataclasses.AttachmentInListDTO(
id=row.id,
object_key=row.object_key,
created_at=row.created_at,
staging_key=row.staging_key,
status=row.status,
updated_at=row.updated_at,
)
@staticmethod
def _stale_dto(row) -> dataclasses.AttachmentInListDTO:
return dataclasses.AttachmentInListDTO(
id=row.id,
object_key=row.object_key,
created_at=row.created_at,
staging_key=row.staging_key,
)
async def insert_attachment(
self,
*,
attachment: dataclasses.AttachmentFullDTO,
) -> dataclasses.AttachmentFullDTO:
# как INSERT: пометка, код ошибки и варианты в него не входят
self._db.attachments[attachment.id] = replace(
attachment,
lost_at=None,
error_code=None,
variants=(),
)
return attachment
async def mark_queued(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> dataclasses.AttachmentFullDTO | None:
row = self._db.attachments.get(attachment_id)
if (
row is None
or row.status != AttachmentStatus.PENDING
or row.updated_at != row.created_at
):
return None
return self._set(
row,
updated_at=updated_at,
status=AttachmentStatus.QUEUED,
)
async def mark_processing(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None or row.status not in _IN_WORK:
return False
self._set(
row,
updated_at=updated_at,
status=AttachmentStatus.PROCESSING,
)
return True
async def return_to_queued(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None or row.status != AttachmentStatus.PROCESSING:
return False
self._set(row, updated_at=updated_at, status=AttachmentStatus.QUEUED)
return True
async def return_group_to_queued(
self,
*,
attachment_ids: Collection[UUID],
updated_at: datetime,
) -> int:
count = 0
for attachment_id in set(attachment_ids):
row = self._db.attachments.get(attachment_id)
if row is not None and row.status == AttachmentStatus.PROCESSING:
self._set(
row,
updated_at=updated_at,
status=AttachmentStatus.QUEUED,
)
count += 1
return count
async def replay_failed(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None or row.status != AttachmentStatus.FAILED:
return False
self._set(
row,
updated_at=updated_at,
status=AttachmentStatus.QUEUED,
error_code=None,
)
return True
async def lock_attachment(
self,
*,
attachment_id: UUID,
) -> dataclasses.AttachmentFullDTO | None:
return self._db.attachments.get(attachment_id)
async def get_staging_candidates(
self,
*,
status: AttachmentStatus,
updated_before: datetime | None,
after: tuple[datetime, UUID] | None,
limit: int,
) -> list[dataclasses.AttachmentInListDTO]:
rows = sorted(
(
row
for row in self._db.attachments.values()
if self._staging_matches(row, status, updated_before)
and (after is None or (row.updated_at, row.id) > after)
),
key=lambda row: (row.updated_at, row.id),
)
return [self._staging_dto(row) for row in rows[:limit]]
async def lock_staging_candidate(
self,
*,
attachment_id: UUID,
status: AttachmentStatus,
updated_before: datetime | None,
) -> dataclasses.AttachmentInListDTO | None:
row = self._db.attachments.get(attachment_id)
if (
row is None
or attachment_id in self._db.held
or not self._staging_matches(row, status, updated_before)
):
return None
return self._staging_dto(row)
async def clear_staging_key(self, *, attachment_id: UUID) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None:
return False
self._set(row, staging_key=None)
return True
async def commit_ready(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None or row.status not in _IN_WORK:
return False
self._set(row, updated_at=updated_at, status=AttachmentStatus.READY)
return True
async def commit_failed(
self,
*,
attachment_id: UUID,
error_code: AttachmentErrorCode,
updated_at: datetime,
) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None or row.status not in _IN_WORK:
return False
self._set(
row,
updated_at=updated_at,
status=AttachmentStatus.FAILED,
error_code=error_code,
)
return True
async def get_attachment(
self,
*,
attachment_id: UUID,
) -> dataclasses.AttachmentFullDTO | None:
return self._db.attachments.get(attachment_id)
async def get_attachments(
self,
*,
attachment_ids: Collection[UUID],
) -> list[dataclasses.AttachmentFullDTO]:
return [
self._db.attachments[item]
for item in set(attachment_ids)
if item in self._db.attachments
]
async def get_stale_pending(
self,
*,
older_than: datetime,
after: tuple[datetime, UUID] | None,
limit: int,
) -> list[dataclasses.AttachmentInListDTO]:
rows = sorted(
(
row
for row in self._db.attachments.values()
if row.status == AttachmentStatus.PENDING
and row.created_at < older_than
and (after is None or (row.created_at, row.id) > after)
),
key=lambda row: (row.created_at, row.id),
)
return [self._stale_dto(row) for row in rows[:limit]]
async def lock_stale_pending(
self,
*,
attachment_id: UUID,
older_than: datetime,
) -> dataclasses.AttachmentInListDTO | None:
row = self._db.attachments.get(attachment_id)
if (
row is None
or attachment_id in self._db.held
or row.status != AttachmentStatus.PENDING
or row.created_at >= older_than
):
return None
return self._stale_dto(row)
async def mark_removing(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None:
return False
self._db.attachments[attachment_id] = replace(
row,
updated_at=updated_at,
)
return True
async def delete_attachment(self, *, attachment_id: UUID) -> bool:
return self._db.attachments.pop(attachment_id, None) is not None
async def get_attachments_for_objects(
self,
*,
attachment_ids: Collection[UUID],
object_keys: Collection[str],
) -> list[dataclasses.AttachmentFullDTO]:
ids = set(attachment_ids)
keys = set(object_keys)
return [
row
for row in self._db.attachments.values()
if row.id in ids or row.object_key in keys
]
async def get_ready_page(
self,
*,
after: UUID | None,
limit: int,
) -> list[dataclasses.AttachmentFullDTO]:
rows = sorted(
(
row
for row in self._db.attachments.values()
if row.status == AttachmentStatus.READY
and (after is None or row.id > after)
),
key=lambda row: row.id,
)
return rows[:limit]
async def find_attachment_reference(
self,
*,
attachment_id: UUID,
object_key: str,
) -> list[dataclasses.AttachmentFullDTO]:
return [
row
for row in self._db.attachments.values()
if row.id == attachment_id or row.object_key == object_key
]
async def mark_lost(
self,
*,
attachment_id: UUID,
object_key: str,
lost_at: datetime,
) -> bool:
row = self._db.attachments.get(attachment_id)
if (
row is None
or row.status != AttachmentStatus.READY
or row.lost_at is not None
or row.object_key != object_key
):
return False
self._set(row, lost_at=lost_at)
return True
async def clear_lost(
self,
*,
attachment_id: UUID,
object_key: str,
) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None or row.lost_at is None or row.object_key != object_key:
return False
self._set(row, lost_at=None)
return True
def _due_at(job: dataclasses.AttachmentJobDTO) -> datetime:
return job.next_attempt_at or job.created_at
class FakeAttachmentJobRepository(
_FakeRepository,
AbstractAttachmentJobRepository,
):
event_prefix = "jobs"
def _set(self, job, now: datetime | None = None, **fields):
if now is not None:
fields["updated_at"] = max(now, job.updated_at)
changed = replace(job, **fields)
self._db.jobs[job.id] = changed
return changed
def _published(self, older_than: datetime | None = None):
return [
job
for job in self._db.jobs.values()
if job.state == AttachmentJobState.QUEUED
and job.published_at is not None
and (older_than is None or job.published_at < older_than)
]
async def insert_job(
self,
*,
job: dataclasses.AttachmentJobDTO,
) -> dataclasses.AttachmentJobDTO:
self._db.jobs[job.id] = dataclasses.AttachmentJobDTO(
id=job.id,
attachment_id=job.attachment_id,
pipeline_version=job.pipeline_version,
state=job.state,
attempt=job.attempt,
created_at=job.created_at,
updated_at=job.updated_at,
)
return job
async def lock_job(
self,
*,
job_id: UUID,
) -> dataclasses.AttachmentJobDTO | None:
return self._db.jobs.get(job_id)
async def get_job(
self,
*,
job_id: UUID,
) -> dataclasses.AttachmentJobDTO | None:
return self._db.jobs.get(job_id)
async def count_unfinished(self, *, limit: int) -> int:
groups = (
[
job
for job in self._db.jobs.values()
if job.state == AttachmentJobState.QUEUED
and job.published_at is None
],
self._published(),
[
job
for job in self._db.jobs.values()
if job.state == AttachmentJobState.PROCESSING
],
)
return sum(min(len(group), limit) for group in groups)
async def get_attachment_job(
self,
*,
attachment_id: UUID,
pipeline_version: int,
) -> dataclasses.AttachmentJobDTO | None:
for job in self._db.jobs.values():
if (
job.attachment_id == attachment_id
and job.pipeline_version == pipeline_version
):
return job
return None
async def start_attempt(
self,
*,
job_id: UUID,
lease_expires_at: datetime,
now: datetime,
) -> dataclasses.AttachmentJobDTO | None:
job = self._db.jobs.get(job_id)
if job is None:
return None
return self._set(
job,
now=now,
state=AttachmentJobState.PROCESSING,
attempt=job.attempt + 1,
lease_expires_at=lease_expires_at,
next_attempt_at=None,
)
async def return_to_queued(
self,
*,
job_id: UUID,
attempt: int,
reason: AttachmentJobReason,
next_attempt_at: datetime,
now: datetime,
) -> bool:
job = self._db.jobs.get(job_id)
if (
job is None
or job.state != AttachmentJobState.PROCESSING
or job.attempt != attempt
):
return False
self._set(
job,
now=now,
state=AttachmentJobState.QUEUED,
last_error_code=reason.value,
next_attempt_at=next_attempt_at,
lease_expires_at=None,
published_at=None,
)
return True
async def finish_job(
self,
*,
job_id: UUID,
state: AttachmentJobState,
reason: AttachmentJobReason | None,
now: datetime,
) -> bool:
job = self._db.jobs.get(job_id)
if job is None:
return False
fields = {} if reason is None else {"last_error_code": reason.value}
self._set(
job,
now=now,
state=state,
lease_expires_at=None,
next_attempt_at=None,
finished_at=now,
**fields,
)
return True
async def lock_due_jobs(
self,
*,
now: datetime,
limit: int,
) -> list[dataclasses.AttachmentJobDTO]:
rows = sorted(
(
job
for job in self._db.jobs.values()
if job.state == AttachmentJobState.QUEUED
and job.published_at is None
and now >= _due_at(job)
and job.id not in self._db.held
),
key=lambda job: (_due_at(job), job.id),
)
return rows[:limit]
async def count_published(self) -> int:
return len(self._published())
async def mark_published(
self,
*,
job_ids: Collection[UUID],
now: datetime,
) -> int:
count = 0
for job_id in set(job_ids):
job = self._db.jobs.get(job_id)
if job is not None:
self._set(job, now=now, published_at=now)
count += 1
return count
async def recover_expired_leases(
self,
*,
now: datetime,
limit: int,
) -> list[dataclasses.AttachmentJobDTO]:
expired = sorted(
(
job
for job in self._db.jobs.values()
if job.state == AttachmentJobState.PROCESSING
and job.lease_expires_at is not None
and job.lease_expires_at < now
and job.id not in self._db.held
),
key=lambda job: job.lease_expires_at,
)
return [
self._set(
job,
now=now,
state=AttachmentJobState.QUEUED,
last_error_code=AttachmentJobReason.LEASE_EXPIRED.value,
lease_expires_at=None,
next_attempt_at=None,
published_at=None,
)
for job in expired[:limit]
]
async def has_published_before(self, *, older_than: datetime) -> bool:
return bool(self._published(older_than))
async def reset_published_before(
self,
*,
older_than: datetime,
now: datetime,
) -> int:
rows = self._published(older_than)
for job in rows:
self._set(job, now=now, published_at=None)
return len(rows)
async def replay_job(self, *, job_id: UUID, now: datetime) -> bool:
job = self._db.jobs.get(job_id)
if job is None or job.state != AttachmentJobState.FAILED:
return False
self._set(
job,
now=now,
state=AttachmentJobState.QUEUED,
attempt_base=job.attempt,
last_error_code=None,
next_attempt_at=None,
lease_expires_at=None,
published_at=None,
finished_at=None,
)
return True
async def list_failed(
self,
*,
error_code: str | None,
reason: str | None,
limit: int,
) -> list[dataclasses.FailedJobDTO]:
rows = []
for job in self._db.jobs.values():
attachment = self._db.attachments.get(job.attachment_id)
if (
job.state != AttachmentJobState.FAILED
or attachment is None
or (
error_code is not None
and attachment.error_code != error_code
)
or (reason is not None and job.last_error_code != reason)
):
continue
rows.append(
dataclasses.FailedJobDTO(
job_id=job.id,
attachment_id=job.attachment_id,
error_code=attachment.error_code,
reason=job.last_error_code,
attempt=job.attempt,
attempt_base=job.attempt_base,
finished_at=job.finished_at,
),
)
# finished_at по убыванию, затем id по возрастанию: сортировки
# устойчивы
rows.sort(key=lambda row: row.job_id)
rows.sort(key=lambda row: row.finished_at, reverse=True)
return rows[:limit]
class FakeAttachmentVariantRepository(
_FakeRepository,
AbstractAttachmentVariantRepository,
):
event_prefix = "variants"
async def insert_variant(
self,
*,
attachment_id: UUID,
variant: dataclasses.AttachmentVariantDTO,
) -> bool:
key = (attachment_id, variant.pipeline_version, variant.name)
if key in self._db.variants:
return False
self._db.variants[key] = variant
return True
async def get_variants(
self,
*,
attachment_id: UUID,
) -> list[dataclasses.AttachmentVariantDTO]:
rows = [
variant
for key, variant in self._db.variants.items()
if key[0] == attachment_id
]
return sorted(rows, key=lambda variant: variant.name.value)
async def get_variant(
self,
*,
attachment_id: UUID,
name: AttachmentVariantName,
) -> dataclasses.AttachmentVariantDTO | None:
rows = [
variant
for key, variant in self._db.variants.items()
if key[0] == attachment_id and key[2] == name
]
if not rows:
return None
return max(rows, key=lambda variant: variant.pipeline_version)
class FakeAttachmentJobReplayRepository(
_FakeRepository,
AbstractAttachmentJobReplayRepository,
):
event_prefix = "job_replays"
async def insert_replay(
self,
*,
replay: dataclasses.AttachmentJobReplayDTO,
) -> dataclasses.AttachmentJobReplayDTO:
self._db.job_replays[replay.id] = replay
return replay
async def get_job_replays(
self,
*,
job_id: UUID,
) -> list[dataclasses.AttachmentJobReplayDTO]:
rows = [
replay
for replay in self._db.job_replays.values()
if replay.job_id == job_id
]
return sorted(rows, key=lambda replay: (replay.created_at, replay.id))
+72
View File
@@ -0,0 +1,72 @@
"""Фейковая единица работы на том же базовом классе: те же ошибки вложенного
блока и repo вне блока, откат возвращает снимок таблиц.
"""
from types import TracebackType
from src.core.ports.uow import AbstractUnitOfWork, Repositories
from .database import FakeDatabase
from .repos import (
FakeAttachmentJobReplayRepository,
FakeAttachmentJobRepository,
FakeAttachmentRepository,
FakeAttachmentVariantRepository,
FakeChatRepository,
FakeIdempotencyRepository,
FakeMessageRepository,
FakeSessionRepository,
FakeUserRepository,
)
class FakeUnitOfWork(AbstractUnitOfWork):
def __init__(self, database: FakeDatabase) -> None:
super().__init__()
self.database = database
self._snapshot: dict[str, dict] | None = None
async def _open(self) -> Repositories:
self.database.record("enter")
self._snapshot = self.database.snapshot()
return Repositories(
users=FakeUserRepository(self.database),
sessions=FakeSessionRepository(self.database),
chats=FakeChatRepository(self.database),
messages=FakeMessageRepository(self.database),
idempotency=FakeIdempotencyRepository(self.database),
attachments=FakeAttachmentRepository(self.database),
jobs=FakeAttachmentJobRepository(self.database),
variants=FakeAttachmentVariantRepository(self.database),
job_replays=FakeAttachmentJobReplayRepository(self.database),
)
async def _close(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> bool | None:
# после фиксации снимка нет: откатывать нечего
if self._snapshot is not None:
self.database.restore(self._snapshot)
self._snapshot = None
self.database.events.append("exit")
return None
async def _commit(self) -> None:
database = self.database
if database.fail_commit is not None:
if database.commits_before_fail == 0:
failure, database.fail_commit = database.fail_commit, None
database.events.append("commit_failed")
raise failure
database.commits_before_fail -= 1
database.events.append("commit")
self._snapshot = None
async def _rollback(self) -> None:
if self._snapshot is not None:
self.database.restore(self._snapshot)
self._snapshot = None
self.database.events.append("rollback")
+6
View File
@@ -0,0 +1,6 @@
[pytest]
# pyproject.toml здесь не применяется: его addopts и маркеры — для student-tests
pythonpath = .. .
addopts = -q --strict-markers -p no:cacheprovider
markers =
anyio: async def тест, запускает плагин anyio
File diff suppressed because it is too large Load Diff
+75
View File
@@ -0,0 +1,75 @@
"""Быстрые тесты сервисов: без PostgreSQL, Valkey, S3, брокера, docker и сети.
`settings` читает `.env` и `config.toml` по абсолютному пути, поэтому поля, от
которых зависят ветки сервисов, подставляются здесь: результат не зависит от
локальных файлов и окружения (design change `unit-of-work`, решение 13).
"""
import pytest
from fakes import (
FakeCache,
FakeDatabase,
FakeJobPublisher,
FakeObjectStorage,
FakeUnitOfWork,
)
from src.config import settings
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
@pytest.fixture(autouse=True)
def fixed_settings(monkeypatch: pytest.MonkeyPatch) -> None:
fixed = (
(
settings.worker,
{
"max_attempts": 3,
"job_timeout_seconds": 60,
"lease_margin_seconds": 10,
"retry_base_delay_seconds": 5,
"retry_max_delay_seconds": 300,
"reconnect_seconds": 0.01,
},
),
(settings.auth, {"session_ttl_seconds": 3600}),
(settings.idempotency, {"ttl_seconds": 86400}),
(settings.cache, {"chat_ttl_seconds": 600}),
(
settings.uploads,
{"body_timeout_seconds": 1, "max_unfinished_jobs": 0},
),
(settings.app, {"instance_id": "test-instance"}),
)
for section, fields in fixed:
for name, value in fields.items():
monkeypatch.setattr(section, name, value)
@pytest.fixture
def database() -> FakeDatabase:
return FakeDatabase()
@pytest.fixture
def uow(database: FakeDatabase) -> FakeUnitOfWork:
return FakeUnitOfWork(database)
@pytest.fixture
def cache(database: FakeDatabase) -> FakeCache:
return FakeCache(database)
@pytest.fixture
def storage(database: FakeDatabase) -> FakeObjectStorage:
return FakeObjectStorage(database)
@pytest.fixture
def publisher(database: FakeDatabase) -> FakeJobPublisher:
return FakeJobPublisher(database)
+329
View File
@@ -0,0 +1,329 @@
"""Сервисы и порты зависят только от абстракций; порт, реализация и фейк — один
набор методов; фейки клиентов — те же сигнатуры, что у настоящих клиентов.
Импорты проверяются разбором файлов, а не по `sys.modules`: `src.config.settings`
сам импортирует SQLAlchemy (design change `unit-of-work`, Context).
"""
import ast
import inspect
from pathlib import Path
import pytest
import fakes
from src.core.ports.attachment import AbstractAttachmentRepository
from src.core.ports.attachment_job import AbstractAttachmentJobRepository
from src.core.ports.attachment_job_replay import (
AbstractAttachmentJobReplayRepository,
)
from src.core.ports.attachment_variant import (
AbstractAttachmentVariantRepository,
)
from src.core.ports.chat import AbstractChatRepository
from src.core.ports.idempotency import AbstractIdempotencyRepository
from src.core.ports.message import AbstractMessageRepository
from src.core.ports.session import AbstractSessionRepository
from src.core.ports.user import AbstractUserRepository
from src.core.repos.attachment import SqlAlchemyAttachmentRepository
from src.core.repos.attachment_job import SqlAlchemyAttachmentJobRepository
from src.core.repos.attachment_job_replay import (
SqlAlchemyAttachmentJobReplayRepository,
)
from src.core.repos.attachment_variant import (
SqlAlchemyAttachmentVariantRepository,
)
from src.core.repos.chat import SqlAlchemyChatRepository
from src.core.repos.idempotency import SqlAlchemyIdempotencyRepository
from src.core.repos.message import SqlAlchemyMessageRepository
from src.core.repos.session import SqlAlchemySessionRepository
from src.core.repos.user import SqlAlchemyUserRepository
from src.infra.broker import JobPublisher
from src.infra.cache import Cache
from src.infra.render import ImageRenderer
from src.infra.s3 import ObjectStorage
from src.infra.s3.client import StoredObject
ROOT = Path(__file__).resolve().parents[2]
REPOSITORIES = (
(
AbstractUserRepository,
SqlAlchemyUserRepository,
fakes.FakeUserRepository,
),
(
AbstractSessionRepository,
SqlAlchemySessionRepository,
fakes.FakeSessionRepository,
),
(
AbstractChatRepository,
SqlAlchemyChatRepository,
fakes.FakeChatRepository,
),
(
AbstractMessageRepository,
SqlAlchemyMessageRepository,
fakes.FakeMessageRepository,
),
(
AbstractIdempotencyRepository,
SqlAlchemyIdempotencyRepository,
fakes.FakeIdempotencyRepository,
),
(
AbstractAttachmentRepository,
SqlAlchemyAttachmentRepository,
fakes.FakeAttachmentRepository,
),
(
AbstractAttachmentJobRepository,
SqlAlchemyAttachmentJobRepository,
fakes.FakeAttachmentJobRepository,
),
(
AbstractAttachmentVariantRepository,
SqlAlchemyAttachmentVariantRepository,
fakes.FakeAttachmentVariantRepository,
),
(
AbstractAttachmentJobReplayRepository,
SqlAlchemyAttachmentJobReplayRepository,
fakes.FakeAttachmentJobReplayRepository,
),
)
CLIENTS = (
(Cache, fakes.FakeCache, ("get", "set", "aclose")),
(
ObjectStorage,
fakes.FakeObjectStorage,
(
"stats",
"start",
"aclose",
"put",
"head",
"list_page",
"open",
"delete",
),
),
(StoredObject, fakes.FakeStoredObject, ("iter_chunks", "read")),
(
JobPublisher,
fakes.FakeJobPublisher,
("publish_many", "ready_messages", "aclose"),
),
(ImageRenderer, fakes.FakeImageRenderer, ("render",)),
)
# модуль запрещён целиком или вместе с подмодулями
FORBIDDEN_MODULES = (
"sqlalchemy",
"asyncpg",
"src.infra.db",
"src.infra.upload_slots",
"src.infra.cache.instance",
"src.infra.s3.instance",
)
# repo на SQL; `chat_cache` и `attachment_object` — над клиентами, решение 8
SQL_REPOS = (
"attachment",
"attachment_job",
"attachment_job_replay",
"attachment_variant",
"chat",
"idempotency",
"message",
"session",
"user",
)
def _module_files() -> list[Path]:
root = ROOT / "src" / "core"
return [
*sorted((root / "services").glob("*.py")),
*sorted((root / "ports").glob("*.py")),
]
def _is_type_checking(node: ast.If) -> bool:
return isinstance(node.test, ast.Name) and node.test.id == "TYPE_CHECKING"
def _imports(tree: ast.AST) -> list[tuple[int, str]]:
"""Полные имена импортов модуля, кроме блока `TYPE_CHECKING`."""
found: list[tuple[int, str]] = []
def visit(node: ast.AST) -> None:
if isinstance(node, ast.If) and _is_type_checking(node):
for child in node.orelse:
visit(child)
return
if isinstance(node, ast.Import):
found.extend((node.lineno, item.name) for item in node.names)
elif isinstance(node, ast.ImportFrom) and node.module:
found.append((node.lineno, node.module))
found.extend(
(node.lineno, f"{node.module}.{item.name}")
for item in node.names
)
for child in ast.iter_child_nodes(node):
visit(child)
visit(tree)
return found
def _is_forbidden(name: str) -> bool:
if any(
name == module or name.startswith(f"{module}.")
for module in FORBIDDEN_MODULES
):
return True
return any(name == f"src.core.repos.{repo}" for repo in SQL_REPOS)
def forbidden_imports(path: Path) -> list[str]:
tree = ast.parse(path.read_text(encoding="utf-8"))
return [
f"{path.relative_to(ROOT)}:{line} imports {name}"
for line, name in _imports(tree)
if _is_forbidden(name)
]
def _public_methods(cls: type) -> dict[str, inspect.Signature]:
return {
name: inspect.signature(member)
for name, member in inspect.getmembers(cls, inspect.isfunction)
if not name.startswith("_")
}
def _method_shape(signature: inspect.Signature) -> list[tuple]:
"""Имена, вид и наличие значения по умолчанию; аннотации клиентов и фейков
не сравниваются: у фейка свои типы результата."""
return [
(item.name, item.kind, item.default is inspect.Parameter.empty)
for item in signature.parameters.values()
]
def repository_mismatches(port: type, implementation: type) -> list[str]:
"""Расхождения реализации с портом: класс и метод — в сообщении."""
problems = []
expected = _public_methods(port)
# унаследованный абстрактный метод порта — не реализация
actual = {
name: signature
for name, signature in _public_methods(implementation).items()
if not getattr(
getattr(implementation, name),
"__isabstractmethod__",
False,
)
}
for name in expected.keys() - actual.keys():
problems.append(f"{implementation.__name__}.{name}: нет метода порта")
for name in actual.keys() - expected.keys():
problems.append(
f"{implementation.__name__}.{name}: метода нет в порте",
)
for name in expected.keys() & actual.keys():
if _method_shape(expected[name]) != _method_shape(actual[name]):
problems.append(
f"{implementation.__name__}.{name}: сигнатура "
f"{actual[name]} вместо {expected[name]}",
)
return problems
def test_no_forbidden_imports() -> None:
"""Сценарий «Запрещённый импорт»: называет файл и импорт."""
problems = [
problem
for path in _module_files()
for problem in forbidden_imports(path)
]
assert not problems, "\n".join(problems)
def test_services_have_no_session_names() -> None:
root = ROOT / "src" / "core" / "services"
problems = [
f"{path.relative_to(ROOT)}: {word}"
for path in sorted(root.glob("*.py"))
for word in ("AsyncSession", "db_scope(", "db_session=")
if word in path.read_text(encoding="utf-8")
]
assert not problems, "\n".join(problems)
@pytest.mark.parametrize(
("port", "implementation", "fake"),
REPOSITORIES,
ids=[item[0].__name__ for item in REPOSITORIES],
)
def test_port_implementation_fake_match(
port: type,
implementation: type,
fake: type,
) -> None:
"""Сценарий «Новый метод без фейка»: называет класс и метод."""
problems = [
*repository_mismatches(port, implementation),
*repository_mismatches(port, fake),
]
assert not problems, "\n".join(problems)
@pytest.mark.parametrize(
("client", "fake", "methods"),
CLIENTS,
ids=[item[0].__name__ for item in CLIENTS],
)
def test_client_fakes_match(
client: type,
fake: type,
methods: tuple[str, ...],
) -> None:
problems = []
for name in methods:
real = getattr(client, name, None)
faked = getattr(fake, name, None)
if real is None or faked is None:
problems.append(f"{fake.__name__}.{name}: нет метода")
continue
if _method_shape(inspect.signature(real)) != _method_shape(
inspect.signature(faked),
):
problems.append(
f"{fake.__name__}.{name}: сигнатура "
f"{inspect.signature(faked)} вместо "
f"{inspect.signature(real)}",
)
assert not problems, "\n".join(problems)
public = _public_methods(client).keys()
extra = set(public) - set(methods)
assert not extra, f"{client.__name__}: новые методы без фейка {extra}"
def test_forbidden_import_detector() -> None:
"""Сам разбор: импорт ловится, `TYPE_CHECKING` — нет."""
source = (
"from typing import TYPE_CHECKING\n"
"from src.core.repos import attachment as attachment_repo\n"
"from sqlalchemy.ext.asyncio import AsyncSession\n"
"if TYPE_CHECKING:\n"
" from src.infra.upload_slots import UploadSlots\n"
)
problems = [
name for _, name in _imports(ast.parse(source)) if _is_forbidden(name)
]
assert "src.core.repos.attachment" in problems
assert any(name.startswith("sqlalchemy") for name in problems)
assert not any("upload_slots" in name for name in problems)
@@ -0,0 +1,401 @@
"""`AttachmentCleanupService`: два блока уборки, сигнал, очистка staging."""
from uuid import uuid4
import pytest
from builders import NOW, at, attachment_dto
from fakes import FakeDatabase, FakeObjectStorage, FakeUnitOfWork
from src.core import exceptions
from src.core.repos import attachment_object
from src.core.services.attachment_cleanup import (
INTERRUPTED_BY_DATABASE,
INTERRUPTED_BY_OBJECT_STORAGE,
INTERRUPTED_BY_STOP,
AttachmentCleanupService,
)
from src.schemas import dataclasses
from src.schemas.enums import (
AttachmentErrorCode,
AttachmentStatus,
AttachmentVariantName,
)
from src.utils.constants import ATTACHMENT_PIPELINE_VERSION
pytestmark = pytest.mark.anyio
@pytest.fixture
def service(
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
) -> AttachmentCleanupService:
return AttachmentCleanupService(uow, storage)
async def _stale(
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
*,
seconds: float = -1000,
staging: bool = True,
) -> dataclasses.AttachmentFullDTO:
row = attachment_dto(
chat_id=uuid4(),
owner_id=uuid4(),
created_at=at(seconds),
staging=staging,
)
async with uow:
await uow.attachments.insert_attachment(attachment=row)
await uow.commit()
storage.seed(row.staging_key or row.object_key)
return row
async def _clean(
service: AttachmentCleanupService,
*,
batch_size: int = 10,
stop_requested=None,
) -> dataclasses.CleanupPassDTO:
kwargs = (
{} if stop_requested is None else {"stop_requested": stop_requested}
)
return await service.clean_stale_pending(
older_than=NOW,
batch_size=batch_size,
**kwargs,
)
async def test_two_blocks_object_before_row(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
row = await _stale(uow, storage)
database.events.clear()
result = await _clean(service)
assert result.removed == 1
assert database.events == [
"enter",
"attachments.get_stale_pending",
"exit",
"enter",
"attachments.lock_stale_pending",
"attachments.mark_removing",
"commit",
"exit",
"enter",
"attachments.lock_stale_pending",
"storage.delete",
"attachments.delete_attachment",
"commit",
"exit",
]
assert database.attachments == {}
assert row.staging_key not in storage.objects
async def test_old_version_row_deletes_final_object(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
row = await _stale(uow, storage, staging=False)
await _clean(service)
assert row.object_key not in storage.objects
assert database.attachments == {}
async def test_storage_failure_keeps_mark_and_row(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
"""Сценарий «Порядок уборки»: пометка зафиксирована, второй блок откачен."""
row = await _stale(uow, storage)
database.fail_on["storage.delete"] = exceptions.ObjectStorageUnavailable()
result = await _clean(service)
assert result.interrupted_by == INTERRUPTED_BY_OBJECT_STORAGE
assert result.removed == 0
kept = database.attachments[row.id]
assert kept.updated_at > kept.created_at
assert "attachments.delete_attachment" not in database.events
# следующий проход убирает
database.fail_on.clear()
assert (await _clean(service)).removed == 1
async def test_row_delete_failure_rolls_back_second_block(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
row = await _stale(uow, storage)
database.fail_on["attachments.delete_attachment"] = (
exceptions.ServiceUnavailable()
)
result = await _clean(service)
assert result.interrupted_by == INTERRUPTED_BY_DATABASE
# объект удалён раньше строки: строка без объекта, а не наоборот
assert row.staging_key not in storage.objects
assert row.id in database.attachments
async def test_database_failure_on_candidates(
service: AttachmentCleanupService,
database: FakeDatabase,
) -> None:
database.fail_on["attachments.get_stale_pending"] = (
exceptions.ServiceUnavailable()
)
assert (await _clean(service)).interrupted_by == INTERRUPTED_BY_DATABASE
async def test_held_row_skipped(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
row = await _stale(uow, storage)
database.held.add(row.id)
result = await _clean(service)
assert (result.removed, result.skipped) == (0, 1)
assert row.staging_key in storage.objects
async def test_keyset_more_than_one_batch(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
for index in range(5):
await _stale(uow, storage, seconds=-1000 + index)
result = await _clean(service, batch_size=2)
assert result.removed == 5
assert database.attachments == {}
async def test_stop_before_row(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
await _stale(uow, storage)
result = await _clean(service, stop_requested=lambda: True)
assert result.interrupted_by == INTERRUPTED_BY_STOP
assert "attachments.lock_stale_pending" not in database.events
async def test_stop_between_steps_keeps_mark(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
"""Сигнал между шагами: первый блок зафиксирован, второго нет."""
row = await _stale(uow, storage)
calls = 0
def stop_requested() -> bool:
nonlocal calls
calls += 1
return calls > 1
database.events.clear()
result = await _clean(service, stop_requested=stop_requested)
assert result.interrupted_by == INTERRUPTED_BY_STOP
assert database.events.count("attachments.lock_stale_pending") == 1
assert database.attachments[row.id].updated_at > row.created_at
assert row.staging_key in storage.objects
async def _for_staging(
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
*,
status: AttachmentStatus,
updated_seconds: float = -1000,
object_key: str | None = None,
) -> dataclasses.AttachmentFullDTO:
row = attachment_dto(
chat_id=uuid4(),
owner_id=uuid4(),
status=AttachmentStatus.QUEUED
if status == AttachmentStatus.FAILED
else status,
created_at=at(updated_seconds),
object_key=object_key,
)
async with uow:
await uow.attachments.insert_attachment(attachment=row)
if status == AttachmentStatus.FAILED:
await uow.attachments.commit_failed(
attachment_id=row.id,
error_code=AttachmentErrorCode.INVALID_IMAGE,
updated_at=at(updated_seconds),
)
await uow.commit()
storage.seed(row.staging_key)
return row
async def _staging_pass(
service: AttachmentCleanupService,
*,
batch_size: int = 10,
stop_requested=None,
) -> dataclasses.StagingCleanupPassDTO:
kwargs = (
{} if stop_requested is None else {"stop_requested": stop_requested}
)
return await service.clean_staging(
retention_before=NOW,
batch_size=batch_size,
**kwargs,
)
async def test_ready_staging_removed_at_next_pass(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
# у ready срока нет: даже свежая строка
row = await _for_staging(
uow,
storage,
status=AttachmentStatus.READY,
updated_seconds=100,
)
storage.seed(row.object_key)
database.events.clear()
result = await _staging_pass(service)
assert result.removed_ready == 1
assert row.staging_key not in storage.objects
# конечный оригинал ready не трогается
assert row.object_key in storage.objects
stored = database.attachments[row.id]
assert stored.staging_key is None
assert stored.updated_at == row.updated_at
block = database.events[database.events.index("enter", 2) :]
assert block == [
"enter",
"attachments.lock_staging_candidate",
"storage.delete",
"attachments.clear_staging_key",
"commit",
"exit",
*block[6:],
]
async def test_failed_staging_removed_with_variants_after_retention(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
old = await _for_staging(uow, storage, status=AttachmentStatus.FAILED)
young = await _for_staging(
uow,
storage,
status=AttachmentStatus.FAILED,
updated_seconds=100,
)
storage.seed(old.object_key)
keys = attachment_object.variant_keys(
storage,
attachment_id=old.id,
pipeline_version=ATTACHMENT_PIPELINE_VERSION,
)
for key in keys:
storage.seed(key)
result = await _staging_pass(service)
assert result.removed_failed == 1
assert old.staging_key not in storage.objects
assert old.object_key not in storage.objects
assert all(key not in storage.objects for key in keys)
assert len(keys) == len(AttachmentVariantName)
# моложе срока хранения: на месте
assert young.staging_key in storage.objects
assert database.attachments[young.id].staging_key is not None
async def test_current_work_not_touched(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
) -> None:
row = await _for_staging(uow, storage, status=AttachmentStatus.QUEUED)
result = await _staging_pass(service)
assert result.removed_ready + result.removed_failed == 0
assert row.staging_key in storage.objects
async def test_foreign_staging_key_not_removed(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
row = attachment_dto(
chat_id=uuid4(),
owner_id=uuid4(),
status=AttachmentStatus.READY,
namespace="other",
)
async with uow:
await uow.attachments.insert_attachment(attachment=row)
await uow.commit()
storage.seed(row.staging_key)
result = await _staging_pass(service)
assert result.skipped == 1
assert row.staging_key in storage.objects
assert database.attachments[row.id].staging_key == row.staging_key
async def test_staging_held_and_storage_failure_and_stop(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
row = await _for_staging(uow, storage, status=AttachmentStatus.READY)
database.held.add(row.id)
assert (await _staging_pass(service)).skipped == 1
database.held.clear()
database.fail_on["storage.delete"] = exceptions.ObjectStorageUnavailable()
result = await _staging_pass(service)
assert result.interrupted_by == INTERRUPTED_BY_OBJECT_STORAGE
assert database.attachments[row.id].staging_key is not None
database.fail_on.clear()
result = await _staging_pass(service, stop_requested=lambda: True)
assert result.interrupted_by == INTERRUPTED_BY_STOP
assert database.attachments[row.id].staging_key is not None
async def test_staging_keyset_more_than_one_batch(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
) -> None:
for index in range(5):
await _for_staging(
uow,
storage,
status=AttachmentStatus.READY,
updated_seconds=-1000 + index,
)
result = await _staging_pass(service, batch_size=2)
assert result.removed_ready == 5
@@ -0,0 +1,547 @@
"""`AttachmentProcessingService`: claim, fencing, итоги попытки, блоки."""
import asyncio
from dataclasses import replace
from datetime import timedelta
from uuid import UUID, uuid4
import pytest
from builders import attachment_dto, chat_dto, job_dto, user_dto
from fakes import (
FakeDatabase,
FakeImageRenderer,
FakeObjectStorage,
FakeUnitOfWork,
)
from src.config import settings
from src.core import exceptions
from src.core.services.attachment_processing import (
AttachmentProcessingService,
retry_delay,
)
from src.schemas import dataclasses
from src.schemas.enums import (
AttachmentErrorCode,
AttachmentJobReason,
AttachmentJobState,
AttachmentStatus,
AttachmentVariantName,
JobOutcome,
)
from src.schemas.jobs import build_job_body
from src.utils.utc import utcnow
pytestmark = pytest.mark.anyio
SOURCE = b"source-bytes"
def _rendered() -> dataclasses.RenderedVariantsDTO:
return dataclasses.RenderedVariantsDTO(
variants=tuple(
dataclasses.RenderedVariantDTO(
name=name,
content_type="image/jpeg",
width=10,
height=10,
data=name.value.encode(),
)
for name in AttachmentVariantName
),
peak_kib=100,
memory_limit_applied=True,
render_ms=5,
)
@pytest.fixture
def renderer(database: FakeDatabase) -> FakeImageRenderer:
return FakeImageRenderer(database, _rendered())
@pytest.fixture
def service(
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
renderer: FakeImageRenderer,
) -> AttachmentProcessingService:
return AttachmentProcessingService(uow, storage, renderer, asyncio.Event())
@pytest.fixture
async def queued(
uow: FakeUnitOfWork,
database: FakeDatabase,
storage: FakeObjectStorage,
) -> dataclasses.AttachmentJobDTO:
owner = user_dto()
chat = chat_dto(member_ids=(owner.id,))
now = utcnow()
row = attachment_dto(
chat_id=chat.id,
owner_id=owner.id,
status=AttachmentStatus.QUEUED,
created_at=now,
data=SOURCE,
)
job = job_dto(attachment_id=row.id, created_at=now)
async with uow:
await uow.attachments.insert_attachment(attachment=row)
await uow.jobs.insert_job(job=job)
await uow.commit()
storage.seed(row.staging_key, SOURCE)
database.events.clear()
return job
def _body(job: dataclasses.AttachmentJobDTO) -> bytes:
return build_job_body(job, attempt=job.attempt + 1)
async def _handle(
service: AttachmentProcessingService,
job: dataclasses.AttachmentJobDTO,
) -> JobOutcome:
return await service.handle(body=_body(job), redelivered=False)
def _set_job(database: FakeDatabase, job_id: UUID, **fields) -> None:
database.jobs[job_id] = replace(database.jobs[job_id], **fields)
async def test_success_commits_ready_with_variants(
service: AttachmentProcessingService,
database: FakeDatabase,
storage: FakeObjectStorage,
queued: dataclasses.AttachmentJobDTO,
) -> None:
outcome = await _handle(service, queued)
assert outcome == JobOutcome.ACK
row = database.attachments[queued.attachment_id]
job = database.jobs[queued.id]
assert row.status == AttachmentStatus.READY
assert job.state == AttachmentJobState.SUCCEEDED
assert job.attempt == 1
assert len(database.variants) == 3
# оригинал в конечном ключе и объекты вариантов
assert storage.objects[row.object_key][0] == SOURCE
assert len(storage.objects) == 5
async def test_put_is_not_inside_a_block(
service: AttachmentProcessingService,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
) -> None:
"""Вызовов S3 в транзакциях worker нет."""
await _handle(service, queued)
assert "storage.put" in database.events
assert not database.inside_block("storage.put")
assert not database.inside_block("storage.get")
assert not database.inside_block("renderer.render")
async def test_ready_and_variants_one_block(
service: AttachmentProcessingService,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
) -> None:
await _handle(service, queued)
events = database.events
start = events.index("attachments.commit_ready")
assert events[start - 1] == "jobs.lock_job"
assert events[start:] == [
"attachments.commit_ready",
"variants.insert_variant",
"variants.insert_variant",
"variants.insert_variant",
"jobs.finish_job",
"commit",
"exit",
]
async def test_malformed_message_dropped(
service: AttachmentProcessingService,
database: FakeDatabase,
) -> None:
outcome = await service.handle(body=b"not json", redelivered=False)
assert outcome == JobOutcome.DROP
assert database.events == []
async def test_unknown_job_acked_without_attempt(
service: AttachmentProcessingService,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
) -> None:
other = replace(queued, id=uuid4())
assert await _handle(service, other) == JobOutcome.ACK
assert database.jobs[queued.id].attempt == 0
async def test_foreign_attachment_acked_without_attempt(
service: AttachmentProcessingService,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
) -> None:
other = replace(queued, attachment_id=uuid4())
assert await _handle(service, other) == JobOutcome.ACK
assert database.jobs[queued.id].attempt == 0
async def test_finished_jobs_acked_without_write(
service: AttachmentProcessingService,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
) -> None:
await _handle(service, queued)
database.events.clear()
# повторная доставка завершённого
assert await _handle(service, queued) == JobOutcome.ACK
assert database.jobs[queued.id].attempt == 1
assert "commit" not in database.events
_set_job(database, queued.id, state=AttachmentJobState.FAILED)
database.events.clear()
assert await _handle(service, queued) == JobOutcome.ACK
assert "commit" not in database.events
async def test_not_due_acked_without_attempt(
service: AttachmentProcessingService,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
) -> None:
_set_job(
database,
queued.id,
next_attempt_at=utcnow() + timedelta(seconds=30),
)
assert await _handle(service, queued) == JobOutcome.ACK
assert database.jobs[queued.id].attempt == 0
async def test_published_retry_is_taken_before_its_time(
service: AttachmentProcessingService,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
) -> None:
"""Отметка публикации есть: срок уже проверил relay."""
_set_job(
database,
queued.id,
next_attempt_at=utcnow() + timedelta(seconds=30),
published_at=utcnow(),
)
await _handle(service, queued)
assert database.jobs[queued.id].state == AttachmentJobState.SUCCEEDED
async def test_live_lease_acked_without_attempt(
service: AttachmentProcessingService,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
) -> None:
_set_job(
database,
queued.id,
state=AttachmentJobState.PROCESSING,
attempt=1,
lease_expires_at=utcnow() + timedelta(seconds=30),
)
assert await _handle(service, queued) == JobOutcome.ACK
assert database.jobs[queued.id].attempt == 1
assert "renderer.render" not in database.events
async def test_expired_lease_is_taken(
service: AttachmentProcessingService,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
) -> None:
_set_job(
database,
queued.id,
state=AttachmentJobState.PROCESSING,
attempt=1,
lease_expires_at=utcnow() - timedelta(seconds=1),
)
await _handle(service, queued)
job = database.jobs[queued.id]
assert job.attempt == 2
assert job.state == AttachmentJobState.SUCCEEDED
async def test_budget_spent_fails_without_attempt(
service: AttachmentProcessingService,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
) -> None:
attempts = settings.worker.max_attempts
_set_job(database, queued.id, attempt=attempts)
assert await _handle(service, queued) == JobOutcome.ACK
job = database.jobs[queued.id]
row = database.attachments[queued.attachment_id]
assert job.state == AttachmentJobState.FAILED
assert job.attempt == attempts
assert row.error_code == AttachmentErrorCode.RETRY_EXHAUSTED
assert "renderer.render" not in database.events
async def test_budget_counts_from_attempt_base(
service: AttachmentProcessingService,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
) -> None:
attempts = settings.worker.max_attempts
_set_job(database, queued.id, attempt=attempts, attempt_base=attempts)
await _handle(service, queued)
assert database.jobs[queued.id].state == AttachmentJobState.SUCCEEDED
async def test_attempt_takes_lease_and_processing(
service: AttachmentProcessingService,
database: FakeDatabase,
renderer: FakeImageRenderer,
queued: dataclasses.AttachmentJobDTO,
) -> None:
"""Взятие: аренда и `processing` зафиксированы до работы с байтами."""
seen: dict[str, object] = {}
async def render(data: bytes) -> dataclasses.RenderedVariantsDTO:
seen["job"] = database.jobs[queued.id]
seen["status"] = database.attachments[queued.attachment_id].status
return _rendered()
renderer.render = render
before = utcnow()
await _handle(service, queued)
job = seen["job"]
worker = settings.worker
margin = worker.job_timeout_seconds + worker.lease_margin_seconds
assert seen["status"] == AttachmentStatus.PROCESSING
assert job.state == AttachmentJobState.PROCESSING
assert job.lease_expires_at >= before + timedelta(seconds=margin)
async def test_permanent_error_fails_at_once(
service: AttachmentProcessingService,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
) -> None:
database.fail_on["renderer.render"] = exceptions.ImageRejected(
reason=AttachmentJobReason.UNDECODABLE,
)
assert await _handle(service, queued) == JobOutcome.ACK
row = database.attachments[queued.attachment_id]
job = database.jobs[queued.id]
assert row.status == AttachmentStatus.FAILED
assert row.error_code == AttachmentErrorCode.INVALID_IMAGE
assert job.state == AttachmentJobState.FAILED
assert job.last_error_code == AttachmentJobReason.UNDECODABLE.value
@pytest.mark.parametrize(
("change", "reason"),
[
("missing", AttachmentJobReason.SOURCE_MISSING),
("size", AttachmentJobReason.SOURCE_CORRUPTED),
("checksum", AttachmentJobReason.SOURCE_CORRUPTED),
],
)
async def test_damaged_source_fails_at_once(
service: AttachmentProcessingService,
database: FakeDatabase,
storage: FakeObjectStorage,
queued: dataclasses.AttachmentJobDTO,
change: str,
reason: AttachmentJobReason,
) -> None:
key = database.attachments[queued.attachment_id].staging_key
if change == "missing":
del storage.objects[key]
elif change == "size":
storage.seed(key, b"other size bytes!")
else:
storage.seed(key, b"X" * len(SOURCE))
assert await _handle(service, queued) == JobOutcome.ACK
row = database.attachments[queued.attachment_id]
assert row.status == AttachmentStatus.FAILED
assert row.error_code == AttachmentErrorCode.PROCESSING_FAILED
assert database.jobs[queued.id].last_error_code == reason.value
@pytest.mark.parametrize(
("event", "failure", "reason"),
[
(
"storage.get",
exceptions.ObjectStorageUnavailable(),
AttachmentJobReason.STORAGE_UNAVAILABLE,
),
(
"storage.put",
exceptions.ObjectStorageUnavailable(),
AttachmentJobReason.STORAGE_UNAVAILABLE,
),
(
"renderer.render",
exceptions.RenderInterrupted(
reason=AttachmentJobReason.RENDER_KILLED,
),
AttachmentJobReason.RENDER_KILLED,
),
(
"renderer.render",
RuntimeError("boom"),
AttachmentJobReason.UNEXPECTED,
),
],
ids=["get", "put", "render_killed", "unexpected"],
)
async def test_temporary_error_returns_to_queue(
service: AttachmentProcessingService,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
event: str,
failure: BaseException,
reason: AttachmentJobReason,
) -> None:
database.fail_on[event] = failure
before = utcnow()
assert await _handle(service, queued) == JobOutcome.ACK
job = database.jobs[queued.id]
row = database.attachments[queued.attachment_id]
assert job.state == AttachmentJobState.QUEUED
assert job.attempt == 1
assert job.last_error_code == reason.value
assert job.published_at is None
assert job.next_attempt_at >= before + timedelta(seconds=2.5)
assert row.status == AttachmentStatus.QUEUED
async def test_temporary_error_after_budget_is_failed(
service: AttachmentProcessingService,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
) -> None:
_set_job(database, queued.id, attempt=settings.worker.max_attempts - 1)
database.fail_on["storage.get"] = exceptions.ObjectStorageUnavailable()
assert await _handle(service, queued) == JobOutcome.ACK
row = database.attachments[queued.attachment_id]
assert row.error_code == AttachmentErrorCode.RETRY_EXHAUSTED
assert database.jobs[queued.id].state == AttachmentJobState.FAILED
async def _with_supersede(
service: AttachmentProcessingService,
database: FakeDatabase,
renderer: FakeImageRenderer,
queued: dataclasses.AttachmentJobDTO,
*,
failure: BaseException | None = None,
) -> tuple[JobOutcome, dataclasses.AttachmentJobDTO]:
"""Пока попытка работает, задание взяла следующая попытка."""
async def render(data: bytes) -> dataclasses.RenderedVariantsDTO:
job = database.jobs[queued.id]
_set_job(database, queued.id, attempt=job.attempt + 1)
if failure is not None:
raise failure
return _rendered()
renderer.render = render
outcome = await _handle(service, queued)
return outcome, database.jobs[queued.id]
async def test_superseded_on_ready_no_effect(
service: AttachmentProcessingService,
database: FakeDatabase,
renderer: FakeImageRenderer,
queued: dataclasses.AttachmentJobDTO,
) -> None:
outcome, job = await _with_supersede(service, database, renderer, queued)
assert outcome == JobOutcome.ACK
assert job.state == AttachmentJobState.PROCESSING
assert database.attachments[queued.attachment_id].status == (
AttachmentStatus.PROCESSING
)
assert database.variants == {}
async def test_superseded_on_failed_no_effect(
service: AttachmentProcessingService,
database: FakeDatabase,
renderer: FakeImageRenderer,
queued: dataclasses.AttachmentJobDTO,
) -> None:
outcome, job = await _with_supersede(
service,
database,
renderer,
queued,
failure=exceptions.ImageRejected(
reason=AttachmentJobReason.UNDECODABLE,
),
)
assert outcome == JobOutcome.ACK
assert job.state == AttachmentJobState.PROCESSING
assert database.attachments[queued.attachment_id].error_code is None
async def test_superseded_on_return_no_effect(
service: AttachmentProcessingService,
database: FakeDatabase,
renderer: FakeImageRenderer,
queued: dataclasses.AttachmentJobDTO,
) -> None:
outcome, job = await _with_supersede(
service,
database,
renderer,
queued,
failure=exceptions.RenderInterrupted(
reason=AttachmentJobReason.RENDER_KILLED,
),
)
assert outcome == JobOutcome.ACK
assert job.state == AttachmentJobState.PROCESSING
assert database.attachments[queued.attachment_id].status == (
AttachmentStatus.PROCESSING
)
async def test_database_failure_requeues_and_pauses(
service: AttachmentProcessingService,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
) -> None:
database.fail_on["jobs.lock_job"] = exceptions.ServiceUnavailable()
assert await _handle(service, queued) == JobOutcome.REQUEUE
assert database.jobs[queued.id].attempt == 0
async def test_stop_interrupts_pause(
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
renderer: FakeImageRenderer,
database: FakeDatabase,
queued: dataclasses.AttachmentJobDTO,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(settings.worker, "reconnect_seconds", 30)
stop = asyncio.Event()
stop.set()
service = AttachmentProcessingService(uow, storage, renderer, stop)
database.fail_on["jobs.lock_job"] = exceptions.ServiceUnavailable()
async with asyncio.timeout(1):
assert await _handle(service, queued) == JobOutcome.REQUEUE
def test_retry_delay_bounds() -> None:
for attempt in range(1, 8):
delay = retry_delay(attempt=attempt, base=5, maximum=60)
top = min(60, 5 * 2 ** (attempt - 1))
assert top / 2 <= delay <= top
@@ -0,0 +1,469 @@
"""`AttachmentReconcileService`: находки обеих стратегий, действия, счёт блоков."""
from dataclasses import replace
from datetime import timedelta
from hashlib import sha256
from uuid import uuid4
import pytest
from builders import attachment_dto
from fakes import FakeDatabase, FakeObjectStorage, FakeUnitOfWork
from src.core import exceptions
from src.core.services.attachment_cleanup import (
INTERRUPTED_BY_DATABASE,
INTERRUPTED_BY_OBJECT_STORAGE,
INTERRUPTED_BY_STOP,
)
from src.core.services.attachment_reconcile import AttachmentReconcileService
from src.schemas import dataclasses
from src.schemas.enums import (
AttachmentStatus,
ReconcileFinding,
ReconcileStrategy,
)
from src.utils.utc import utcnow
pytestmark = pytest.mark.anyio
STRATEGIES = list(ReconcileStrategy)
def _long_ago():
return utcnow() - timedelta(hours=2)
@pytest.fixture
def service(
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
) -> AttachmentReconcileService:
return AttachmentReconcileService(uow, storage)
async def _ready(
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
*,
with_object: bool = True,
data: bytes = b"content",
object_key: str | None = None,
updated_at=None,
) -> dataclasses.AttachmentFullDTO:
moment = updated_at or _long_ago()
row = attachment_dto(
chat_id=uuid4(),
owner_id=uuid4(),
status=AttachmentStatus.READY,
created_at=moment,
staging=False,
data=data,
object_key=object_key,
)
async with uow:
await uow.attachments.insert_attachment(attachment=row)
await uow.commit()
if with_object:
storage.seed(row.object_key, data, last_modified=_long_ago())
return row
def _key(storage: FakeObjectStorage, name: str) -> str:
return f"{storage.namespace}/attachments/{name}"
async def _pass(
service: AttachmentReconcileService,
*,
apply: bool = False,
strategy: ReconcileStrategy = ReconcileStrategy.BATCH,
deep: bool = False,
max_changes: int = 100,
stop_requested=None,
page_size: int = 2,
) -> dataclasses.ReconcilePassDTO:
now = utcnow()
kwargs = (
{} if stop_requested is None else {"stop_requested": stop_requested}
)
return await service.reconcile(
older_than=now - timedelta(minutes=15),
staging_older_than=now - timedelta(minutes=15),
apply=apply,
max_changes=max_changes,
page_size=page_size,
batch_size=2,
strategy=strategy,
deep=deep,
**kwargs,
)
async def _all_classes(
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
) -> dict[str, object]:
"""По одному расхождению каждого класса без чтения содержимого."""
await _ready(uow, storage)
orphan_id = uuid4()
orphan = _key(storage, f"{orphan_id}/original")
storage.seed(orphan, last_modified=_long_ago())
variant_orphan = _key(storage, f"{uuid4()}/v1-thumbnail")
storage.seed(variant_orphan, last_modified=_long_ago())
unknown = _key(storage, "weird-object")
storage.seed(unknown, last_modified=_long_ago())
staging_orphan = f"{storage.namespace}/staging/{uuid4()}/original"
storage.seed(staging_orphan, last_modified=_long_ago())
staging_unknown = f"{storage.namespace}/staging/weird"
storage.seed(staging_unknown, last_modified=_long_ago())
missing = await _ready(uow, storage, with_object=False)
size = await _ready(uow, storage, with_object=False)
storage.seed(size.object_key, b"other size!", last_modified=_long_ago())
foreign = await _ready(
uow,
storage,
with_object=False,
object_key="other-db/attachments/x/original",
)
pending = attachment_dto(
chat_id=uuid4(),
owner_id=uuid4(),
created_at=_long_ago(),
)
async with uow:
await uow.attachments.insert_attachment(attachment=pending)
await uow.commit()
storage.seed(pending.staging_key, last_modified=_long_ago())
return {
"orphan": orphan,
"variant_orphan": variant_orphan,
"unknown": unknown,
"staging_orphan": staging_orphan,
"staging_unknown": staging_unknown,
"missing": missing,
"size": size,
"foreign": foreign,
"pending": pending,
}
EXPECTED = {
ReconcileFinding.ORPHAN_OBJECT: 2,
ReconcileFinding.UNKNOWN_OBJECT: 3,
ReconcileFinding.ORPHAN_STAGING: 1,
ReconcileFinding.MISSING_OBJECT: 1,
ReconcileFinding.SIZE_MISMATCH: 1,
ReconcileFinding.STALE_PENDING: 1,
}
@pytest.mark.parametrize("strategy", STRATEGIES)
async def test_dry_run_finds_all_and_changes_nothing(
service: AttachmentReconcileService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
strategy: ReconcileStrategy,
) -> None:
await _all_classes(uow, storage)
rows = database.snapshot()["attachments"]
objects = dict(storage.objects)
result = await _pass(service, strategy=strategy)
assert dict(result.found) == EXPECTED
assert result.fixed == {}
assert result.remaining == sum(EXPECTED.values())
assert result.interrupted_by is None
assert database.attachments == rows
assert storage.objects == objects
async def test_apply_order_and_effects(
service: AttachmentReconcileService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
seeded = await _all_classes(uow, storage)
database.events.clear()
result = await _pass(service, apply=True)
assert result.fixed[ReconcileFinding.ORPHAN_OBJECT] == 2
assert result.fixed[ReconcileFinding.ORPHAN_STAGING] == 1
assert result.fixed[ReconcileFinding.MISSING_OBJECT] == 1
assert result.fixed[ReconcileFinding.SIZE_MISMATCH] == 1
assert result.fixed[ReconcileFinding.STALE_PENDING] == 1
# чужое не исправляется
assert ReconcileFinding.UNKNOWN_OBJECT not in result.fixed
assert result.remaining == 3
assert seeded["orphan"] not in storage.objects
assert seeded["unknown"] in storage.objects
assert seeded["staging_unknown"] in storage.objects
assert database.attachments[seeded["missing"].id].lost_at is not None
assert database.attachments[seeded["size"].id].lost_at is not None
assert database.attachments[seeded["foreign"].id].lost_at is None
assert seeded["pending"].id not in database.attachments
# порядок решения 7: зависшие → объекты → пометки
events = database.events
removed = events.index("attachments.delete_attachment")
first_lost = events.index("attachments.mark_lost")
deletes = [
index for index, name in enumerate(events) if name == "storage.delete"
]
assert removed < first_lost
assert deletes[-1] < first_lost
async def test_change_limit_refuses_and_stops_rechecks(
service: AttachmentReconcileService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
for _ in range(5):
storage.seed(
_key(storage, f"{uuid4()}/original"),
last_modified=_long_ago(),
)
objects = dict(storage.objects)
result = await _pass(service, apply=True, max_changes=2)
assert result.refused
assert result.unchecked == 2
assert storage.objects == objects
assert "storage.delete" not in database.events
async def test_dry_run_rechecks_everything_over_limit(
service: AttachmentReconcileService,
storage: FakeObjectStorage,
) -> None:
for _ in range(4):
storage.seed(
_key(storage, f"{uuid4()}/original"),
last_modified=_long_ago(),
)
result = await _pass(service, apply=False, max_changes=1)
assert result.unchecked == 0
assert dict(result.found) == {ReconcileFinding.ORPHAN_OBJECT: 4}
async def test_recheck_drops_candidate_that_got_a_row(
uow: FakeUnitOfWork,
database: FakeDatabase,
storage: FakeObjectStorage,
) -> None:
"""Перед перепроверкой появилась строка: кандидат выбывает."""
attachment_id = uuid4()
key = _key(storage, f"{attachment_id}/original")
storage.seed(key, last_modified=_long_ago())
service = AttachmentReconcileService(uow, storage)
original = service._recheck_all
async def recheck_all(state, *, max_changes):
row = attachment_dto(
chat_id=uuid4(),
owner_id=uuid4(),
status=AttachmentStatus.READY,
created_at=_long_ago(),
staging=False,
object_key=key,
)
database.attachments[attachment_id] = replace(row, id=attachment_id)
await original(state, max_changes=max_changes)
service._recheck_all = recheck_all
result = await _pass(service, apply=True)
assert result.found == {}
assert key in storage.objects
async def test_fresh_object_is_not_a_finding(
service: AttachmentReconcileService,
storage: FakeObjectStorage,
) -> None:
storage.seed(
_key(storage, f"{uuid4()}/original"),
last_modified=utcnow(),
)
result = await _pass(service)
assert result.found == {}
assert result.fresh_objects == 1
async def test_fresh_row_is_not_a_finding(
service: AttachmentReconcileService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
) -> None:
await _ready(uow, storage, with_object=False, updated_at=utcnow())
result = await _pass(service)
assert result.found == {}
assert result.fresh_rows == 1
@pytest.mark.parametrize("strategy", STRATEGIES)
async def test_deep_finds_checksum_mismatch(
service: AttachmentReconcileService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
strategy: ReconcileStrategy,
) -> None:
row = await _ready(uow, storage)
storage.seed(row.object_key, b"CONTENT", last_modified=_long_ago())
assert (await _pass(service, strategy=strategy)).found == {}
result = await _pass(service, strategy=strategy, deep=True, apply=True)
assert result.found == {ReconcileFinding.CHECKSUM_MISMATCH: 1}
assert database.attachments[row.id].lost_at is not None
assert result.read_bytes > 0
async def test_restored_object_same_sha_clears_mark(
service: AttachmentReconcileService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
row = await _ready(uow, storage)
async with uow:
await uow.attachments.mark_lost(
attachment_id=row.id,
object_key=row.object_key,
lost_at=_long_ago(),
)
await uow.commit()
result = await _pass(service, apply=True)
assert result.fixed == {ReconcileFinding.RESTORED_OBJECT: 1}
assert database.attachments[row.id].lost_at is None
async def test_restored_object_other_sha_keeps_mark(
service: AttachmentReconcileService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
row = await _ready(uow, storage)
storage.seed(row.object_key, b"CONTENT", last_modified=_long_ago())
async with uow:
await uow.attachments.mark_lost(
attachment_id=row.id,
object_key=row.object_key,
lost_at=_long_ago(),
)
await uow.commit()
result = await _pass(service, apply=True)
assert result.fixed == {}
assert result.lost_known == 1
assert database.attachments[row.id].lost_at is not None
assert row.sha256 == sha256(b"content").digest()
async def test_stop_before_call_and_failures(
service: AttachmentReconcileService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
await _ready(uow, storage)
result = await _pass(service, stop_requested=lambda: True)
assert result.interrupted_by == INTERRUPTED_BY_STOP
assert "storage.list" not in database.events
database.fail_on["storage.list"] = exceptions.ObjectStorageUnavailable()
result = await _pass(service)
assert result.interrupted_by == INTERRUPTED_BY_OBJECT_STORAGE
database.fail_on.clear()
database.fail_on["attachments.get_ready_page"] = (
exceptions.ServiceUnavailable()
)
result = await _pass(service)
assert result.interrupted_by == INTERRUPTED_BY_DATABASE
# отказ после сигнала считается остановкой
calls = 0
def stopping() -> bool:
nonlocal calls
calls += 1
return calls > 3
result = await _pass(service, stop_requested=stopping)
assert result.interrupted_by == INTERRUPTED_BY_STOP
async def test_interrupted_recheck_changes_nothing(
service: AttachmentReconcileService,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
storage.seed(
_key(storage, f"{uuid4()}/original"),
last_modified=_long_ago(),
)
objects = dict(storage.objects)
database.fail_on["attachments.find_attachment_reference"] = (
exceptions.ServiceUnavailable()
)
result = await _pass(service, apply=True)
assert result.interrupted_by == INTERRUPTED_BY_DATABASE
assert storage.objects == objects
@pytest.mark.parametrize("strategy", STRATEGIES)
async def test_db_sessions_equal_blocks_with_cleanup(
service: AttachmentReconcileService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
strategy: ReconcileStrategy,
) -> None:
"""Сценарий «Счёт блоков сверки»: и блоки уборки зависших загрузок."""
await _all_classes(uow, storage)
database.events.clear()
result = await _pass(service, apply=True, strategy=strategy)
assert result.db_sessions == database.events.count("enter")
# уборка одной зависшей — два блока сверх остальных
assert result.fixed[ReconcileFinding.STALE_PENDING] == 1
locks = database.events.count("attachments.lock_stale_pending")
assert locks == 2
async def test_db_sessions_is_per_pass(
service: AttachmentReconcileService,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
storage.seed(
_key(storage, f"{uuid4()}/original"),
last_modified=_long_ago(),
)
await _pass(service)
database.events.clear()
result = await _pass(service)
assert result.db_sessions == database.events.count("enter")
async def test_cost_counters(
service: AttachmentReconcileService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
) -> None:
await _ready(uow, storage)
result = await _pass(service, strategy=ReconcileStrategy.HEAD)
assert result.s3_requests["head"] == 1
assert result.storage_objects == result.listed_objects + 1
assert set(result.phase_ms) == {"list", "rows", "stale", "recheck", "act"}
async def test_object_of_other_row_key_compared_by_rows_step(
service: AttachmentReconcileService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
"""Строка с ключом `<id>/original` другого вложения — HEAD её объекта."""
other = uuid4()
key = _key(storage, f"{other}/original")
await _ready(uow, storage, with_object=False, object_key=key)
storage.seed(key, b"different", last_modified=_long_ago())
database.events.clear()
result = await _pass(service)
assert result.found.get(ReconcileFinding.SIZE_MISMATCH) == 1
assert "storage.head" in database.events
+283
View File
@@ -0,0 +1,283 @@
"""`AttachmentRelayService`: порядок публикации, предел, аренды, потерянные."""
from dataclasses import replace
from datetime import timedelta
from uuid import uuid4
import pytest
from builders import attachment_dto, job_dto
from fakes import FakeDatabase, FakeJobPublisher, FakeUnitOfWork
from src.core import exceptions
from src.core.services.attachment_relay import AttachmentRelayService
from src.schemas import dataclasses
from src.schemas.enums import (
AttachmentJobReason,
AttachmentJobState,
AttachmentStatus,
)
from src.utils.utc import utcnow
pytestmark = pytest.mark.anyio
@pytest.fixture
def service(
uow: FakeUnitOfWork,
publisher: FakeJobPublisher,
) -> AttachmentRelayService:
return AttachmentRelayService(uow, publisher)
async def _jobs(
uow: FakeUnitOfWork,
database: FakeDatabase,
count: int = 1,
) -> list[dataclasses.AttachmentJobDTO]:
now = utcnow() - timedelta(seconds=1)
jobs = []
async with uow:
for index in range(count):
row = attachment_dto(
chat_id=uuid4(),
owner_id=uuid4(),
status=AttachmentStatus.QUEUED,
created_at=now,
)
job = job_dto(
attachment_id=row.id,
created_at=now + timedelta(milliseconds=index),
)
await uow.attachments.insert_attachment(attachment=row)
await uow.jobs.insert_job(job=job)
jobs.append(job)
await uow.commit()
database.events.clear()
return jobs
async def _pass(
service: AttachmentRelayService,
*,
batch_size: int = 10,
max_backlog: int = 100,
stop_requested=None,
):
return await service.publish_pass(
batch_size=batch_size,
max_published_backlog=max_backlog,
republish_after_seconds=60,
**(
{}
if stop_requested is None
else {"stop_requested": stop_requested}
),
)
async def test_publish_order_in_one_block(
service: AttachmentRelayService,
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
"""Сценарий «Порядок публикации»."""
jobs = await _jobs(uow, database, 2)
result = await _pass(service)
assert result.published == 2
start = database.events.index("jobs.lock_due_jobs")
assert database.events[start:] == [
"jobs.lock_due_jobs",
"publisher.publish_many",
"jobs.mark_published",
"commit",
"exit",
]
assert database.inside_block("publisher.publish_many")
assert all(database.jobs[job.id].published_at for job in jobs)
async def test_confirmed_subset_marked(
service: AttachmentRelayService,
uow: FakeUnitOfWork,
publisher: FakeJobPublisher,
database: FakeDatabase,
) -> None:
first, second = await _jobs(uow, database, 2)
publisher.unconfirmed = {second.id}
result = await _pass(service)
assert result.published == 1
assert result.unconfirmed == 1
assert database.jobs[first.id].published_at is not None
assert database.jobs[second.id].published_at is None
async def test_nothing_confirmed_no_mark(
service: AttachmentRelayService,
uow: FakeUnitOfWork,
publisher: FakeJobPublisher,
database: FakeDatabase,
) -> None:
(first,) = await _jobs(uow, database, 1)
publisher.unconfirmed = {first.id}
result = await _pass(service)
assert result.unconfirmed == 1
assert "jobs.mark_published" not in database.events
async def test_backlog_limit(
service: AttachmentRelayService,
uow: FakeUnitOfWork,
publisher: FakeJobPublisher,
database: FakeDatabase,
) -> None:
jobs = await _jobs(uow, database, 3)
result = await _pass(service, max_backlog=2)
assert result.published == 2
assert result.published_backlog == 2
assert not result.backlog_full
publisher.published.clear()
result = await _pass(service, max_backlog=2)
assert result.published == 0
assert result.backlog_full
assert publisher.published == []
assert database.jobs[jobs[2].id].published_at is None
async def test_held_job_skipped(
service: AttachmentRelayService,
uow: FakeUnitOfWork,
database: FakeDatabase,
publisher: FakeJobPublisher,
) -> None:
first, second = await _jobs(uow, database, 2)
database.held.add(first.id)
await _pass(service)
assert publisher.published == [second.id]
async def test_expired_leases_one_block(
service: AttachmentRelayService,
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
(job,) = await _jobs(uow, database, 1)
async with uow:
await uow.jobs.start_attempt(
job_id=job.id,
lease_expires_at=utcnow() - timedelta(seconds=1),
now=utcnow(),
)
await uow.attachments.mark_processing(
attachment_id=job.attachment_id,
updated_at=utcnow(),
)
await uow.commit()
database.events.clear()
result = await _pass(service)
assert result.recovered == 1
assert database.events[:4] == [
"enter",
"jobs.recover_expired_leases",
"attachments.return_group_to_queued",
"commit",
]
stored = database.jobs[job.id]
assert stored.last_error_code == AttachmentJobReason.LEASE_EXPIRED.value
assert database.attachments[job.attachment_id].status == (
AttachmentStatus.QUEUED
)
async def _published_long_ago(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> dataclasses.AttachmentJobDTO:
(job,) = await _jobs(uow, database, 1)
database.jobs[job.id] = replace(
database.jobs[job.id],
published_at=utcnow() - timedelta(seconds=600),
)
database.events.clear()
return job
async def test_lost_messages_reset_at_zero_ready(
service: AttachmentRelayService,
uow: FakeUnitOfWork,
database: FakeDatabase,
publisher: FakeJobPublisher,
) -> None:
job = await _published_long_ago(uow, database)
publisher.ready = 0
result = await _pass(service)
assert result.republished == 1
# тем же проходом опубликовано заново
assert result.published == 1
assert database.jobs[job.id].published_at is not None
assert not database.inside_block("publisher.ready_messages")
async def test_lost_messages_kept_when_queue_has_ready(
service: AttachmentRelayService,
uow: FakeUnitOfWork,
database: FakeDatabase,
publisher: FakeJobPublisher,
) -> None:
await _published_long_ago(uow, database)
publisher.ready = 5
result = await _pass(service)
assert result.republished == 0
assert "jobs.reset_published_before" not in database.events
async def test_broker_not_asked_without_candidates(
service: AttachmentRelayService,
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
await _jobs(uow, database, 1)
await _pass(service)
assert "publisher.ready_messages" not in database.events
@pytest.mark.parametrize(
("ready_calls", "expected_absent"),
[
(1, ["jobs.has_published_before", "jobs.lock_due_jobs"]),
(2, ["jobs.lock_due_jobs"]),
],
ids=["after_recover", "after_lost"],
)
async def test_stop_between_steps(
service: AttachmentRelayService,
uow: FakeUnitOfWork,
database: FakeDatabase,
ready_calls: int,
expected_absent: list[str],
) -> None:
await _jobs(uow, database, 1)
calls = 0
def stop_requested() -> bool:
nonlocal calls
calls += 1
return calls >= ready_calls
result = await _pass(service, stop_requested=stop_requested)
assert result.published == 0
for name in expected_absent:
assert name not in database.events
async def test_broker_failure_rolls_back_block(
service: AttachmentRelayService,
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
(job,) = await _jobs(uow, database, 1)
database.fail_on["publisher.publish_many"] = exceptions.BrokerUnavailable()
with pytest.raises(exceptions.BrokerUnavailable):
await _pass(service)
stored = database.jobs[job.id]
assert stored.published_at is None
assert stored.state == AttachmentJobState.QUEUED
@@ -0,0 +1,241 @@
"""`AttachmentReplayService`: таблица отказов, аудит одним блоком, показ."""
from uuid import UUID, uuid4
import pytest
from builders import NOW, attachment_dto, job_dto
from fakes import FakeDatabase, FakeUnitOfWork
from src.core import exceptions
from src.core.services.attachment_replay import (
REFUSAL_ALREADY_READY,
REFUSAL_NOT_FAILED,
REFUSAL_NOT_FOUND,
REFUSAL_SOURCE_GONE,
AttachmentReplayService,
)
from src.schemas.enums import (
AttachmentErrorCode,
AttachmentJobReason,
AttachmentJobState,
AttachmentStatus,
)
from src.utils.constants import ATTACHMENT_PIPELINE_VERSION
pytestmark = pytest.mark.anyio
@pytest.fixture
def service(uow: FakeUnitOfWork) -> AttachmentReplayService:
return AttachmentReplayService(uow)
async def _row(
uow: FakeUnitOfWork,
*,
status: AttachmentStatus = AttachmentStatus.QUEUED,
job: bool = True,
failed: bool = False,
staging: bool = True,
code: AttachmentErrorCode = AttachmentErrorCode.INVALID_IMAGE,
reason: AttachmentJobReason = AttachmentJobReason.UNDECODABLE,
) -> UUID:
row = attachment_dto(
chat_id=uuid4(),
owner_id=uuid4(),
status=status,
staging=staging,
)
async with uow:
await uow.attachments.insert_attachment(attachment=row)
if job:
created = job_dto(
attachment_id=row.id,
pipeline_version=ATTACHMENT_PIPELINE_VERSION,
)
await uow.jobs.insert_job(job=created)
if failed:
await uow.attachments.commit_failed(
attachment_id=row.id,
error_code=code,
updated_at=NOW,
)
await uow.jobs.finish_job(
job_id=created.id,
state=AttachmentJobState.FAILED,
reason=reason,
now=NOW,
)
await uow.commit()
return row.id
async def _replay(service: AttachmentReplayService, attachment_id: UUID):
return await service.replay_one(
attachment_id=attachment_id,
apply=True,
operator="op",
)
async def test_refusals_change_nothing(
service: AttachmentReplayService,
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
ready = await _row(uow, status=AttachmentStatus.READY)
no_job = await _row(uow, job=False)
queued = await _row(uow)
gone = await _row(uow, failed=True, staging=False)
before = database.snapshot()
assert (await _replay(service, uuid4())).refusal == REFUSAL_NOT_FOUND
assert (await _replay(service, no_job)).refusal == REFUSAL_NOT_FOUND
assert (await _replay(service, ready)).refusal == REFUSAL_ALREADY_READY
assert (await _replay(service, queued)).refusal == REFUSAL_NOT_FAILED
assert (await _replay(service, gone)).refusal == REFUSAL_SOURCE_GONE
assert database.snapshot() == before
assert "commit" not in database.events[-20:]
async def test_apply_returns_job_with_audit_in_one_block(
service: AttachmentReplayService,
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
attachment_id = await _row(uow, failed=True)
database.events.clear()
result = await _replay(service, attachment_id)
assert result.refusal is None
assert result.error_code == AttachmentErrorCode.INVALID_IMAGE.value
assert result.reason == AttachmentJobReason.UNDECODABLE.value
assert database.events == [
"enter",
"jobs.get_attachment_job",
"jobs.lock_job",
"attachments.lock_attachment",
"attachments.replay_failed",
"jobs.replay_job",
"job_replays.insert_replay",
"commit",
"exit",
]
row = database.attachments[attachment_id]
job = next(iter(database.jobs.values()))
audit = next(iter(database.job_replays.values()))
assert row.status == AttachmentStatus.QUEUED
assert row.error_code is None
assert job.state == AttachmentJobState.QUEUED
assert job.attempt_base == job.attempt
assert audit.operator == "op"
assert audit.error_code == AttachmentErrorCode.INVALID_IMAGE.value
async def test_audit_failure_rolls_back_all(
service: AttachmentReplayService,
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
attachment_id = await _row(uow, failed=True)
database.fail_on["job_replays.insert_replay"] = (
exceptions.ServiceUnavailable()
)
with pytest.raises(exceptions.ServiceUnavailable):
await _replay(service, attachment_id)
assert database.attachments[attachment_id].status == (
AttachmentStatus.FAILED
)
assert next(iter(database.jobs.values())).state == (
AttachmentJobState.FAILED
)
async def test_show_without_apply_changes_nothing(
service: AttachmentReplayService,
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
await _row(uow, failed=True)
before = database.snapshot()
result = await service.replay_pass(
attachment_ids=[],
error_code=None,
reason=None,
limit=10,
apply=False,
operator="op",
)
assert (result.shown, result.replayed, result.refused) == (1, 0, 0)
assert database.snapshot() == before
async def test_selection_by_code_and_reason(
service: AttachmentReplayService,
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
invalid = await _row(uow, failed=True)
other = await _row(
uow,
failed=True,
code=AttachmentErrorCode.PROCESSING_FAILED,
reason=AttachmentJobReason.SOURCE_MISSING,
)
result = await service.replay_pass(
attachment_ids=[],
error_code=AttachmentErrorCode.INVALID_IMAGE.value,
reason=None,
limit=10,
apply=True,
operator="op",
)
assert result.replayed == 1
assert database.attachments[invalid].status == AttachmentStatus.QUEUED
assert database.attachments[other].status == AttachmentStatus.FAILED
result = await service.replay_pass(
attachment_ids=[],
error_code=None,
reason=AttachmentJobReason.SOURCE_MISSING.value,
limit=10,
apply=False,
operator="op",
)
assert result.shown == 1
async def test_by_id_counts_refusals_and_limit(
service: AttachmentReplayService,
uow: FakeUnitOfWork,
) -> None:
good = await _row(uow, failed=True)
bad = await _row(uow)
third = await _row(uow, failed=True)
result = await service.replay_pass(
attachment_ids=[good, bad, third],
error_code=None,
reason=None,
limit=2,
apply=True,
operator="op",
)
assert (result.replayed, result.refused) == (1, 1)
async def test_stop_signal_interrupts(
service: AttachmentReplayService,
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
attachment_id = await _row(uow, failed=True)
result = await service.replay_pass(
attachment_ids=[attachment_id],
error_code=None,
reason=None,
limit=10,
apply=True,
operator="op",
stop_requested=lambda: True,
)
assert result.interrupted
assert database.attachments[attachment_id].status == (
AttachmentStatus.FAILED
)
@@ -0,0 +1,581 @@
"""`AttachmentService`: порядок проверок и записи, компенсация, чтение."""
import asyncio
from collections.abc import AsyncIterator
from dataclasses import replace
from pathlib import Path
from uuid import UUID, uuid4
import pytest
from builders import (
NOW,
attachment_dto,
chat_dto,
job_dto,
user_dto,
variant_dto,
)
from fakes import FakeCache, FakeDatabase, FakeObjectStorage, FakeUnitOfWork
from src.api.errors import DOMAIN_ERRORS, RETRY_AFTER
from src.api.schemas import ErrorCode
from src.config import settings
from src.core import exceptions
from src.core.services import AttachmentService
from src.infra.upload_slots import UploadSlots
from src.schemas.enums import (
AttachmentErrorCode,
AttachmentJobState,
AttachmentStatus,
AttachmentVariantName,
)
from src.utils.constants import ATTACHMENT_MAX_BYTES
pytestmark = pytest.mark.anyio
SAMPLE = (
Path(__file__).resolve().parents[2] / "tests" / "fixtures" / "sample.png"
).read_bytes()
UNAVAILABLE = exceptions.ServiceUnavailable
def _slots(*, max_concurrent: int = 1, max_waiting: int = 0) -> UploadSlots:
return UploadSlots(
max_concurrent=max_concurrent,
max_waiting=max_waiting,
wait_timeout_seconds=0.01,
)
async def _body(*chunks: bytes) -> AsyncIterator[bytes]:
for chunk in chunks:
yield chunk
@pytest.fixture
def service(
uow: FakeUnitOfWork,
cache: FakeCache,
storage: FakeObjectStorage,
) -> AttachmentService:
return AttachmentService(uow, cache, storage, _slots())
@pytest.fixture
async def world(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> tuple[UUID, UUID, UUID]:
alice = user_dto()
bob = user_dto()
chat = chat_dto(member_ids=(alice.id,))
async with uow:
await uow.users.insert_user(user=alice, password_hash="h")
await uow.users.insert_user(user=bob, password_hash="h")
await uow.chats.insert_chat(chat=chat)
await uow.chats.insert_chat_members(chat=chat)
await uow.commit()
database.events.clear()
return alice.id, bob.id, chat.id
async def _upload(
service: AttachmentService,
world: tuple[UUID, UUID, UUID],
*,
owner: UUID | None = None,
media_type: str | None = "image/png",
content_length: int | None = None,
body: AsyncIterator[bytes] | None = None,
):
alice, _, chat_id = world
return await service.upload(
chat_id=chat_id,
owner_id=owner or alice,
filename="a.png",
media_type=media_type,
content_length=content_length,
body=body if body is not None else _body(SAMPLE),
)
class _Untouched:
"""Тело, которое нельзя начать читать."""
def __aiter__(self):
raise AssertionError("body must not be read")
async def test_upload_order_and_events(
service: AttachmentService,
database: FakeDatabase,
storage: FakeObjectStorage,
world: tuple[UUID, UUID, UUID],
) -> None:
attachment = await _upload(service, world)
assert attachment.status == AttachmentStatus.QUEUED
assert database.attachments[attachment.id].status == (
AttachmentStatus.QUEUED
)
job = next(iter(database.jobs.values()))
assert job.attachment_id == attachment.id
assert job.state == AttachmentJobState.QUEUED
assert storage.objects[attachment.staging_key][0] == SAMPLE
events = [item for item in database.events if not item.startswith("cache")]
assert events == [
"enter",
"chats.get_chat",
"exit",
"enter",
"attachments.insert_attachment",
"commit",
"exit",
"storage.put",
"enter",
"attachments.mark_queued",
"jobs.insert_job",
"commit",
"exit",
]
assert not database.inside_block("storage.put")
def _fill_backlog(database: FakeDatabase, count: int) -> None:
"""`count` незавершённых заданий: `queued` и `processing` поровну."""
for number in range(count):
state = (
AttachmentJobState.QUEUED
if number % 2 == 0
else AttachmentJobState.PROCESSING
)
job = job_dto(attachment_id=uuid4())
database.jobs[job.id] = replace(job, state=state)
async def test_backlog_full_rejects_without_body_or_slot(
uow: FakeUnitOfWork,
cache: FakeCache,
storage: FakeObjectStorage,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(settings.uploads, "max_unfinished_jobs", 3)
_fill_backlog(database, 3)
slots = _slots()
service = AttachmentService(uow, cache, storage, slots)
# все места заняты: 429 предела приходит раньше очереди мест
async with slots.slot():
with pytest.raises(exceptions.UploadBacklogFull):
await _upload(service, world, body=_Untouched())
assert database.attachments == {}
assert storage.objects == {}
assert "jobs.count_unfinished" in database.events
# отказ не занял места: занятое выше освобождено, новая берётся
async with slots.slot():
pass
async def test_backlog_below_limit_accepts(
service: AttachmentService,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(settings.uploads, "max_unfinished_jobs", 3)
_fill_backlog(database, 2)
attachment = await _upload(service, world)
assert attachment.status == AttachmentStatus.QUEUED
assert database.events.index("jobs.count_unfinished") < (
database.events.index("attachments.insert_attachment")
)
# счёт — в первом блоке, рядом с членством: шаг с БД до тела один
first_block = database.events[
database.events.index("enter") : database.events.index("exit")
]
assert "jobs.count_unfinished" in first_block
async def test_backlog_finished_jobs_not_counted(
service: AttachmentService,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(settings.uploads, "max_unfinished_jobs", 2)
for state in (AttachmentJobState.SUCCEEDED, AttachmentJobState.FAILED):
for _ in range(3):
job = job_dto(attachment_id=uuid4())
database.jobs[job.id] = replace(job, state=state)
attachment = await _upload(service, world)
assert attachment.status == AttachmentStatus.QUEUED
async def test_backlog_off_makes_no_query(
service: AttachmentService,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(settings.uploads, "max_unfinished_jobs", 0)
_fill_backlog(database, 5)
attachment = await _upload(service, world)
assert attachment.status == AttachmentStatus.QUEUED
assert "jobs.count_unfinished" not in database.events
@pytest.mark.parametrize(
("kind", "error"),
[
("stranger", exceptions.ChatNotFound),
("type", exceptions.UnsupportedMediaType),
("size", exceptions.PayloadTooLarge),
],
)
async def test_backlog_checked_after_cheap_checks(
service: AttachmentService,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
monkeypatch: pytest.MonkeyPatch,
kind: str,
error: type[Exception],
) -> None:
monkeypatch.setattr(settings.uploads, "max_unfinished_jobs", 1)
_fill_backlog(database, 1)
_, bob, _ = world
arguments = {
"stranger": {"owner": bob},
"type": {"media_type": "text/plain"},
"size": {"content_length": ATTACHMENT_MAX_BYTES + 1},
}[kind]
with pytest.raises(error):
await _upload(service, world, body=_Untouched(), **arguments)
assert "jobs.count_unfinished" not in database.events
async def test_backlog_error_maps_to_429_with_retry_after() -> None:
assert DOMAIN_ERRORS[exceptions.UploadBacklogFull] == (
429,
ErrorCode.RATE_LIMITED,
)
assert RETRY_AFTER[exceptions.UploadBacklogFull] == 5
async def test_not_member_404_before_everything(
service: AttachmentService,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
) -> None:
_, bob, _ = world
with pytest.raises(exceptions.ChatNotFound):
await _upload(
service,
world,
owner=bob,
media_type="text/plain",
body=_Untouched(),
)
assert database.attachments == {}
async def test_type_415_before_size_413(
service: AttachmentService,
world: tuple[UUID, UUID, UUID],
) -> None:
with pytest.raises(exceptions.UnsupportedMediaType):
await _upload(
service,
world,
media_type="text/plain",
content_length=ATTACHMENT_MAX_BYTES + 1,
body=_Untouched(),
)
async def test_declared_size_413_before_slot(
uow: FakeUnitOfWork,
cache: FakeCache,
storage: FakeObjectStorage,
world: tuple[UUID, UUID, UUID],
) -> None:
slots = _slots()
service = AttachmentService(uow, cache, storage, slots)
async with slots.slot():
# места нет, а отказ всё равно 413: место не ждали
with pytest.raises(exceptions.PayloadTooLarge):
await _upload(
service,
world,
content_length=ATTACHMENT_MAX_BYTES + 1,
body=_Untouched(),
)
async def test_busy_slots_429_without_reading_body(
uow: FakeUnitOfWork,
cache: FakeCache,
storage: FakeObjectStorage,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
) -> None:
slots = _slots()
service = AttachmentService(uow, cache, storage, slots)
async with slots.slot():
with pytest.raises(exceptions.UploadsBusy):
await _upload(service, world, body=_Untouched())
assert database.attachments == {}
async def test_counter_413_interrupt_and_body_timeout(
service: AttachmentService,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
) -> None:
with pytest.raises(exceptions.PayloadTooLarge):
await _upload(
service,
world,
body=_body(b"x" * ATTACHMENT_MAX_BYTES, b"x"),
)
async def interrupted() -> AsyncIterator[bytes]:
yield b"x"
raise exceptions.UploadInterrupted
with pytest.raises(exceptions.UploadInterrupted):
await _upload(service, world, body=interrupted())
async def slow() -> AsyncIterator[bytes]:
yield b"x"
await asyncio.sleep(30)
with pytest.raises(exceptions.UploadTimedOut):
await _upload(service, world, body=slow())
assert database.attachments == {}
@pytest.mark.parametrize(
("data", "media_type"),
[
(b"not an image", "image/png"),
(SAMPLE, "image/jpeg"),
(b"", "image/png"),
],
ids=["content", "mismatch", "empty"],
)
async def test_bad_content_415_no_row(
service: AttachmentService,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
data: bytes,
media_type: str,
) -> None:
with pytest.raises(exceptions.UnsupportedMediaType):
await _upload(
service,
world,
media_type=media_type,
body=_body(data),
)
assert database.attachments == {}
async def test_put_failure_leaves_pending_without_compensation(
service: AttachmentService,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
) -> None:
database.fail_on["storage.put"] = exceptions.ObjectStorageUnavailable()
with pytest.raises(exceptions.ObjectStorageUnavailable):
await _upload(service, world)
row = next(iter(database.attachments.values()))
assert row.status == AttachmentStatus.PENDING
assert "storage.delete" not in database.events
async def test_failure_on_statement_compensates(
service: AttachmentService,
database: FakeDatabase,
storage: FakeObjectStorage,
world: tuple[UUID, UUID, UUID],
) -> None:
"""Сценарий «Компенсация различает исход фиксации»: упало выражение."""
database.fail_on["jobs.insert_job"] = UNAVAILABLE()
with pytest.raises(UNAVAILABLE):
await _upload(service, world)
row = next(iter(database.attachments.values()))
assert row.status == AttachmentStatus.PENDING
assert storage.objects == {}
assert "storage.delete" in database.events
assert database.jobs == {}
async def test_failure_on_commit_keeps_object(
service: AttachmentService,
database: FakeDatabase,
storage: FakeObjectStorage,
world: tuple[UUID, UUID, UUID],
) -> None:
"""Тот же сценарий: упала фиксация, исход неизвестен, объект на месте."""
database.fail_commit = UNAVAILABLE()
# первая фиксация — строка pending
database.commits_before_fail = 1
with pytest.raises(UNAVAILABLE):
await _upload(service, world)
row = next(iter(database.attachments.values()))
assert row.staging_key in storage.objects
assert "storage.delete" not in database.events
async def test_removed_row_compensates_and_503(
uow: FakeUnitOfWork,
cache: FakeCache,
database: FakeDatabase,
storage: FakeObjectStorage,
world: tuple[UUID, UUID, UUID],
) -> None:
"""`mark_queued` → `None`: уборщик пометил строку."""
class Marking(FakeObjectStorage):
async def put(self, key, body, *, size, content_type) -> None:
await super().put(key, body, size=size, content_type=content_type)
row = next(iter(database.attachments.values()))
database.attachments[row.id] = replace(
row,
updated_at=row.created_at.replace(year=2100),
)
marking = Marking(database)
service = AttachmentService(uow, cache, marking, _slots())
with pytest.raises(UNAVAILABLE):
await _upload(service, world)
assert marking.objects == {}
assert database.jobs == {}
assert storage.objects == {}
async def test_compensation_failure_keeps_original_error(
service: AttachmentService,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
) -> None:
database.fail_on["jobs.insert_job"] = UNAVAILABLE("db")
database.fail_on["storage.delete"] = exceptions.ObjectStorageUnavailable()
with pytest.raises(UNAVAILABLE) as error:
await _upload(service, world)
assert not isinstance(error.value, exceptions.ObjectStorageUnavailable)
async def _row(
uow: FakeUnitOfWork,
world: tuple[UUID, UUID, UUID],
*,
status: AttachmentStatus,
):
alice, _, chat_id = world
row = attachment_dto(chat_id=chat_id, owner_id=alice, status=status)
async with uow:
await uow.attachments.insert_attachment(attachment=row)
await uow.commit()
return row
async def test_metadata_hidden_and_variants_only_ready(
service: AttachmentService,
uow: FakeUnitOfWork,
world: tuple[UUID, UUID, UUID],
) -> None:
alice, bob, _ = world
pending = await _row(uow, world, status=AttachmentStatus.PENDING)
queued = await _row(uow, world, status=AttachmentStatus.QUEUED)
ready = await _row(uow, world, status=AttachmentStatus.READY)
variant = variant_dto(attachment_id=ready.id)
async with uow:
await uow.variants.insert_variant(
attachment_id=ready.id,
variant=variant,
)
await uow.variants.insert_variant(
attachment_id=queued.id,
variant=variant_dto(attachment_id=queued.id),
)
await uow.commit()
with pytest.raises(exceptions.AttachmentNotFound):
await service.get_attachment(attachment_id=pending.id, user_id=alice)
with pytest.raises(exceptions.AttachmentNotFound):
await service.get_attachment(attachment_id=uuid4(), user_id=alice)
with pytest.raises(exceptions.AttachmentNotFound):
await service.get_attachment(attachment_id=ready.id, user_id=bob)
shown = await service.get_attachment(attachment_id=ready.id, user_id=alice)
assert shown.variants == (variant,)
waiting = await service.get_attachment(
attachment_id=queued.id,
user_id=alice,
)
assert waiting.variants == ()
async def test_open_content_branches(
service: AttachmentService,
uow: FakeUnitOfWork,
database: FakeDatabase,
storage: FakeObjectStorage,
world: tuple[UUID, UUID, UUID],
) -> None:
alice, _, _ = world
queued = await _row(uow, world, status=AttachmentStatus.QUEUED)
with pytest.raises(exceptions.AttachmentNotReady):
await service.open_content(attachment_id=queued.id, user_id=alice)
ready = await _row(uow, world, status=AttachmentStatus.READY)
# нет варианта
with pytest.raises(exceptions.AttachmentNotFound):
await service.open_content(
attachment_id=ready.id,
user_id=alice,
variant=AttachmentVariantName.CROP,
)
# нет объекта
with pytest.raises(exceptions.AttachmentContentMissing):
await service.open_content(attachment_id=ready.id, user_id=alice)
# другой размер
storage.seed(ready.object_key, b"different size")
with pytest.raises(exceptions.AttachmentContentMissing):
await service.open_content(attachment_id=ready.id, user_id=alice)
# целый объект
storage.seed(ready.object_key, b"content")
content = await service.open_content(attachment_id=ready.id, user_id=alice)
assert b"".join([chunk async for chunk in content.chunks]) == b"content"
await content.close()
# потерянный — 404 без обращения к S3
async with uow:
await uow.attachments.mark_lost(
attachment_id=ready.id,
object_key=ready.object_key,
lost_at=NOW,
)
await uow.commit()
database.events.clear()
with pytest.raises(exceptions.AttachmentNotFound):
await service.open_content(attachment_id=ready.id, user_id=alice)
assert "storage.get" not in database.events
async def test_failed_attachment_metadata_has_code(
service: AttachmentService,
uow: FakeUnitOfWork,
world: tuple[UUID, UUID, UUID],
) -> None:
alice, _, _ = world
row = await _row(uow, world, status=AttachmentStatus.QUEUED)
async with uow:
await uow.attachments.commit_failed(
attachment_id=row.id,
error_code=AttachmentErrorCode.INVALID_IMAGE,
updated_at=NOW,
)
await uow.commit()
shown = await service.get_attachment(attachment_id=row.id, user_id=alice)
assert shown.error_code == AttachmentErrorCode.INVALID_IMAGE
with pytest.raises(exceptions.AttachmentNotReady):
await service.open_content(attachment_id=row.id, user_id=alice)
+222
View File
@@ -0,0 +1,222 @@
"""`ChatService`: кэш после фиксации, откат составной операции, страницы."""
from uuid import UUID, uuid4
import pytest
from builders import chat_dto, user_dto
from fakes import FakeCache, FakeDatabase, FakeUnitOfWork
from src.core import exceptions, services
from src.core.repos import chat_cache
from src.utils.cursor import chat_messages_scope, encode_cursor
pytestmark = pytest.mark.anyio
async def _users(uow: FakeUnitOfWork, count: int = 2) -> list[UUID]:
users = [user_dto() for _ in range(count)]
async with uow:
for user in users:
await uow.users.insert_user(user=user, password_hash="h")
await uow.commit()
return [user.id for user in users]
async def test_create_chat_commits_then_caches(
uow: FakeUnitOfWork,
cache: FakeCache,
database: FakeDatabase,
) -> None:
alice, bob = await _users(uow)
database.events.clear()
chat = await services.ChatService(uow, cache).create_chat(
current_user_id=alice,
title="Team",
member_ids=[alice, bob],
)
assert database.chats[chat.id].member_ids == (alice, bob)
assert database.events.index("commit") < database.events.index("cache.set")
assert database.events.index("exit") < database.events.index("cache.set")
assert await chat_cache.get_chat(cache, chat_id=chat.id) == chat
@pytest.mark.parametrize("case", ["duplicates", "caller_missing"])
async def test_invalid_members_open_no_block(
uow: FakeUnitOfWork,
cache: FakeCache,
database: FakeDatabase,
case: str,
) -> None:
alice, bob = await _users(uow)
database.events.clear()
members = [alice, alice] if case == "duplicates" else [bob]
with pytest.raises(exceptions.InvalidChatMembers):
await services.ChatService(uow, cache).create_chat(
current_user_id=alice,
title="Team",
member_ids=members,
)
assert "enter" not in database.events
async def test_unknown_member_rejected(
uow: FakeUnitOfWork,
cache: FakeCache,
database: FakeDatabase,
) -> None:
alice, _ = await _users(uow)
with pytest.raises(exceptions.InvalidChatMembers):
await services.ChatService(uow, cache).create_chat(
current_user_id=alice,
title="Team",
member_ids=[alice, uuid4()],
)
assert database.chats == {}
async def test_members_failure_rolls_back_chat_and_cache(
uow: FakeUnitOfWork,
cache: FakeCache,
database: FakeDatabase,
) -> None:
alice, bob = await _users(uow)
database.fail_on["chats.insert_chat_members"] = (
exceptions.ServiceUnavailable()
)
with pytest.raises(exceptions.ServiceUnavailable):
await services.ChatService(uow, cache).create_chat(
current_user_id=alice,
title="Team",
member_ids=[alice, bob],
)
assert database.chats == {}
assert cache.values == {}
async def test_commit_failure_leaves_cache_empty(
uow: FakeUnitOfWork,
cache: FakeCache,
database: FakeDatabase,
) -> None:
alice, bob = await _users(uow)
database.fail_commit = exceptions.ServiceUnavailable()
with pytest.raises(exceptions.ServiceUnavailable):
await services.ChatService(uow, cache).create_chat(
current_user_id=alice,
title="Team",
member_ids=[alice, bob],
)
assert database.chats == {}
assert cache.values == {}
async def test_cache_hit_does_not_touch_repo(
uow: FakeUnitOfWork,
cache: FakeCache,
database: FakeDatabase,
) -> None:
member = uuid4()
chat = chat_dto(member_ids=(member,))
await chat_cache.put_chat(cache, chat=chat, ttl_seconds=60)
database.events.clear()
found = await services.ChatService(uow, cache).get_chat_for_member(
chat_id=chat.id,
user_id=member,
)
assert found == chat
assert "chats.get_chat" not in database.events
async def test_cache_miss_reads_and_fills(
uow: FakeUnitOfWork,
cache: FakeCache,
) -> None:
alice, _ = await _users(uow)
chat = chat_dto(member_ids=(alice,))
async with uow:
await uow.chats.insert_chat(chat=chat)
await uow.chats.insert_chat_members(chat=chat)
await uow.commit()
found = await services.ChatService(uow, cache).get_chat_for_member(
chat_id=chat.id,
user_id=alice,
)
assert found == chat
assert await chat_cache.get_chat(cache, chat_id=chat.id) == chat
async def test_outsider_and_missing_are_same_not_found(
uow: FakeUnitOfWork,
cache: FakeCache,
) -> None:
alice, bob = await _users(uow)
chat = chat_dto(member_ids=(alice,))
async with uow:
await uow.chats.insert_chat(chat=chat)
await uow.chats.insert_chat_members(chat=chat)
await uow.commit()
service = services.ChatService(uow, cache)
with pytest.raises(exceptions.ChatNotFound):
await service.get_chat_for_member(chat_id=chat.id, user_id=bob)
absent = uuid4()
with pytest.raises(exceptions.ChatNotFound):
await service.get_chat_for_member(chat_id=absent, user_id=alice)
# отсутствующий чат не кэшируется
assert await chat_cache.get_chat(cache, chat_id=absent) is None
async def test_failed_cache_falls_back_to_database(
uow: FakeUnitOfWork,
cache: FakeCache,
) -> None:
alice, _ = await _users(uow)
chat = chat_dto(member_ids=(alice,))
async with uow:
await uow.chats.insert_chat(chat=chat)
await uow.chats.insert_chat_members(chat=chat)
await uow.commit()
cache.failing = True
found = await services.ChatService(uow, cache).get_chat_for_member(
chat_id=chat.id,
user_id=alice,
)
assert found == chat
async def test_pages_and_foreign_cursor(
uow: FakeUnitOfWork,
cache: FakeCache,
) -> None:
alice, _ = await _users(uow)
service = services.ChatService(uow, cache)
created = [
await service.create_chat(
current_user_id=alice,
title=f"T{index}",
member_ids=[alice],
)
for index in range(3)
]
first = await service.list_user_chats(
user_id=alice,
limit=2,
cursor=None,
)
assert [item.id for item in first.items] == [
chat.id for chat in created[:2]
]
assert first.next_cursor is not None
second = await service.list_user_chats(
user_id=alice,
limit=2,
cursor=first.next_cursor,
)
assert [item.id for item in second.items] == [created[2].id]
assert second.next_cursor is None
foreign = encode_cursor(
scope=chat_messages_scope(uuid4()),
created_at=created[0].created_at,
item_id=created[0].id,
)
with pytest.raises(exceptions.InvalidCursor):
await service.list_user_chats(user_id=alice, limit=2, cursor=foreign)
+310
View File
@@ -0,0 +1,310 @@
"""`MessageService`: один блок на отправку, порядок членство → вложения → ключ."""
from dataclasses import dataclass
from uuid import UUID, uuid4
import pytest
from builders import attachment_dto, chat_dto, user_dto
from fakes import FakeCache, FakeDatabase, FakeUnitOfWork
from src.core import exceptions, services
from src.core.services.message import message_request_hash
from src.schemas.enums import AttachmentErrorCode, AttachmentStatus
pytestmark = pytest.mark.anyio
KEY = "key-1"
@dataclass
class World:
alice: UUID
bob: UUID
chat_id: UUID
@pytest.fixture
async def world(uow: FakeUnitOfWork, database: FakeDatabase) -> World:
alice = user_dto()
bob = user_dto()
chat = chat_dto(member_ids=(alice.id,))
async with uow:
await uow.users.insert_user(user=alice, password_hash="h")
await uow.users.insert_user(user=bob, password_hash="h")
await uow.chats.insert_chat(chat=chat)
await uow.chats.insert_chat_members(chat=chat)
await uow.commit()
database.events.clear()
return World(alice.id, bob.id, chat.id)
@pytest.fixture
def service(uow: FakeUnitOfWork, cache: FakeCache) -> services.MessageService:
return services.MessageService(uow, cache)
async def _attachment(
uow: FakeUnitOfWork,
world: World,
*,
status: AttachmentStatus = AttachmentStatus.READY,
chat_id: UUID | None = None,
) -> UUID:
row = attachment_dto(
chat_id=chat_id or world.chat_id,
owner_id=world.alice,
status=status,
)
async with uow:
await uow.attachments.insert_attachment(attachment=row)
await uow.commit()
return row.id
async def _failed(uow: FakeUnitOfWork, world: World) -> UUID:
attachment_id = await _attachment(
uow,
world,
status=AttachmentStatus.QUEUED,
)
async with uow:
await uow.attachments.commit_failed(
attachment_id=attachment_id,
error_code=AttachmentErrorCode.INVALID_IMAGE,
updated_at=attachment_dto(
chat_id=world.chat_id,
owner_id=world.alice,
).created_at,
)
await uow.commit()
return attachment_id
async def _send(
service: services.MessageService,
world: World,
*,
text: str = "hello",
attachment_ids: tuple[UUID, ...] = (),
sender: UUID | None = None,
):
return await service.send_message(
chat_id=world.chat_id,
sender_id=sender or world.alice,
text=text,
idempotency_key=KEY,
attachment_ids=attachment_ids,
)
async def test_new_message_one_block(
service: services.MessageService,
database: FakeDatabase,
world: World,
) -> None:
message = await _send(service, world)
assert database.messages[message.id].text == "hello"
assert database.events.count("enter") == 1
assert database.events[-2:] == ["commit", "exit"]
assert database.events.index(
"idempotency.claim_key",
) < database.events.index("messages.insert_message")
async def test_replay_same_body_returns_saved(
service: services.MessageService,
database: FakeDatabase,
world: World,
) -> None:
first = await _send(service, world)
database.events.clear()
second = await _send(service, world)
assert second == first
assert len(database.messages) == 1
assert "messages.insert_message" not in database.events
# блокировка строки ключа снимается фиксацией до ответа
assert database.events[-2:] == ["commit", "exit"]
async def test_other_body_conflict_after_commit(
service: services.MessageService,
database: FakeDatabase,
world: World,
) -> None:
await _send(service, world)
database.events.clear()
with pytest.raises(exceptions.IdempotencyConflict):
await _send(service, world, text="other")
assert "commit" in database.events
assert len(database.messages) == 1
async def test_failed_attachment_new_key_rolled_back(
service: services.MessageService,
uow: FakeUnitOfWork,
database: FakeDatabase,
world: World,
) -> None:
failed = await _failed(uow, world)
with pytest.raises(exceptions.AttachmentFailed):
await _send(service, world, attachment_ids=(failed,))
assert database.idempotency == {}
assert database.messages == {}
# ключ свободен: то же тело без вложения проходит
message = await _send(service, world)
assert message.attachment_ids == ()
async def test_failed_attachment_taken_key_is_replay(
service: services.MessageService,
uow: FakeUnitOfWork,
world: World,
) -> None:
attachment_id = await _attachment(
uow,
world,
status=AttachmentStatus.QUEUED,
)
first = await _send(service, world, attachment_ids=(attachment_id,))
async with uow:
await uow.attachments.commit_failed(
attachment_id=attachment_id,
error_code=AttachmentErrorCode.INVALID_IMAGE,
updated_at=first.created_at,
)
await uow.commit()
replay = await _send(service, world, attachment_ids=(attachment_id,))
assert replay == first
@pytest.mark.parametrize("case", ["unknown", "pending", "other_chat"])
async def test_bad_attachment_rejected_before_key(
service: services.MessageService,
uow: FakeUnitOfWork,
database: FakeDatabase,
world: World,
case: str,
) -> None:
attachment_id = uuid4()
if case == "pending":
attachment_id = await _attachment(
uow,
world,
status=AttachmentStatus.PENDING,
)
elif case == "other_chat":
attachment_id = await _attachment(uow, world, chat_id=uuid4())
database.events.clear()
with pytest.raises(exceptions.AttachmentNotFound):
await _send(service, world, attachment_ids=(attachment_id,))
assert "idempotency.claim_key" not in database.events
assert database.idempotency == {}
async def test_attachment_order_kept(
service: services.MessageService,
uow: FakeUnitOfWork,
database: FakeDatabase,
world: World,
) -> None:
ids = tuple(
sorted(
[await _attachment(uow, world) for _ in range(3)],
reverse=True,
),
)
message = await _send(service, world, attachment_ids=ids)
assert message.attachment_ids == ids
assert database.messages[message.id].attachment_ids == ids
async def test_write_failure_leaves_key_free(
service: services.MessageService,
database: FakeDatabase,
world: World,
) -> None:
database.fail_on["messages.insert_message"] = (
exceptions.ServiceUnavailable()
)
with pytest.raises(exceptions.ServiceUnavailable):
await _send(service, world)
assert database.idempotency == {}
database.fail_on.clear()
assert (await _send(service, world)).text == "hello"
async def test_outsider_not_found_before_key(
service: services.MessageService,
database: FakeDatabase,
world: World,
) -> None:
with pytest.raises(exceptions.ChatNotFound):
await _send(service, world, sender=world.bob)
assert "idempotency.claim_key" not in database.events
async def test_pages_outsider_and_foreign_cursor(
service: services.MessageService,
database: FakeDatabase,
world: World,
) -> None:
sent = []
for index in range(3):
sent.append(
await service.send_message(
chat_id=world.chat_id,
sender_id=world.alice,
text=str(index),
idempotency_key=f"key-{index}",
),
)
first = await service.list_messages(
chat_id=world.chat_id,
user_id=world.alice,
limit=2,
cursor=None,
)
assert [item.id for item in first.items] == [item.id for item in sent[:2]]
second = await service.list_messages(
chat_id=world.chat_id,
user_id=world.alice,
limit=2,
cursor=first.next_cursor,
)
assert [item.id for item in second.items] == [sent[2].id]
assert second.next_cursor is None
with pytest.raises(exceptions.ChatNotFound):
await service.list_messages(
chat_id=world.chat_id,
user_id=world.bob,
limit=2,
cursor=None,
)
with pytest.raises(exceptions.InvalidCursor):
await service.list_messages(
chat_id=world.chat_id,
user_id=world.alice,
limit=2,
cursor="not-a-cursor",
)
# чтение — один блок и без фиксации
database.events.clear()
await service.list_messages(
chat_id=world.chat_id,
user_id=world.alice,
limit=2,
cursor=None,
)
assert database.events.count("enter") == 1
assert "commit" not in database.events
def test_request_hash_rules() -> None:
first, second = uuid4(), uuid4()
empty = message_request_hash(text="a")
assert empty == message_request_hash(text="a", attachment_ids=())
assert empty != message_request_hash(text="b")
assert message_request_hash(
text="a",
attachment_ids=(first, second),
) != message_request_hash(text="a", attachment_ids=(second, first))
+18
View File
@@ -0,0 +1,18 @@
"""Набор `repo_contract.py` на фейке; тот же набор на SQL —
`db/test_repo_contract_sql.py`."""
import pytest
from fakes import FakeDatabase, FakeUnitOfWork
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(check, database: FakeDatabase) -> None:
await check(lambda: FakeUnitOfWork(database))
+151
View File
@@ -0,0 +1,151 @@
"""`SessionService`: вход двумя блоками, отказ одинаков, токен и отзыв."""
from datetime import timedelta
import pytest
from builders import user_dto
from fakes import FakeDatabase, FakeUnitOfWork
from src.core import exceptions, services
from src.core.services import session as session_module
from src.core.services.session import hash_token
from src.schemas import dataclasses
from src.utils.utc import utcnow
pytestmark = pytest.mark.anyio
PASSWORD = "password-1234"
@pytest.fixture(autouse=True)
def cheap_kdf(monkeypatch: pytest.MonkeyPatch, database: FakeDatabase) -> None:
async def verify_password(*, password: str, password_hash: str | None):
database.events.append("kdf")
return password_hash == f"hash:{password}"
monkeypatch.setattr(session_module, "verify_password", verify_password)
async def _user(uow: FakeUnitOfWork) -> dataclasses.UserFullDTO:
user = user_dto(username="alice")
async with uow:
await uow.users.insert_user(
user=user,
password_hash=f"hash:{PASSWORD}",
)
await uow.commit()
return user
async def test_login_two_blocks_kdf_outside(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
user = await _user(uow)
database.events.clear()
result = await services.SessionService(uow).login(
username="alice",
password=PASSWORD,
)
assert result.user == user
assert database.events == [
"enter",
"users.get_user_credentials",
"exit",
"kdf",
"enter",
"sessions.insert_session",
"commit",
"exit",
]
stored = next(iter(database.sessions.values()))
assert stored.token_hash == hash_token(result.token)
@pytest.mark.parametrize(
("username", "password"),
[("alice", "wrong-password"), ("unknown", PASSWORD)],
ids=["wrong_password", "unknown_user"],
)
async def test_login_failure_same_and_no_write_block(
uow: FakeUnitOfWork,
database: FakeDatabase,
username: str,
password: str,
) -> None:
await _user(uow)
database.events.clear()
with pytest.raises(exceptions.InvalidCredentials):
await services.SessionService(uow).login(
username=username,
password=password,
)
# неизвестный пользователь тоже проходит KDF, блока записи нет
assert "kdf" in database.events
assert database.events.count("enter") == 1
assert database.sessions == {}
async def test_authenticate_without_token_opens_no_block(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
with pytest.raises(exceptions.Unauthenticated):
await services.SessionService(uow).authenticate(token=None)
assert database.events == []
async def test_authenticate_valid_expired_unknown(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
user = await _user(uow)
service = services.SessionService(uow)
login = await service.login(username="alice", password=PASSWORD)
current = await service.authenticate(token=login.token)
assert current.user == user
with pytest.raises(exceptions.Unauthenticated):
await service.authenticate(token="unknown-token")
# истёкшая сессия
stored = next(iter(database.sessions.values()))
database.sessions[stored.id] = dataclasses.SessionFullDTO(
id=stored.id,
user_id=stored.user_id,
token_hash=stored.token_hash,
created_at=stored.created_at,
expires_at=utcnow() - timedelta(seconds=1),
)
with pytest.raises(exceptions.Unauthenticated):
await service.authenticate(token=login.token)
async def test_revoke_and_second_revoke(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
await _user(uow)
service = services.SessionService(uow)
login = await service.login(username="alice", password=PASSWORD)
current = await service.authenticate(token=login.token)
await service.revoke(session_id=current.id)
assert database.sessions == {}
# параллельный выход уже удалил: не ошибка
await service.revoke(session_id=current.id)
with pytest.raises(exceptions.Unauthenticated):
await service.authenticate(token=login.token)
async def test_database_failure_on_login_propagates(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
await _user(uow)
database.fail_on["sessions.insert_session"] = (
exceptions.ServiceUnavailable()
)
with pytest.raises(exceptions.ServiceUnavailable):
await services.SessionService(uow).login(
username="alice",
password=PASSWORD,
)
assert database.sessions == {}
+28
View File
@@ -0,0 +1,28 @@
"""Значения `[uploads]` (спек `service-configuration`, «Неверный параметр
загрузок»). Сама секция, а не `Settings`: тот читает `.env` и `config.toml`.
"""
import pytest
from pydantic import ValidationError
from src.config.settings import Uploads
@pytest.mark.parametrize(
("field", "value"),
[
("max_concurrent", 0),
("max_waiting", -1),
("max_unfinished_jobs", -1),
("body_timeout_seconds", "abc"),
],
)
def test_wrong_value_names_field(field: str, value: object) -> None:
with pytest.raises(ValidationError) as caught:
Uploads(**{field: value})
assert [error["loc"] for error in caught.value.errors()] == [(field,)]
def test_zero_turns_backlog_limit_off() -> None:
assert Uploads(max_unfinished_jobs=0).max_unfinished_jobs == 0
assert Uploads().max_unfinished_jobs == 250
+161
View File
@@ -0,0 +1,161 @@
"""Спек `unit-of-work`: граница транзакции на фейке, те же правила базового
класса, что у настоящей единицы работы."""
from dataclasses import replace
from datetime import UTC, datetime
from uuid import uuid4
import pytest
from fakes import FakeDatabase, FakeUnitOfWork
from src.core import exceptions
from src.core.ports.uow import UnitOfWorkError
from src.schemas.dataclasses import UserFullDTO
pytestmark = pytest.mark.anyio
NOW = datetime(2026, 1, 1, tzinfo=UTC)
def _user() -> UserFullDTO:
return UserFullDTO(
id=uuid4(),
username=f"u{uuid4().hex[:8]}",
display_name="User",
created_at=NOW,
)
async def _found(database: FakeDatabase, username: str) -> bool:
async with FakeUnitOfWork(database) as other:
found = await other.users.get_user_credentials(username=username)
return found is not None
async def test_exit_without_commit_rolls_back(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
"""Сценарий «Выход без фиксации»."""
user = _user()
async with uow:
await uow.users.insert_user(user=user, password_hash="h")
assert not await _found(database, user.username)
async def test_exception_rolls_back_and_propagates(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
"""Сценарий «Исключение внутри блока»."""
user = _user()
with pytest.raises(exceptions.UsernameTaken):
async with uow:
await uow.users.insert_user(user=user, password_hash="h")
raise exceptions.UsernameTaken
assert not await _found(database, user.username)
async def test_commit_is_visible_to_other_unit(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
"""Сценарий «Фиксация»."""
user = _user()
async with uow:
await uow.users.insert_user(user=user, password_hash="h")
await uow.commit()
assert await _found(database, user.username)
async def test_repo_after_commit_is_an_error(uow: FakeUnitOfWork) -> None:
"""Сценарий «Работа после фиксации»."""
async with uow:
await uow.commit()
with pytest.raises(UnitOfWorkError):
_ = uow.users
async def test_second_commit_is_an_error(uow: FakeUnitOfWork) -> None:
async with uow:
await uow.commit()
with pytest.raises(UnitOfWorkError):
await uow.commit()
async def test_nested_block_is_an_error(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
"""Сценарий «Вложенный блок»: второго блока нет."""
with pytest.raises(UnitOfWorkError):
async with uow, uow:
pass
assert database.events.count("enter") == 1
async def test_repo_outside_block_is_an_error(uow: FakeUnitOfWork) -> None:
"""Сценарий «Repo вне блока»: и до входа, и после выхода."""
with pytest.raises(UnitOfWorkError):
_ = uow.users
async with uow:
pass
with pytest.raises(UnitOfWorkError):
_ = uow.users
async def test_commit_outside_block_is_an_error(uow: FakeUnitOfWork) -> None:
with pytest.raises(UnitOfWorkError):
await uow.commit()
async def test_failed_commit_ends_block_and_rolls_back(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
user = _user()
database.fail_commit = exceptions.ServiceUnavailable()
with pytest.raises(exceptions.ServiceUnavailable):
async with uow:
await uow.users.insert_user(user=user, password_hash="h")
await uow.commit()
assert not await _found(database, user.username)
async def test_block_can_reopen_and_counts_entries(
uow: FakeUnitOfWork,
) -> None:
async with uow:
pass
async with uow:
await uow.commit()
assert uow.blocks_opened == 2
async def test_rollback_restores_and_ends_block(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
user = _user()
async with uow:
await uow.users.insert_user(user=user, password_hash="h")
await uow.rollback()
with pytest.raises(UnitOfWorkError):
_ = uow.users
assert not await _found(database, user.username)
async def test_snapshot_returns_previous_row(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
"""Откат возвращает снимок, а не только убирает новое."""
user = _user()
async with uow:
await uow.users.insert_user(user=user, password_hash="h")
await uow.commit()
database.users[user.id] = user
before = database.users[user.id]
async with uow:
database.users[user.id] = replace(user, display_name="Changed")
assert database.users[user.id] == before
+60
View File
@@ -0,0 +1,60 @@
"""`UserService`: KDF вне блока, занятый username."""
import pytest
from fakes import FakeDatabase, FakeUnitOfWork
from src.core import exceptions, services
from src.core.services import user as user_module
pytestmark = pytest.mark.anyio
@pytest.fixture(autouse=True)
def cheap_kdf(monkeypatch: pytest.MonkeyPatch, database: FakeDatabase) -> None:
async def hash_password(password: str) -> str:
database.events.append("kdf")
return f"hash:{password}"
monkeypatch.setattr(user_module, "hash_password", hash_password)
async def test_register_stores_user_outside_kdf(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
created = await services.UserService(uow).register(
username="alice",
display_name="Alice",
password="password-1234",
)
assert database.users[created.id] == created
assert database.credentials["alice"].password_hash == "hash:password-1234"
# KDF до блока, соединение не занято
assert database.events[0] == "kdf"
assert database.events[1:] == [
"enter",
"users.insert_user",
"commit",
"exit",
]
async def test_taken_username_rejected_without_commit(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
service = services.UserService(uow)
await service.register(
username="alice",
display_name="Alice",
password="password-1234",
)
database.events.clear()
with pytest.raises(exceptions.UsernameTaken):
await service.register(
username="alice",
display_name="Other",
password="password-5678",
)
assert "commit" not in database.events
assert len(database.users) == 1
@@ -0,0 +1,146 @@
"""Сценарий «Одновременные доставки»: сервис и единица работы на доставку.
Импорт `src.worker.main` не открывает соединений: клиентов создаёт `run()`, а
здесь только `service_factory` и `_handle` на фейках. Единица работы подменена
фейком там, где точка входа выбирает реализацию.
"""
import asyncio
from dataclasses import dataclass, field
import pytest
from builders import attachment_dto, chat_dto, job_dto, user_dto
from fakes import (
FakeDatabase,
FakeImageRenderer,
FakeObjectStorage,
FakeUnitOfWork,
)
from src.core.ports.uow import Repositories
from src.schemas import dataclasses
from src.schemas.enums import AttachmentStatus, AttachmentVariantName
from src.schemas.jobs import build_job_body
from src.utils.utc import utcnow
from src.worker import main as worker_main
pytestmark = pytest.mark.anyio
SOURCE = b"source-bytes"
class _YieldingUnitOfWork(FakeUnitOfWork):
"""Уступает цикл внутри блока, как настоящая единица работы на обмене с
PostgreSQL: вторая задача на том же экземпляре попадает в открытый блок."""
async def _open(self) -> Repositories:
repositories = await super()._open()
await asyncio.sleep(0)
return repositories
@dataclass
class _Delivery:
"""Сообщение брокера: итог — какой метод подтверждения вызван."""
body: bytes
redelivered: bool = False
settled: list[str] = field(default_factory=list)
async def ack(self) -> None:
self.settled.append("ack")
async def drop(self) -> None:
self.settled.append("drop")
async def requeue(self) -> None:
self.settled.append("requeue")
def _rendered() -> dataclasses.RenderedVariantsDTO:
return dataclasses.RenderedVariantsDTO(
variants=tuple(
dataclasses.RenderedVariantDTO(
name=name,
content_type="image/jpeg",
width=10,
height=10,
data=name.value.encode(),
)
for name in AttachmentVariantName
),
peak_kib=100,
memory_limit_applied=True,
render_ms=5,
)
async def _queued_job(
database: FakeDatabase,
storage: FakeObjectStorage,
) -> dataclasses.AttachmentJobDTO:
owner = user_dto()
chat = chat_dto(member_ids=(owner.id,))
now = utcnow()
row = attachment_dto(
chat_id=chat.id,
owner_id=owner.id,
status=AttachmentStatus.QUEUED,
created_at=now,
data=SOURCE,
)
job = job_dto(attachment_id=row.id, created_at=now)
uow = FakeUnitOfWork(database)
async with uow:
await uow.attachments.insert_attachment(attachment=row)
await uow.jobs.insert_job(job=job)
await uow.commit()
storage.seed(row.staging_key, SOURCE)
return job
async def test_concurrent_deliveries_have_own_unit_of_work(
database: FakeDatabase,
storage: FakeObjectStorage,
monkeypatch: pytest.MonkeyPatch,
) -> None:
created: list[FakeUnitOfWork] = []
def make_uow(
_factory: object,
*,
timeout_seconds: float,
) -> FakeUnitOfWork:
created.append(_YieldingUnitOfWork(database))
return created[-1]
monkeypatch.setattr(worker_main, "SqlAlchemyUnitOfWork", make_uow)
stop = asyncio.Event()
make_service = worker_main.service_factory(
object(),
storage=storage,
renderer=FakeImageRenderer(database, _rendered()),
stop=stop,
)
jobs = [await _queued_job(database, storage) for _ in range(2)]
database.events.clear()
deliveries = [
_Delivery(body=build_job_body(job, attempt=job.attempt + 1))
for job in jobs
]
slots = asyncio.Semaphore(2)
await asyncio.gather(
*(
worker_main._handle(make_service, delivery, slots, stop)
for delivery in deliveries
),
)
assert [delivery.settled for delivery in deliveries] == [["ack"], ["ack"]]
assert len(created) == 2
# вторая доставка вошла в свой блок, пока открыт блок первой
assert database.events[:2] == ["enter", "enter"]
for job in jobs:
attachment = database.attachments[job.attachment_id]
assert attachment.status == AttachmentStatus.READY