ЛР 4 — БПИ2303 — Костылев — на 5 #162
@@ -1,15 +1,15 @@
|
|||||||
## 1. Зона `attachments`: приложение
|
## 1. Зона `attachments`: приложение
|
||||||
|
|
||||||
- [ ] 1.1 `Pass`: хеширование объекта строки в карантине с совпавшим размером и без `--deep`; `_healthy` только после совпавшего хеша
|
- [x] 1.1 `Pass`: хеширование объекта строки в карантине с совпавшим размером и без `--deep`; `_healthy` только после совпавшего хеша
|
||||||
- [ ] 1.2 `Pass._rows`: выборка `страница + 1`, без пустой страницы
|
- [x] 1.2 `Pass._rows`: выборка `страница + 1`, без пустой страницы
|
||||||
- [ ] 1.3 `StorageReconciler` с портом `EventPublisher`: публикация событий после удаления намерения
|
- [x] 1.3 `StorageReconciler` с портом `EventPublisher`: публикация событий после удаления намерения
|
||||||
- [ ] 1.4 Проверка группы: `make lint`
|
- [x] 1.4 Проверка группы: `make lint`
|
||||||
|
|
||||||
## 2. Зона `attachments`: точка входа
|
## 2. Зона `attachments`: точка входа
|
||||||
|
|
||||||
- [ ] 2.1 `AttachmentStorageProvider` в `entrypoints/ioc.py`; `ReconcileProvider` и сборка `make_async_container` в `entrypoints/reconcile.py`; журнал удалений через `EventBus`
|
- [x] 2.1 `AttachmentStorageProvider` в `entrypoints/ioc.py`; `ReconcileProvider` и сборка `make_async_container` в `entrypoints/reconcile.py`; журнал удалений через `EventBus`
|
||||||
- [ ] 2.2 `main`: любая ошибка прохода → `reconcile.failed`, код `1`
|
- [x] 2.2 `main`: любая ошибка прохода → `reconcile.failed`, код `1`
|
||||||
- [ ] 2.3 Проверка группы: API-тесты: другие байты той же длины оставляют карантин; восстановленные снимают его без `--deep` одним `GET`; SQL-страниц `⌈N/страница⌉`; событие `reason=reconcile`; ошибка не `Unavailable` → `reconcile.failed`, код `1`
|
- [x] 2.3 Проверка группы: API-тесты: другие байты той же длины оставляют карантин; восстановленные снимают его без `--deep` одним `GET`; SQL-страниц `⌈N/страница⌉`; событие `reason=reconcile`; ошибка не `Unavailable` → `reconcile.failed`, код `1`
|
||||||
|
|
||||||
## 3. Обвязка трека
|
## 3. Обвязка трека
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ from messenger.attachments.domain.models import (
|
|||||||
Quarantine,
|
Quarantine,
|
||||||
)
|
)
|
||||||
from messenger.shared.application.errors import Unavailable
|
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]
|
type UnitOfWorkFactory = Callable[[], AttachmentsUnitOfWork]
|
||||||
|
|
||||||
@@ -46,7 +46,7 @@ class Reconciliation:
|
|||||||
|
|
||||||
|
|
||||||
class StorageReconciler:
|
class StorageReconciler:
|
||||||
__slots__ = ("_clock", "_logger", "_single", "_storage", "_uow")
|
__slots__ = ("_clock", "_logger", "_publisher", "_single", "_storage", "_uow")
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -54,13 +54,16 @@ class StorageReconciler:
|
|||||||
storage: ObjectStorage,
|
storage: ObjectStorage,
|
||||||
single: SingleRun,
|
single: SingleRun,
|
||||||
clock: Clock,
|
clock: Clock,
|
||||||
|
*,
|
||||||
logger: Logger,
|
logger: Logger,
|
||||||
|
publisher: EventPublisher,
|
||||||
) -> None:
|
) -> None:
|
||||||
self._uow = uow
|
self._uow = uow
|
||||||
self._storage = storage
|
self._storage = storage
|
||||||
self._single = single
|
self._single = single
|
||||||
self._clock = clock
|
self._clock = clock
|
||||||
self._logger = logger
|
self._logger = logger
|
||||||
|
self._publisher = publisher
|
||||||
|
|
||||||
async def __call__(self, command: ReconcileStorage) -> Reconciliation:
|
async def __call__(self, command: ReconcileStorage) -> Reconciliation:
|
||||||
report = Reconciliation(apply=command.apply)
|
report = Reconciliation(apply=command.apply)
|
||||||
@@ -76,13 +79,23 @@ class StorageReconciler:
|
|||||||
before=before,
|
before=before,
|
||||||
report=report,
|
report=report,
|
||||||
logger=self._logger,
|
logger=self._logger,
|
||||||
|
publisher=self._publisher,
|
||||||
).run()
|
).run()
|
||||||
report.seconds = round(monotonic() - started, 3)
|
report.seconds = round(monotonic() - started, 3)
|
||||||
return report
|
return report
|
||||||
|
|
||||||
|
|
||||||
class Pass:
|
class Pass:
|
||||||
__slots__ = ("_before", "_command", "_logger", "_report", "_slots", "_storage", "_uow")
|
__slots__ = (
|
||||||
|
"_before",
|
||||||
|
"_command",
|
||||||
|
"_logger",
|
||||||
|
"_publisher",
|
||||||
|
"_report",
|
||||||
|
"_slots",
|
||||||
|
"_storage",
|
||||||
|
"_uow",
|
||||||
|
)
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -93,6 +106,7 @@ class Pass:
|
|||||||
before: datetime,
|
before: datetime,
|
||||||
report: Reconciliation,
|
report: Reconciliation,
|
||||||
logger: Logger,
|
logger: Logger,
|
||||||
|
publisher: EventPublisher,
|
||||||
) -> None:
|
) -> None:
|
||||||
self._uow = uow
|
self._uow = uow
|
||||||
self._storage = storage
|
self._storage = storage
|
||||||
@@ -100,6 +114,7 @@ class Pass:
|
|||||||
self._before = before
|
self._before = before
|
||||||
self._report = report
|
self._report = report
|
||||||
self._logger = logger
|
self._logger = logger
|
||||||
|
self._publisher = publisher
|
||||||
self._slots = asyncio.Semaphore(command.deep_concurrency)
|
self._slots = asyncio.Semaphore(command.deep_concurrency)
|
||||||
|
|
||||||
async def run(self) -> None:
|
async def run(self) -> None:
|
||||||
@@ -141,14 +156,15 @@ class Pass:
|
|||||||
async def _rows(self) -> AsyncIterator[Attachment]:
|
async def _rows(self) -> AsyncIterator[Attachment]:
|
||||||
after, size = "", self._command.page_size
|
after, size = "", self._command.page_size
|
||||||
while True:
|
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.requests["sql"] += 1
|
||||||
self._report.rows += len(page)
|
rows = page[:size]
|
||||||
for row in page:
|
self._report.rows += len(rows)
|
||||||
|
for row in rows:
|
||||||
yield row
|
yield row
|
||||||
if len(page) < size:
|
if len(page) <= size:
|
||||||
return
|
return
|
||||||
after = page[-1].object_key
|
after = rows[-1].object_key
|
||||||
|
|
||||||
async def _page(self, after: str, size: int) -> Sequence[Attachment]:
|
async def _page(self, after: str, size: int) -> Sequence[Attachment]:
|
||||||
uow = self._uow()
|
uow = self._uow()
|
||||||
@@ -206,11 +222,9 @@ class Pass:
|
|||||||
await self._broken(row, Quarantine.MISSING)
|
await self._broken(row, Quarantine.MISSING)
|
||||||
elif item.size != row.size_bytes:
|
elif item.size != row.size_bytes:
|
||||||
await self._broken(row, Quarantine.SIZE_MISMATCH)
|
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()
|
await self._slots.acquire()
|
||||||
checks.create_task(self._verify(row))
|
checks.create_task(self._verify(row))
|
||||||
else:
|
|
||||||
await self._healthy(row, verified=False)
|
|
||||||
|
|
||||||
async def _verify(self, row: Attachment) -> None:
|
async def _verify(self, row: Attachment) -> None:
|
||||||
try:
|
try:
|
||||||
@@ -228,7 +242,7 @@ class Pass:
|
|||||||
elif digest != row.sha256:
|
elif digest != row.sha256:
|
||||||
await self._broken(row, Quarantine.SHA_MISMATCH)
|
await self._broken(row, Quarantine.SHA_MISMATCH)
|
||||||
else:
|
else:
|
||||||
await self._healthy(row, verified=True)
|
await self._healthy(row)
|
||||||
|
|
||||||
async def _digest(self, key: str) -> str | None:
|
async def _digest(self, key: str) -> str | None:
|
||||||
self._report.requests["s3_get"] += 1
|
self._report.requests["s3_get"] += 1
|
||||||
@@ -260,12 +274,9 @@ class Pass:
|
|||||||
await self._mark(row)
|
await self._mark(row)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
async def _healthy(self, row: Attachment, *, verified: bool) -> None:
|
async def _healthy(self, row: Attachment) -> None:
|
||||||
if row.quarantine is None:
|
if row.quarantine is None:
|
||||||
return
|
return
|
||||||
if row.quarantine is Quarantine.SHA_MISMATCH and not verified:
|
|
||||||
self._found("quarantined", str(row.id))
|
|
||||||
return
|
|
||||||
self._found("healed", str(row.id))
|
self._found("healed", str(row.id))
|
||||||
if self._command.apply:
|
if self._command.apply:
|
||||||
await self._safely("healed", self._release(row), row.id)
|
await self._safely("healed", self._release(row), row.id)
|
||||||
@@ -303,4 +314,5 @@ class Pass:
|
|||||||
return False
|
return False
|
||||||
self._report.requests["s3_delete"] += 1
|
self._report.requests["s3_delete"] += 1
|
||||||
await drop(uow, self._storage, current, "reconcile")
|
await drop(uow, self._storage, current, "reconcile")
|
||||||
|
await self._publisher.publish(uow.collect_new_events())
|
||||||
return True
|
return True
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ from messenger.shared.application.ports import Clock, EventPublisher, IdGenerato
|
|||||||
from messenger.shared.infrastructure.postgres import Database
|
from messenger.shared.infrastructure.postgres import Database
|
||||||
|
|
||||||
|
|
||||||
class AttachmentsProvider(Provider):
|
class AttachmentStorageProvider(Provider):
|
||||||
def __init__(self, settings: AttachmentsSettings) -> None:
|
def __init__(self, settings: AttachmentsSettings) -> None:
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self._settings = settings
|
self._settings = settings
|
||||||
@@ -52,6 +52,8 @@ class AttachmentsProvider(Provider):
|
|||||||
) as client:
|
) as client:
|
||||||
yield S3ObjectStorage(client, settings.s3_bucket)
|
yield S3ObjectStorage(client, settings.s3_bucket)
|
||||||
|
|
||||||
|
|
||||||
|
class AttachmentsProvider(AttachmentStorageProvider):
|
||||||
@provide(scope=Scope.APP)
|
@provide(scope=Scope.APP)
|
||||||
def images(self, settings: AttachmentsSettings) -> ImageInspector:
|
def images(self, settings: AttachmentsSettings) -> ImageInspector:
|
||||||
return PillowImageInspector(settings.max_image_pixels, settings.image_check_concurrency)
|
return PillowImageInspector(settings.max_image_pixels, settings.image_check_concurrency)
|
||||||
|
|||||||
@@ -7,19 +7,24 @@ from collections.abc import Callable, Sequence
|
|||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
from dishka import Scope, make_async_container, provide
|
||||||
|
|
||||||
from messenger.attachments.application.commands import ReconcileStorage
|
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.application.reconcile import Reconciliation, StorageReconciler
|
||||||
from messenger.attachments.config import AttachmentsSettings
|
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 (
|
from messenger.attachments.infrastructure.postgres import (
|
||||||
PostgresAttachmentsUnitOfWork,
|
PostgresAttachmentsUnitOfWork,
|
||||||
PostgresSingleRun,
|
PostgresSingleRun,
|
||||||
)
|
)
|
||||||
from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client
|
|
||||||
from messenger.shared.application.errors import Unavailable
|
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.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.logging import PLATFORM_FIELDS, StructlogLogger
|
||||||
from messenger.shared.infrastructure.postgres import Database
|
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("--skew", type=bounded(0), default=60, help="запас на часы, секунды")
|
||||||
parser.add_argument("--deep", action="store_true", help="сверить SHA-256 каждого объекта")
|
parser.add_argument("--deep", action="store_true", help="сверить SHA-256 каждого объекта")
|
||||||
parser.add_argument("--page-size", type=bounded(1, 1000), default=1000)
|
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)
|
parser.add_argument("--samples", type=bounded(0, 1000), default=20)
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
return ReconcileStorage(
|
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(
|
async def reconcile(
|
||||||
command: ReconcileStorage,
|
command: ReconcileStorage,
|
||||||
platform: PlatformSettings,
|
platform: PlatformSettings,
|
||||||
settings: AttachmentsSettings,
|
settings: AttachmentsSettings,
|
||||||
logger: Logger,
|
logger: Logger,
|
||||||
) -> Reconciliation:
|
) -> Reconciliation:
|
||||||
database = Database(
|
container = make_async_container(
|
||||||
platform.database_url.get_secret_value(),
|
PlatformProvider(platform, logger), ReconcileProvider(settings)
|
||||||
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()
|
bus = await container.get(EventBus)
|
||||||
|
bus.subscribe(AttachmentDiscarded, AttachmentsJournal(logger).on_attachment_discarded)
|
||||||
|
bus.start()
|
||||||
try:
|
try:
|
||||||
async with s3_client(
|
reconciler = await container.get(StorageReconciler)
|
||||||
endpoint=settings.s3_endpoint,
|
return await reconciler(command)
|
||||||
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:
|
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]:
|
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:
|
def main(argv: Sequence[str] | None = None) -> None:
|
||||||
command = command_of(argv)
|
command = command_of(argv)
|
||||||
platform, settings = PlatformSettings(), AttachmentsSettings()
|
platform = PlatformSettings(db_pool_max_size=command.deep_concurrency + 2)
|
||||||
|
settings = AttachmentsSettings()
|
||||||
logger = StructlogLogger(
|
logger = StructlogLogger(
|
||||||
level=platform.log_level, allowed_fields=PLATFORM_FIELDS | LOG_FIELDS, stream=sys.stderr
|
level=platform.log_level, allowed_fields=PLATFORM_FIELDS | LOG_FIELDS, stream=sys.stderr
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
result = asyncio.run(reconcile(command, platform, settings, logger))
|
result = asyncio.run(reconcile(command, platform, settings, logger))
|
||||||
except Unavailable as error:
|
except Exception as error:
|
||||||
logger.error("reconcile.failed", error=type(error.__cause__ or error).__name__)
|
logger.error("reconcile.failed", error=failure(error))
|
||||||
raise SystemExit(1) from None
|
raise SystemExit(1) from None
|
||||||
sys.stdout.write(json.dumps(report_of(command, result), ensure_ascii=False, indent=2) + "\n")
|
sys.stdout.write(json.dumps(report_of(command, result), ensure_ascii=False, indent=2) + "\n")
|
||||||
raise SystemExit(1 if result.errors else 0)
|
raise SystemExit(1 if result.errors else 0)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from contextlib import asynccontextmanager
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import UTC, datetime, timedelta
|
from datetime import UTC, datetime, timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
import asyncpg
|
import asyncpg
|
||||||
import pytest
|
import pytest
|
||||||
@@ -13,9 +13,11 @@ from httpx import AsyncClient
|
|||||||
from test_attachments import storage, trio, upload
|
from test_attachments import storage, trio, upload
|
||||||
|
|
||||||
from conftest import actor, keyed, running_app
|
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.commands import ReconcileStorage
|
||||||
from messenger.attachments.application.reconcile import Reconciliation, StorageReconciler
|
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.entrypoints.reconcile import LOCK_KEY
|
||||||
from messenger.attachments.infrastructure.postgres import (
|
from messenger.attachments.infrastructure.postgres import (
|
||||||
PostgresAttachmentsUnitOfWork,
|
PostgresAttachmentsUnitOfWork,
|
||||||
@@ -61,6 +63,7 @@ class Stand:
|
|||||||
store: MemoryObjectStorage
|
store: MemoryObjectStorage
|
||||||
database: Database
|
database: Database
|
||||||
users: tuple[dict[str, Any], ...]
|
users: tuple[dict[str, Any], ...]
|
||||||
|
published: RecordingPublisher
|
||||||
|
|
||||||
async def run(self, *, apply: bool = False, deep: bool = False) -> Reconciliation:
|
async def run(self, *, apply: bool = False, deep: bool = False) -> Reconciliation:
|
||||||
reconciler = StorageReconciler(
|
reconciler = StorageReconciler(
|
||||||
@@ -68,7 +71,8 @@ class Stand:
|
|||||||
self.store,
|
self.store,
|
||||||
PostgresSingleRun(self.database, LOCK_KEY),
|
PostgresSingleRun(self.database, LOCK_KEY),
|
||||||
MonotonicUtcClock(),
|
MonotonicUtcClock(),
|
||||||
NullLogger(),
|
logger=NullLogger(),
|
||||||
|
publisher=self.published,
|
||||||
)
|
)
|
||||||
command = ReconcileStorage(
|
command = ReconcileStorage(
|
||||||
apply=apply, grace=GRACE, skew=timedelta(0), deep=deep, page_size=2
|
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()
|
await database.open()
|
||||||
try:
|
try:
|
||||||
yield Stand(http, await storage(http), database, await trio(http))
|
yield Stand(http, await storage(http), database, await trio(http), RecordingPublisher())
|
||||||
finally:
|
finally:
|
||||||
await database.close()
|
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 dict(shallow.found) == {k: v for k, v in EVERY_CLASS.items() if k != "sha_mismatch"}
|
||||||
assert not deep.fixed
|
assert not deep.fixed
|
||||||
assert not shallow.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
|
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["sized"]["id"]] == "size_mismatch"
|
||||||
assert reasons[damaged["flipped"]["id"]] == "sha_mismatch"
|
assert reasons[damaged["flipped"]["id"]] == "sha_mismatch"
|
||||||
assert reasons[damaged["healthy"]["id"]] is None
|
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 reasons[damaged["fresh"]["id"]] is None
|
||||||
assert damaged["stale"]["id"] not in reasons
|
assert damaged["stale"]["id"] not in reasons
|
||||||
assert key(damaged["stale"]) not in objects
|
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.objects[key(lost)] = s.store.objects[key(flipped)] = (SAMPLE, "image/png")
|
||||||
s.store.modified[key(lost)] = s.store.modified[key(flipped)]
|
s.store.modified[key(lost)] = s.store.modified[key(flipped)]
|
||||||
shallow = await s.run(apply=True)
|
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))
|
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 isolated.fixed["missing"] == isolated.fixed["sha_mismatch"] == 1
|
||||||
assert shallow.fixed["healed"] == 1
|
assert shallow.fixed["healed"] == 2
|
||||||
assert shallow.found["quarantined"] == 1
|
assert shallow.requests["s3_get"] == 2
|
||||||
assert deep.fixed["healed"] == 1
|
assert not again.fixed
|
||||||
|
assert again.requests["s3_get"] == 0
|
||||||
assert hashlib.sha256(content.content).hexdigest() == lost["sha256"]
|
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 def test_row_written_after_listing_keeps_the_object(dsn: str) -> None:
|
||||||
async with stand(dsn) as s:
|
async with stand(dsn) as s:
|
||||||
first, last = await s.upload(), await s.upload()
|
first, last = await s.upload(), await s.upload()
|
||||||
|
|||||||
@@ -88,3 +88,13 @@ class MemoryStorageProvider(Provider):
|
|||||||
@provide(scope=Scope.APP)
|
@provide(scope=Scope.APP)
|
||||||
def storage(self) -> ObjectStorage:
|
def storage(self) -> ObjectStorage:
|
||||||
return MemoryObjectStorage()
|
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)
|
||||||
|
|||||||
Reference in New Issue
Block a user