feat: добавить reconciler PostgreSQL и S3

This commit is contained in:
2026-11-05 21:21:43 +03:00
parent 0ed4b9cea5
commit a3bbdeef42
12 changed files with 751 additions and 15 deletions
+13 -9
View File
@@ -64,17 +64,21 @@ class MessageRepository:
return None
if attachment_ids:
found = set(
await session.scalars(
select(AttachmentRow.id).where(
AttachmentRow.id.in_(attachment_ids),
AttachmentRow.chat_id == accessible_chat_id,
AttachmentRow.status == 'ready',
found = {
attachment_id: status
for attachment_id, status in (
await session.execute(
select(AttachmentRow.id, AttachmentRow.status).where(
AttachmentRow.id.in_(attachment_ids),
AttachmentRow.chat_id == accessible_chat_id,
)
)
)
)
if found != set(attachment_ids):
).all()
}
if set(found) != set(attachment_ids):
raise NotFound('вложение не найдено')
if any(status != 'ready' for status in found.values()):
raise Conflict('оригинал вложения недоступен')
statement = (
insert(MessageRow)
+3
View File
@@ -12,6 +12,7 @@ from uuid import UUID, uuid4
from PIL import Image, UnidentifiedImageError
from ..domain.errors import (
Conflict,
Invalid,
NotFound,
PayloadTooLarge,
@@ -137,6 +138,8 @@ class AttachmentService:
async def content(self, actor: User, attachment_id: UUID) -> tuple[Attachment, ObjectStream]:
attachment = await self.get(actor, attachment_id)
if attachment.status != 'ready':
raise Conflict('оригинал вложения недоступен')
try:
stream = await self._storage.get(attachment.object_key)
except FileNotFoundError as error:
+205
View File
@@ -0,0 +1,205 @@
from __future__ import annotations
import argparse
import asyncio
import json
import time
import tracemalloc
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Callable, Sequence
from uuid import UUID
from sqlalchemy import select, update
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from ..config import load_settings
from ..db import create_engine, create_session_factory
from ..models.attachment import AttachmentRow
from ..storage import S3Storage, StoredObject
MISSING_ERROR_CODE = 'original_missing'
@dataclass(frozen=True, slots=True)
class AttachmentSnapshot:
id: UUID
object_key: str
status: str
updated_at: datetime
@dataclass(frozen=True, slots=True)
class ReconcilePlan:
orphan: tuple[StoredObject, ...]
fresh_orphan: tuple[StoredObject, ...]
missing: tuple[AttachmentSnapshot, ...]
fresh_missing: tuple[AttachmentSnapshot, ...]
correct: int
def build_plan(
attachments: Sequence[AttachmentSnapshot],
objects: Sequence[StoredObject],
cutoff: datetime,
) -> ReconcilePlan:
"""Compare immutable PostgreSQL and S3 snapshots without changing either side."""
known_keys = {attachment.object_key for attachment in attachments}
object_keys = {item.key for item in objects}
unknown_objects = [item for item in objects if item.key not in known_keys]
orphan = tuple(item for item in unknown_objects if item.last_modified <= cutoff)
fresh_orphan = tuple(item for item in unknown_objects if item.last_modified > cutoff)
ready_without_object = [
attachment
for attachment in attachments
if attachment.status == 'ready' and attachment.object_key not in object_keys
]
missing = tuple(
attachment for attachment in ready_without_object if attachment.updated_at <= cutoff
)
fresh_missing = tuple(
attachment for attachment in ready_without_object if attachment.updated_at > cutoff
)
correct = sum(attachment.object_key in object_keys for attachment in attachments)
return ReconcilePlan(orphan, fresh_orphan, missing, fresh_missing, correct)
async def _load_attachments(
sessions: async_sessionmaker[AsyncSession],
) -> tuple[AttachmentSnapshot, ...]:
async with sessions() as session:
rows = (
await session.execute(
select(
AttachmentRow.id,
AttachmentRow.object_key,
AttachmentRow.status,
AttachmentRow.updated_at,
)
)
).all()
return tuple(AttachmentSnapshot(*row) for row in rows)
async def reconcile(
sessions: async_sessionmaker[AsyncSession],
storage: S3Storage,
*,
apply: bool,
grace_seconds: int,
now: datetime | None = None,
output: Callable[[str], None] = print,
) -> dict[str, int | float | str]:
started = time.perf_counter()
tracemalloc.start()
current_time = now or datetime.now(timezone.utc)
cutoff = current_time - timedelta(seconds=grace_seconds)
attachments = await _load_attachments(sessions)
objects = await storage.list('originals/')
plan = build_plan(attachments, objects, cutoff)
for item in plan.fresh_orphan:
output(
f'SKIP_FRESH_ORPHAN key={item.key} modified={item.last_modified.isoformat()}'
)
for attachment in plan.fresh_missing:
output(
'SKIP_FRESH_MISSING '
f'attachment_id={attachment.id} key={attachment.object_key} '
f'updated={attachment.updated_at.isoformat()}'
)
removed = 0
for item in plan.orphan:
action = 'DELETE_ORPHAN' if apply else 'WOULD_DELETE_ORPHAN'
output(f'{action} key={item.key} modified={item.last_modified.isoformat()}')
if apply:
await storage.remove(item.key)
removed += 1
marked_failed = 0
for attachment in plan.missing:
action = 'MARK_MISSING' if apply else 'WOULD_MARK_MISSING'
output(
f'{action} attachment_id={attachment.id} key={attachment.object_key} '
f'updated={attachment.updated_at.isoformat()}'
)
if apply and plan.missing:
async with sessions() as session:
async with session.begin():
result = await session.execute(
update(AttachmentRow)
.where(
AttachmentRow.id.in_([item.id for item in plan.missing]),
AttachmentRow.status == 'ready',
)
.values(
status='failed',
error_code=MISSING_ERROR_CODE,
updated_at=current_time,
)
)
marked_failed = result.rowcount or 0
_, peak_bytes = tracemalloc.get_traced_memory()
tracemalloc.stop()
summary: dict[str, int | float | str] = {
'mode': 'apply' if apply else 'dry-run',
'metadata': len(attachments),
'objects': len(objects),
'correct': plan.correct,
'orphan': len(plan.orphan),
'missing': len(plan.missing),
'fresh_protected': len(plan.fresh_orphan) + len(plan.fresh_missing),
'removed': removed,
'marked_failed': marked_failed,
'grace_seconds': grace_seconds,
'elapsed_ms': round((time.perf_counter() - started) * 1000, 3),
'peak_memory_bytes': peak_bytes,
}
output(f'summary {json.dumps(summary, sort_keys=True)}')
return summary
async def run(apply: bool, grace_seconds: int) -> int:
settings = load_settings()
engine = create_engine(settings.database_url)
storage = S3Storage(
settings.s3_endpoint,
settings.s3_access_key_id,
settings.s3_secret_access_key,
settings.s3_bucket,
settings.s3_region,
)
try:
await reconcile(
create_session_factory(engine),
storage,
apply=apply,
grace_seconds=grace_seconds,
)
return 0
finally:
await engine.dispose()
def main() -> None:
parser = argparse.ArgumentParser(
description='Reconcile attachment metadata in PostgreSQL with original objects in S3'
)
mode = parser.add_mutually_exclusive_group(required=True)
mode.add_argument('--dry-run', action='store_true')
mode.add_argument('--apply', action='store_true')
parser.add_argument('--grace-seconds', type=int, default=3600)
args = parser.parse_args()
if args.grace_seconds < 60:
parser.error('--grace-seconds must be at least 60')
raise SystemExit(asyncio.run(run(args.apply, args.grace_seconds)))
if __name__ == '__main__':
main()
+136
View File
@@ -0,0 +1,136 @@
from __future__ import annotations
import argparse
import asyncio
from datetime import datetime, timedelta, timezone
from io import BytesIO
from uuid import NAMESPACE_URL, uuid5
from sqlalchemy import delete, insert
from ..config import load_settings
from ..db import create_engine, create_session_factory
from ..models.attachment import AttachmentRow
from ..models.chat import ChatMemberRow, ChatRow
from ..models.user import UserRow
from ..storage import S3Storage
USER_ID = uuid5(NAMESPACE_URL, 'reconciler-benchmark:user')
CHAT_ID = uuid5(NAMESPACE_URL, 'reconciler-benchmark:chat')
OBJECT_PREFIX = 'originals/reconciler-benchmark/'
WORKERS = 16
async def _put_objects(
storage: S3Storage,
keys: list[str],
) -> None:
for offset in range(0, len(keys), WORKERS):
batch = keys[offset : offset + WORKERS]
await asyncio.gather(
*(storage.put(key, BytesIO(b'x'), 1, 'application/octet-stream') for key in batch)
)
async def prepare(size: int) -> None:
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,
)
old = datetime.now(timezone.utc) - timedelta(hours=2)
rows = [
{
'id': uuid5(NAMESPACE_URL, f'reconciler-benchmark:attachment:{index}'),
'chat_id': CHAT_ID,
'owner_id': USER_ID,
'filename': f'benchmark-{index}.png',
'object_key': f'{OBJECT_PREFIX}{index}',
'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,
}
for index in range(size)
]
try:
async with sessions() as session:
async with session.begin():
session.add(UserRow(
id=USER_ID,
username=f'bench-{USER_ID.hex[:16]}',
display_name='Reconciler benchmark',
password_hash='not-used',
created_at=old,
))
session.add(ChatRow(id=CHAT_ID, title='Reconciler benchmark', created_at=old))
await session.flush()
session.add(ChatMemberRow(chat_id=CHAT_ID, user_id=USER_ID))
await session.flush()
for offset in range(0, size, 500):
await session.execute(insert(AttachmentRow), rows[offset : offset + 500])
await _put_objects(storage, [row['object_key'] for row in rows])
print(f'prepared metadata={size} objects={size}')
finally:
await engine.dispose()
async def cleanup() -> None:
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,
)
try:
objects = await storage.list(OBJECT_PREFIX)
keys = [item.key for item in objects]
for offset in range(0, len(keys), WORKERS):
await asyncio.gather(
*(storage.remove(key) for key in keys[offset : offset + WORKERS])
)
async with sessions() as session:
async with session.begin():
await session.execute(delete(ChatRow).where(ChatRow.id == CHAT_ID))
await session.execute(delete(UserRow).where(UserRow.id == USER_ID))
print(f'cleaned objects={len(keys)}')
finally:
await engine.dispose()
def main() -> None:
parser = argparse.ArgumentParser(
description='Prepare and clean isolated PostgreSQL/S3 data for reconciler benchmarks'
)
subparsers = parser.add_subparsers(dest='command', required=True)
prepare_parser = subparsers.add_parser('prepare')
prepare_parser.add_argument('--size', type=int, required=True)
subparsers.add_parser('cleanup')
args = parser.parse_args()
if args.command == 'prepare':
if args.size < 1 or args.size > 10000:
parser.error('--size must be between 1 and 10000')
asyncio.run(prepare(args.size))
else:
asyncio.run(cleanup())
if __name__ == '__main__':
main()