forked from mtusi2026/mtusi2026lab4
feat: усилить reconciler для lab4
This commit is contained in:
@@ -46,6 +46,7 @@ class StorageThatMustNotBeRead:
|
||||
|
||||
|
||||
def test_uploaded_object_is_removed_when_metadata_commit_fails():
|
||||
"""Удаляет объект после ошибки сохранения метаданных."""
|
||||
storage = RecordingStorage()
|
||||
service = AttachmentService(FailingRepository(), storage, 10 * 1024 * 1024, 40_000_000)
|
||||
actor = User(uuid4(), 'tester', 'Tester', datetime.now(timezone.utc))
|
||||
@@ -70,6 +71,7 @@ def test_uploaded_object_is_removed_when_metadata_commit_fails():
|
||||
|
||||
|
||||
def test_failed_attachment_content_returns_conflict_without_s3_read():
|
||||
"""Возвращает конфликт для ошибочного вложения без чтения S3."""
|
||||
now = datetime.now(timezone.utc)
|
||||
attachment = Attachment(
|
||||
id=uuid4(),
|
||||
|
||||
@@ -37,22 +37,26 @@ def oversized_dimensions_png(content: bytes) -> bytes:
|
||||
|
||||
|
||||
def test_file_larger_than_10_mib_is_rejected(scenario):
|
||||
"""Отклоняет файл размером больше 10 MiB."""
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
upload(client, alice, chat, b'x' * (10 * 1024 * 1024 + 1), expected=413)
|
||||
|
||||
|
||||
def test_corrupted_image_is_rejected(scenario):
|
||||
"""Отклоняет повреждённое изображение."""
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
upload(client, alice, chat, b'not-a-png', expected=415)
|
||||
|
||||
|
||||
def test_mime_mismatch_is_rejected(scenario):
|
||||
"""Отклоняет MIME, не совпадающий с содержимым."""
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
upload(client, alice, chat, content, content_type='image/jpeg', expected=415)
|
||||
|
||||
|
||||
def test_pixel_limit_is_checked_before_decode(scenario):
|
||||
"""Проверяет лимит пикселей до полной декомпрессии."""
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
content = oversized_dimensions_png((ROOT / 'tests/fixtures/sample.png').read_bytes())
|
||||
upload(client, alice, chat, content, expected=413)
|
||||
@@ -63,12 +67,14 @@ def test_pixel_limit_is_checked_before_decode(scenario):
|
||||
['../escape.png', 'folder\\escape.png', 'bad\x00name.png', 'bad\x85name.png'],
|
||||
)
|
||||
def test_dangerous_filename_is_rejected(scenario, filename):
|
||||
"""Отклоняет опасное отображаемое имя файла."""
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
upload(client, alice, chat, content, filename=filename, expected=400)
|
||||
|
||||
|
||||
def test_outsider_cannot_read_attachment(scenario):
|
||||
"""Скрывает метаданные и содержимое от постороннего пользователя."""
|
||||
client, alice, _bob, eve, chat = scenario
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
attachment = upload(client, alice, chat, content)['json']
|
||||
@@ -77,6 +83,7 @@ def test_outsider_cannot_read_attachment(scenario):
|
||||
|
||||
|
||||
def test_attachment_from_another_chat_cannot_be_linked(scenario):
|
||||
"""Запрещает прикреплять вложение другого чата."""
|
||||
client, alice, bob, _eve, chat = scenario
|
||||
other_chat = client.call(
|
||||
'POST',
|
||||
@@ -99,6 +106,7 @@ def test_attachment_from_another_chat_cannot_be_linked(scenario):
|
||||
|
||||
|
||||
def test_idempotency_distinguishes_attachment_list(scenario):
|
||||
"""Включает список вложений в сравнение идемпотентного запроса."""
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
attachment = upload(client, alice, chat, content)['json']
|
||||
@@ -129,6 +137,7 @@ def test_idempotency_distinguishes_attachment_list(scenario):
|
||||
|
||||
|
||||
def test_missing_attachment_ids_equals_empty_list_for_idempotency(scenario):
|
||||
"""Считает отсутствие attachment_ids эквивалентным пустому списку."""
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
key = uuid.uuid4().hex
|
||||
first = client.message(alice, chat, 'обычный текст', key=key)['json']
|
||||
|
||||
@@ -6,6 +6,7 @@ from app.tools.reconcile_attachments import AttachmentSnapshot, build_plan
|
||||
|
||||
|
||||
def test_plan_classifies_both_sides_and_protects_fresh_items():
|
||||
"""Классифицирует orphan/missing и защищает свежие расхождения."""
|
||||
now = datetime.now(timezone.utc)
|
||||
cutoff = now - timedelta(minutes=1)
|
||||
correct_key = f'originals/{uuid4()}'
|
||||
@@ -35,6 +36,7 @@ def test_plan_classifies_both_sides_and_protects_fresh_items():
|
||||
|
||||
|
||||
def test_failed_metadata_still_protects_its_object_from_orphan_cleanup():
|
||||
"""Проверяет защиту объекта существующей failed-metadata."""
|
||||
now = datetime.now(timezone.utc)
|
||||
key = f'originals/{uuid4()}'
|
||||
failed = AttachmentSnapshot(uuid4(), key, 'failed', now - timedelta(hours=2))
|
||||
|
||||
@@ -8,7 +8,7 @@ from io import BytesIO
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import select, update
|
||||
|
||||
from app.config import load_settings
|
||||
from app.db import create_engine, create_session_factory
|
||||
@@ -24,7 +24,24 @@ pytestmark = pytest.mark.skipif(
|
||||
)
|
||||
|
||||
|
||||
class AfterListStorage:
|
||||
def __init__(self, storage, after_list):
|
||||
self._storage = storage
|
||||
self._after_list = after_list
|
||||
|
||||
async def list(self, prefix=''):
|
||||
snapshot = await self._storage.list(prefix)
|
||||
if self._after_list is not None:
|
||||
after_list, self._after_list = self._after_list, None
|
||||
await after_list()
|
||||
return snapshot
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._storage, name)
|
||||
|
||||
|
||||
def test_dry_run_apply_and_repeat_are_safe():
|
||||
"""Проверяет пробный, изменяющий и повторный запуски."""
|
||||
asyncio.run(_check_dry_run_apply_and_repeat_are_safe())
|
||||
|
||||
|
||||
@@ -43,9 +60,14 @@ async def _check_dry_run_apply_and_repeat_are_safe():
|
||||
old = now - timedelta(hours=2)
|
||||
simulated_after_grace = now + timedelta(seconds=61)
|
||||
user_id, chat_id, message_id = uuid4(), uuid4(), uuid4()
|
||||
correct_id, missing_id = uuid4(), uuid4()
|
||||
correct_id, missing_id, restored_id = uuid4(), uuid4(), uuid4()
|
||||
changed_id, appeared_id = uuid4(), uuid4()
|
||||
correct_key = f'originals/reconcile-correct-{uuid4()}'
|
||||
orphan_key = f'originals/reconcile-orphan-{uuid4()}'
|
||||
restored_key = f'originals/reconcile-restored-{uuid4()}'
|
||||
changed_key = f'originals/reconcile-changed-{uuid4()}'
|
||||
appeared_key = f'originals/reconcile-appeared-{uuid4()}'
|
||||
fresh_key = f'originals/reconcile-fresh-{uuid4()}'
|
||||
|
||||
try:
|
||||
async with sessions() as session:
|
||||
@@ -63,6 +85,8 @@ async def _check_dry_run_apply_and_repeat_are_safe():
|
||||
for attachment_id, key in (
|
||||
(correct_id, correct_key),
|
||||
(missing_id, f'originals/reconcile-missing-{uuid4()}'),
|
||||
(restored_id, restored_key),
|
||||
(changed_id, changed_key),
|
||||
):
|
||||
session.add(AttachmentRow(
|
||||
id=attachment_id,
|
||||
@@ -108,7 +132,7 @@ async def _check_dry_run_apply_and_repeat_are_safe():
|
||||
output=lambda _line: None,
|
||||
)
|
||||
assert dry_run['orphan'] == 1
|
||||
assert dry_run['missing'] == 1
|
||||
assert dry_run['missing'] == 3
|
||||
assert dry_run['removed'] == 0
|
||||
assert dry_run['marked_failed'] == 0
|
||||
assert {item.key for item in await storage.list('originals/')} >= {
|
||||
@@ -116,9 +140,19 @@ async def _check_dry_run_apply_and_repeat_are_safe():
|
||||
orphan_key,
|
||||
}
|
||||
|
||||
async def restore_missing_after_snapshot():
|
||||
await storage.put(restored_key, BytesIO(b'x'), 1, 'application/octet-stream')
|
||||
async with sessions() as session:
|
||||
async with session.begin():
|
||||
await session.execute(
|
||||
update(AttachmentRow)
|
||||
.where(AttachmentRow.id == changed_id)
|
||||
.values(updated_at=now)
|
||||
)
|
||||
|
||||
applied = await reconcile(
|
||||
sessions,
|
||||
storage,
|
||||
AfterListStorage(storage, restore_missing_after_snapshot),
|
||||
apply=True,
|
||||
grace_seconds=60,
|
||||
now=simulated_after_grace,
|
||||
@@ -126,6 +160,11 @@ async def _check_dry_run_apply_and_repeat_are_safe():
|
||||
)
|
||||
assert applied['removed'] == 1
|
||||
assert applied['marked_failed'] == 1
|
||||
assert applied['race_protected'] == 2
|
||||
|
||||
# Make the concurrently changed metadata healthy before checking that
|
||||
# the next complete run has no work left.
|
||||
await storage.put(changed_key, BytesIO(b'x'), 1, 'application/octet-stream')
|
||||
|
||||
repeated = await reconcile(
|
||||
sessions,
|
||||
@@ -142,6 +181,8 @@ async def _check_dry_run_apply_and_repeat_are_safe():
|
||||
|
||||
object_keys = {item.key for item in await storage.list('originals/')}
|
||||
assert correct_key in object_keys
|
||||
assert restored_key in object_keys
|
||||
assert changed_key in object_keys
|
||||
assert orphan_key not in object_keys
|
||||
async with sessions() as session:
|
||||
missing_row = await session.get(AttachmentRow, missing_id)
|
||||
@@ -153,9 +194,73 @@ async def _check_dry_run_apply_and_repeat_are_safe():
|
||||
MessageAttachmentRow.message_id == message_id
|
||||
)
|
||||
) == correct_id
|
||||
|
||||
restored_row = await session.get(AttachmentRow, restored_id)
|
||||
assert restored_row is not None
|
||||
assert restored_row.status == 'ready'
|
||||
|
||||
changed_row = await session.get(AttachmentRow, changed_id)
|
||||
assert changed_row is not None
|
||||
assert changed_row.status == 'ready'
|
||||
|
||||
# An object younger than the grace period survives a real apply run.
|
||||
await storage.put(fresh_key, BytesIO(b'x'), 1, 'application/octet-stream')
|
||||
fresh_apply = await reconcile(
|
||||
sessions,
|
||||
storage,
|
||||
apply=True,
|
||||
grace_seconds=60,
|
||||
now=datetime.now(timezone.utc),
|
||||
output=lambda _line: None,
|
||||
)
|
||||
assert fresh_apply['fresh_protected'] == 1
|
||||
assert fresh_apply['removed'] == 0
|
||||
assert await storage.exists(fresh_key)
|
||||
await storage.remove(fresh_key)
|
||||
|
||||
# Metadata created after the initial snapshots also protects an old
|
||||
# object from the destructive orphan action.
|
||||
await storage.put(appeared_key, BytesIO(b'x'), 1, 'application/octet-stream')
|
||||
|
||||
async def create_metadata_after_snapshot():
|
||||
async with sessions() as session:
|
||||
async with session.begin():
|
||||
session.add(AttachmentRow(
|
||||
id=appeared_id,
|
||||
chat_id=chat_id,
|
||||
owner_id=user_id,
|
||||
filename='appeared.png',
|
||||
object_key=appeared_key,
|
||||
content_type='image/png',
|
||||
size_bytes=1,
|
||||
sha256='0' * 64,
|
||||
width=1,
|
||||
height=1,
|
||||
status='ready',
|
||||
error_code=None,
|
||||
created_at=old,
|
||||
updated_at=old,
|
||||
))
|
||||
|
||||
appeared_apply = await reconcile(
|
||||
sessions,
|
||||
AfterListStorage(storage, create_metadata_after_snapshot),
|
||||
apply=True,
|
||||
grace_seconds=60,
|
||||
now=datetime.now(timezone.utc) + timedelta(seconds=61),
|
||||
output=lambda _line: None,
|
||||
)
|
||||
assert appeared_apply['orphan'] == 1
|
||||
assert appeared_apply['removed'] == 0
|
||||
assert appeared_apply['race_protected'] == 1
|
||||
assert await storage.exists(appeared_key)
|
||||
finally:
|
||||
await storage.remove(correct_key)
|
||||
await storage.remove(orphan_key)
|
||||
await storage.remove(restored_key)
|
||||
await storage.remove(changed_key)
|
||||
await storage.remove(appeared_key)
|
||||
await storage.remove(fresh_key)
|
||||
async with sessions() as session:
|
||||
async with session.begin():
|
||||
chat = await session.get(ChatRow, chat_id)
|
||||
|
||||
Reference in New Issue
Block a user