diff --git a/openspec/changes/add-lab4-storage-reconciler/tasks.md b/openspec/changes/add-lab4-storage-reconciler/tasks.md index 1deabe08..b9503843 100644 --- a/openspec/changes/add-lab4-storage-reconciler/tasks.md +++ b/openspec/changes/add-lab4-storage-reconciler/tasks.md @@ -5,18 +5,18 @@ ## 2. Зона `attachments`: домен и приложение -- [ ] 2.1 Домен: `Quarantine`, поле `quarantine` агрегата -- [ ] 2.2 Порты: `StoredObject`, `ObjectStorage.listing/stat`, `AttachmentRepository.page_after/by_key/claim/mark`, `SingleRun`; команда `ReconcileStorage` -- [ ] 2.3 `StorageReconciler`: слияние потоков, классы, повторные проверки, действия, `--deep` под ограничением, отчёт `Reconciliation` -- [ ] 2.4 `OpenAttachment`: карантин → `404` без S3 -- [ ] 2.5 Проверка группы: `make lint` +- [x] 2.1 Домен: `Quarantine`, поле `quarantine` агрегата +- [x] 2.2 Порты: `StoredObject`, `ObjectStorage.listing/stat`, `AttachmentRepository.page_after/by_key/claim/mark`, `SingleRun`; команда `ReconcileStorage` +- [x] 2.3 `StorageReconciler`: слияние потоков, классы, повторные проверки, действия, `--deep` под ограничением, отчёт `Reconciliation` +- [x] 2.4 `OpenAttachment`: карантин → `404` без S3 +- [x] 2.5 Проверка группы: `make lint` ## 3. Зона `attachments`: адаптеры и точка входа -- [ ] 3.1 Адаптер S3: листинг страницами, `HEAD`; адаптер PostgreSQL: колонка карантина, keyset, по ключу, `SKIP LOCKED`, `UPDATE` карантина, `PostgresSingleRun` -- [ ] 3.2 Платформа: поток журнала настраивается -- [ ] 3.3 CLI `messenger.attachments.entrypoints.reconcile`: флаги, сборка адаптеров, JSON в stdout, коды выхода -- [ ] 3.4 Проверка группы: API-тесты сверки против одноразового PostgreSQL (каждый класс в dry-run без изменений, apply и повтор = 0, свежее и используемое сохранены, строка появилась после листинга, карантин и `404`, `healed`, `--deep`, занятая блокировка); тест адаптера против RustFS (порядок листинга, страницы, `HEAD`) +- [x] 3.1 Адаптер S3: листинг страницами, `HEAD`; адаптер PostgreSQL: колонка карантина, keyset, по ключу, `SKIP LOCKED`, `UPDATE` карантина, `PostgresSingleRun` +- [x] 3.2 Платформа: поток журнала настраивается +- [x] 3.3 CLI `messenger.attachments.entrypoints.reconcile`: флаги, сборка адаптеров, JSON в stdout, коды выхода +- [x] 3.4 Проверка группы: API-тесты сверки против одноразового PostgreSQL (каждый класс в dry-run без изменений, apply и повтор = 0, свежее и используемое сохранены, строка появилась после листинга, карантин и `404`, `healed`, `--deep`, занятая блокировка); тест адаптера против RustFS (порядок листинга, страницы, `HEAD`) ## 4. Стенд diff --git a/src/messenger/attachments/application/commands.py b/src/messenger/attachments/application/commands.py index b42141fa..40293321 100644 --- a/src/messenger/attachments/application/commands.py +++ b/src/messenger/attachments/application/commands.py @@ -19,3 +19,14 @@ class UploadAttachment(Command): class SweepAbandonedUploads(Command): grace: timedelta limit: int + + +@dataclass(frozen=True, slots=True) +class ReconcileStorage(Command): + apply: bool + grace: timedelta + skew: timedelta + deep: bool = False + page_size: int = 1000 + deep_concurrency: int = 8 + samples: int = 20 diff --git a/src/messenger/attachments/application/ports.py b/src/messenger/attachments/application/ports.py index b1339546..56a2c067 100644 --- a/src/messenger/attachments/application/ports.py +++ b/src/messenger/attachments/application/ports.py @@ -1,4 +1,5 @@ -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Sequence +from contextlib import AbstractAsyncContextManager from dataclasses import dataclass from datetime import datetime from typing import Protocol, runtime_checkable @@ -15,6 +16,13 @@ class ObjectContent: chunks: AsyncIterator[bytes] +@dataclass(frozen=True, slots=True) +class StoredObject: + key: str + size: int + modified: datetime + + @runtime_checkable class ObjectStorage(Protocol): async def put(self, key: str, data: bytes, content_type: str) -> None: ... @@ -23,6 +31,10 @@ class ObjectStorage(Protocol): async def delete(self, key: str) -> None: ... + def listing(self, prefix: str, page_size: int) -> AsyncIterator[Sequence[StoredObject]]: ... + + async def stat(self, key: str) -> StoredObject | None: ... + @runtime_checkable class ImageInspector(Protocol): @@ -46,6 +58,14 @@ class AttachmentRepository(Protocol): async def remove(self, attachment: Attachment) -> None: ... + async def page_after(self, key: str, limit: int) -> Sequence[Attachment]: ... + + async def by_key(self, key: str) -> Attachment | None: ... + + async def claim(self, attachment_id: UUID) -> Attachment | None: ... + + async def mark(self, attachment: Attachment) -> None: ... + @runtime_checkable class AttachmentsUnitOfWork(UnitOfWork, Protocol): @@ -56,3 +76,8 @@ class AttachmentsUnitOfWork(UnitOfWork, Protocol): @runtime_checkable class AttachmentDirectory(Protocol): async def ready(self, attachment_id: UUID) -> Attachment | None: ... + + +@runtime_checkable +class SingleRun(Protocol): + def hold(self) -> AbstractAsyncContextManager[bool]: ... diff --git a/src/messenger/attachments/application/queries.py b/src/messenger/attachments/application/queries.py index d88c6740..c671cec1 100644 --- a/src/messenger/attachments/application/queries.py +++ b/src/messenger/attachments/application/queries.py @@ -38,6 +38,9 @@ class OpenAttachment: self, attachment_id: UUID, user_id: UUID ) -> tuple[Attachment, ObjectContent]: attachment = await self._get(attachment_id, user_id) + if attachment.quarantine is not None: + self._logger.warning("attachment.quarantined", attachment_id=str(attachment.id)) + raise AttachmentNotFound("вложение не найдено") try: content = await self._storage.open(attachment.object_key) except ObjectMissingError as error: diff --git a/src/messenger/attachments/application/reconcile.py b/src/messenger/attachments/application/reconcile.py new file mode 100644 index 00000000..2856d7b9 --- /dev/null +++ b/src/messenger/attachments/application/reconcile.py @@ -0,0 +1,301 @@ +import asyncio +from collections import Counter +from collections.abc import AsyncIterator, Awaitable, Callable, Sequence +from dataclasses import dataclass, field +from datetime import datetime +from hashlib import sha256 +from time import monotonic +from uuid import UUID + +from messenger.attachments.application.commands import ReconcileStorage +from messenger.attachments.application.errors import ObjectMissingError +from messenger.attachments.application.handlers import drop +from messenger.attachments.application.ports import ( + AttachmentsUnitOfWork, + ObjectStorage, + SingleRun, + StoredObject, +) +from messenger.attachments.domain.models import ( + OBJECT_PREFIX, + Attachment, + AttachmentStatus, + Quarantine, +) +from messenger.shared.application.ports import Clock, Logger + +type UnitOfWorkFactory = Callable[[], AttachmentsUnitOfWork] + + +@dataclass(slots=True) +class Reconciliation: + apply: bool + skipped: bool = False + objects: int = 0 + rows: int = 0 + found: Counter[str] = field(default_factory=Counter) + fixed: Counter[str] = field(default_factory=Counter) + rechecked: Counter[str] = field(default_factory=Counter) + requests: Counter[str] = field(default_factory=Counter) + waited: dict[str, float] = field(default_factory=dict) + samples: dict[str, list[str]] = field(default_factory=dict) + hashed_bytes: int = 0 + errors: int = 0 + seconds: float = 0.0 + + +class StorageReconciler: + __slots__ = ("_clock", "_logger", "_single", "_storage", "_uow") + + def __init__( + self, + uow: UnitOfWorkFactory, + storage: ObjectStorage, + single: SingleRun, + clock: Clock, + logger: Logger, + ) -> None: + self._uow = uow + self._storage = storage + self._single = single + self._clock = clock + self._logger = logger + + async def __call__(self, command: ReconcileStorage) -> Reconciliation: + report = Reconciliation(apply=command.apply) + started = monotonic() + async with self._single.hold() as held: + report.skipped = not held + if held: + before = self._clock.now() - command.grace - command.skew + await Pass( + self._uow, + self._storage, + command, + before=before, + report=report, + logger=self._logger, + ).run() + report.seconds = round(monotonic() - started, 3) + return report + + +class Pass: + __slots__ = ("_before", "_command", "_logger", "_report", "_slots", "_storage", "_uow") + + def __init__( + self, + uow: UnitOfWorkFactory, + storage: ObjectStorage, + command: ReconcileStorage, + *, + before: datetime, + report: Reconciliation, + logger: Logger, + ) -> None: + self._uow = uow + self._storage = storage + self._command = command + self._before = before + self._report = report + self._logger = logger + self._slots = asyncio.Semaphore(command.deep_concurrency) + + async def run(self) -> None: + objects = aiter(self._objects()) + item = await anext(objects, None) + async with asyncio.TaskGroup() as checks: + async for row in self._rows(): + while item is not None and item.key < row.object_key: + await self._orphan(item) + item = await anext(objects, None) + matched = item if item is not None and item.key == row.object_key else None + await self._row(row, matched, checks) + if matched is not None: + item = await anext(objects, None) + while item is not None: + await self._orphan(item) + item = await anext(objects, None) + + async def _timed[ResultT](self, name: str, step: Awaitable[ResultT]) -> ResultT: + started = monotonic() + try: + return await step + finally: + spent = self._report.waited.get(name, 0.0) + monotonic() - started + self._report.waited[name] = spent + + async def _objects(self) -> AsyncIterator[StoredObject]: + pages = aiter(self._storage.listing(OBJECT_PREFIX, self._command.page_size)) + while (page := await self._timed("s3_list", anext(pages, None))) is not None: + self._report.requests["s3_list"] += 1 + self._report.objects += len(page) + for item in page: + yield item + + async def _rows(self) -> AsyncIterator[Attachment]: + after, size = "", self._command.page_size + while True: + page = await self._timed("sql", self._page(after, size)) + self._report.requests["sql"] += 1 + self._report.rows += len(page) + for row in page: + yield row + if len(page) < size: + return + after = page[-1].object_key + + async def _page(self, after: str, size: int) -> Sequence[Attachment]: + uow = self._uow() + async with uow.transaction(): + return await uow.attachments.page_after(after, size) + + def _found(self, name: str, subject: str) -> None: + self._report.found[name] += 1 + sample = self._report.samples.setdefault(name, []) + if len(sample) < self._command.samples: + sample.append(subject) + + async def _safely(self, name: str, action: Awaitable[bool], subject: UUID | None) -> None: + attachment_id = None if subject is None else str(subject) + try: + done = await action + except Exception as error: + self._report.errors += 1 + self._logger.warning( + "reconcile.action_failed", + reason=name, + attachment_id=attachment_id, + error=type(error).__name__, + ) + return + (self._report.fixed if done else self._report.rechecked)[name] += 1 + event = "reconcile.fixed" if done else "reconcile.rechecked" + self._logger.info(event, reason=name, attachment_id=attachment_id) + + async def _orphan(self, item: StoredObject) -> None: + if item.modified >= self._before: + self._found("orphan_fresh", item.key) + return + self._found("orphan_stale", item.key) + if self._command.apply: + await self._safely("orphan_stale", self._delete_orphan(item), None) + + async def _delete_orphan(self, item: StoredObject) -> bool: + uow = self._uow() + async with uow.transaction(): + owner = await uow.attachments.by_key(item.key) + self._report.requests["sql"] += 1 + if owner is not None: + return False + self._report.requests["s3_delete"] += 1 + await self._storage.delete(item.key) + return True + + async def _row( + self, row: Attachment, item: StoredObject | None, checks: asyncio.TaskGroup + ) -> None: + if row.status is AttachmentStatus.PENDING: + await self._pending(row) + elif item is None: + await self._broken(row, Quarantine.MISSING) + elif item.size != row.size_bytes: + await self._broken(row, Quarantine.SIZE_MISMATCH) + elif self._command.deep: + await self._slots.acquire() + checks.create_task(self._verify(row)) + else: + await self._healthy(row, verified=False) + + async def _verify(self, row: Attachment) -> None: + try: + digest = await self._digest(row.object_key) + except Exception as error: + self._report.errors += 1 + self._logger.warning( + "reconcile.hash_failed", attachment_id=str(row.id), error=type(error).__name__ + ) + return + finally: + self._slots.release() + if digest is None: + await self._broken(row, Quarantine.MISSING) + elif digest != row.sha256: + await self._broken(row, Quarantine.SHA_MISMATCH) + else: + await self._healthy(row, verified=True) + + async def _digest(self, key: str) -> str | None: + self._report.requests["s3_get"] += 1 + try: + content = await self._storage.open(key) + except ObjectMissingError: + return None + digest = sha256() + async for chunk in content.chunks: + digest.update(chunk) + self._report.hashed_bytes += len(chunk) + return digest.hexdigest() + + async def _broken(self, row: Attachment, reason: Quarantine) -> None: + if row.quarantine is not None: + self._found("quarantined", str(row.id)) + return + self._found(reason.value, str(row.id)) + if self._command.apply: + await self._safely(reason.value, self._isolate(row, reason), row.id) + + async def _isolate(self, row: Attachment, reason: Quarantine) -> bool: + if reason is not Quarantine.SHA_MISMATCH: + self._report.requests["s3_head"] += 1 + found = await self._storage.stat(row.object_key) + if found is not None and found.size == row.size_bytes: + return False + row.isolate(reason) + await self._mark(row) + return True + + async def _healthy(self, row: Attachment, *, verified: bool) -> None: + if row.quarantine is None: + return + if row.quarantine is Quarantine.SHA_MISMATCH and not verified: + self._found("quarantined", str(row.id)) + return + self._found("healed", str(row.id)) + if self._command.apply: + await self._safely("healed", self._release(row), row.id) + + async def _release(self, row: Attachment) -> bool: + row.release() + await self._mark(row) + return True + + async def _mark(self, row: Attachment) -> None: + uow = self._uow() + async with uow.transaction(): + await uow.attachments.mark(row) + await uow.commit() + self._report.requests["sql"] += 1 + + async def _pending(self, row: Attachment) -> None: + if row.created_at >= self._before: + self._found("pending_fresh", str(row.id)) + return + self._found("pending_stale", str(row.id)) + if self._command.apply: + await self._safely("pending_stale", self._drop(row), row.id) + + async def _drop(self, row: Attachment) -> bool: + uow = self._uow() + async with uow.transaction(): + current = await uow.attachments.claim(row.id) + self._report.requests["sql"] += 1 + if ( + current is None + or current.status is not AttachmentStatus.PENDING + or current.created_at >= self._before + ): + return False + self._report.requests["s3_delete"] += 1 + await drop(uow, self._storage, current, "reconcile") + return True diff --git a/src/messenger/attachments/domain/models.py b/src/messenger/attachments/domain/models.py index fef585eb..532742f4 100644 --- a/src/messenger/attachments/domain/models.py +++ b/src/messenger/attachments/domain/models.py @@ -15,6 +15,12 @@ class AttachmentStatus(StrEnum): READY = "ready" +class Quarantine(StrEnum): + MISSING = "missing" + SIZE_MISMATCH = "size_mismatch" + SHA_MISMATCH = "sha_mismatch" + + @dataclass(slots=True) class Attachment: id: UUID @@ -28,6 +34,7 @@ class Attachment: status: AttachmentStatus created_at: datetime updated_at: datetime + quarantine: Quarantine | None = None _events: list[DomainEvent] = field(init=False, default_factory=list, repr=False, compare=False) @classmethod @@ -78,6 +85,13 @@ class Attachment: AttachmentDiscarded(attachment_id=self.id, chat_id=self.chat_id, reason=reason) ) + def isolate(self, reason: Quarantine) -> None: + if self.status is AttachmentStatus.READY: + self.quarantine = reason + + def release(self) -> None: + self.quarantine = None + def collect_events(self) -> list[DomainEvent]: events, self._events = self._events, [] return events diff --git a/src/messenger/attachments/entrypoints/reconcile.py b/src/messenger/attachments/entrypoints/reconcile.py new file mode 100644 index 00000000..4073358a --- /dev/null +++ b/src/messenger/attachments/entrypoints/reconcile.py @@ -0,0 +1,154 @@ +import argparse +import asyncio +import json +import resource +import sys +from collections.abc import Callable, Sequence +from datetime import timedelta +from typing import Any + +from messenger.attachments.application.commands import ReconcileStorage +from messenger.attachments.application.reconcile import Reconciliation, StorageReconciler +from messenger.attachments.config import AttachmentsSettings +from messenger.attachments.entrypoints.journal import LOG_FIELDS +from messenger.attachments.infrastructure.postgres import ( + PostgresAttachmentsUnitOfWork, + PostgresSingleRun, +) +from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client +from messenger.shared.application.errors import Unavailable +from messenger.shared.application.ports import Logger +from messenger.shared.config import PlatformSettings +from messenger.shared.infrastructure.clock import MonotonicUtcClock +from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger +from messenger.shared.infrastructure.postgres import Database + +LOCK_KEY = 20_260_004 +CLASSES = ( + "orphan_stale", + "orphan_fresh", + "missing", + "size_mismatch", + "sha_mismatch", + "pending_stale", + "pending_fresh", + "quarantined", + "healed", +) +FIXABLE = ("orphan_stale", "missing", "size_mismatch", "sha_mismatch", "pending_stale", "healed") +REQUESTS = ("s3_list", "s3_head", "s3_get", "s3_delete", "sql") + + +def bounded(low: int, high: int | None = None) -> Callable[[str], int]: + def parse(text: str) -> int: + value = int(text) + if value < low or (high is not None and value > high): + raise argparse.ArgumentTypeError(f"ожидается {low}..{high or '∞'}") + return value + + return parse + + +def command_of(argv: Sequence[str] | None = None) -> ReconcileStorage: + parser = argparse.ArgumentParser( + prog="python -m messenger.attachments.entrypoints.reconcile", + description="Сверка метаданных вложений в PostgreSQL с объектами bucket S3", + ) + mode = parser.add_mutually_exclusive_group() + mode.add_argument("--dry-run", dest="apply", action="store_false", help="только отчёт") + mode.add_argument("--apply", dest="apply", action="store_true", help="исправить найденное") + parser.add_argument("--grace", type=bounded(60), default=3600, help="секунды, ≥ 60") + parser.add_argument("--skew", type=bounded(0), default=60, help="запас на часы, секунды") + parser.add_argument("--deep", action="store_true", help="сверить SHA-256 каждого объекта") + parser.add_argument("--page-size", type=bounded(1, 1000), default=1000) + parser.add_argument("--deep-concurrency", type=bounded(1, 64), default=8) + parser.add_argument("--samples", type=bounded(0, 1000), default=20) + args = parser.parse_args(argv) + return ReconcileStorage( + apply=args.apply, + grace=timedelta(seconds=args.grace), + skew=timedelta(seconds=args.skew), + deep=args.deep, + page_size=args.page_size, + deep_concurrency=args.deep_concurrency, + samples=args.samples, + ) + + +async def reconcile( + command: ReconcileStorage, + platform: PlatformSettings, + settings: AttachmentsSettings, + logger: Logger, +) -> Reconciliation: + database = Database( + platform.database_url.get_secret_value(), + max_size=command.deep_concurrency + 2, + connect_timeout=platform.db_connect_timeout_seconds, + acquire_timeout=platform.db_acquire_timeout_seconds, + command_timeout=platform.db_command_timeout_seconds, + ) + await database.open() + try: + async with s3_client( + endpoint=settings.s3_endpoint, + region=settings.s3_region, + access_key_id=settings.s3_access_key_id.get_secret_value(), + secret_access_key=settings.s3_secret_access_key.get_secret_value(), + connect_timeout=settings.s3_connect_timeout_seconds, + read_timeout=settings.s3_read_timeout_seconds, + max_attempts=settings.s3_max_attempts, + ) as client: + reconciler = StorageReconciler( + lambda: PostgresAttachmentsUnitOfWork(database), + S3ObjectStorage(client, settings.s3_bucket), + PostgresSingleRun(database, LOCK_KEY), + MonotonicUtcClock(), + logger, + ) + return await reconciler(command) + finally: + await database.close() + + +def report_of(command: ReconcileStorage, result: Reconciliation) -> dict[str, Any]: + return { + "mode": "apply" if command.apply else "dry-run", + "skipped": result.skipped, + "grace_seconds": int(command.grace.total_seconds()), + "skew_seconds": int(command.skew.total_seconds()), + "deep": command.deep, + "page_size": command.page_size, + "scanned": {"objects": result.objects, "rows": result.rows}, + "found": {name: result.found[name] for name in CLASSES}, + "fixed": {name: result.fixed[name] for name in FIXABLE}, + "rechecked": dict(result.rechecked), + "errors": result.errors, + "samples": result.samples, + "cost": { + "seconds": result.seconds, + "requests": {name: result.requests[name] for name in REQUESTS}, + "waited_seconds": {name: round(spent, 3) for name, spent in result.waited.items()}, + "hashed_bytes": result.hashed_bytes, + "max_rss_mib": round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024, 1), + }, + } + + +def main(argv: Sequence[str] | None = None) -> None: + command = command_of(argv) + platform, settings = PlatformSettings(), AttachmentsSettings() + logger = StructlogLogger( + level=platform.log_level, allowed_fields=PLATFORM_FIELDS | LOG_FIELDS, stream=sys.stderr + ) + try: + result = asyncio.run(reconcile(command, platform, settings, logger)) + except Unavailable as error: + logger.error("reconcile.failed", error=type(error.__cause__ or error).__name__) + raise SystemExit(1) from None + sys.stdout.write(json.dumps(report_of(command, result), ensure_ascii=False, indent=2) + "\n") + raise SystemExit(1 if result.errors else 0) + + +if __name__ == "__main__": + main() diff --git a/src/messenger/attachments/infrastructure/postgres.py b/src/messenger/attachments/infrastructure/postgres.py index c47d0f18..8d95508f 100644 --- a/src/messenger/attachments/infrastructure/postgres.py +++ b/src/messenger/attachments/infrastructure/postgres.py @@ -1,10 +1,12 @@ +from collections.abc import AsyncIterator, Sequence +from contextlib import asynccontextmanager from datetime import datetime from uuid import UUID from asyncpg import ForeignKeyViolationError, Record from messenger.attachments.domain.errors import ChatNotFound -from messenger.attachments.domain.models import Attachment, AttachmentStatus +from messenger.attachments.domain.models import Attachment, AttachmentStatus, Quarantine from messenger.attachments.domain.values import Filename, ImageInfo, ImageKind from messenger.shared.application.errors import Unavailable from messenger.shared.infrastructure.postgres import ( @@ -22,7 +24,7 @@ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) MARK = "UPDATE attachments SET status = $2, updated_at = $3 WHERE id = $1 AND status = 'pending'" COLUMNS = """ SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height, - object_key, status, created_at, updated_at + object_key, status, created_at, updated_at, quarantine_reason FROM attachments """ READY = COLUMNS + "WHERE id = $1 AND status = 'ready'" @@ -33,6 +35,15 @@ ABANDONED = ( ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED""" ) REMOVE = "DELETE FROM attachments WHERE id = $1 AND status = 'pending'" +PAGE = COLUMNS + "WHERE object_key > $1 ORDER BY object_key LIMIT $2" +BY_KEY = COLUMNS + "WHERE object_key = $1" +CLAIM = LOCK + " SKIP LOCKED" +QUARANTINE = """ +UPDATE attachments +SET quarantine_reason = $2::text, + quarantined_at = CASE WHEN $2::text IS NULL THEN NULL ELSE now() END +WHERE id = $1 AND status = 'ready' +""" def attachment_of(row: Record) -> Attachment: @@ -48,6 +59,7 @@ def attachment_of(row: Record) -> Attachment: status=AttachmentStatus(row["status"]), created_at=row["created_at"], updated_at=row["updated_at"], + quarantine=Quarantine(row["quarantine_reason"]) if row["quarantine_reason"] else None, ) @@ -100,6 +112,21 @@ class PostgresAttachmentRepository: await self._connection.execute(REMOVE, attachment.id) self._seen.append(attachment) + async def page_after(self, key: str, limit: int) -> Sequence[Attachment]: + return [attachment_of(row) for row in await self._connection.fetch(PAGE, key, limit)] + + async def by_key(self, key: str) -> Attachment | None: + row = await self._connection.fetchrow(BY_KEY, key) + return None if row is None else attachment_of(row) + + async def claim(self, attachment_id: UUID) -> Attachment | None: + row = await self._connection.fetchrow(CLAIM, attachment_id) + return None if row is None else attachment_of(row) + + async def mark(self, attachment: Attachment) -> None: + reason = None if attachment.quarantine is None else attachment.quarantine.value + await self._connection.execute(QUARANTINE, attachment.id, reason) + class PostgresAttachmentsUnitOfWork(PostgresUnitOfWork): __slots__ = () @@ -119,3 +146,21 @@ class PostgresAttachmentDirectory: async with self._database.connection() as connection: row = await connection.fetchrow(READY, attachment_id) return None if row is None else attachment_of(row) + + +class PostgresSingleRun: + __slots__ = ("_database", "_key") + + def __init__(self, database: Database, key: int) -> None: + self._database = database + self._key = key + + @asynccontextmanager + async def hold(self) -> AsyncIterator[bool]: + async with self._database.connection() as connection: + held = await connection.fetchval("SELECT pg_try_advisory_lock($1)", self._key) + try: + yield held + finally: + if held: + await connection.fetchval("SELECT pg_advisory_unlock($1)", self._key) diff --git a/src/messenger/attachments/infrastructure/s3.py b/src/messenger/attachments/infrastructure/s3.py index 5d47ecf0..dbebf5d6 100644 --- a/src/messenger/attachments/infrastructure/s3.py +++ b/src/messenger/attachments/infrastructure/s3.py @@ -1,4 +1,4 @@ -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Sequence from contextlib import asynccontextmanager from typing import Any @@ -8,7 +8,7 @@ from botocore.exceptions import BotoCoreError, ClientError from botocore.handlers import add_expect_header from messenger.attachments.application.errors import ObjectMissingError -from messenger.attachments.application.ports import ObjectContent +from messenger.attachments.application.ports import ObjectContent, StoredObject from messenger.shared.application.errors import Unavailable CHUNK_BYTES = 64 * 1024 @@ -83,6 +83,28 @@ class S3ObjectStorage: except FAILURES as error: raise Unavailable("S3 недоступно") from error + async def listing(self, prefix: str, page_size: int) -> AsyncIterator[Sequence[StoredObject]]: + pages = self._client.get_paginator("list_objects_v2").paginate( + Bucket=self._bucket, Prefix=prefix, PaginationConfig={"PageSize": page_size} + ) + try: + async for page in pages: + yield [ + StoredObject(item["Key"], item["Size"], item["LastModified"]) + for item in page.get("Contents", ()) + ] + except FAILURES as error: + raise Unavailable("S3 недоступно") from error + + async def stat(self, key: str) -> StoredObject | None: + try: + head = await self._client.head_object(Bucket=self._bucket, Key=key) + except FAILURES as error: + if missing(error): + return None + raise Unavailable("S3 недоступно") from error + return StoredObject(key, head["ContentLength"], head["LastModified"]) + async def _chunks(self, body: Any) -> AsyncIterator[bytes]: async with body as stream: async for chunk in stream.iter_chunks(CHUNK_BYTES): diff --git a/src/messenger/shared/infrastructure/logging.py b/src/messenger/shared/infrastructure/logging.py index a3936546..c7259691 100644 --- a/src/messenger/shared/infrastructure/logging.py +++ b/src/messenger/shared/infrastructure/logging.py @@ -1,6 +1,6 @@ import logging import sys -from typing import Any +from typing import Any, TextIO import orjson import structlog @@ -51,7 +51,11 @@ def field_filter(allowed: frozenset[str]) -> Processor: return drop_unlisted_fields -def configure(level: str = "INFO", allowed_fields: frozenset[str] = PLATFORM_FIELDS) -> None: +def configure( + level: str = "INFO", + allowed_fields: frozenset[str] = PLATFORM_FIELDS, + stream: TextIO | None = None, +) -> None: shared = [ structlog.contextvars.merge_contextvars, structlog.processors.add_log_level, @@ -63,7 +67,7 @@ def configure(level: str = "INFO", allowed_fields: frozenset[str] = PLATFORM_FIE wrapper_class=structlog.stdlib.BoundLogger, cache_logger_on_first_use=False, ) - handler = logging.StreamHandler(sys.stdout) + handler = logging.StreamHandler(stream or sys.stdout) handler.setFormatter( structlog.stdlib.ProcessorFormatter( foreign_pre_chain=shared, @@ -99,8 +103,9 @@ class StructlogLogger: name: str = "messenger", level: str = "INFO", allowed_fields: frozenset[str] = PLATFORM_FIELDS, + stream: TextIO | None = None, ) -> None: - configure(level, allowed_fields) + configure(level, allowed_fields, stream) self._logger = structlog.get_logger(name) def info(self, event: str, /, **fields: Any) -> None: diff --git a/student-tests/adapters/test_s3_storage.py b/student-tests/adapters/test_s3_storage.py index e4e631c3..786c702c 100644 --- a/student-tests/adapters/test_s3_storage.py +++ b/student-tests/adapters/test_s3_storage.py @@ -71,6 +71,27 @@ async def test_round_trip_of_the_largest_object(rustfs: str) -> None: await objects.delete(key) +async def test_listing_is_paged_in_byte_order_and_stat_reads_size(rustfs: str) -> None: + prefix = f"reconcile-{uuid4().hex}/" + keys = [f"{prefix}{name}" for name in ("b", "a", "Z", "a-1", "é")] + async with storage(rustfs) as objects: + for size, key in enumerate(keys, start=1): + await objects.put(key, b"x" * size, "image/png") + pages = [page async for page in objects.listing(prefix, 2)] + assert [len(page) for page in pages] == [2, 2, 1] + listed = [item.key for page in pages for item in page] + assert listed == sorted(keys, key=str.encode) + sizes = {item.key: item.size for page in pages for item in page} + assert sizes == {key: size for size, key in enumerate(keys, start=1)} + found = await objects.stat(keys[0]) + assert found is not None + assert found.size == 1 + assert await objects.stat(f"{prefix}absent") is None + for key in keys: + await objects.delete(key) + assert not [item async for page in objects.listing(prefix, 2) for item in page] + + async def test_unreachable_endpoint_is_unavailable_in_bounded_time() -> None: started = time.monotonic() async with storage_without_bucket("http://127.0.0.1:1") as objects: @@ -78,7 +99,11 @@ async def test_unreachable_endpoint_is_unavailable_in_bounded_time() -> None: await objects.put("attachments/x", b"x", "image/png") with pytest.raises(Unavailable): await objects.open("attachments/x") - assert time.monotonic() - started < 8 + with pytest.raises(Unavailable): + await objects.stat("attachments/x") + with pytest.raises(Unavailable): + await anext(aiter(objects.listing("attachments/", 10))) + assert time.monotonic() - started < 12 @asynccontextmanager diff --git a/student-tests/api/test_reconciler.py b/student-tests/api/test_reconciler.py new file mode 100644 index 00000000..c582bcd3 --- /dev/null +++ b/student-tests/api/test_reconciler.py @@ -0,0 +1,273 @@ +import asyncio +import hashlib +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from dataclasses import dataclass +from datetime import UTC, datetime, timedelta +from typing import Any +from uuid import uuid4 + +import asyncpg +import pytest +from httpx import AsyncClient +from test_attachments import storage, trio, upload + +from conftest import actor, keyed, running_app +from fakes import MemoryObjectStorage, NullLogger +from messenger.attachments.application.commands import ReconcileStorage +from messenger.attachments.application.reconcile import Reconciliation, StorageReconciler +from messenger.attachments.entrypoints.reconcile import LOCK_KEY +from messenger.attachments.infrastructure.postgres import ( + PostgresAttachmentsUnitOfWork, + PostgresSingleRun, +) +from messenger.migrate import migrate +from messenger.shared.infrastructure.clock import MonotonicUtcClock +from messenger.shared.infrastructure.postgres import Database +from pictures import SAMPLE + +GRACE = timedelta(seconds=60) +OLD = timedelta(hours=2) +AGED_PENDING = """UPDATE attachments SET status = 'pending', updated_at = created_at, +created_at = created_at - interval '2 hours' WHERE id = $1""" +LATE_ROW = """INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, + sha256, width, height, object_key, status, created_at, updated_at) +SELECT gen_random_uuid(), chat_id, owner_id, 'late.png', content_type, size_bytes, sha256, + width, height, $2, 'pending', now(), now() +FROM attachments WHERE id = $1""" + + +@pytest.fixture +def dsn(database: str) -> str: + name = f"reconcile_{uuid4().hex[:12]}" + + async def create() -> None: + connection = await asyncpg.connect(database) + try: + await connection.execute(f"CREATE DATABASE {name}") + finally: + await connection.close() + await migrate(target) + + target = f"{database.rsplit('/', 1)[0]}/{name}" + asyncio.run(create()) + return target + + +@dataclass(slots=True) +class Stand: + http: AsyncClient + store: MemoryObjectStorage + database: Database + users: tuple[dict[str, Any], ...] + + async def run(self, *, apply: bool = False, deep: bool = False) -> Reconciliation: + reconciler = StorageReconciler( + lambda: PostgresAttachmentsUnitOfWork(self.database), + self.store, + PostgresSingleRun(self.database, LOCK_KEY), + MonotonicUtcClock(), + NullLogger(), + ) + command = ReconcileStorage( + apply=apply, grace=GRACE, skew=timedelta(0), deep=deep, page_size=2 + ) + return await reconciler(command) + + async def sql(self, query: str, *args: Any) -> Any: + async with self.database.connection() as connection: + return await connection.fetch(query, *args) + + async def upload(self) -> dict[str, Any]: + alice, _, _, chat = self.users + response = await upload(self.http, alice, chat) + assert response.status_code == 201, response.text + return response.json() + + def age(self, key: str) -> None: + self.store.modified[key] = datetime.now(UTC) - OLD + + def state(self) -> dict[str, bytes]: + return {key: data for key, (data, _) in self.store.objects.items()} + + +@asynccontextmanager +async def stand(dsn: str) -> AsyncIterator[Stand]: + async with running_app(database_url=dsn) as http: + database = Database( + dsn, max_size=12, connect_timeout=2, acquire_timeout=2, command_timeout=5 + ) + await database.open() + try: + yield Stand(http, await storage(http), database, await trio(http)) + finally: + await database.close() + + +def key(attachment: dict[str, Any]) -> str: + return f"attachments/{attachment['id']}" + + +async def damage(s: Stand) -> dict[str, Any]: + alice, _, _, chat = s.users + healthy, missing, sized, flipped, stale, fresh = [await s.upload() for _ in range(6)] + posted = await s.http.post( + f"/api/v1/chats/{chat['id']}/messages", + json={"text": "", "attachment_ids": [missing["id"]]}, + headers=keyed(alice), + ) + assert posted.status_code == 201, posted.text + del s.store.objects[key(missing)] + s.store.objects[key(sized)] = (SAMPLE[:100], "image/png") + s.store.objects[key(flipped)] = (SAMPLE[::-1], "image/png") + await s.sql(AGED_PENDING, stale["id"]) + await s.sql("UPDATE attachments SET status = 'pending' WHERE id = $1", fresh["id"]) + orphan, newborn = f"attachments/{uuid4()}", f"attachments/{uuid4()}" + s.store.objects[orphan] = s.store.objects[newborn] = (SAMPLE, "image/png") + s.store.modified[newborn] = datetime.now(UTC) + s.age(orphan) + return { + "healthy": healthy, + "missing": missing, + "sized": sized, + "flipped": flipped, + "stale": stale, + "fresh": fresh, + "orphan": orphan, + "newborn": newborn, + "message": posted.json(), + } + + +EVERY_CLASS = { + "orphan_stale": 1, + "orphan_fresh": 1, + "missing": 1, + "size_mismatch": 1, + "sha_mismatch": 1, + "pending_stale": 1, + "pending_fresh": 1, +} + + +async def test_dry_run_reports_every_class_and_changes_nothing(dsn: str) -> None: + async with stand(dsn) as s: + await damage(s) + objects = s.state() + rows = await s.sql("SELECT id, status, quarantine_reason FROM attachments ORDER BY id") + shallow = await s.run() + deep = await s.run(deep=True) + assert s.state() == objects + assert ( + await s.sql("SELECT id, status, quarantine_reason FROM attachments ORDER BY id") == rows + ) + assert dict(deep.found) == EVERY_CLASS + assert dict(shallow.found) == {k: v for k, v in EVERY_CLASS.items() if k != "sha_mismatch"} + assert not deep.fixed + assert not shallow.fixed + assert shallow.requests == {"s3_list": 4, "sql": 4} + assert deep.requests["s3_get"] == 2 + + +async def test_apply_fixes_what_it_found_and_repeats_as_noop(dsn: str) -> None: + async with stand(dsn) as s: + damaged = await damage(s) + alice, bob, _, chat = s.users + first = await s.run(apply=True, deep=True) + second = await s.run(apply=True, deep=True) + reasons = { + str(row["id"]): row["quarantine_reason"] + for row in await s.sql("SELECT id, quarantine_reason FROM attachments") + } + history = await s.http.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(bob)) + meta = await s.http.get( + f"/api/v1/attachments/{damaged['flipped']['id']}", headers=actor(bob) + ) + broken = await s.http.get( + f"/api/v1/attachments/{damaged['flipped']['id']}/content", headers=actor(bob) + ) + intact = await s.http.get( + f"/api/v1/attachments/{damaged['healthy']['id']}/content", headers=actor(alice) + ) + objects = s.state() + assert {name: first.fixed[name] for name in EVERY_CLASS} == { + **EVERY_CLASS, + "orphan_fresh": 0, + "pending_fresh": 0, + } + assert not second.fixed + assert dict(second.found) == {"orphan_fresh": 1, "pending_fresh": 1, "quarantined": 3} + assert reasons[damaged["missing"]["id"]] == "missing" + assert reasons[damaged["sized"]["id"]] == "size_mismatch" + assert reasons[damaged["flipped"]["id"]] == "sha_mismatch" + assert reasons[damaged["healthy"]["id"]] is None + assert reasons[damaged["fresh"]["id"]] is None + assert damaged["stale"]["id"] not in reasons + assert key(damaged["stale"]) not in objects + assert damaged["orphan"] not in objects + assert damaged["newborn"] in objects + assert key(damaged["flipped"]) in objects + assert history.json()["items"][0]["attachment_ids"] == [damaged["missing"]["id"]] + assert meta.status_code == 200 + assert meta.json()["sha256"] == damaged["flipped"]["sha256"] + assert broken.status_code == 404 + assert broken.json()["error"]["code"] == "not_found" + assert intact.status_code == 200 + assert intact.content == SAMPLE + + +async def test_restored_object_leaves_quarantine(dsn: str) -> None: + async with stand(dsn) as s: + _, bob, _, _ = s.users + lost, flipped = await s.upload(), await s.upload() + del s.store.objects[key(lost)] + s.store.objects[key(flipped)] = (SAMPLE[::-1], "image/png") + isolated = await s.run(apply=True, deep=True) + s.store.objects[key(lost)] = s.store.objects[key(flipped)] = (SAMPLE, "image/png") + s.store.modified[key(lost)] = s.store.modified[key(flipped)] + shallow = await s.run(apply=True) + deep = await s.run(apply=True, deep=True) + content = await s.http.get(f"/api/v1/attachments/{lost['id']}/content", headers=actor(bob)) + assert isolated.fixed["missing"] == isolated.fixed["sha_mismatch"] == 1 + assert shallow.fixed["healed"] == 1 + assert shallow.found["quarantined"] == 1 + assert deep.fixed["healed"] == 1 + assert hashlib.sha256(content.content).hexdigest() == lost["sha256"] + + +async def test_row_written_after_listing_keeps_the_object(dsn: str) -> None: + async with stand(dsn) as s: + first, last = await s.upload(), await s.upload() + fresh, late = f"{key(first)}-a", f"{key(first)}-b" + for name in (fresh, late): + s.store.objects[name] = (SAMPLE, "image/png") + s.store.modified[name] = datetime.now(UTC) + s.age(late) + + async def row_appears() -> None: + s.store.after_page = None + await s.sql(LATE_ROW, first["id"], late) + + s.store.after_page = row_appears + report = await s.run(apply=True) + objects = s.state() + assert key(first) < fresh < late < key(last) + assert report.found["orphan_stale"] == 1 + assert report.rechecked["orphan_stale"] == 1 + assert not report.fixed + assert late in objects + + +async def test_second_pass_is_skipped_while_one_runs(dsn: str) -> None: + async with stand(dsn) as s: + orphan = f"attachments/{uuid4()}" + s.store.objects[orphan] = (SAMPLE, "image/png") + s.age(orphan) + async with PostgresSingleRun(s.database, LOCK_KEY).hold() as held: + busy = await s.run(apply=True) + free = await s.run(apply=True) + assert held + assert busy.skipped + assert not busy.found + assert not free.skipped + assert free.fixed["orphan_stale"] == 1 diff --git a/student-tests/fakes.py b/student-tests/fakes.py index e0d3633e..12a3eaaf 100644 --- a/student-tests/fakes.py +++ b/student-tests/fakes.py @@ -1,11 +1,11 @@ -from collections.abc import AsyncIterator, Awaitable, Callable -from datetime import datetime, timedelta +from collections.abc import AsyncIterator, Awaitable, Callable, Sequence +from datetime import UTC, datetime, timedelta from typing import Any from dishka import Provider, Scope, provide from messenger.attachments.application.errors import ObjectMissingError -from messenger.attachments.application.ports import ObjectContent, ObjectStorage +from messenger.attachments.application.ports import ObjectContent, ObjectStorage, StoredObject from messenger.shared.application.errors import Unavailable @@ -36,20 +36,38 @@ async def pieces(data: bytes, size: int = 65_536) -> AsyncIterator[bytes]: class MemoryObjectStorage: - __slots__ = ("after_put", "failing", "objects") + __slots__ = ("after_page", "after_put", "failing", "modified", "objects") def __init__(self) -> None: self.objects: dict[str, tuple[bytes, str]] = {} + self.modified: dict[str, datetime] = {} self.failing = False self.after_put: Callable[[str], Awaitable[None]] | None = None + self.after_page: Callable[[], Awaitable[None]] | None = None async def put(self, key: str, data: bytes, content_type: str) -> None: if self.failing: raise Unavailable("S3 недоступно") self.objects[key] = (bytes(data), content_type) + self.modified[key] = datetime.now(UTC) if self.after_put is not None: await self.after_put(key) + async def listing(self, prefix: str, page_size: int) -> AsyncIterator[Sequence[StoredObject]]: + if self.failing: + raise Unavailable("S3 недоступно") + keys = sorted(key for key in self.objects if key.startswith(prefix)) + for start in range(0, len(keys), page_size): + yield [self._stored(key) for key in keys[start : start + page_size]] + if self.after_page is not None: + await self.after_page() + + async def stat(self, key: str) -> StoredObject | None: + return self._stored(key) if key in self.objects else None + + def _stored(self, key: str) -> StoredObject: + return StoredObject(key, len(self.objects[key][0]), self.modified[key]) + async def open(self, key: str) -> ObjectContent: if self.failing: raise Unavailable("S3 недоступно") @@ -60,6 +78,7 @@ class MemoryObjectStorage: async def delete(self, key: str) -> None: self.objects.pop(key, None) + self.modified.pop(key, None) class MemoryStorageProvider(Provider):