forked from mtusi2026/mtusi2026lab4
Release the quarantine only after the object hashes to the row again
A pass without --deep released the quarantine of a missing or resized attachment as soon as an object of the same size appeared under its key, so other bytes of the same length went back to /content. The pass now streams and hashes the object of every quarantined row whose size matches again, deep or not, and releases it only when the SHA-256 matches; other bytes keep the row quarantined. Consistent data still costs no GET. The keyset reads page + 1 rows, so a pass takes exactly ceil(N/page) SQL pages instead of one more for the empty tail. The reconciler is assembled by dishka from PlatformProvider and the attachment storage provider that the API uses too, and it publishes the events of the intents it drops, so audit.attachment_discarded reason=reconcile reaches the journal. Any failure of a pass, not only Unavailable, ends as reconcile.failed with the error type and exit code 1. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
b6c04f2296
commit
3de1dcdc84
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user