forked from mtusi2026/mtusi2026lab4
feat: добавить reconciler PostgreSQL и S3
This commit is contained in:
@@ -6,6 +6,8 @@ from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from app.domain.errors import Conflict
|
||||
from app.domain.models import Attachment
|
||||
from app.domain.models import User
|
||||
from app.services.attachments import AttachmentService
|
||||
|
||||
@@ -30,6 +32,19 @@ class RecordingStorage:
|
||||
self.removed_key = key
|
||||
|
||||
|
||||
class FailedAttachmentRepository:
|
||||
def __init__(self, attachment):
|
||||
self.attachment = attachment
|
||||
|
||||
async def get_for_member(self, attachment_id, user_id):
|
||||
return self.attachment
|
||||
|
||||
|
||||
class StorageThatMustNotBeRead:
|
||||
async def get(self, key):
|
||||
raise AssertionError('failed attachment must not read S3')
|
||||
|
||||
|
||||
def test_uploaded_object_is_removed_when_metadata_commit_fails():
|
||||
storage = RecordingStorage()
|
||||
service = AttachmentService(FailingRepository(), storage, 10 * 1024 * 1024, 40_000_000)
|
||||
@@ -52,3 +67,30 @@ def test_uploaded_object_is_removed_when_metadata_commit_fails():
|
||||
|
||||
assert storage.put_key is not None
|
||||
assert storage.removed_key == storage.put_key
|
||||
|
||||
|
||||
def test_failed_attachment_content_returns_conflict_without_s3_read():
|
||||
now = datetime.now(timezone.utc)
|
||||
attachment = Attachment(
|
||||
id=uuid4(),
|
||||
chat_id=uuid4(),
|
||||
owner_id=uuid4(),
|
||||
filename='missing.png',
|
||||
object_key=f'originals/{uuid4()}',
|
||||
content_type='image/png',
|
||||
size_bytes=1,
|
||||
sha256='0' * 64,
|
||||
width=1,
|
||||
height=1,
|
||||
status='failed',
|
||||
error_code='original_missing',
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
service = AttachmentService(
|
||||
FailedAttachmentRepository(attachment), StorageThatMustNotBeRead(), 1, 1
|
||||
)
|
||||
actor = User(uuid4(), 'tester', 'Tester', now)
|
||||
|
||||
with pytest.raises(Conflict, match='недоступен'):
|
||||
asyncio.run(service.content(actor, attachment.id))
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
from app.storage import StoredObject
|
||||
from app.tools.reconcile_attachments import AttachmentSnapshot, build_plan
|
||||
|
||||
|
||||
def test_plan_classifies_both_sides_and_protects_fresh_items():
|
||||
now = datetime.now(timezone.utc)
|
||||
cutoff = now - timedelta(minutes=1)
|
||||
correct_key = f'originals/{uuid4()}'
|
||||
missing = AttachmentSnapshot(uuid4(), f'originals/{uuid4()}', 'ready', cutoff)
|
||||
fresh_missing = AttachmentSnapshot(uuid4(), f'originals/{uuid4()}', 'ready', now)
|
||||
already_failed = AttachmentSnapshot(uuid4(), f'originals/{uuid4()}', 'failed', cutoff)
|
||||
attachments = (
|
||||
AttachmentSnapshot(uuid4(), correct_key, 'ready', cutoff),
|
||||
missing,
|
||||
fresh_missing,
|
||||
already_failed,
|
||||
)
|
||||
old_orphan = StoredObject(f'originals/{uuid4()}', cutoff)
|
||||
fresh_orphan = StoredObject(f'originals/{uuid4()}', now)
|
||||
|
||||
plan = build_plan(
|
||||
attachments,
|
||||
(StoredObject(correct_key, cutoff), old_orphan, fresh_orphan),
|
||||
cutoff,
|
||||
)
|
||||
|
||||
assert plan.correct == 1
|
||||
assert plan.orphan == (old_orphan,)
|
||||
assert plan.fresh_orphan == (fresh_orphan,)
|
||||
assert plan.missing == (missing,)
|
||||
assert plan.fresh_missing == (fresh_missing,)
|
||||
|
||||
|
||||
def test_failed_metadata_still_protects_its_object_from_orphan_cleanup():
|
||||
now = datetime.now(timezone.utc)
|
||||
key = f'originals/{uuid4()}'
|
||||
failed = AttachmentSnapshot(uuid4(), key, 'failed', now - timedelta(hours=2))
|
||||
|
||||
plan = build_plan(
|
||||
(failed,),
|
||||
(StoredObject(key, now - timedelta(hours=2)),),
|
||||
now - timedelta(hours=1),
|
||||
)
|
||||
|
||||
assert plan.correct == 1
|
||||
assert plan.orphan == ()
|
||||
assert plan.missing == ()
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Real PostgreSQL + S3 fault injection for grade 5, track 2."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from io import BytesIO
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.config import load_settings
|
||||
from app.db import create_engine, create_session_factory
|
||||
from app.models.attachment import AttachmentRow, MessageAttachmentRow
|
||||
from app.models.chat import ChatMemberRow, ChatRow
|
||||
from app.models.message import MessageRow
|
||||
from app.models.user import UserRow
|
||||
from app.storage import S3Storage
|
||||
from app.tools.reconcile_attachments import MISSING_ERROR_CODE, reconcile
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not os.getenv('DATABASE_URL'), reason='requires the compose PostgreSQL and S3 services'
|
||||
)
|
||||
|
||||
|
||||
def test_dry_run_apply_and_repeat_are_safe():
|
||||
asyncio.run(_check_dry_run_apply_and_repeat_are_safe())
|
||||
|
||||
|
||||
async def _check_dry_run_apply_and_repeat_are_safe():
|
||||
settings = load_settings()
|
||||
engine = create_engine(settings.database_url)
|
||||
sessions = create_session_factory(engine)
|
||||
storage = S3Storage(
|
||||
settings.s3_endpoint,
|
||||
settings.s3_access_key_id,
|
||||
settings.s3_secret_access_key,
|
||||
settings.s3_bucket,
|
||||
settings.s3_region,
|
||||
)
|
||||
now = datetime.now(timezone.utc)
|
||||
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_key = f'originals/reconcile-correct-{uuid4()}'
|
||||
orphan_key = f'originals/reconcile-orphan-{uuid4()}'
|
||||
|
||||
try:
|
||||
async with sessions() as session:
|
||||
async with session.begin():
|
||||
session.add(UserRow(
|
||||
id=user_id,
|
||||
username=f'reconcile-{user_id.hex[:16]}',
|
||||
display_name='Reconciler test',
|
||||
password_hash='not-used',
|
||||
created_at=old,
|
||||
))
|
||||
session.add(ChatRow(id=chat_id, title='Reconciler test', created_at=old))
|
||||
await session.flush()
|
||||
session.add(ChatMemberRow(chat_id=chat_id, user_id=user_id))
|
||||
for attachment_id, key in (
|
||||
(correct_id, correct_key),
|
||||
(missing_id, f'originals/reconcile-missing-{uuid4()}'),
|
||||
):
|
||||
session.add(AttachmentRow(
|
||||
id=attachment_id,
|
||||
chat_id=chat_id,
|
||||
owner_id=user_id,
|
||||
filename='test.png',
|
||||
object_key=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,
|
||||
))
|
||||
await session.flush()
|
||||
session.add(MessageRow(
|
||||
id=message_id,
|
||||
chat_id=chat_id,
|
||||
sender_id=user_id,
|
||||
text='used attachment must survive',
|
||||
created_at=old,
|
||||
idempotency_key=f'reconcile-{message_id}',
|
||||
))
|
||||
await session.flush()
|
||||
session.add(MessageAttachmentRow(
|
||||
message_id=message_id,
|
||||
attachment_id=correct_id,
|
||||
position=0,
|
||||
))
|
||||
|
||||
for key in (correct_key, orphan_key):
|
||||
await storage.put(key, BytesIO(b'x'), 1, 'application/octet-stream')
|
||||
|
||||
dry_run = await reconcile(
|
||||
sessions,
|
||||
storage,
|
||||
apply=False,
|
||||
grace_seconds=60,
|
||||
now=simulated_after_grace,
|
||||
output=lambda _line: None,
|
||||
)
|
||||
assert dry_run['orphan'] == 1
|
||||
assert dry_run['missing'] == 1
|
||||
assert dry_run['removed'] == 0
|
||||
assert dry_run['marked_failed'] == 0
|
||||
assert {item.key for item in await storage.list('originals/')} >= {
|
||||
correct_key,
|
||||
orphan_key,
|
||||
}
|
||||
|
||||
applied = await reconcile(
|
||||
sessions,
|
||||
storage,
|
||||
apply=True,
|
||||
grace_seconds=60,
|
||||
now=simulated_after_grace,
|
||||
output=lambda _line: None,
|
||||
)
|
||||
assert applied['removed'] == 1
|
||||
assert applied['marked_failed'] == 1
|
||||
|
||||
repeated = await reconcile(
|
||||
sessions,
|
||||
storage,
|
||||
apply=True,
|
||||
grace_seconds=60,
|
||||
now=simulated_after_grace,
|
||||
output=lambda _line: None,
|
||||
)
|
||||
assert repeated['orphan'] == 0
|
||||
assert repeated['missing'] == 0
|
||||
assert repeated['removed'] == 0
|
||||
assert repeated['marked_failed'] == 0
|
||||
|
||||
object_keys = {item.key for item in await storage.list('originals/')}
|
||||
assert correct_key in object_keys
|
||||
assert orphan_key not in object_keys
|
||||
async with sessions() as session:
|
||||
missing_row = await session.get(AttachmentRow, missing_id)
|
||||
assert missing_row is not None
|
||||
assert missing_row.status == 'failed'
|
||||
assert missing_row.error_code == MISSING_ERROR_CODE
|
||||
assert await session.scalar(
|
||||
select(MessageAttachmentRow.attachment_id).where(
|
||||
MessageAttachmentRow.message_id == message_id
|
||||
)
|
||||
) == correct_id
|
||||
finally:
|
||||
await storage.remove(correct_key)
|
||||
await storage.remove(orphan_key)
|
||||
async with sessions() as session:
|
||||
async with session.begin():
|
||||
chat = await session.get(ChatRow, chat_id)
|
||||
if chat is not None:
|
||||
await session.delete(chat)
|
||||
await session.flush()
|
||||
user = await session.get(UserRow, user_id)
|
||||
if user is not None:
|
||||
await session.delete(user)
|
||||
await engine.dispose()
|
||||
Reference in New Issue
Block a user