Forward the lab 5 foundation while preserving lab 6 telemetry

Source: immutable lab5 snapshot f88e9ba43cdfd7eb6a5a7ae5feb4247b4e820071; forward the allowed diff from 64d5c67. Carry SQLAlchemy, Alembic, reliability fixes, versioned jobs, infrastructure and student tests without changing protected coursework files.

Validation: make check, validate, lint; 515 student tests passed with one Linux-only skip; public smoke with telemetry enabled and repeat migration passed. Stop the owned stack and retain volumes. Preserve the existing OTel work in progress; grade implementation remains a separate phase.
This commit is contained in:
Artyom
2026-11-06 12:29:35 +03:00
parent dc9256baf9
commit 12db77133f
161 changed files with 11160 additions and 1467 deletions
@@ -47,3 +47,21 @@ class CleanStaging(Command):
class ReplayAttachment(Command):
attachment_id: UUID
operator: str
@dataclass(frozen=True, slots=True)
class ReprocessAttachment(Command):
attachment_id: UUID
pipeline_version: int
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
@@ -8,6 +8,7 @@ from messenger.attachments.application.commands import (
PublishOutbox,
RecoverExpiredLeases,
ReplayAttachment,
ReprocessAttachment,
)
from messenger.attachments.application.ports import (
AttachmentsUnitOfWork,
@@ -18,20 +19,26 @@ from messenger.attachments.application.ports import (
VariantRenderer,
)
from messenger.attachments.domain.errors import LeaseLost, UnreadableImage
from messenger.attachments.domain.events import AttachmentReplayRequested, JobSettled
from messenger.attachments.domain.events import (
AttachmentReplayRequested,
AttachmentReprocessRequested,
JobSettled,
)
from messenger.attachments.domain.jobs import (
PIPELINE_VERSIONS,
Claim,
FailureCode,
Job,
Lease,
Outcome,
ReplayResult,
ReprocessResult,
RetryPolicy,
)
from messenger.attachments.domain.models import Attachment, AttachmentStatus, original_key
from messenger.attachments.domain.variants import Variant, variant_key
from messenger.shared.application.errors import Unavailable
from messenger.shared.application.ports import IdGenerator
from messenger.shared.application.ports import Clock, IdGenerator
TRANSIENT_ERROR = "transient_error"
STALL_AFTER_CLAIM = "stall_after_claim"
@@ -299,3 +306,39 @@ class ReplayAttachmentHandler:
return ReplayResult.EXPIRED
job = await self._uow.jobs.replay(attachment, operator)
return ReplayResult.NOOP if job is None else ReplayResult.REPLAYED
class ReprocessAttachmentHandler:
__slots__ = ("_clock", "_ids", "_uow")
def __init__(self, uow: AttachmentsUnitOfWork, ids: IdGenerator, clock: Clock) -> None:
self._uow = uow
self._ids = ids
self._clock = clock
async def __call__(self, command: ReprocessAttachment) -> ReprocessResult:
if command.pipeline_version not in PIPELINE_VERSIONS:
raise ValueError("неподдерживаемая версия pipeline")
async with self._uow.transaction():
attachment = await self._uow.attachments.lock(command.attachment_id)
result = await self._schedule(attachment, command)
self._uow.record(
AttachmentReprocessRequested(
command.attachment_id, command.pipeline_version, command.operator, result.value
)
)
await self._uow.commit()
return result
async def _schedule(
self, attachment: Attachment | None, command: ReprocessAttachment
) -> ReprocessResult:
if attachment is None:
return ReprocessResult.NOT_FOUND
if attachment.status in (AttachmentStatus.PENDING, AttachmentStatus.FAILED):
return ReprocessResult.CONFLICT
if command.pipeline_version <= attachment.published_version:
return ReprocessResult.NOOP
job = Job(self._ids.new_id(), attachment.id, command.pipeline_version, 1, self._clock.now())
added = await self._uow.jobs.reprocess(job, command.operator)
return ReprocessResult.QUEUED if added else ReprocessResult.NOOP
@@ -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: ...
@@ -104,6 +124,8 @@ class AttachmentRepository(Protocol):
class JobRepository(Protocol):
async def add(self, job: Job) -> None: ...
async def reprocess(self, job: Job, operator: str) -> bool: ...
async def claim(self, job: Job, token: UUID, lease: timedelta) -> Claim | None: ...
async def complete(
@@ -158,3 +180,8 @@ class AttachmentDirectory(Protocol):
@runtime_checkable
class JobObserver(Protocol):
def observe(self, job: Job, outcome: str, seconds: float) -> None: ...
@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
@@ -33,6 +33,15 @@ class JobSettled(DomainEvent):
name: str = field(init=False, default="job.settled")
@dataclass(frozen=True, slots=True)
class AttachmentReprocessRequested(DomainEvent):
attachment_id: UUID
pipeline_version: int
operator: str
result: str
name: str = field(init=False, default="attachment.reprocess_requested")
@dataclass(frozen=True, slots=True)
class AttachmentReplayRequested(DomainEvent):
attachment_id: UUID
+8
View File
@@ -6,6 +6,7 @@ from uuid import UUID
JOB_TYPE = "attachment.process.v1"
SCHEMA_VERSION = 1
PIPELINE_VERSIONS = (1, 2)
class FailureCode(StrEnum):
@@ -21,6 +22,13 @@ class ReplayResult(StrEnum):
NOT_FOUND = "not_found"
class ReprocessResult(StrEnum):
QUEUED = "queued"
NOOP = "noop"
CONFLICT = "conflict"
NOT_FOUND = "not_found"
class Outcome(StrEnum):
DONE = "done"
DUPLICATE = "duplicate_noop"
@@ -8,6 +8,7 @@ from messenger.attachments.domain.values import Filename, ImageInfo
from messenger.attachments.domain.variants import Variant
from messenger.shared.domain.events import DomainEvent
OBJECT_PREFIX = "attachments/"
STAGING_PREFIX = "staging/"
ORIGINALS_PREFIX = "originals/"
@@ -24,6 +25,12 @@ def original_key(attachment_id: UUID) -> str:
return f"{ORIGINALS_PREFIX}{attachment_id}"
class Quarantine(StrEnum):
MISSING = "missing"
SIZE_MISMATCH = "size_mismatch"
SHA_MISMATCH = "sha_mismatch"
@dataclass(slots=True)
class Attachment:
id: UUID
@@ -41,6 +48,7 @@ class Attachment:
published_version: int = 0
error_code: str | None = None
variants: tuple[Variant, ...] = ()
quarantine: Quarantine | None = None
_events: list[DomainEvent] = field(init=False, default_factory=list, repr=False, compare=False)
@classmethod
@@ -70,6 +78,10 @@ class Attachment:
staging_key=f"{STAGING_PREFIX}{attachment_id}",
)
@property
def object_key(self) -> str:
return self.original_key or self.staging_key or f"{OBJECT_PREFIX}{self.id}"
@property
def content_type(self) -> str:
return self.image.kind.value
@@ -98,6 +110,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
+19 -5
View File
@@ -9,9 +9,9 @@ from uuid import UUID
from dishka import AsyncContainer
from messenger.attachments.application.bus import AttachmentsCommandBus
from messenger.attachments.application.commands import ReplayAttachment
from messenger.attachments.application.commands import ReplayAttachment, ReprocessAttachment
from messenger.attachments.application.ports import AttachmentDirectory
from messenger.attachments.domain.jobs import ReplayResult
from messenger.attachments.domain.jobs import PIPELINE_VERSIONS, ReplayResult, ReprocessResult
REGISTRY_LIMIT = 20
@@ -26,6 +26,10 @@ def parser() -> argparse.ArgumentParser:
replay = commands.add_parser("replay", help="вернуть failed-вложение в очередь")
replay.add_argument("--attachment-id", type=UUID, required=True)
replay.add_argument("--operator", default=os.environ.get("OPERATOR", "cli"))
reprocess = commands.add_parser("reprocess", help="поставить новую версию pipeline")
reprocess.add_argument("--attachment-id", type=UUID, required=True)
reprocess.add_argument("--pipeline-version", type=int, choices=PIPELINE_VERSIONS, required=True)
reprocess.add_argument("--operator", default=os.environ.get("OPERATOR", "cli"))
return root
@@ -36,10 +40,20 @@ async def run(container: AsyncContainer, argv: list[str]) -> dict[str, Any]:
directory = await scope.get(AttachmentDirectory)
return {"failed": [asdict(job) for job in await directory.failed_jobs(args.limit)]}
bus = await scope.get(AttachmentsCommandBus)
result: ReplayResult = await bus.execute(
ReplayAttachment(args.attachment_id, args.operator)
command = (
ReprocessAttachment(args.attachment_id, args.pipeline_version, args.operator)
if args.command == "reprocess"
else ReplayAttachment(args.attachment_id, args.operator)
)
return {"result": result.value, "attachment_id": args.attachment_id, "operator": args.operator}
result: ReplayResult | ReprocessResult = await bus.execute(command)
report = {
"result": result.value,
"attachment_id": args.attachment_id,
"operator": args.operator,
}
if args.command == "reprocess":
report["pipeline_version"] = args.pipeline_version
return report
def plain(value: object) -> str:
+8 -3
View File
@@ -12,6 +12,7 @@ from messenger.attachments.application.commands import (
PublishOutbox,
RecoverExpiredLeases,
ReplayAttachment,
ReprocessAttachment,
SweepAbandonedUploads,
UploadAttachment,
)
@@ -26,6 +27,7 @@ from messenger.attachments.application.pipeline import (
PublishOutboxHandler,
RecoverExpiredLeasesHandler,
ReplayAttachmentHandler,
ReprocessAttachmentHandler,
)
from messenger.attachments.application.ports import (
AttachmentDirectory,
@@ -76,7 +78,7 @@ async def object_storage(settings: AttachmentsSettings) -> AsyncIterator[ObjectS
yield S3ObjectStorage(client, settings.s3_bucket)
class AttachmentsProvider(Provider):
class AttachmentStorageProvider(Provider):
def __init__(self, settings: AttachmentsSettings) -> None:
super().__init__()
self._settings = settings
@@ -90,6 +92,8 @@ class AttachmentsProvider(Provider):
async with object_storage(settings) as storage:
yield storage
class AttachmentsProvider(AttachmentStorageProvider):
@provide(scope=Scope.APP)
def images(self, settings: AttachmentsSettings) -> ImageInspector:
return PillowImageInspector(settings.max_image_pixels, settings.image_check_concurrency)
@@ -266,9 +270,10 @@ class AdminProvider(Provider):
@provide(scope=Scope.REQUEST)
def command_bus(
self, uow: AttachmentsUnitOfWork, publisher: EventPublisher
self, uow: AttachmentsUnitOfWork, publisher: EventPublisher, ids: IdGenerator, clock: Clock
) -> AttachmentsCommandBus:
handlers: dict[type[Command], CommandHandler] = {
ReplayAttachment: ReplayAttachmentHandler(uow)
ReplayAttachment: ReplayAttachmentHandler(uow),
ReprocessAttachment: ReprocessAttachmentHandler(uow, ids, clock),
}
return AttachmentsCommandBus(handlers, uow, publisher)
@@ -2,6 +2,7 @@ from messenger.attachments.domain.events import (
AttachmentDiscarded,
AttachmentQueued,
AttachmentReplayRequested,
AttachmentReprocessRequested,
JobSettled,
)
from messenger.shared.application.messagebus import EventBus
@@ -69,6 +70,15 @@ class AttachmentsJournal:
result=event.result,
)
async def on_reprocess_requested(self, event: AttachmentReprocessRequested) -> None:
self._logger.info(
"audit.attachment_reprocess",
attachment_id=str(event.attachment_id),
pipeline_version=event.pipeline_version,
operator=event.operator,
result=event.result,
)
def subscribe_journal(bus: EventBus, logger: Logger) -> None:
journal = AttachmentsJournal(logger)
@@ -76,3 +86,4 @@ def subscribe_journal(bus: EventBus, logger: Logger) -> None:
bus.subscribe(AttachmentDiscarded, journal.on_attachment_discarded)
bus.subscribe(JobSettled, journal.on_job_settled)
bus.subscribe(AttachmentReplayRequested, journal.on_replay_requested)
bus.subscribe(AttachmentReprocessRequested, journal.on_reprocess_requested)
@@ -0,0 +1,174 @@
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 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.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.shared.application.errors import Unavailable
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.entrypoints.ioc import PlatformProvider
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, 48), 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,
)
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:
container = make_async_container(
PlatformProvider(platform, logger), ReconcileProvider(settings)
)
bus = await container.get(EventBus)
bus.subscribe(AttachmentDiscarded, AttachmentsJournal(logger).on_attachment_discarded)
bus.start()
try:
reconciler = await container.get(StorageReconciler)
return await reconciler(command)
finally:
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]:
usage = resource.getrusage(resource.RUSAGE_SELF)
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,
"cpu_seconds": round(usage.ru_utime + usage.ru_stime, 3),
"max_rss_mib": round(usage.ru_maxrss / 1024, 1),
},
}
def main(argv: Sequence[str] | None = None) -> None:
command = command_of(argv)
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 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)
if __name__ == "__main__":
main()
@@ -40,7 +40,12 @@ async def handle_job(
outcome = (await bus.execute(ProcessJob(job))).value
except Exception as error:
observed(job, "error", started, observer, logger)
logger.warning("job.requeued", job_id=str(job.id), error=type(error).__name__)
logger.warning(
"job.requeued",
job_id=str(job.id),
error=type(error).__name__,
error_code=getattr(getattr(error, "orig", error), "sqlstate", None),
)
await asyncio.sleep(REQUEUE_DELAY_SECONDS)
await message.nack(requeue=True)
return
@@ -34,8 +34,8 @@ BOMBS = (Image.DecompressionBombError, Image.DecompressionBombWarning)
JPEG_SCALE = 8
WIDE_MODES = frozenset({"I", "I;16", "I;16B", "I;16L", "I;16N"})
ALPHA_MODES = frozenset({"LA", "La", "PA", "RGBa"})
JPEG = {"quality": 85, "optimize": True}
WEBP = {"quality": 80, "method": 4}
JPEG = {1: {"quality": 85, "optimize": True}, 2: {"quality": 90, "optimize": True}}
WEBP = {1: {"quality": 80, "method": 4}, 2: {"quality": 85, "method": 4}}
ENCODINGS = {"JPEG": (ImageKind.JPEG.value, "jpg"), "WEBP": ("image/webp", "webp")}
REDUCING_GAP = 3.0
@@ -128,15 +128,27 @@ def decoded(data: bytes, max_pixels: int) -> tuple[Image.Image, int, int]:
raise UnreadableImage("изображение не декодируется") from error
def render_variants(data: bytes, limits: RenderLimits) -> list[Rendition]:
def render_variants(
data: bytes, limits: RenderLimits, pipeline_version: int = 1
) -> list[Rendition]:
if len(data) > limits.max_bytes:
raise ImageTooDemanding("оригинал больше допустимого размера")
upright, width, height = decoded(data, limits.max_pixels)
square = ImageOps.fit(upright, (CROP_SIDE, CROP_SIDE), Image.Resampling.LANCZOS)
return [
encoded(THUMBNAIL, scaled(upright, fit(width, height, THUMBNAIL_BOX)), "JPEG", **JPEG),
encoded(CROP, square, "JPEG", **JPEG),
encoded(OPTIMIZED, scaled(upright, fit(width, height, OPTIMIZED_BOX)), "WEBP", **WEBP),
encoded(
THUMBNAIL,
scaled(upright, fit(width, height, THUMBNAIL_BOX)),
"JPEG",
**JPEG[pipeline_version],
),
encoded(CROP, square, "JPEG", **JPEG[pipeline_version]),
encoded(
OPTIMIZED,
scaled(upright, fit(width, height, OPTIMIZED_BOX)),
"WEBP",
**WEBP[pipeline_version],
),
]
@@ -145,7 +157,7 @@ def limit_memory(limit_bytes: int) -> None:
resource.setrlimit(resource.RLIMIT_AS, (limit_bytes, limit_bytes))
type Render = Callable[[bytes, RenderLimits], list[Rendition]]
type Render = Callable[[bytes, RenderLimits, int], list[Rendition]]
class ProcessVariantRenderer:
@@ -173,7 +185,9 @@ class ProcessVariantRenderer:
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
pool = await self._idle.get()
try:
future = asyncio.wrap_future(pool.submit(self._render, data, self._limits))
future = asyncio.wrap_future(
pool.submit(self._render, data, self._limits, pipeline_version)
)
return await asyncio.wait_for(future, self._timeout)
except TimeoutError as error:
pool = self._replace(pool)
File diff suppressed because it is too large Load Diff
+24 -2
View File
@@ -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
@@ -98,6 +98,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):