diff --git a/openspec/changes/harden-lab4-storage-reconciler/tasks.md b/openspec/changes/harden-lab4-storage-reconciler/tasks.md index 542cebce..31379224 100644 --- a/openspec/changes/harden-lab4-storage-reconciler/tasks.md +++ b/openspec/changes/harden-lab4-storage-reconciler/tasks.md @@ -1,15 +1,15 @@ ## 1. Зона `attachments`: приложение -- [ ] 1.1 `Pass`: хеширование объекта строки в карантине с совпавшим размером и без `--deep`; `_healthy` только после совпавшего хеша -- [ ] 1.2 `Pass._rows`: выборка `страница + 1`, без пустой страницы -- [ ] 1.3 `StorageReconciler` с портом `EventPublisher`: публикация событий после удаления намерения -- [ ] 1.4 Проверка группы: `make lint` +- [x] 1.1 `Pass`: хеширование объекта строки в карантине с совпавшим размером и без `--deep`; `_healthy` только после совпавшего хеша +- [x] 1.2 `Pass._rows`: выборка `страница + 1`, без пустой страницы +- [x] 1.3 `StorageReconciler` с портом `EventPublisher`: публикация событий после удаления намерения +- [x] 1.4 Проверка группы: `make lint` ## 2. Зона `attachments`: точка входа -- [ ] 2.1 `AttachmentStorageProvider` в `entrypoints/ioc.py`; `ReconcileProvider` и сборка `make_async_container` в `entrypoints/reconcile.py`; журнал удалений через `EventBus` -- [ ] 2.2 `main`: любая ошибка прохода → `reconcile.failed`, код `1` -- [ ] 2.3 Проверка группы: API-тесты: другие байты той же длины оставляют карантин; восстановленные снимают его без `--deep` одним `GET`; SQL-страниц `⌈N/страница⌉`; событие `reason=reconcile`; ошибка не `Unavailable` → `reconcile.failed`, код `1` +- [x] 2.1 `AttachmentStorageProvider` в `entrypoints/ioc.py`; `ReconcileProvider` и сборка `make_async_container` в `entrypoints/reconcile.py`; журнал удалений через `EventBus` +- [x] 2.2 `main`: любая ошибка прохода → `reconcile.failed`, код `1` +- [x] 2.3 Проверка группы: API-тесты: другие байты той же длины оставляют карантин; восстановленные снимают его без `--deep` одним `GET`; SQL-страниц `⌈N/страница⌉`; событие `reason=reconcile`; ошибка не `Unavailable` → `reconcile.failed`, код `1` ## 3. Обвязка трека diff --git a/src/messenger/attachments/application/reconcile.py b/src/messenger/attachments/application/reconcile.py index 9de89638..638be559 100644 --- a/src/messenger/attachments/application/reconcile.py +++ b/src/messenger/attachments/application/reconcile.py @@ -23,7 +23,7 @@ from messenger.attachments.domain.models import ( Quarantine, ) from messenger.shared.application.errors import Unavailable -from messenger.shared.application.ports import Clock, Logger +from messenger.shared.application.ports import Clock, EventPublisher, Logger type UnitOfWorkFactory = Callable[[], AttachmentsUnitOfWork] @@ -46,7 +46,7 @@ class Reconciliation: class StorageReconciler: - __slots__ = ("_clock", "_logger", "_single", "_storage", "_uow") + __slots__ = ("_clock", "_logger", "_publisher", "_single", "_storage", "_uow") def __init__( self, @@ -54,13 +54,16 @@ class StorageReconciler: storage: ObjectStorage, single: SingleRun, clock: Clock, + *, logger: Logger, + publisher: EventPublisher, ) -> None: self._uow = uow self._storage = storage self._single = single self._clock = clock self._logger = logger + self._publisher = publisher async def __call__(self, command: ReconcileStorage) -> Reconciliation: report = Reconciliation(apply=command.apply) @@ -76,13 +79,23 @@ class StorageReconciler: before=before, report=report, logger=self._logger, + publisher=self._publisher, ).run() report.seconds = round(monotonic() - started, 3) return report class Pass: - __slots__ = ("_before", "_command", "_logger", "_report", "_slots", "_storage", "_uow") + __slots__ = ( + "_before", + "_command", + "_logger", + "_publisher", + "_report", + "_slots", + "_storage", + "_uow", + ) def __init__( self, @@ -93,6 +106,7 @@ class Pass: before: datetime, report: Reconciliation, logger: Logger, + publisher: EventPublisher, ) -> None: self._uow = uow self._storage = storage @@ -100,6 +114,7 @@ class Pass: self._before = before self._report = report self._logger = logger + self._publisher = publisher self._slots = asyncio.Semaphore(command.deep_concurrency) async def run(self) -> None: @@ -141,14 +156,15 @@ class Pass: async def _rows(self) -> AsyncIterator[Attachment]: after, size = "", self._command.page_size while True: - page = await self._timed("sql", self._page(after, size)) + page = await self._timed("sql", self._page(after, size + 1)) self._report.requests["sql"] += 1 - self._report.rows += len(page) - for row in page: + rows = page[:size] + self._report.rows += len(rows) + for row in rows: yield row - if len(page) < size: + if len(page) <= size: return - after = page[-1].object_key + after = rows[-1].object_key async def _page(self, after: str, size: int) -> Sequence[Attachment]: uow = self._uow() @@ -206,11 +222,9 @@ class Pass: await self._broken(row, Quarantine.MISSING) elif item.size != row.size_bytes: await self._broken(row, Quarantine.SIZE_MISMATCH) - elif self._command.deep: + elif self._command.deep or row.quarantine is not None: 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: @@ -228,7 +242,7 @@ class Pass: elif digest != row.sha256: await self._broken(row, Quarantine.SHA_MISMATCH) else: - await self._healthy(row, verified=True) + await self._healthy(row) async def _digest(self, key: str) -> str | None: self._report.requests["s3_get"] += 1 @@ -260,12 +274,9 @@ class Pass: await self._mark(row) return True - async def _healthy(self, row: Attachment, *, verified: bool) -> None: + async def _healthy(self, row: Attachment) -> 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) @@ -303,4 +314,5 @@ class Pass: return False self._report.requests["s3_delete"] += 1 await drop(uow, self._storage, current, "reconcile") + await self._publisher.publish(uow.collect_new_events()) return True diff --git a/src/messenger/attachments/entrypoints/ioc.py b/src/messenger/attachments/entrypoints/ioc.py index a7ca5464..fa734643 100644 --- a/src/messenger/attachments/entrypoints/ioc.py +++ b/src/messenger/attachments/entrypoints/ioc.py @@ -30,7 +30,7 @@ from messenger.shared.application.ports import Clock, EventPublisher, IdGenerato from messenger.shared.infrastructure.postgres import Database -class AttachmentsProvider(Provider): +class AttachmentStorageProvider(Provider): def __init__(self, settings: AttachmentsSettings) -> None: super().__init__() self._settings = settings @@ -52,6 +52,8 @@ class AttachmentsProvider(Provider): ) as client: yield S3ObjectStorage(client, settings.s3_bucket) + +class AttachmentsProvider(AttachmentStorageProvider): @provide(scope=Scope.APP) def images(self, settings: AttachmentsSettings) -> ImageInspector: return PillowImageInspector(settings.max_image_pixels, settings.image_check_concurrency) diff --git a/src/messenger/attachments/entrypoints/reconcile.py b/src/messenger/attachments/entrypoints/reconcile.py index f1479605..bdecddff 100644 --- a/src/messenger/attachments/entrypoints/reconcile.py +++ b/src/messenger/attachments/entrypoints/reconcile.py @@ -7,19 +7,24 @@ from collections.abc import Callable, Sequence from datetime import timedelta from typing import Any +from dishka import Scope, make_async_container, provide + from messenger.attachments.application.commands import ReconcileStorage +from messenger.attachments.application.ports import ObjectStorage 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.domain.events import AttachmentDiscarded +from messenger.attachments.entrypoints.ioc import AttachmentStorageProvider +from messenger.attachments.entrypoints.journal import LOG_FIELDS, AttachmentsJournal 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.application.messagebus import EventBus +from messenger.shared.application.ports import Clock, EventPublisher, Logger from messenger.shared.config import PlatformSettings -from messenger.shared.infrastructure.clock import MonotonicUtcClock +from messenger.shared.entrypoints.ioc import PlatformProvider from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger from messenger.shared.infrastructure.postgres import Database @@ -61,7 +66,7 @@ def command_of(argv: Sequence[str] | None = None) -> ReconcileStorage: 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("--deep-concurrency", type=bounded(1, 48), default=8) parser.add_argument("--samples", type=bounded(0, 1000), default=20) args = parser.parse_args(argv) return ReconcileStorage( @@ -75,40 +80,52 @@ def command_of(argv: Sequence[str] | None = None) -> ReconcileStorage: ) +class ReconcileProvider(AttachmentStorageProvider): + @provide(scope=Scope.APP) + def reconciler( + self, + database: Database, + storage: ObjectStorage, + clock: Clock, + logger: Logger, + publisher: EventPublisher, + ) -> StorageReconciler: + return StorageReconciler( + lambda: PostgresAttachmentsUnitOfWork(database), + storage, + PostgresSingleRun(database, LOCK_KEY), + clock, + logger=logger, + publisher=publisher, + ) + + 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, + container = make_async_container( + PlatformProvider(platform, logger), ReconcileProvider(settings) ) - await database.open() + bus = await container.get(EventBus) + bus.subscribe(AttachmentDiscarded, AttachmentsJournal(logger).on_attachment_discarded) + bus.start() 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) + reconciler = await container.get(StorageReconciler) + return await reconciler(command) finally: - await database.close() + await bus.stop() + await container.close() + + +def failure(error: BaseException) -> str: + if isinstance(error, BaseExceptionGroup): + return failure(error.exceptions[0]) + if isinstance(error, Unavailable) and error.__cause__ is not None: + return type(error.__cause__).__name__ + return type(error).__name__ def report_of(command: ReconcileStorage, result: Reconciliation) -> dict[str, Any]: @@ -139,14 +156,15 @@ def report_of(command: ReconcileStorage, result: Reconciliation) -> dict[str, An def main(argv: Sequence[str] | None = None) -> None: command = command_of(argv) - platform, settings = PlatformSettings(), AttachmentsSettings() + platform = PlatformSettings(db_pool_max_size=command.deep_concurrency + 2) + settings = 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__) + except Exception as error: + logger.error("reconcile.failed", error=failure(error)) 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) diff --git a/student-tests/api/test_reconciler.py b/student-tests/api/test_reconciler.py index 737664cd..68859756 100644 --- a/student-tests/api/test_reconciler.py +++ b/student-tests/api/test_reconciler.py @@ -5,7 +5,7 @@ from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import UTC, datetime, timedelta from typing import Any -from uuid import uuid4 +from uuid import UUID, uuid4 import asyncpg import pytest @@ -13,9 +13,11 @@ from httpx import AsyncClient from test_attachments import storage, trio, upload from conftest import actor, keyed, running_app -from fakes import MemoryObjectStorage, NullLogger +from fakes import MemoryObjectStorage, NullLogger, RecordingPublisher from messenger.attachments.application.commands import ReconcileStorage from messenger.attachments.application.reconcile import Reconciliation, StorageReconciler +from messenger.attachments.domain.events import AttachmentDiscarded +from messenger.attachments.entrypoints import reconcile as entrypoint from messenger.attachments.entrypoints.reconcile import LOCK_KEY from messenger.attachments.infrastructure.postgres import ( PostgresAttachmentsUnitOfWork, @@ -61,6 +63,7 @@ class Stand: store: MemoryObjectStorage database: Database users: tuple[dict[str, Any], ...] + published: RecordingPublisher async def run(self, *, apply: bool = False, deep: bool = False) -> Reconciliation: reconciler = StorageReconciler( @@ -68,7 +71,8 @@ class Stand: self.store, PostgresSingleRun(self.database, LOCK_KEY), MonotonicUtcClock(), - NullLogger(), + logger=NullLogger(), + publisher=self.published, ) command = ReconcileStorage( apply=apply, grace=GRACE, skew=timedelta(0), deep=deep, page_size=2 @@ -100,7 +104,7 @@ async def stand(dsn: str) -> AsyncIterator[Stand]: ) await database.open() try: - yield Stand(http, await storage(http), database, await trio(http)) + yield Stand(http, await storage(http), database, await trio(http), RecordingPublisher()) finally: await database.close() @@ -166,7 +170,7 @@ async def test_dry_run_reports_every_class_and_changes_nothing(dsn: str) -> None 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 shallow.requests == {"s3_list": 4, "sql": 3} assert deep.requests["s3_get"] == 2 @@ -202,6 +206,11 @@ async def test_apply_fixes_what_it_found_and_repeats_as_noop(dsn: str) -> None: assert reasons[damaged["sized"]["id"]] == "size_mismatch" assert reasons[damaged["flipped"]["id"]] == "sha_mismatch" assert reasons[damaged["healthy"]["id"]] is None + assert [ + (event.attachment_id, event.reason) + for event in s.published.events + if isinstance(event, AttachmentDiscarded) + ] == [(UUID(damaged["stale"]["id"]), "reconcile")] assert reasons[damaged["fresh"]["id"]] is None assert damaged["stale"]["id"] not in reasons assert key(damaged["stale"]) not in objects @@ -227,15 +236,69 @@ async def test_restored_object_leaves_quarantine(dsn: str) -> None: 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) + again = await s.run(apply=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 shallow.fixed["healed"] == 2 + assert shallow.requests["s3_get"] == 2 + assert not again.fixed + assert again.requests["s3_get"] == 0 assert hashlib.sha256(content.content).hexdigest() == lost["sha256"] +async def test_other_bytes_of_the_same_length_keep_the_quarantine(dsn: str) -> None: + async with stand(dsn) as s: + _, bob, _, _ = s.users + lost = await s.upload() + del s.store.objects[key(lost)] + isolated = await s.run(apply=True) + s.store.objects[key(lost)] = (bytes(len(SAMPLE)), "image/png") + s.age(key(lost)) + shallow = await s.run(apply=True) + content = await s.http.get(f"/api/v1/attachments/{lost['id']}/content", headers=actor(bob)) + reason = await s.sql("SELECT quarantine_reason FROM attachments WHERE id = $1", lost["id"]) + assert isolated.fixed["missing"] == 1 + assert not shallow.fixed + assert shallow.found["quarantined"] == 1 + assert shallow.requests["s3_get"] == 1 + assert content.status_code == 404 + assert reason[0]["quarantine_reason"] == "missing" + + +async def test_pages_of_rows_are_not_followed_by_an_empty_one(dsn: str) -> None: + async with stand(dsn) as s: + empty = await s.run() + for _ in range(4): + await s.upload() + full = await s.run() + assert (empty.rows, empty.requests["sql"]) == (0, 1) + assert (full.rows, full.requests["sql"]) == (4, 2) + + +def test_any_pass_failure_ends_as_reconcile_failed( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + async def broken(*_args: Any) -> Reconciliation: + cancelled = asyncpg.exceptions.QueryCanceledError("statement timeout") + raise ExceptionGroup("pass", [cancelled]) + + monkeypatch.setattr(entrypoint, "reconcile", broken) + for name, value in { + "DATABASE_URL": "postgresql://unused@127.0.0.1:1/unused", + "S3_ACCESS_KEY_ID": "reconciler", + "S3_SECRET_ACCESS_KEY": "reconciler-secret", + }.items(): + monkeypatch.setenv(name, value) + with pytest.raises(SystemExit) as stopped: + entrypoint.main(["--apply"]) + captured = capsys.readouterr() + assert stopped.value.code == 1 + assert captured.out == "" + assert "reconcile.failed" in captured.err + assert "QueryCanceledError" in captured.err + assert "Traceback" not in captured.err + + 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() diff --git a/student-tests/fakes.py b/student-tests/fakes.py index 2572fc8d..82ac80f8 100644 --- a/student-tests/fakes.py +++ b/student-tests/fakes.py @@ -88,3 +88,13 @@ class MemoryStorageProvider(Provider): @provide(scope=Scope.APP) def storage(self) -> ObjectStorage: return MemoryObjectStorage() + + +class RecordingPublisher: + __slots__ = ("events",) + + def __init__(self) -> None: + self.events: list[Any] = [] + + async def publish(self, events: Sequence[Any]) -> None: + self.events.extend(events)