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
+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