forked from mtusi2026/mtusi2026lab5
feat: крролик, по тщ 5 лаба
This commit is contained in:
+36
-12
@@ -47,14 +47,19 @@ class FakeChatRepository(ChatRepository):
|
||||
def __init__(self) -> None:
|
||||
self.foreign: set[UUID] = set()
|
||||
|
||||
async def create(self, title: str, created_by: UUID, member_ids: list[UUID]) -> ChatSchema:
|
||||
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)
|
||||
id=chat_id,
|
||||
title="chat",
|
||||
member_ids=[member_id],
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
|
||||
async def list_for_member(
|
||||
@@ -69,7 +74,9 @@ class FakeAttachmentRepository(FaultInjection, AttachmentRepository):
|
||||
self.rows: dict[UUID, dict] = {}
|
||||
self.ready_returns_none = False
|
||||
|
||||
def add_row(self, object_key: str, status: AttachmentStatus, age_seconds: float) -> UUID:
|
||||
def add_row(
|
||||
self, object_key: str, status: AttachmentStatus, age_seconds: float
|
||||
) -> UUID:
|
||||
attachment_id = uuid4()
|
||||
self.rows[attachment_id] = {
|
||||
"status": status,
|
||||
@@ -81,21 +88,30 @@ class FakeAttachmentRepository(FaultInjection, AttachmentRepository):
|
||||
|
||||
async def create_pending(self, attachment: NewAttachmentSchema) -> UUID:
|
||||
await self._enter("create_pending")
|
||||
attachment_id = self.add_row(attachment.object_key, AttachmentStatus.PENDING, 0)
|
||||
attachment_id = self.add_row(
|
||||
"staging/" + attachment.object_key, AttachmentStatus.PENDING, 0
|
||||
)
|
||||
self.rows[attachment_id]["new"] = attachment
|
||||
return attachment_id
|
||||
|
||||
async def mark_ready(self, attachment_id: UUID, grace_seconds: int) -> AttachmentSchema | None:
|
||||
await self._enter("mark_ready")
|
||||
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:
|
||||
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.READY
|
||||
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,
|
||||
@@ -120,10 +136,15 @@ class FakeAttachmentRepository(FaultInjection, AttachmentRepository):
|
||||
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)
|
||||
or (
|
||||
row["status"] == AttachmentStatus.PENDING
|
||||
and row["created_at"] < threshold
|
||||
)
|
||||
]
|
||||
|
||||
async def claim_unfinished(self, grace_seconds: int, limit: int) -> list[UnfinishedUploadSchema]:
|
||||
async def claim_unfinished(
|
||||
self, grace_seconds: int, limit: int
|
||||
) -> list[UnfinishedUploadSchema]:
|
||||
await self._enter("claim_unfinished")
|
||||
# Повторный вызов в том же проходе не должен возвращать те же строки
|
||||
claimed = [
|
||||
@@ -135,10 +156,13 @@ class FakeAttachmentRepository(FaultInjection, AttachmentRepository):
|
||||
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
|
||||
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]:
|
||||
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"])
|
||||
|
||||
@@ -82,18 +82,18 @@ def run(coro):
|
||||
return asyncio.run(coro)
|
||||
|
||||
|
||||
def test_success_stores_object_and_ready_row() -> None:
|
||||
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.READY]
|
||||
assert stand.attachments.statuses() == [AttachmentStatus.QUEUED]
|
||||
[(stored, _)] = stand.storage.objects.values()
|
||||
assert stored == data
|
||||
[key] = stand.storage.objects
|
||||
assert key.startswith("originals/") and "a.png" not in key
|
||||
assert key.startswith("staging/originals/") and "a.png" not in key
|
||||
# Строка записана до PUT, подтверждена после
|
||||
assert stand.attachments.calls[:2] == ["create_pending", "mark_ready"]
|
||||
assert stand.attachments.calls[:2] == ["create_pending", "mark_queued"]
|
||||
|
||||
|
||||
def test_s3_failure_after_write_is_compensated() -> None:
|
||||
@@ -109,7 +109,7 @@ def test_s3_failure_after_write_is_compensated() -> None:
|
||||
def test_db_failure_between_s3_and_commit_is_compensated() -> None:
|
||||
"""Объект записан в S3, подтверждение в БД не прошло"""
|
||||
stand = Stand()
|
||||
stand.attachments.fail.add("mark_ready")
|
||||
stand.attachments.fail.add("mark_queued")
|
||||
with pytest.raises(UnavailableError):
|
||||
run(stand.upload())
|
||||
assert stand.storage.objects == {}
|
||||
@@ -122,7 +122,7 @@ def test_db_down_leaves_pending_row_that_janitor_cleans() -> None:
|
||||
строкой pending; janitor после grace period удаляет и объект, и строку.
|
||||
"""
|
||||
stand = Stand()
|
||||
stand.attachments.fail.update({"mark_ready", "claim_pending"})
|
||||
stand.attachments.fail.update({"mark_queued", "claim_pending"})
|
||||
with pytest.raises(UnavailableError):
|
||||
run(stand.upload())
|
||||
assert len(stand.storage.objects) == 1
|
||||
@@ -140,7 +140,7 @@ def test_db_down_leaves_pending_row_that_janitor_cleans() -> None:
|
||||
|
||||
def test_s3_down_during_compensation_leaves_deleting_row_for_janitor() -> None:
|
||||
stand = Stand()
|
||||
stand.attachments.fail.add("mark_ready")
|
||||
stand.attachments.fail.add("mark_queued")
|
||||
stand.storage.fail.add("delete")
|
||||
with pytest.raises(UnavailableError):
|
||||
run(stand.upload())
|
||||
@@ -241,12 +241,16 @@ def test_foreign_chat_is_404_before_reading_body() -> None:
|
||||
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"")))
|
||||
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())
|
||||
attachment = run(stand.upload()).model_copy(update={"status": "ready"})
|
||||
|
||||
async def get_for_member(attachment_id, member_id):
|
||||
[key] = stand.storage.objects
|
||||
@@ -258,4 +262,6 @@ def test_missing_variant_is_404() -> None:
|
||||
)
|
||||
assert content.content_length == attachment.size_bytes
|
||||
with pytest.raises(NotFoundError):
|
||||
run(stand.service.open_content(USER, attachment.id, AttachmentVariant.THUMBNAIL))
|
||||
run(
|
||||
stand.service.open_content(USER, attachment.id, AttachmentVariant.THUMBNAIL)
|
||||
)
|
||||
|
||||
@@ -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"}
|
||||
Reference in New Issue
Block a user