feat: перенос 5 лабы логики

This commit is contained in:
Enterxx2
2026-11-10 13:48:00 +03:00
parent 470d9d6f1e
commit 60a71dc839
182 changed files with 14717 additions and 8 deletions
+12
View File
@@ -0,0 +1,12 @@
"""
Unit-тесты слоя сервисов без стенда: зависимости заменены фейками интерфейсов.
Конфигурация берётся из .env.example; сеть, PostgreSQL и S3 не нужны.
"""
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
os.environ["ENV_FILE"] = str(ROOT / ".env.example")
sys.path.insert(0, str(ROOT / "src"))
+243
View File
@@ -0,0 +1,243 @@
"""
In-memory реализации интерфейсов с внедрением отказов.
fail — имена методов, которые бросают UnavailableError (как репозитории
при недоступной БД/S3); hang — методы, которые зависают.
"""
import asyncio
import io
from collections.abc import AsyncIterator
from datetime import UTC, datetime, timedelta
from typing import BinaryIO
from uuid import UUID, uuid4
from domain import (
AttachmentSchema,
AttachmentStatus,
ChatSchema,
NewAttachmentSchema,
PageKey,
StoredAttachmentSchema,
UnfinishedUploadSchema,
)
from domain.errors import UnavailableError
from interfaces import AttachmentRepository, ChatRepository, ObjectStorage, StoredObject
HANG_SEC = 3600
class FaultInjection:
def __init__(self) -> None:
self.fail: set[str] = set()
self.hang: set[str] = set()
self.calls: list[str] = []
async def _enter(self, name: str) -> None:
self.calls.append(name)
if name in self.hang:
await asyncio.sleep(HANG_SEC)
if name in self.fail:
raise UnavailableError()
class FakeChatRepository(ChatRepository):
"""Пользователь — участник любого чата, кроме перечисленных в foreign"""
def __init__(self) -> None:
self.foreign: set[UUID] = set()
async def create(
self, title: str, created_by: UUID, member_ids: list[UUID]
) -> ChatSchema:
raise NotImplementedError
async def get_for_member(self, chat_id: UUID, member_id: UUID) -> ChatSchema | None:
if chat_id in self.foreign:
return None
return ChatSchema(
id=chat_id,
title="chat",
member_ids=[member_id],
created_at=datetime.now(UTC),
)
async def list_for_member(
self, member_id: UUID, after: PageKey | None, limit: int
) -> list[ChatSchema]:
raise NotImplementedError
class FakeAttachmentRepository(FaultInjection, AttachmentRepository):
def __init__(self) -> None:
super().__init__()
self.rows: dict[UUID, dict] = {}
self.ready_returns_none = False
def add_row(
self, object_key: str, status: AttachmentStatus, age_seconds: float
) -> UUID:
attachment_id = uuid4()
self.rows[attachment_id] = {
"status": status,
"object_key": object_key,
"created_at": datetime.now(UTC) - timedelta(seconds=age_seconds),
"new": None,
}
return attachment_id
async def create_pending(self, attachment: NewAttachmentSchema) -> UUID:
await self._enter("create_pending")
attachment_id = self.add_row(
"staging/" + attachment.object_key, AttachmentStatus.PENDING, 0
)
self.rows[attachment_id]["new"] = attachment
return attachment_id
async def mark_queued(
self, attachment_id: UUID, grace_seconds: int
) -> AttachmentSchema | None:
await self._enter("mark_queued")
row = self.rows.get(attachment_id)
if (
self.ready_returns_none
or row is None
or row["status"] != AttachmentStatus.PENDING
):
return None
if row["created_at"] <= datetime.now(UTC) - timedelta(seconds=grace_seconds):
return None
row["status"] = AttachmentStatus.QUEUED
new: NewAttachmentSchema = row["new"]
return AttachmentSchema(
id=attachment_id,
status="queued",
chat_id=new.chat_id,
owner_id=new.owner_id,
filename=new.filename,
content_type=new.content_type,
size_bytes=new.size_bytes,
sha256=new.sha256.hex(),
created_at=row["created_at"],
updated_at=datetime.now(UTC),
)
async def claim_pending(self, attachment_id: UUID) -> UnfinishedUploadSchema | None:
await self._enter("claim_pending")
row = self.rows.get(attachment_id)
if row is None or row["status"] != AttachmentStatus.PENDING:
return None
row["status"] = AttachmentStatus.DELETING
return UnfinishedUploadSchema(id=attachment_id, object_key=row["object_key"])
def _unfinished(self, grace_seconds: int) -> list[UUID]:
threshold = datetime.now(UTC) - timedelta(seconds=grace_seconds)
return [
attachment_id
for attachment_id, row in self.rows.items()
if row["status"] == AttachmentStatus.DELETING
or (
row["status"] == AttachmentStatus.PENDING
and row["created_at"] < threshold
)
]
async def claim_unfinished(
self, grace_seconds: int, limit: int
) -> list[UnfinishedUploadSchema]:
await self._enter("claim_unfinished")
# Повторный вызов в том же проходе не должен возвращать те же строки
claimed = [
attachment_id
for attachment_id in self._unfinished(grace_seconds)
if not self.rows[attachment_id].get("claimed_now")
][:limit]
for attachment_id in claimed:
self.rows[attachment_id]["status"] = AttachmentStatus.DELETING
self.rows[attachment_id]["claimed_now"] = True
return [
UnfinishedUploadSchema(id=i, object_key=self.rows[i]["object_key"])
for i in claimed
]
async def list_unfinished(
self, grace_seconds: int, limit: int
) -> list[UnfinishedUploadSchema]:
await self._enter("list_unfinished")
return [
UnfinishedUploadSchema(id=i, object_key=self.rows[i]["object_key"])
for i in self._unfinished(grace_seconds)[:limit]
]
async def delete_claimed(self, attachment_ids: list[UUID]) -> int:
await self._enter("delete_claimed")
deleted = [
i
for i in attachment_ids
if i in self.rows and self.rows[i]["status"] == AttachmentStatus.DELETING
]
for attachment_id in deleted:
del self.rows[attachment_id]
return len(deleted)
async def get_for_member(
self, attachment_id: UUID, member_id: UUID
) -> StoredAttachmentSchema | None:
raise NotImplementedError
async def find_known_keys(self, object_keys: list[str]) -> set[str]:
await self._enter("find_known_keys")
known = {row["object_key"] for row in self.rows.values()}
return {key for key in object_keys if key in known}
def statuses(self) -> list[str]:
return sorted(row["status"] for row in self.rows.values())
class FakeStoredObject(StoredObject):
def __init__(self, data: bytes) -> None:
self._data = data
self.content_length = len(data)
async def iter_chunks(self) -> AsyncIterator[bytes]:
yield self._data
async def close(self) -> None:
pass
class FakeObjectStorage(FaultInjection, ObjectStorage):
def __init__(self) -> None:
super().__init__()
self.objects: dict[str, tuple[bytes, datetime]] = {}
def add_object(self, key: str, age_seconds: float) -> None:
self.objects[key] = (b"x", datetime.now(UTC) - timedelta(seconds=age_seconds))
async def put(
self, key: str, body: BinaryIO, size: int, content_type: str, sha256: bytes
) -> None:
# Как S3: объект появляется до того, как вызывающий получит ответ
self.objects[key] = (body.read(), datetime.now(UTC))
await self._enter("put")
async def open(self, key: str) -> StoredObject | None:
await self._enter("open")
stored = self.objects.get(key)
return FakeStoredObject(stored[0]) if stored else None
async def delete(self, key: str) -> None:
await self._enter("delete")
self.objects.pop(key, None)
async def list_objects(self, prefix: str) -> AsyncIterator[tuple[str, datetime]]:
await self._enter("list_objects")
for key, (_, modified_at) in list(self.objects.items()):
if key.startswith(prefix):
yield key, modified_at
async def chunks_of(data: bytes, size: int = 64 * 1024) -> AsyncIterator[bytes]:
stream = io.BytesIO(data)
while chunk := stream.read(size):
yield chunk
@@ -0,0 +1,267 @@
"""
Согласованность S3 и БД при загрузке: любой отказ после записи строки
не оставляет неучтённых объектов — компенсация сразу или janitor позже.
"""
import asyncio
import hashlib
import io
from collections.abc import AsyncIterator
from datetime import UTC, datetime
from uuid import uuid4
import pytest
from fakes import (
FakeAttachmentRepository,
FakeChatRepository,
FakeObjectStorage,
chunks_of,
)
from PIL import Image
from domain import (
AttachmentStatus,
AttachmentVariant,
StoredAttachmentSchema,
UserSchema,
)
from domain.errors import (
InvalidRequestError,
NotFoundError,
PayloadTooLargeError,
UnavailableError,
UnsupportedMediaTypeError,
)
from infrastructure.media import ImageInspector
from infrastructure.services import AttachmentService, StorageReconciler
MAX_BYTES = 1024 * 1024
GRACE_SECONDS = 900
USER = UserSchema(
id=uuid4(), username="alice", display_name="Алиса", created_at=datetime.now(UTC)
)
def png(width: int = 8, height: int = 8) -> bytes:
buffer = io.BytesIO()
Image.new("RGB", (width, height), (1, 2, 3)).save(buffer, "PNG")
return buffer.getvalue()
class Stand:
"""Сервис с фейками; inspector настоящий"""
def __init__(self, store_timeout: float = 5) -> None:
self.chats = FakeChatRepository()
self.attachments = FakeAttachmentRepository()
self.storage = FakeObjectStorage()
self.inspector = ImageInspector(workers=1, max_pixels=1_000_000)
self.service = AttachmentService(
self.chats,
self.attachments,
self.storage,
self.inspector,
max_upload_bytes=MAX_BYTES,
spool_memory_bytes=1024,
store_timeout_seconds=store_timeout,
pending_grace_seconds=GRACE_SECONDS,
)
async def upload(self, data: bytes | None = None, content_type: str = "image/png"):
data = data if data is not None else png()
return await self.service.upload(
USER, uuid4(), "a.png", content_type, len(data), chunks_of(data, 100)
)
async def reconcile(self, grace_seconds: int = GRACE_SECONDS):
reconciler = StorageReconciler(self.attachments, self.storage, grace_seconds)
return await reconciler.run_once()
def run(coro):
return asyncio.run(coro)
def test_success_stores_staging_and_queued_row() -> None:
stand = Stand()
data = png()
attachment = run(stand.upload(data))
assert attachment.sha256 == hashlib.sha256(data).hexdigest()
assert stand.attachments.statuses() == [AttachmentStatus.QUEUED]
[(stored, _)] = stand.storage.objects.values()
assert stored == data
[key] = stand.storage.objects
assert key.startswith("staging/originals/") and "a.png" not in key
# Строка записана до PUT, подтверждена после
assert stand.attachments.calls[:2] == ["create_pending", "mark_queued"]
def test_s3_failure_after_write_is_compensated() -> None:
"""PUT дошёл до S3, но ответ — ошибка: объект удаляется, строка тоже"""
stand = Stand()
stand.storage.fail.add("put")
with pytest.raises(UnavailableError):
run(stand.upload())
assert stand.storage.objects == {}
assert stand.attachments.rows == {}
def test_db_failure_between_s3_and_commit_is_compensated() -> None:
"""Объект записан в S3, подтверждение в БД не прошло"""
stand = Stand()
stand.attachments.fail.add("mark_queued")
with pytest.raises(UnavailableError):
run(stand.upload())
assert stand.storage.objects == {}
assert stand.attachments.rows == {}
def test_db_down_leaves_pending_row_that_janitor_cleans() -> None:
"""
БД пропала после PUT: ни подтвердить, ни компенсировать. Объект учтён
строкой pending; janitor после grace period удаляет и объект, и строку.
"""
stand = Stand()
stand.attachments.fail.update({"mark_queued", "claim_pending"})
with pytest.raises(UnavailableError):
run(stand.upload())
assert len(stand.storage.objects) == 1
assert stand.attachments.statuses() == [AttachmentStatus.PENDING]
stand.attachments.fail.clear()
fresh = run(stand.reconcile(GRACE_SECONDS))
assert fresh.unfinished_claimed == 0, "свежая загрузка не трогается"
assert len(stand.storage.objects) == 1
report = run(stand.reconcile(grace_seconds=0))
assert report.unfinished_objects_deleted == report.unfinished_rows_deleted == 1
assert stand.storage.objects == {} and stand.attachments.rows == {}
def test_s3_down_during_compensation_leaves_deleting_row_for_janitor() -> None:
stand = Stand()
stand.attachments.fail.add("mark_queued")
stand.storage.fail.add("delete")
with pytest.raises(UnavailableError):
run(stand.upload())
assert stand.attachments.statuses() == [AttachmentStatus.DELETING]
assert len(stand.storage.objects) == 1
stand.storage.fail.clear()
# deleting очищается независимо от возраста
report = run(stand.reconcile(GRACE_SECONDS))
assert report.unfinished_rows_deleted == 1
assert stand.storage.objects == {} and stand.attachments.rows == {}
def test_store_timeout_is_compensated() -> None:
stand = Stand(store_timeout=0.2)
stand.storage.hang.add("put")
with pytest.raises(UnavailableError):
run(stand.upload())
assert stand.storage.objects == {} and stand.attachments.rows == {}
def test_cancelled_upload_is_compensated() -> None:
"""Остановка реплики посреди PUT: задача отменяется, компенсация выполняется"""
stand = Stand()
stand.storage.hang.add("put")
async def scenario() -> None:
task = asyncio.create_task(stand.upload())
while "put" not in stand.storage.calls:
await asyncio.sleep(0.01)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
run(scenario())
assert stand.storage.objects == {} and stand.attachments.rows == {}
def test_upload_claimed_by_janitor_is_not_confirmed() -> None:
stand = Stand()
stand.attachments.ready_returns_none = True
with pytest.raises(UnavailableError):
run(stand.upload())
assert stand.storage.objects == {} and stand.attachments.rows == {}
def test_validation_errors_store_nothing() -> None:
stand = Stand()
cases = [
(png(), "image/jpeg", UnsupportedMediaTypeError),
(b"not an image", "image/png", UnsupportedMediaTypeError),
(png()[:40], "image/png", UnsupportedMediaTypeError),
(png(2000, 1000), "image/png", PayloadTooLargeError),
(b"", "image/png", InvalidRequestError),
]
for data, content_type, error in cases:
with pytest.raises(error):
run(stand.upload(data, content_type))
assert stand.storage.objects == {} and stand.attachments.rows == {}
assert "create_pending" not in stand.attachments.calls
def test_declared_length_over_limit_is_rejected_without_reading() -> None:
stand = Stand()
consumed = []
async def body() -> AsyncIterator[bytes]:
consumed.append(True)
yield b"x"
with pytest.raises(PayloadTooLargeError):
run(
stand.service.upload(
USER, uuid4(), "a.png", "image/png", MAX_BYTES + 1, body()
)
)
assert consumed == []
def test_streamed_body_over_limit_stops_reading() -> None:
"""Без Content-Length чтение обрывается на первом байте сверх лимита"""
stand = Stand()
chunks_read = 0
async def endless() -> AsyncIterator[bytes]:
nonlocal chunks_read
while True:
chunks_read += 1
yield b"\x00" * 64 * 1024
with pytest.raises(PayloadTooLargeError):
run(stand.service.upload(USER, uuid4(), "a.png", "image/png", None, endless()))
assert chunks_read == MAX_BYTES // (64 * 1024) + 1
def test_foreign_chat_is_404_before_reading_body() -> None:
stand = Stand()
chat_id = uuid4()
stand.chats.foreign.add(chat_id)
with pytest.raises(NotFoundError):
run(
stand.service.upload(
USER, chat_id, "a.png", "image/png", 10, chunks_of(b"")
)
)
def test_missing_variant_is_404() -> None:
stand = Stand()
attachment = run(stand.upload()).model_copy(update={"status": "ready"})
async def get_for_member(attachment_id, member_id):
[key] = stand.storage.objects
return StoredAttachmentSchema(attachment=attachment, object_key=key)
stand.attachments.get_for_member = get_for_member
_, content = run(
stand.service.open_content(USER, attachment.id, AttachmentVariant.ORIGINAL)
)
assert content.content_length == attachment.size_bytes
with pytest.raises(NotFoundError):
run(
stand.service.open_content(USER, attachment.id, AttachmentVariant.THUMBNAIL)
)
+71
View File
@@ -0,0 +1,71 @@
"""Восстановление после обрыва AMQP при объявлении топологии"""
import asyncio
from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import AsyncMock
from uuid import uuid4
import pytest
from aiormq import spec
import infrastructure.broker.rabbit as rabbit_module
from domain.jobs import JobMessageSchema
from infrastructure.broker import RabbitBrokerManager
def connection(fail_bind: bool):
bound = False
async def bind(*args, **kwargs):
nonlocal bound
if fail_bind:
raise ConnectionError("connection lost during queue.bind")
bound = True
async def publish(*args, **kwargs):
if not bound:
raise ConnectionError("mandatory message was unroutable")
return spec.Basic.Ack()
exchange = SimpleNamespace(publish=AsyncMock(side_effect=publish))
queue = SimpleNamespace(bind=AsyncMock(side_effect=bind))
channel = SimpleNamespace(
set_qos=AsyncMock(),
declare_exchange=AsyncMock(return_value=exchange),
declare_queue=AsyncMock(return_value=queue),
)
return SimpleNamespace(
channel=AsyncMock(return_value=channel), ready=AsyncMock(), close=AsyncMock()
)
@pytest.mark.parametrize("reopen", [False, True])
def test_publish_recovers_after_connection_loss_during_binding(
tmp_path, monkeypatch, reopen
):
url_file = tmp_path / "broker_url"
url_file.write_text("amqp://synthetic")
first, second = connection(True), connection(False)
connections = ([connection(False)] if reopen else []) + [first, second]
connect = AsyncMock(side_effect=connections)
monkeypatch.setattr(rabbit_module.aio_pika, "connect_robust", connect)
message = JobMessageSchema(
job_id=uuid4(), attachment_id=uuid4(), attempt=1, created_at=datetime.now(UTC)
)
async def run():
broker = RabbitBrokerManager(url_file, 2)
try:
if reopen:
await broker.publish(message)
await broker.close()
with pytest.raises(ConnectionError, match="queue.bind"):
await broker.publish(message)
await broker.publish(message)
assert connect.await_count == (3 if reopen else 2)
first.close.assert_awaited_once()
finally:
await broker.close()
asyncio.run(run())
@@ -0,0 +1,62 @@
"""Проверка границ worker: checksum и остановка зависшего декодера"""
import asyncio
import hashlib
import os
from datetime import UTC, datetime
from uuid import uuid4
import pytest
from fakes import FakeObjectStorage
import infrastructure.services.image_pipeline.pipeline as pipeline_module
from domain.jobs import ClaimedJobSchema, JobMessageSchema, ProcessingError
from infrastructure.services.image_pipeline import ImagePipeline
def stand(data=b"source", checksum=None):
storage = FakeObjectStorage()
storage.objects["staging/source"] = (data, datetime.now(UTC))
job = ClaimedJobSchema(
message=JobMessageSchema(
job_id=uuid4(),
attachment_id=uuid4(),
attempt=1,
created_at=datetime.now(UTC),
),
lease_token=uuid4(),
object_key="originals/final",
staging_key="staging/source",
size_bytes=len(data),
sha256=checksum or hashlib.sha256(data).hexdigest(),
content_type="image/png",
)
return ImagePipeline(None, storage, 1024, 40000000, 768, 60), storage, job
def test_checksum_mismatch_cannot_publish_original():
pipeline, storage, job = stand(checksum="0" * 64)
with pytest.raises(ProcessingError, match="checksum_mismatch"):
asyncio.run(pipeline.process(job))
assert set(storage.objects) == {"staging/source"}
def test_timeout_kills_child_and_leaves_no_effect(tmp_path, monkeypatch):
pid_file = tmp_path / "pid"
decoder = tmp_path / "decoder.py"
decoder.write_text(
f"import os, time\nfrom pathlib import Path\nPath({str(pid_file)!r}).write_text(str(os.getpid()))\ntime.sleep(30)\n"
)
monkeypatch.setattr(pipeline_module, "TRANSFORM_SCRIPT", decoder)
pipeline, storage, job = stand()
async def run():
async with asyncio.timeout(0.5):
await pipeline.process(job)
with pytest.raises(TimeoutError):
asyncio.run(run())
pid = int(pid_file.read_text())
with pytest.raises(ProcessLookupError):
os.kill(pid, 0)
assert set(storage.objects) == {"staging/source"}
@@ -0,0 +1,96 @@
"""
Janitor: незавершённые загрузки и сироты удаляются только после grace period;
готовые и свежие вложения не трогаются; dry-run ничего не меняет.
"""
import asyncio
import pytest
from fakes import FakeAttachmentRepository, FakeObjectStorage
from domain import AttachmentStatus
from domain.errors import UnavailableError
from infrastructure.services import StorageReconciler
GRACE = 600
OLD = 3600
FRESH = 1
def build() -> tuple[FakeAttachmentRepository, FakeObjectStorage]:
rows, storage = FakeAttachmentRepository(), FakeObjectStorage()
cases = {
"originals/ready-old": (AttachmentStatus.READY, OLD),
"originals/ready-fresh": (AttachmentStatus.READY, FRESH),
"originals/pending-old": (AttachmentStatus.PENDING, OLD),
"originals/pending-fresh": (AttachmentStatus.PENDING, FRESH),
"originals/deleting-fresh": (AttachmentStatus.DELETING, FRESH),
}
for key, (status, age) in cases.items():
rows.add_row(key, status, age)
storage.add_object(key, age)
# pending без объекта: процесс упал до PUT
rows.add_row("originals/pending-no-object", AttachmentStatus.PENDING, OLD)
storage.add_object("originals/orphan-old", OLD)
storage.add_object("originals/orphan-fresh", FRESH)
storage.add_object("other/not-ours", OLD)
return rows, storage
def run(rows, storage, dry_run: bool = False):
return asyncio.run(StorageReconciler(rows, storage, GRACE).run_once(dry_run))
def test_reconcile_removes_only_stale_unaccounted_data() -> None:
rows, storage = build()
report = run(rows, storage)
assert sorted(storage.objects) == [
"originals/orphan-fresh",
"originals/pending-fresh",
"originals/ready-fresh",
"originals/ready-old",
"other/not-ours",
]
assert sorted(row["object_key"] for row in rows.rows.values()) == [
"originals/pending-fresh",
"originals/ready-fresh",
"originals/ready-old",
]
assert report.unfinished_claimed == 3
assert report.unfinished_rows_deleted == 3
assert report.orphan_objects_found == report.orphan_objects_deleted == 1
def test_dry_run_changes_nothing() -> None:
rows, storage = build()
before_rows = {k: dict(v) for k, v in rows.rows.items()}
before_objects = dict(storage.objects)
report = run(rows, storage, dry_run=True)
assert rows.rows == before_rows and storage.objects == before_objects
assert report.unfinished_claimed == 3 and report.orphan_objects_found == 1
assert report.orphan_objects_deleted == 0
def test_second_run_is_noop() -> None:
rows, storage = build()
run(rows, storage)
report = run(rows, storage)
assert report.unfinished_claimed == 0 and report.orphan_objects_found == 0
def test_interrupted_cleanup_is_resumed() -> None:
"""S3 упал после claim: строки остаются deleting и дочищаются в следующий раз"""
rows, storage = build()
storage.fail.add("delete")
with pytest.raises(UnavailableError):
run(rows, storage)
assert AttachmentStatus.PENDING not in [
row["status"] for row in rows.rows.values() if "old" in row["object_key"]
]
storage.fail.clear()
for row in rows.rows.values():
row.pop("claimed_now", None)
run(rows, storage)
assert not any("old" in key and "ready" not in key for key in storage.objects)
assert all(row["status"] != AttachmentStatus.DELETING for row in rows.rows.values())