Reconcile attachment metadata with the bucket in one merge pass
StorageReconciler walks the sorted bucket listing and keyset pages of attachments ordered by object key side by side, so a pass is linear and keeps one page of each side in memory. An object without a row is deleted only when it is older than grace plus skew and a lookup by key right before the delete still finds no row; a ready row whose object is missing, has another size or, with the deep check, another digest is put in quarantine after a HEAD recheck and is never deleted; a stale intent is claimed with SKIP LOCKED and dropped object first; a quarantined row whose object matches again is released. Deep checks hash objects in a bounded task group, each action uses its own unit of work, and failures of single actions are counted instead of aborting. An advisory lock lets one pass run at a time. Content of a quarantined attachment answers 404 without touching S3, its metadata is unchanged. The storage port gains listing pages and HEAD, the repository keyset pages, lookup by key, claim and quarantine marking; the platform logger can write to another stream. The one-off entry point python -m messenger.attachments.entrypoints.reconcile is a dry run unless --apply is given, assembles the adapters with the API key of S3 and prints a JSON report with counts per class, samples and the cost of the pass to stdout while the journal goes to stderr. Tests run the reconciler against its own migrated database with every class, apply and repeat, the row that appears after the listing, the busy lock and the release, and check paged byte-order listing and HEAD against RustFS. 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
62986245a2
commit
91731fd317
@@ -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
|
||||
|
||||
@@ -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]: ...
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user