forked from mtusi2026/mtusi2026lab5
Complete versioned attachment processing and fault invariants
This commit is contained in:
@@ -3,7 +3,7 @@ import sys
|
||||
|
||||
from dishka import make_async_container
|
||||
|
||||
from messenger.attachments.domain.jobs import ReplayResult
|
||||
from messenger.attachments.domain.jobs import ReplayResult, ReprocessResult
|
||||
from messenger.attachments.entrypoints.admin import rendered, run
|
||||
from messenger.attachments.entrypoints.ioc import AdminProvider
|
||||
from messenger.attachments.entrypoints.journal import LOG_FIELDS, subscribe_journal
|
||||
@@ -26,7 +26,7 @@ async def serve(argv: list[str]) -> int:
|
||||
await bus.stop()
|
||||
await container.close()
|
||||
sys.stdout.write(rendered(report) + "\n")
|
||||
return int(report.get("result") == ReplayResult.NOT_FOUND)
|
||||
return int(report.get("result") in (ReplayResult.NOT_FOUND, ReprocessResult.CONFLICT))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
|
||||
@@ -49,6 +49,13 @@ class ReplayAttachment(Command):
|
||||
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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -124,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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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,
|
||||
@@ -262,9 +264,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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -519,6 +519,19 @@ class PostgresJobRepository:
|
||||
await self._enqueue(job)
|
||||
await self._note(job, "enqueued")
|
||||
|
||||
async def reprocess(self, job: Job, operator: str) -> bool:
|
||||
existing = await self._session.scalar(
|
||||
select(JobRow.job_id).where(
|
||||
JobRow.attachment_id == job.attachment_id,
|
||||
JobRow.pipeline_version == job.pipeline_version,
|
||||
)
|
||||
)
|
||||
if existing is not None:
|
||||
return False
|
||||
await self.add(job)
|
||||
await self._note(job, "reprocess_requested", {"operator": operator})
|
||||
return True
|
||||
|
||||
async def claim(self, job: Job, token: UUID, lease: timedelta) -> Claim | None:
|
||||
row = (
|
||||
await self._session.execute(
|
||||
@@ -686,8 +699,31 @@ class PostgresJobRepository:
|
||||
)
|
||||
if attempt is None:
|
||||
return False
|
||||
await self._move(
|
||||
lease.job.attachment_id, ["queued", "processing"], "failed", error_code=code.value
|
||||
await self._session.execute(
|
||||
select(AttachmentRow.id)
|
||||
.where(AttachmentRow.id == lease.job.attachment_id)
|
||||
.with_for_update()
|
||||
)
|
||||
active = (
|
||||
select(JobRow.job_id)
|
||||
.where(
|
||||
JobRow.attachment_id == lease.job.attachment_id,
|
||||
JobRow.status.in_(["queued", "processing"]),
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
await self._session.execute(
|
||||
update(AttachmentRow)
|
||||
.where(
|
||||
AttachmentRow.id == lease.job.attachment_id,
|
||||
AttachmentRow.status.in_(["queued", "processing"]),
|
||||
~active,
|
||||
)
|
||||
.values(
|
||||
status="failed",
|
||||
error_code=code.value,
|
||||
updated_at=func.greatest(func.now(), AttachmentRow.created_at),
|
||||
)
|
||||
)
|
||||
await self._note(
|
||||
lease.job.retried(attempt), "failed", {"error_code": code.value, "error": error}
|
||||
|
||||
Reference in New Issue
Block a user