forked from mtusi2026/mtusi2026lab2
Forward the lab 4 foundation and migrate the lab 5 pipeline to SQLAlchemy
This commit is contained in:
@@ -47,3 +47,14 @@ class CleanStaging(Command):
|
||||
class ReplayAttachment(Command):
|
||||
attachment_id: UUID
|
||||
operator: str
|
||||
|
||||
|
||||
@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, Sequence
|
||||
from contextlib import AbstractAsyncContextManager
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Protocol, runtime_checkable
|
||||
@@ -40,6 +41,13 @@ class StagedObject:
|
||||
key: str
|
||||
|
||||
|
||||
@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: ...
|
||||
@@ -52,6 +60,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):
|
||||
@@ -95,6 +107,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: ...
|
||||
|
||||
async def staged(self, limit: int, retention: timedelta) -> list[StagedObject]: ...
|
||||
|
||||
async def unstage(self, attachment_ids: Sequence[UUID]) -> None: ...
|
||||
@@ -153,3 +173,8 @@ class AttachmentDirectory(Protocol):
|
||||
async def failed_among(self, chat_id: UUID, attachment_ids: Sequence[UUID]) -> bool: ...
|
||||
|
||||
async def failed_jobs(self, limit: int) -> list[FailedJob]: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class SingleRun(Protocol):
|
||||
def hold(self) -> AbstractAsyncContextManager[bool]: ...
|
||||
|
||||
@@ -49,6 +49,9 @@ class OpenAttachment:
|
||||
if found is None:
|
||||
raise AttachmentNotFound("у вложения нет такого варианта")
|
||||
key, content_type = found.object_key, found.content_type
|
||||
if attachment.quarantine is not None:
|
||||
self._logger.warning("attachment.quarantined", attachment_id=str(attachment.id))
|
||||
raise AttachmentNotFound("вложение не найдено")
|
||||
try:
|
||||
content = await self._storage.open(str(key))
|
||||
except ObjectMissingError as error:
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
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.errors import Unavailable
|
||||
from messenger.shared.application.ports import Clock, EventPublisher, 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", "_publisher", "_single", "_storage", "_uow")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
uow: UnitOfWorkFactory,
|
||||
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)
|
||||
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,
|
||||
publisher=self._publisher,
|
||||
).run()
|
||||
report.seconds = round(monotonic() - started, 3)
|
||||
return report
|
||||
|
||||
|
||||
class Pass:
|
||||
__slots__ = (
|
||||
"_before",
|
||||
"_command",
|
||||
"_logger",
|
||||
"_publisher",
|
||||
"_report",
|
||||
"_slots",
|
||||
"_storage",
|
||||
"_uow",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
uow: UnitOfWorkFactory,
|
||||
storage: ObjectStorage,
|
||||
command: ReconcileStorage,
|
||||
*,
|
||||
before: datetime,
|
||||
report: Reconciliation,
|
||||
logger: Logger,
|
||||
publisher: EventPublisher,
|
||||
) -> None:
|
||||
self._uow = uow
|
||||
self._storage = storage
|
||||
self._command = command
|
||||
self._before = before
|
||||
self._report = report
|
||||
self._logger = logger
|
||||
self._publisher = publisher
|
||||
self._slots = asyncio.Semaphore(command.deep_concurrency)
|
||||
|
||||
async def run(self) -> None:
|
||||
objects = aiter(self._objects())
|
||||
item = await anext(objects, None)
|
||||
try:
|
||||
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)
|
||||
except* Unavailable as failed:
|
||||
error = failed.exceptions[0]
|
||||
raise error from error.__cause__
|
||||
|
||||
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 + 1))
|
||||
self._report.requests["sql"] += 1
|
||||
rows = page[:size]
|
||||
self._report.rows += len(rows)
|
||||
for row in rows:
|
||||
yield row
|
||||
if len(page) <= size:
|
||||
return
|
||||
after = rows[-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 or row.quarantine is not None:
|
||||
await self._slots.acquire()
|
||||
checks.create_task(self._verify(row))
|
||||
|
||||
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)
|
||||
|
||||
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) -> None:
|
||||
if row.quarantine is None:
|
||||
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")
|
||||
await self._publisher.publish(uow.collect_new_events())
|
||||
return True
|
||||
Reference in New Issue
Block a user