Carry over the lab 5 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack,
HAProxy, k6, RustFS and RabbitMQ configuration, migrations, hooks,
scenario scripts and the CI job from the lab 5 solution commit 64d5c67,
keep the lab 5 Makefile targets on top of the unchanged skeleton
targets, and append the lab 5 solution variables to the skeleton
.env.example. The package and the application follow the contract
version 1.6.0, and the image, the throwaway test containers and the
broker vhost description are tagged lab6 so they do not collide with a
lab 5 stand on the same host.
This is the starting point of the lab 6 cycle: lint, own tests and the
offline skeleton check pass before any lab 6 change.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a0d3947710
commit
5ae3d77152
@@ -0,0 +1,5 @@
|
||||
from messenger.shared.application.messagebus import CommandBus
|
||||
|
||||
|
||||
class AttachmentsCommandBus(CommandBus):
|
||||
__slots__ = ()
|
||||
@@ -0,0 +1,49 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.attachments.domain.jobs import Job
|
||||
from messenger.shared.application.commands import Command
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class UploadAttachment(Command):
|
||||
owner_id: UUID
|
||||
chat_id: UUID
|
||||
filename: str | None
|
||||
content_type: str | None
|
||||
body: AsyncIterator[bytes]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SweepAbandonedUploads(Command):
|
||||
grace: timedelta
|
||||
limit: int
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ProcessJob(Command):
|
||||
job: Job
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PublishOutbox(Command):
|
||||
limit: int
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RecoverExpiredLeases(Command):
|
||||
limit: int
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CleanStaging(Command):
|
||||
limit: int
|
||||
retention: timedelta
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ReplayAttachment(Command):
|
||||
attachment_id: UUID
|
||||
operator: str
|
||||
@@ -0,0 +1,2 @@
|
||||
class ObjectMissingError(Exception):
|
||||
pass
|
||||
@@ -0,0 +1,158 @@
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator
|
||||
from hashlib import sha256
|
||||
|
||||
from messenger.attachments.application.commands import SweepAbandonedUploads, UploadAttachment
|
||||
from messenger.attachments.application.ports import (
|
||||
AttachmentsUnitOfWork,
|
||||
ChatMembership,
|
||||
ImageInspector,
|
||||
ObjectStorage,
|
||||
)
|
||||
from messenger.attachments.domain.errors import ChatNotFound, PayloadTooLarge
|
||||
from messenger.attachments.domain.jobs import Job
|
||||
from messenger.attachments.domain.models import Attachment, AttachmentStatus
|
||||
from messenger.attachments.domain.values import Filename, ImageKind
|
||||
from messenger.shared.application.ports import Clock, IdGenerator, Logger
|
||||
|
||||
|
||||
class UploadSlots(asyncio.Semaphore):
|
||||
pass
|
||||
|
||||
|
||||
async def read_limited(body: AsyncIterator[bytes], limit: int) -> tuple[bytes, str]:
|
||||
chunks: list[bytes] = []
|
||||
digest = sha256()
|
||||
size = 0
|
||||
async for chunk in body:
|
||||
size += len(chunk)
|
||||
if size > limit:
|
||||
raise PayloadTooLarge(f"тело больше {limit} байт")
|
||||
digest.update(chunk)
|
||||
chunks.append(chunk)
|
||||
return b"".join(chunks), digest.hexdigest()
|
||||
|
||||
|
||||
async def drop(
|
||||
uow: AttachmentsUnitOfWork, storage: ObjectStorage, attachment: Attachment, reason: str
|
||||
) -> None:
|
||||
if attachment.staging_key is not None:
|
||||
await storage.delete(attachment.staging_key)
|
||||
attachment.discard(reason)
|
||||
await uow.attachments.remove(attachment)
|
||||
await uow.commit()
|
||||
|
||||
|
||||
class UploadAttachmentHandler:
|
||||
__slots__ = (
|
||||
"_clock",
|
||||
"_ids",
|
||||
"_images",
|
||||
"_limit",
|
||||
"_logger",
|
||||
"_membership",
|
||||
"_pipeline_version",
|
||||
"_slots",
|
||||
"_storage",
|
||||
"_uow",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
uow: AttachmentsUnitOfWork,
|
||||
membership: ChatMembership,
|
||||
images: ImageInspector,
|
||||
storage: ObjectStorage,
|
||||
*,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
limit: int,
|
||||
slots: UploadSlots,
|
||||
logger: Logger,
|
||||
pipeline_version: int = 1,
|
||||
) -> None:
|
||||
self._uow = uow
|
||||
self._membership = membership
|
||||
self._images = images
|
||||
self._storage = storage
|
||||
self._clock = clock
|
||||
self._ids = ids
|
||||
self._limit = limit
|
||||
self._slots = slots
|
||||
self._logger = logger
|
||||
self._pipeline_version = pipeline_version
|
||||
|
||||
async def __call__(self, command: UploadAttachment) -> Attachment:
|
||||
if not await self._membership.is_member(command.chat_id, command.owner_id):
|
||||
raise ChatNotFound("чат не найден")
|
||||
filename = Filename(command.filename or "")
|
||||
declared = ImageKind.declared(command.content_type)
|
||||
async with self._slots:
|
||||
attachment = await self._write(command, filename, declared)
|
||||
now = self._clock.now()
|
||||
attachment.enqueue(now)
|
||||
job = Job(self._ids.new_id(), attachment.id, self._pipeline_version, 1, now)
|
||||
try:
|
||||
async with self._uow.transaction():
|
||||
await self._uow.attachments.save(attachment)
|
||||
await self._uow.jobs.add(job)
|
||||
await self._uow.commit()
|
||||
except Exception:
|
||||
await self._compensate(attachment)
|
||||
raise
|
||||
return attachment
|
||||
|
||||
async def _write(
|
||||
self, command: UploadAttachment, filename: Filename, declared: ImageKind
|
||||
) -> Attachment:
|
||||
data, digest = await read_limited(command.body, self._limit)
|
||||
image = await self._images.inspect(data, declared)
|
||||
attachment = Attachment.stage(
|
||||
attachment_id=self._ids.new_id(),
|
||||
chat_id=command.chat_id,
|
||||
owner_id=command.owner_id,
|
||||
filename=filename,
|
||||
image=image,
|
||||
size_bytes=len(data),
|
||||
sha256=digest,
|
||||
now=self._clock.now(),
|
||||
)
|
||||
async with self._uow.transaction():
|
||||
await self._uow.attachments.add(attachment)
|
||||
await self._uow.commit()
|
||||
await self._storage.put(str(attachment.staging_key), data, attachment.content_type)
|
||||
return attachment
|
||||
|
||||
async def _compensate(self, staged: Attachment) -> None:
|
||||
try:
|
||||
async with self._uow.transaction():
|
||||
current = await self._uow.attachments.lock(staged.id)
|
||||
if current is None:
|
||||
await self._storage.delete(str(staged.staging_key))
|
||||
elif current.status is AttachmentStatus.PENDING:
|
||||
await drop(self._uow, self._storage, current, "compensation")
|
||||
except Exception as error:
|
||||
self._logger.warning(
|
||||
"attachment.compensation_failed",
|
||||
attachment_id=str(staged.id),
|
||||
error=type(error).__name__,
|
||||
)
|
||||
|
||||
|
||||
class SweepAbandonedUploadsHandler:
|
||||
__slots__ = ("_clock", "_storage", "_uow")
|
||||
|
||||
def __init__(self, uow: AttachmentsUnitOfWork, storage: ObjectStorage, clock: Clock) -> None:
|
||||
self._uow = uow
|
||||
self._storage = storage
|
||||
self._clock = clock
|
||||
|
||||
async def __call__(self, command: SweepAbandonedUploads) -> int:
|
||||
before = self._clock.now() - command.grace
|
||||
for swept in range(command.limit):
|
||||
async with self._uow.transaction():
|
||||
abandoned = await self._uow.attachments.next_abandoned(before)
|
||||
if abandoned is None:
|
||||
return swept
|
||||
await drop(self._uow, self._storage, abandoned, "abandoned")
|
||||
return command.limit
|
||||
@@ -0,0 +1,301 @@
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
from hashlib import sha256
|
||||
|
||||
from messenger.attachments.application.commands import (
|
||||
CleanStaging,
|
||||
ProcessJob,
|
||||
PublishOutbox,
|
||||
RecoverExpiredLeases,
|
||||
ReplayAttachment,
|
||||
)
|
||||
from messenger.attachments.application.ports import (
|
||||
AttachmentsUnitOfWork,
|
||||
Faults,
|
||||
Jitter,
|
||||
JobPublisher,
|
||||
ObjectStorage,
|
||||
VariantRenderer,
|
||||
)
|
||||
from messenger.attachments.domain.errors import LeaseLost, UnreadableImage
|
||||
from messenger.attachments.domain.events import AttachmentReplayRequested, JobSettled
|
||||
from messenger.attachments.domain.jobs import (
|
||||
Claim,
|
||||
FailureCode,
|
||||
Job,
|
||||
Lease,
|
||||
Outcome,
|
||||
ReplayResult,
|
||||
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
|
||||
|
||||
TRANSIENT_ERROR = "transient_error"
|
||||
STALL_AFTER_CLAIM = "stall_after_claim"
|
||||
AFTER_COMMIT_BEFORE_PUBLISH = "after_commit_before_publish"
|
||||
AFTER_PUBLISH_BEFORE_CONFIRM = "after_publish_before_confirm"
|
||||
AFTER_CLAIM = "after_claim_before_side_effect"
|
||||
AFTER_S3_WRITE = "after_s3_write_before_commit"
|
||||
AFTER_COMMIT_BEFORE_ACK = "after_commit_before_ack"
|
||||
RENEWALS = 3
|
||||
|
||||
|
||||
def settled(
|
||||
job: Job,
|
||||
outcome: Outcome,
|
||||
*,
|
||||
error_code: str | None = None,
|
||||
delay_seconds: float | None = None,
|
||||
) -> JobSettled:
|
||||
return JobSettled(
|
||||
job_id=job.id,
|
||||
attachment_id=job.attachment_id,
|
||||
pipeline_version=job.pipeline_version,
|
||||
attempt=job.attempt,
|
||||
outcome=outcome.value,
|
||||
error_code=error_code,
|
||||
delay_seconds=delay_seconds,
|
||||
)
|
||||
|
||||
|
||||
class ProcessJobHandler:
|
||||
__slots__ = ("_faults", "_ids", "_jitter", "_lease", "_policy", "_renderer", "_storage", "_uow")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
uow: AttachmentsUnitOfWork,
|
||||
storage: ObjectStorage,
|
||||
renderer: VariantRenderer,
|
||||
faults: Faults,
|
||||
*,
|
||||
ids: IdGenerator,
|
||||
jitter: Jitter,
|
||||
policy: RetryPolicy,
|
||||
lease: timedelta,
|
||||
) -> None:
|
||||
self._uow = uow
|
||||
self._storage = storage
|
||||
self._renderer = renderer
|
||||
self._faults = faults
|
||||
self._ids = ids
|
||||
self._jitter = jitter
|
||||
self._policy = policy
|
||||
self._lease = lease
|
||||
|
||||
async def __call__(self, command: ProcessJob) -> Outcome:
|
||||
async with self._uow.transaction():
|
||||
claim = await self._uow.jobs.claim(command.job, self._ids.new_id(), self._lease)
|
||||
if claim is None:
|
||||
await self._uow.jobs.note(command.job, Outcome.DUPLICATE)
|
||||
self._uow.record(settled(command.job, Outcome.DUPLICATE))
|
||||
await self._uow.commit()
|
||||
if claim is None:
|
||||
return Outcome.DUPLICATE
|
||||
await self._faults.reach(AFTER_CLAIM)
|
||||
await self._faults.reach(STALL_AFTER_CLAIM)
|
||||
try:
|
||||
variants = await self._held(claim)
|
||||
except LeaseLost:
|
||||
return await self._fenced(claim.lease)
|
||||
except UnreadableImage as error:
|
||||
return await self._fail(claim.lease, FailureCode.INVALID_IMAGE, error)
|
||||
except Unavailable as error:
|
||||
return await self._retry(claim.lease, error)
|
||||
except Exception as error:
|
||||
return await self._fail(claim.lease, FailureCode.PROCESSING_FAILED, error)
|
||||
await self._faults.reach(AFTER_S3_WRITE)
|
||||
outcome = await self._complete(claim.lease, variants)
|
||||
await self._faults.reach(AFTER_COMMIT_BEFORE_ACK)
|
||||
return outcome
|
||||
|
||||
async def _held(self, claim: Claim) -> list[Variant]:
|
||||
await self._renew(claim.lease)
|
||||
work = asyncio.ensure_future(self._produce(claim))
|
||||
try:
|
||||
while not work.done():
|
||||
await asyncio.wait({work}, timeout=self._lease.total_seconds() / RENEWALS)
|
||||
if not work.done():
|
||||
await self._renew(claim.lease)
|
||||
except BaseException:
|
||||
work.cancel()
|
||||
await asyncio.wait({work})
|
||||
raise
|
||||
return work.result()
|
||||
|
||||
async def _renew(self, lease: Lease) -> None:
|
||||
async with self._uow.transaction():
|
||||
held = await self._uow.jobs.renew(lease, self._lease)
|
||||
await self._uow.commit()
|
||||
if not held:
|
||||
raise LeaseLost("аренду задания забрал другой держатель")
|
||||
|
||||
async def _produce(self, claim: Claim) -> list[Variant]:
|
||||
job = claim.lease.job
|
||||
await self._faults.reach(TRANSIENT_ERROR)
|
||||
data = await self._storage.read(claim.source_key)
|
||||
renditions = await self._renderer.render(data, job.pipeline_version)
|
||||
if claim.staged:
|
||||
await self._storage.copy(claim.source_key, original_key(job.attachment_id))
|
||||
variants: list[Variant] = []
|
||||
for rendition in renditions:
|
||||
digest = sha256(rendition.data).hexdigest()
|
||||
key = variant_key(
|
||||
job.attachment_id, job.pipeline_version, rendition.name, digest, rendition.extension
|
||||
)
|
||||
await self._storage.put(key, rendition.data, rendition.content_type)
|
||||
variants.append(
|
||||
Variant(
|
||||
name=rendition.name,
|
||||
content_type=rendition.content_type,
|
||||
size_bytes=len(rendition.data),
|
||||
width=rendition.width,
|
||||
height=rendition.height,
|
||||
sha256=digest,
|
||||
object_key=key,
|
||||
)
|
||||
)
|
||||
return variants
|
||||
|
||||
async def _complete(self, lease: Lease, variants: list[Variant]) -> Outcome:
|
||||
async with self._uow.transaction():
|
||||
outcome = await self._uow.jobs.complete(
|
||||
lease, variants, original_key(lease.job.attachment_id)
|
||||
)
|
||||
self._uow.record(settled(lease.job, outcome))
|
||||
await self._uow.commit()
|
||||
return outcome
|
||||
|
||||
async def _fenced(self, lease: Lease) -> Outcome:
|
||||
async with self._uow.transaction():
|
||||
await self._uow.jobs.note(lease.job, Outcome.FENCED)
|
||||
self._uow.record(settled(lease.job, Outcome.FENCED))
|
||||
await self._uow.commit()
|
||||
return Outcome.FENCED
|
||||
|
||||
async def _retry(self, lease: Lease, error: Exception) -> Outcome:
|
||||
delay = self._policy.delay(lease.job.attempt, self._jitter.spread())
|
||||
if delay is None:
|
||||
return await self._fail(lease, FailureCode.RETRY_EXHAUSTED, error)
|
||||
async with self._uow.transaction():
|
||||
job = await self._uow.jobs.reschedule(
|
||||
lease, delay, Outcome.RESCHEDULED, type(error).__name__
|
||||
)
|
||||
outcome = Outcome.FENCED if job is None else Outcome.RESCHEDULED
|
||||
if job is None:
|
||||
await self._uow.jobs.note(lease.job, outcome)
|
||||
self._uow.record(settled(lease.job, outcome, delay_seconds=delay.total_seconds()))
|
||||
await self._uow.commit()
|
||||
return outcome
|
||||
|
||||
async def _fail(self, lease: Lease, code: FailureCode, error: Exception) -> Outcome:
|
||||
async with self._uow.transaction():
|
||||
done = await self._uow.jobs.fail(lease, code, type(error).__name__)
|
||||
outcome = Outcome.FAILED if done else Outcome.FENCED
|
||||
if not done:
|
||||
await self._uow.jobs.note(lease.job, outcome)
|
||||
self._uow.record(settled(lease.job, outcome, error_code=code.value))
|
||||
await self._uow.commit()
|
||||
return outcome
|
||||
|
||||
|
||||
class PublishOutboxHandler:
|
||||
__slots__ = ("_faults", "_publisher", "_uow")
|
||||
|
||||
def __init__(self, uow: AttachmentsUnitOfWork, publisher: JobPublisher, faults: Faults) -> None:
|
||||
self._uow = uow
|
||||
self._publisher = publisher
|
||||
self._faults = faults
|
||||
|
||||
async def __call__(self, command: PublishOutbox) -> int:
|
||||
failure: Unavailable | None = None
|
||||
published: list[int] = []
|
||||
async with self._uow.transaction():
|
||||
for entry in await self._uow.outbox.pending(command.limit):
|
||||
await self._faults.reach(AFTER_COMMIT_BEFORE_PUBLISH)
|
||||
try:
|
||||
await self._publisher.publish(entry.job_id, entry.body)
|
||||
except Unavailable as error:
|
||||
failure = error
|
||||
break
|
||||
await self._faults.reach(AFTER_PUBLISH_BEFORE_CONFIRM)
|
||||
published.append(entry.id)
|
||||
if published:
|
||||
await self._uow.outbox.published(published)
|
||||
await self._uow.commit()
|
||||
if failure is not None:
|
||||
raise failure
|
||||
return len(published)
|
||||
|
||||
|
||||
class RecoverExpiredLeasesHandler:
|
||||
__slots__ = ("_policy", "_uow")
|
||||
|
||||
def __init__(self, uow: AttachmentsUnitOfWork, policy: RetryPolicy) -> None:
|
||||
self._uow = uow
|
||||
self._policy = policy
|
||||
|
||||
async def __call__(self, command: RecoverExpiredLeases) -> int:
|
||||
async with self._uow.transaction():
|
||||
leases = await self._uow.jobs.expired(command.limit)
|
||||
for lease in leases:
|
||||
if self._policy.exhausted(lease.job.attempt):
|
||||
await self._uow.jobs.fail(
|
||||
lease, FailureCode.RETRY_EXHAUSTED, Outcome.LEASE_EXPIRED.value
|
||||
)
|
||||
outcome = Outcome.FAILED
|
||||
else:
|
||||
await self._uow.jobs.reschedule(
|
||||
lease, timedelta(0), Outcome.LEASE_EXPIRED, Outcome.LEASE_EXPIRED.value
|
||||
)
|
||||
outcome = Outcome.LEASE_EXPIRED
|
||||
self._uow.record(settled(lease.job, outcome))
|
||||
await self._uow.commit()
|
||||
return len(leases)
|
||||
|
||||
|
||||
class CleanStagingHandler:
|
||||
__slots__ = ("_storage", "_uow")
|
||||
|
||||
def __init__(self, uow: AttachmentsUnitOfWork, storage: ObjectStorage) -> None:
|
||||
self._uow = uow
|
||||
self._storage = storage
|
||||
|
||||
async def __call__(self, command: CleanStaging) -> int:
|
||||
async with self._uow.transaction():
|
||||
staged = await self._uow.attachments.staged(command.limit, command.retention)
|
||||
await asyncio.gather(*(self._storage.delete(item.key) for item in staged))
|
||||
await self._uow.attachments.unstage([item.attachment_id for item in staged])
|
||||
await self._uow.commit()
|
||||
return len(staged)
|
||||
|
||||
|
||||
class ReplayAttachmentHandler:
|
||||
__slots__ = ("_uow",)
|
||||
|
||||
def __init__(self, uow: AttachmentsUnitOfWork) -> None:
|
||||
self._uow = uow
|
||||
|
||||
async def __call__(self, command: ReplayAttachment) -> ReplayResult:
|
||||
async with self._uow.transaction():
|
||||
attachment = await self._uow.attachments.lock(command.attachment_id)
|
||||
result = await self._replay(attachment, command.operator)
|
||||
if attachment is not None and result is not ReplayResult.REPLAYED:
|
||||
await self._uow.jobs.note_replay(attachment.id, command.operator, result.value)
|
||||
self._uow.record(
|
||||
AttachmentReplayRequested(command.attachment_id, command.operator, result.value)
|
||||
)
|
||||
await self._uow.commit()
|
||||
return result
|
||||
|
||||
async def _replay(self, attachment: Attachment | None, operator: str) -> ReplayResult:
|
||||
if attachment is None:
|
||||
return ReplayResult.NOT_FOUND
|
||||
if attachment.status is not AttachmentStatus.FAILED:
|
||||
return ReplayResult.NOOP
|
||||
if attachment.staging_key is None:
|
||||
return ReplayResult.EXPIRED
|
||||
job = await self._uow.jobs.replay(attachment, operator)
|
||||
return ReplayResult.NOOP if job is None else ReplayResult.REPLAYED
|
||||
@@ -0,0 +1,155 @@
|
||||
from collections.abc import AsyncIterator, Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Protocol, runtime_checkable
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.attachments.domain.jobs import Claim, FailedJob, FailureCode, Job, Lease, Outcome
|
||||
from messenger.attachments.domain.models import Attachment
|
||||
from messenger.attachments.domain.values import ImageInfo, ImageKind
|
||||
from messenger.attachments.domain.variants import Variant
|
||||
from messenger.shared.application.ports import UnitOfWork
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ObjectContent:
|
||||
size: int
|
||||
chunks: AsyncIterator[bytes]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Rendition:
|
||||
name: str
|
||||
content_type: str
|
||||
extension: str
|
||||
data: bytes
|
||||
width: int
|
||||
height: int
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class OutboxEntry:
|
||||
id: int
|
||||
job_id: UUID
|
||||
body: bytes
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class StagedObject:
|
||||
attachment_id: UUID
|
||||
key: str
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ObjectStorage(Protocol):
|
||||
async def put(self, key: str, data: bytes, content_type: str) -> None: ...
|
||||
|
||||
async def open(self, key: str) -> ObjectContent: ...
|
||||
|
||||
async def read(self, key: str) -> bytes: ...
|
||||
|
||||
async def copy(self, source: str, target: str) -> None: ...
|
||||
|
||||
async def delete(self, key: str) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ImageInspector(Protocol):
|
||||
async def inspect(self, data: bytes, declared: ImageKind) -> ImageInfo: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class VariantRenderer(Protocol):
|
||||
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class JobPublisher(Protocol):
|
||||
async def publish(self, job_id: UUID, body: bytes) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Faults(Protocol):
|
||||
async def reach(self, point: str) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Jitter(Protocol):
|
||||
def spread(self) -> float: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ChatMembership(Protocol):
|
||||
async def is_member(self, chat_id: UUID, user_id: UUID) -> bool: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class AttachmentRepository(Protocol):
|
||||
async def add(self, attachment: Attachment) -> None: ...
|
||||
|
||||
async def save(self, attachment: Attachment) -> None: ...
|
||||
|
||||
async def lock(self, attachment_id: UUID) -> Attachment | None: ...
|
||||
|
||||
async def next_abandoned(self, before: datetime) -> Attachment | None: ...
|
||||
|
||||
async def remove(self, attachment: Attachment) -> None: ...
|
||||
|
||||
async def staged(self, limit: int, retention: timedelta) -> list[StagedObject]: ...
|
||||
|
||||
async def unstage(self, attachment_ids: Sequence[UUID]) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class JobRepository(Protocol):
|
||||
async def add(self, job: Job) -> None: ...
|
||||
|
||||
async def claim(self, job: Job, token: UUID, lease: timedelta) -> Claim | None: ...
|
||||
|
||||
async def complete(
|
||||
self, lease: Lease, variants: Sequence[Variant], original_key: str
|
||||
) -> Outcome: ...
|
||||
|
||||
async def reschedule(
|
||||
self, lease: Lease, delay: timedelta, kind: Outcome, error: str
|
||||
) -> Job | None: ...
|
||||
|
||||
async def renew(self, lease: Lease, duration: timedelta) -> bool: ...
|
||||
|
||||
async def fail(self, lease: Lease, code: FailureCode, error: str) -> bool: ...
|
||||
|
||||
async def note(self, job: Job, kind: Outcome) -> None: ...
|
||||
|
||||
async def expired(self, limit: int) -> list[Lease]: ...
|
||||
|
||||
async def replay(self, attachment: Attachment, operator: str) -> Job | None: ...
|
||||
|
||||
async def note_replay(self, attachment_id: UUID, operator: str, result: str) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class OutboxRepository(Protocol):
|
||||
async def pending(self, limit: int) -> list[OutboxEntry]: ...
|
||||
|
||||
async def published(self, entry_ids: Sequence[int]) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class AttachmentsUnitOfWork(UnitOfWork, Protocol):
|
||||
@property
|
||||
def attachments(self) -> AttachmentRepository: ...
|
||||
|
||||
@property
|
||||
def jobs(self) -> JobRepository: ...
|
||||
|
||||
@property
|
||||
def outbox(self) -> OutboxRepository: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class AttachmentDirectory(Protocol):
|
||||
async def visible(self, attachment_id: UUID) -> Attachment | None: ...
|
||||
|
||||
async def failed_among(self, chat_id: UUID, attachment_ids: Sequence[UUID]) -> bool: ...
|
||||
|
||||
async def failed_jobs(self, limit: int) -> list[FailedJob]: ...
|
||||
@@ -0,0 +1,57 @@
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.attachments.application.errors import ObjectMissingError
|
||||
from messenger.attachments.application.ports import (
|
||||
AttachmentDirectory,
|
||||
ChatMembership,
|
||||
ObjectContent,
|
||||
ObjectStorage,
|
||||
)
|
||||
from messenger.attachments.domain.errors import AttachmentNotFound, AttachmentNotReady
|
||||
from messenger.attachments.domain.models import Attachment
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
ORIGINAL = "original"
|
||||
|
||||
|
||||
class GetAttachment:
|
||||
__slots__ = ("_attachments", "_membership")
|
||||
|
||||
def __init__(self, attachments: AttachmentDirectory, membership: ChatMembership) -> None:
|
||||
self._attachments = attachments
|
||||
self._membership = membership
|
||||
|
||||
async def __call__(self, attachment_id: UUID, user_id: UUID) -> Attachment:
|
||||
attachment = await self._attachments.visible(attachment_id)
|
||||
if attachment is None or not await self._membership.is_member(attachment.chat_id, user_id):
|
||||
raise AttachmentNotFound("вложение не найдено")
|
||||
return attachment
|
||||
|
||||
|
||||
class OpenAttachment:
|
||||
__slots__ = ("_get", "_logger", "_storage")
|
||||
|
||||
def __init__(self, get: GetAttachment, storage: ObjectStorage, logger: Logger) -> None:
|
||||
self._get = get
|
||||
self._storage = storage
|
||||
self._logger = logger
|
||||
|
||||
async def __call__(
|
||||
self, attachment_id: UUID, user_id: UUID, variant: str = ORIGINAL
|
||||
) -> tuple[str, ObjectContent]:
|
||||
attachment = await self._get(attachment_id, user_id)
|
||||
if not attachment.ready:
|
||||
raise AttachmentNotReady("вложение ещё не обработано или обработка не удалась")
|
||||
if variant == ORIGINAL:
|
||||
key, content_type = attachment.original_key, attachment.content_type
|
||||
else:
|
||||
found = attachment.variant(variant)
|
||||
if found is None:
|
||||
raise AttachmentNotFound("у вложения нет такого варианта")
|
||||
key, content_type = found.object_key, found.content_type
|
||||
try:
|
||||
content = await self._storage.open(str(key))
|
||||
except ObjectMissingError as error:
|
||||
self._logger.warning("attachment.object_missing", attachment_id=str(attachment.id))
|
||||
raise AttachmentNotFound("вложение не найдено") from error
|
||||
return content_type, content
|
||||
@@ -0,0 +1,49 @@
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import Field, SecretStr
|
||||
|
||||
from messenger.shared.config import Settings
|
||||
|
||||
UPLOAD_BYTES_MAX = 10_485_760
|
||||
IMAGE_PIXELS_MAX = 40_000_000
|
||||
|
||||
|
||||
class AttachmentsSettings(Settings):
|
||||
s3_endpoint: str = "http://s3:9000"
|
||||
s3_region: str = "us-east-1"
|
||||
s3_bucket: str = Field(default="messenger-attachments", min_length=3)
|
||||
s3_access_key_id: SecretStr = Field(min_length=3)
|
||||
s3_secret_access_key: SecretStr = Field(min_length=8)
|
||||
s3_connect_timeout_seconds: float = Field(default=1.0, gt=0, le=30)
|
||||
s3_read_timeout_seconds: float = Field(default=2.0, gt=0, le=60)
|
||||
s3_max_attempts: int = Field(default=2, ge=1, le=5)
|
||||
max_upload_bytes: int = Field(default=UPLOAD_BYTES_MAX, ge=1, le=UPLOAD_BYTES_MAX)
|
||||
max_image_pixels: int = Field(default=IMAGE_PIXELS_MAX, ge=1, le=IMAGE_PIXELS_MAX)
|
||||
image_check_concurrency: int = Field(default=2, ge=1, le=16)
|
||||
upload_concurrency: int = Field(default=3, ge=1, le=64)
|
||||
upload_grace_seconds: int = Field(default=900, ge=60)
|
||||
upload_sweep_interval_seconds: float = Field(default=30.0, gt=0)
|
||||
upload_sweep_batch: int = Field(default=100, ge=1, le=10_000)
|
||||
|
||||
|
||||
class PipelineSettings(AttachmentsSettings):
|
||||
broker_url: SecretStr = Field(min_length=8)
|
||||
worker_concurrency: int = Field(default=2, ge=1, le=32)
|
||||
job_max_attempts: int = Field(default=5, ge=1, le=20)
|
||||
job_timeout_seconds: float = Field(default=60.0, ge=1, le=290)
|
||||
job_backoff_base_seconds: float = Field(default=2.0, gt=0, le=60)
|
||||
job_backoff_cap_seconds: float = Field(default=60.0, gt=0, le=3600)
|
||||
staging_retention_seconds: int = Field(default=86_400, ge=1)
|
||||
outbox_poll_seconds: float = Field(default=1.0, gt=0, le=10)
|
||||
outbox_batch: int = Field(default=50, ge=1, le=1000)
|
||||
sweep_interval_seconds: float = Field(default=5.0, gt=0, le=300)
|
||||
sweep_batch: int = Field(default=100, ge=1, le=10_000)
|
||||
publish_timeout_seconds: float = Field(default=5.0, gt=0, le=60)
|
||||
shutdown_grace_seconds: float = Field(default=5.0, gt=0, le=9)
|
||||
heartbeat_file: Path | None = None
|
||||
heartbeat_interval_seconds: float = Field(default=5.0, gt=0, le=10)
|
||||
render_timeout_seconds: float = Field(default=30.0, gt=0, le=120)
|
||||
render_memory_mb: int = Field(default=448, ge=0, le=8192)
|
||||
render_tasks_per_child: int = Field(default=100, ge=1, le=10_000)
|
||||
fault_point: str = ""
|
||||
fault_stall_seconds: float = Field(default=15.0, ge=0, le=300)
|
||||
@@ -0,0 +1,45 @@
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
|
||||
|
||||
class AttachmentError(DomainError):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidFilename(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class UnsupportedImage(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class PayloadTooLarge(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class ChatNotFound(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class AttachmentNotFound(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class AttachmentNotReady(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class UploadAborted(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class UnreadableImage(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class ImageTooDemanding(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class LeaseLost(AttachmentError):
|
||||
pass
|
||||
@@ -0,0 +1,41 @@
|
||||
from dataclasses import dataclass, field
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AttachmentQueued(DomainEvent):
|
||||
attachment_id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
size_bytes: int
|
||||
name: str = field(init=False, default="attachment.queued")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AttachmentDiscarded(DomainEvent):
|
||||
attachment_id: UUID
|
||||
chat_id: UUID
|
||||
reason: str
|
||||
name: str = field(init=False, default="attachment.discarded")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class JobSettled(DomainEvent):
|
||||
job_id: UUID
|
||||
attachment_id: UUID
|
||||
pipeline_version: int
|
||||
attempt: int
|
||||
outcome: str
|
||||
error_code: str | None = None
|
||||
delay_seconds: float | None = None
|
||||
name: str = field(init=False, default="job.settled")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AttachmentReplayRequested(DomainEvent):
|
||||
attachment_id: UUID
|
||||
operator: str
|
||||
result: str
|
||||
name: str = field(init=False, default="attachment.replay_requested")
|
||||
@@ -0,0 +1,95 @@
|
||||
from dataclasses import dataclass, replace
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
JOB_TYPE = "attachment.process.v1"
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
class FailureCode(StrEnum):
|
||||
INVALID_IMAGE = "invalid_image"
|
||||
PROCESSING_FAILED = "processing_failed"
|
||||
RETRY_EXHAUSTED = "retry_exhausted"
|
||||
|
||||
|
||||
class ReplayResult(StrEnum):
|
||||
REPLAYED = "replayed"
|
||||
NOOP = "noop"
|
||||
EXPIRED = "expired"
|
||||
NOT_FOUND = "not_found"
|
||||
|
||||
|
||||
class Outcome(StrEnum):
|
||||
DONE = "done"
|
||||
DUPLICATE = "duplicate_noop"
|
||||
FENCED = "fenced"
|
||||
SUPERSEDED = "superseded"
|
||||
RESCHEDULED = "retry_scheduled"
|
||||
LEASE_EXPIRED = "lease_expired"
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Job:
|
||||
id: UUID
|
||||
attachment_id: UUID
|
||||
pipeline_version: int
|
||||
attempt: int
|
||||
created_at: datetime
|
||||
|
||||
def payload(self) -> dict[str, Any]:
|
||||
stamp = self.created_at.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
return {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"job_id": str(self.id),
|
||||
"type": JOB_TYPE,
|
||||
"attachment_id": str(self.attachment_id),
|
||||
"pipeline_version": self.pipeline_version,
|
||||
"attempt": self.attempt,
|
||||
"created_at": stamp,
|
||||
}
|
||||
|
||||
def retried(self, attempt: int) -> Job:
|
||||
return replace(self, attempt=attempt)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Lease:
|
||||
job: Job
|
||||
token: UUID
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Claim:
|
||||
lease: Lease
|
||||
source_key: str
|
||||
staged: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class FailedJob:
|
||||
job_id: UUID
|
||||
attachment_id: UUID
|
||||
pipeline_version: int
|
||||
attempt: int
|
||||
error_code: str | None
|
||||
last_error: str | None
|
||||
failed_at: datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RetryPolicy:
|
||||
max_attempts: int
|
||||
base_seconds: float
|
||||
cap_seconds: float
|
||||
|
||||
def exhausted(self, attempt: int) -> bool:
|
||||
return attempt >= self.max_attempts
|
||||
|
||||
def delay(self, attempt: int, spread: float) -> timedelta | None:
|
||||
if self.exhausted(attempt):
|
||||
return None
|
||||
ceiling = min(self.cap_seconds, self.base_seconds * 2 ** (attempt - 1))
|
||||
return timedelta(seconds=ceiling / 2 * (1 + spread))
|
||||
@@ -0,0 +1,103 @@
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.attachments.domain.events import AttachmentDiscarded, AttachmentQueued
|
||||
from messenger.attachments.domain.values import Filename, ImageInfo
|
||||
from messenger.attachments.domain.variants import Variant
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
STAGING_PREFIX = "staging/"
|
||||
ORIGINALS_PREFIX = "originals/"
|
||||
|
||||
|
||||
class AttachmentStatus(StrEnum):
|
||||
PENDING = "pending"
|
||||
QUEUED = "queued"
|
||||
PROCESSING = "processing"
|
||||
READY = "ready"
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
def original_key(attachment_id: UUID) -> str:
|
||||
return f"{ORIGINALS_PREFIX}{attachment_id}"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Attachment:
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: Filename
|
||||
image: ImageInfo
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: AttachmentStatus
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
staging_key: str | None = None
|
||||
original_key: str | None = None
|
||||
published_version: int = 0
|
||||
error_code: str | None = None
|
||||
variants: tuple[Variant, ...] = ()
|
||||
_events: list[DomainEvent] = field(init=False, default_factory=list, repr=False, compare=False)
|
||||
|
||||
@classmethod
|
||||
def stage(
|
||||
cls,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
chat_id: UUID,
|
||||
owner_id: UUID,
|
||||
filename: Filename,
|
||||
image: ImageInfo,
|
||||
size_bytes: int,
|
||||
sha256: str,
|
||||
now: datetime,
|
||||
) -> Attachment:
|
||||
return cls(
|
||||
id=attachment_id,
|
||||
chat_id=chat_id,
|
||||
owner_id=owner_id,
|
||||
filename=filename,
|
||||
image=image,
|
||||
size_bytes=size_bytes,
|
||||
sha256=sha256,
|
||||
status=AttachmentStatus.PENDING,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
staging_key=f"{STAGING_PREFIX}{attachment_id}",
|
||||
)
|
||||
|
||||
@property
|
||||
def content_type(self) -> str:
|
||||
return self.image.kind.value
|
||||
|
||||
@property
|
||||
def ready(self) -> bool:
|
||||
return self.status is AttachmentStatus.READY
|
||||
|
||||
def variant(self, name: str) -> Variant | None:
|
||||
return next((variant for variant in self.variants if variant.name == name), None)
|
||||
|
||||
def enqueue(self, now: datetime) -> None:
|
||||
self.status = AttachmentStatus.QUEUED
|
||||
self.updated_at = max(now, self.created_at)
|
||||
self._events.append(
|
||||
AttachmentQueued(
|
||||
attachment_id=self.id,
|
||||
chat_id=self.chat_id,
|
||||
owner_id=self.owner_id,
|
||||
size_bytes=self.size_bytes,
|
||||
)
|
||||
)
|
||||
|
||||
def discard(self, reason: str) -> None:
|
||||
self._events.append(
|
||||
AttachmentDiscarded(attachment_id=self.id, chat_id=self.chat_id, reason=reason)
|
||||
)
|
||||
|
||||
def collect_events(self) -> list[DomainEvent]:
|
||||
events, self._events = self._events, []
|
||||
return events
|
||||
@@ -0,0 +1,46 @@
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
|
||||
from messenger.attachments.domain.errors import InvalidFilename, UnsupportedImage
|
||||
|
||||
FILENAME_MAX = 255
|
||||
SEPARATORS = frozenset("/\\")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Filename:
|
||||
value: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.value.strip():
|
||||
raise InvalidFilename("параметр filename обязателен и не может быть пустым")
|
||||
if len(self.value) > FILENAME_MAX:
|
||||
raise InvalidFilename(f"параметр filename длиннее {FILENAME_MAX} символов Unicode")
|
||||
if any(c in SEPARATORS or unicodedata.category(c) == "Cc" for c in self.value):
|
||||
raise InvalidFilename(
|
||||
"параметр filename содержит разделитель пути или управляющий символ"
|
||||
)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.value
|
||||
|
||||
|
||||
class ImageKind(StrEnum):
|
||||
PNG = "image/png"
|
||||
JPEG = "image/jpeg"
|
||||
|
||||
@classmethod
|
||||
def declared(cls, content_type: str | None) -> ImageKind:
|
||||
media = (content_type or "").partition(";")[0].strip().lower()
|
||||
try:
|
||||
return cls(media)
|
||||
except ValueError as error:
|
||||
raise UnsupportedImage("Content-Type должен быть image/png или image/jpeg") from error
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ImageInfo:
|
||||
kind: ImageKind
|
||||
width: int
|
||||
height: int
|
||||
@@ -0,0 +1,35 @@
|
||||
from dataclasses import dataclass
|
||||
from uuid import UUID
|
||||
|
||||
THUMBNAIL = "thumbnail"
|
||||
CROP = "crop"
|
||||
OPTIMIZED = "optimized"
|
||||
THUMBNAIL_BOX = 256
|
||||
CROP_SIDE = 128
|
||||
OPTIMIZED_BOX = 1280
|
||||
VARIANTS_PREFIX = "variants/"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Variant:
|
||||
name: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
object_key: str
|
||||
|
||||
|
||||
def fit(width: int, height: int, box: int) -> tuple[int, int]:
|
||||
if max(width, height) <= box:
|
||||
return width, height
|
||||
if width >= height:
|
||||
return box, max(1, height * box // width)
|
||||
return max(1, width * box // height), box
|
||||
|
||||
|
||||
def variant_key(
|
||||
attachment_id: UUID, pipeline_version: int, name: str, sha256: str, extension: str
|
||||
) -> str:
|
||||
return f"{VARIANTS_PREFIX}{attachment_id}/{pipeline_version}/{name}-{sha256[:16]}.{extension}"
|
||||
@@ -0,0 +1,50 @@
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from dataclasses import asdict
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
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.ports import AttachmentDirectory
|
||||
from messenger.attachments.domain.jobs import ReplayResult
|
||||
|
||||
REGISTRY_LIMIT = 20
|
||||
|
||||
|
||||
def parser() -> argparse.ArgumentParser:
|
||||
root = argparse.ArgumentParser(
|
||||
prog="python -m messenger.admin", description="Реестр failed-заданий и явный replay"
|
||||
)
|
||||
commands = root.add_subparsers(dest="command", required=True)
|
||||
failed = commands.add_parser("failed", help="последние задания в failed")
|
||||
failed.add_argument("--limit", type=int, default=REGISTRY_LIMIT)
|
||||
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"))
|
||||
return root
|
||||
|
||||
|
||||
async def run(container: AsyncContainer, argv: list[str]) -> dict[str, Any]:
|
||||
args = parser().parse_args(argv)
|
||||
async with container() as scope:
|
||||
if args.command == "failed":
|
||||
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)
|
||||
)
|
||||
return {"result": result.value, "attachment_id": args.attachment_id, "operator": args.operator}
|
||||
|
||||
|
||||
def plain(value: object) -> str:
|
||||
return value.isoformat() if isinstance(value, datetime) else str(value)
|
||||
|
||||
|
||||
def rendered(report: dict[str, Any]) -> str:
|
||||
return json.dumps(report, default=plain, ensure_ascii=False)
|
||||
@@ -0,0 +1,20 @@
|
||||
from messenger.attachments.domain.errors import (
|
||||
AttachmentNotFound,
|
||||
AttachmentNotReady,
|
||||
ChatNotFound,
|
||||
InvalidFilename,
|
||||
PayloadTooLarge,
|
||||
UnsupportedImage,
|
||||
UploadAborted,
|
||||
)
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
|
||||
ERROR_CODES: dict[type[DomainError], tuple[str, int]] = {
|
||||
InvalidFilename: ("invalid_request", 400),
|
||||
UploadAborted: ("invalid_request", 400),
|
||||
ChatNotFound: ("not_found", 404),
|
||||
AttachmentNotFound: ("not_found", 404),
|
||||
AttachmentNotReady: ("conflict", 409),
|
||||
PayloadTooLarge: ("payload_too_large", 413),
|
||||
UnsupportedImage: ("unsupported_media_type", 415),
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import asyncio
|
||||
from collections.abc import Awaitable, Callable
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
|
||||
class Heartbeat:
|
||||
__slots__ = ("_interval", "_logger", "_path", "_probe", "_task")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
path: Path | None,
|
||||
probe: Callable[[], Awaitable[bool]],
|
||||
interval: float,
|
||||
logger: Logger,
|
||||
) -> None:
|
||||
self._path = path
|
||||
self._probe = probe
|
||||
self._interval = interval
|
||||
self._logger = logger
|
||||
self._task: asyncio.Task[None] | None = None
|
||||
|
||||
def start(self) -> None:
|
||||
if self._path is not None:
|
||||
self._task = asyncio.create_task(self._run(self._path))
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._task is None:
|
||||
return
|
||||
self._task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await self._task
|
||||
self._task = None
|
||||
|
||||
async def _run(self, path: Path) -> None:
|
||||
while True:
|
||||
try:
|
||||
if await self._probe():
|
||||
await asyncio.to_thread(path.touch)
|
||||
except Exception as error:
|
||||
self._logger.warning("heartbeat.failed", error=type(error).__name__)
|
||||
await asyncio.sleep(self._interval)
|
||||
@@ -0,0 +1,77 @@
|
||||
import re
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from dishka.integrations.fastapi import FromDishka, inject
|
||||
from fastapi import APIRouter, Query, Request, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import UploadAttachment
|
||||
from messenger.attachments.application.queries import GetAttachment, OpenAttachment
|
||||
from messenger.attachments.domain.errors import UploadAborted
|
||||
from messenger.attachments.entrypoints.schemas import AttachmentOut, VariantName
|
||||
from messenger.shared.entrypoints.actor import Actor
|
||||
|
||||
UPLOAD_PATH = re.compile(r"/api/v1/chats/[^/]+/attachments/?")
|
||||
CONTENT_HEADERS = {"X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store"}
|
||||
|
||||
uploads_router = APIRouter(prefix="/api/v1/chats/{chat_id}/attachments", tags=["attachments"])
|
||||
attachments_router = APIRouter(prefix="/api/v1/attachments", tags=["attachments"])
|
||||
|
||||
|
||||
async def body_of(request: Request) -> AsyncIterator[bytes]:
|
||||
try:
|
||||
async for chunk in request.stream():
|
||||
yield chunk
|
||||
except ClientDisconnect as error:
|
||||
raise UploadAborted("клиент оборвал загрузку до конца тела") from error
|
||||
|
||||
|
||||
@uploads_router.post("", status_code=status.HTTP_202_ACCEPTED)
|
||||
@inject
|
||||
async def upload_attachment(
|
||||
chat_id: UUID,
|
||||
actor: Actor,
|
||||
request: Request,
|
||||
bus: FromDishka[AttachmentsCommandBus],
|
||||
filename: Annotated[str | None, Query()] = None,
|
||||
) -> AttachmentOut:
|
||||
attachment = await bus.execute(
|
||||
UploadAttachment(
|
||||
owner_id=actor,
|
||||
chat_id=chat_id,
|
||||
filename=filename,
|
||||
content_type=request.headers.get("content-type"),
|
||||
body=body_of(request),
|
||||
)
|
||||
)
|
||||
return AttachmentOut.of(attachment)
|
||||
|
||||
|
||||
@attachments_router.get("/{attachment_id}")
|
||||
@inject
|
||||
async def read_attachment(
|
||||
attachment_id: UUID,
|
||||
actor: Actor,
|
||||
query: FromDishka[GetAttachment],
|
||||
) -> AttachmentOut:
|
||||
return AttachmentOut.of(await query(attachment_id, actor))
|
||||
|
||||
|
||||
@attachments_router.get("/{attachment_id}/content")
|
||||
@inject
|
||||
async def download_attachment(
|
||||
attachment_id: UUID,
|
||||
actor: Actor,
|
||||
query: FromDishka[OpenAttachment],
|
||||
variant: Annotated[VariantName, Query()] = "original",
|
||||
) -> StreamingResponse:
|
||||
content_type, content = await query(attachment_id, actor, variant)
|
||||
return StreamingResponse(
|
||||
content.chunks,
|
||||
media_type=content_type,
|
||||
headers={**CONTENT_HEADERS, "Content-Length": str(content.size)},
|
||||
)
|
||||
@@ -0,0 +1,268 @@
|
||||
from collections.abc import AsyncIterator, Iterator
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import timedelta
|
||||
|
||||
from dishka import Provider, Scope, provide
|
||||
from faststream.rabbit import RabbitBroker
|
||||
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import (
|
||||
CleanStaging,
|
||||
ProcessJob,
|
||||
PublishOutbox,
|
||||
RecoverExpiredLeases,
|
||||
ReplayAttachment,
|
||||
SweepAbandonedUploads,
|
||||
UploadAttachment,
|
||||
)
|
||||
from messenger.attachments.application.handlers import (
|
||||
SweepAbandonedUploadsHandler,
|
||||
UploadAttachmentHandler,
|
||||
UploadSlots,
|
||||
)
|
||||
from messenger.attachments.application.pipeline import (
|
||||
CleanStagingHandler,
|
||||
ProcessJobHandler,
|
||||
PublishOutboxHandler,
|
||||
RecoverExpiredLeasesHandler,
|
||||
ReplayAttachmentHandler,
|
||||
)
|
||||
from messenger.attachments.application.ports import (
|
||||
AttachmentDirectory,
|
||||
AttachmentsUnitOfWork,
|
||||
ChatMembership,
|
||||
Faults,
|
||||
ImageInspector,
|
||||
Jitter,
|
||||
JobPublisher,
|
||||
ObjectStorage,
|
||||
VariantRenderer,
|
||||
)
|
||||
from messenger.attachments.application.queries import GetAttachment, OpenAttachment
|
||||
from messenger.attachments.config import AttachmentsSettings, PipelineSettings
|
||||
from messenger.attachments.domain.jobs import RetryPolicy
|
||||
from messenger.attachments.infrastructure.faults import EnvironmentFaults
|
||||
from messenger.attachments.infrastructure.images import (
|
||||
PillowImageInspector,
|
||||
ProcessVariantRenderer,
|
||||
RenderLimits,
|
||||
)
|
||||
from messenger.attachments.infrastructure.jitter import RandomJitter
|
||||
from messenger.attachments.infrastructure.postgres import (
|
||||
PostgresAttachmentDirectory,
|
||||
PostgresAttachmentsUnitOfWork,
|
||||
)
|
||||
from messenger.attachments.infrastructure.rabbitmq import RabbitJobPublisher
|
||||
from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client
|
||||
from messenger.shared.application.commands import Command
|
||||
from messenger.shared.application.messagebus import CommandHandler
|
||||
from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator, Logger
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def object_storage(settings: AttachmentsSettings) -> AsyncIterator[ObjectStorage]:
|
||||
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:
|
||||
yield S3ObjectStorage(client, settings.s3_bucket)
|
||||
|
||||
|
||||
class AttachmentsProvider(Provider):
|
||||
def __init__(self, settings: AttachmentsSettings) -> None:
|
||||
super().__init__()
|
||||
self._settings = settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def settings(self) -> AttachmentsSettings:
|
||||
return self._settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
async def storage(self, settings: AttachmentsSettings) -> AsyncIterator[ObjectStorage]:
|
||||
async with object_storage(settings) as storage:
|
||||
yield storage
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def images(self, settings: AttachmentsSettings) -> ImageInspector:
|
||||
return PillowImageInspector(settings.max_image_pixels, settings.image_check_concurrency)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def slots(self, settings: AttachmentsSettings) -> UploadSlots:
|
||||
return UploadSlots(settings.upload_concurrency)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def directory(self, database: Database) -> AttachmentDirectory:
|
||||
return PostgresAttachmentDirectory(database)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def unit_of_work(self, database: Database) -> AttachmentsUnitOfWork:
|
||||
return PostgresAttachmentsUnitOfWork(database)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def attachment(
|
||||
self, directory: AttachmentDirectory, membership: ChatMembership
|
||||
) -> GetAttachment:
|
||||
return GetAttachment(directory, membership)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def content(
|
||||
self, attachment: GetAttachment, storage: ObjectStorage, logger: Logger
|
||||
) -> OpenAttachment:
|
||||
return OpenAttachment(attachment, storage, logger)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def command_bus(
|
||||
self,
|
||||
uow: AttachmentsUnitOfWork,
|
||||
membership: ChatMembership,
|
||||
images: ImageInspector,
|
||||
storage: ObjectStorage,
|
||||
publisher: EventPublisher,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
settings: AttachmentsSettings,
|
||||
slots: UploadSlots,
|
||||
logger: Logger,
|
||||
) -> AttachmentsCommandBus:
|
||||
upload = UploadAttachmentHandler(
|
||||
uow,
|
||||
membership,
|
||||
images,
|
||||
storage,
|
||||
clock=clock,
|
||||
ids=ids,
|
||||
limit=settings.max_upload_bytes,
|
||||
slots=slots,
|
||||
logger=logger,
|
||||
)
|
||||
handlers: dict[type[Command], CommandHandler] = {
|
||||
UploadAttachment: upload,
|
||||
SweepAbandonedUploads: SweepAbandonedUploadsHandler(uow, storage, clock),
|
||||
}
|
||||
return AttachmentsCommandBus(handlers, uow, publisher)
|
||||
|
||||
|
||||
class PipelineProvider(Provider):
|
||||
def __init__(self, settings: PipelineSettings) -> None:
|
||||
super().__init__()
|
||||
self._settings = settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def settings(self) -> PipelineSettings:
|
||||
return self._settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
async def storage(self, settings: PipelineSettings) -> AsyncIterator[ObjectStorage]:
|
||||
async with object_storage(settings) as storage:
|
||||
yield storage
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def policy(self, settings: PipelineSettings) -> RetryPolicy:
|
||||
return RetryPolicy(
|
||||
settings.job_max_attempts,
|
||||
settings.job_backoff_base_seconds,
|
||||
settings.job_backoff_cap_seconds,
|
||||
)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def faults(self, settings: PipelineSettings, logger: Logger) -> Faults:
|
||||
return EnvironmentFaults(settings.fault_point, logger, settings.fault_stall_seconds)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def unit_of_work(self, database: Database) -> AttachmentsUnitOfWork:
|
||||
return PostgresAttachmentsUnitOfWork(database)
|
||||
|
||||
|
||||
class WorkerProvider(Provider):
|
||||
@provide(scope=Scope.APP)
|
||||
def renderer(self, settings: PipelineSettings) -> Iterator[VariantRenderer]:
|
||||
renderer = ProcessVariantRenderer(
|
||||
RenderLimits(settings.max_upload_bytes, settings.max_image_pixels),
|
||||
concurrency=settings.worker_concurrency,
|
||||
timeout=settings.render_timeout_seconds,
|
||||
memory_bytes=settings.render_memory_mb << 20,
|
||||
tasks_per_child=settings.render_tasks_per_child,
|
||||
)
|
||||
yield renderer
|
||||
renderer.close()
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def jitter(self) -> Jitter:
|
||||
return RandomJitter()
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def command_bus(
|
||||
self,
|
||||
uow: AttachmentsUnitOfWork,
|
||||
storage: ObjectStorage,
|
||||
renderer: VariantRenderer,
|
||||
faults: Faults,
|
||||
publisher: EventPublisher,
|
||||
ids: IdGenerator,
|
||||
jitter: Jitter,
|
||||
policy: RetryPolicy,
|
||||
settings: PipelineSettings,
|
||||
) -> AttachmentsCommandBus:
|
||||
process = ProcessJobHandler(
|
||||
uow,
|
||||
storage,
|
||||
renderer,
|
||||
faults,
|
||||
ids=ids,
|
||||
jitter=jitter,
|
||||
policy=policy,
|
||||
lease=timedelta(seconds=settings.job_timeout_seconds),
|
||||
)
|
||||
return AttachmentsCommandBus({ProcessJob: process}, uow, publisher)
|
||||
|
||||
|
||||
class RelayProvider(Provider):
|
||||
def __init__(self, broker: RabbitBroker) -> None:
|
||||
super().__init__()
|
||||
self._broker = broker
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def publisher(self, settings: PipelineSettings) -> JobPublisher:
|
||||
return RabbitJobPublisher(self._broker, settings.publish_timeout_seconds)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def command_bus(
|
||||
self,
|
||||
uow: AttachmentsUnitOfWork,
|
||||
storage: ObjectStorage,
|
||||
jobs: JobPublisher,
|
||||
faults: Faults,
|
||||
publisher: EventPublisher,
|
||||
policy: RetryPolicy,
|
||||
) -> AttachmentsCommandBus:
|
||||
handlers: dict[type[Command], CommandHandler] = {
|
||||
PublishOutbox: PublishOutboxHandler(uow, jobs, faults),
|
||||
RecoverExpiredLeases: RecoverExpiredLeasesHandler(uow, policy),
|
||||
CleanStaging: CleanStagingHandler(uow, storage),
|
||||
}
|
||||
return AttachmentsCommandBus(handlers, uow, publisher)
|
||||
|
||||
|
||||
class AdminProvider(Provider):
|
||||
@provide(scope=Scope.APP)
|
||||
def directory(self, database: Database) -> AttachmentDirectory:
|
||||
return PostgresAttachmentDirectory(database)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def unit_of_work(self, database: Database) -> AttachmentsUnitOfWork:
|
||||
return PostgresAttachmentsUnitOfWork(database)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def command_bus(
|
||||
self, uow: AttachmentsUnitOfWork, publisher: EventPublisher
|
||||
) -> AttachmentsCommandBus:
|
||||
handlers: dict[type[Command], CommandHandler] = {
|
||||
ReplayAttachment: ReplayAttachmentHandler(uow)
|
||||
}
|
||||
return AttachmentsCommandBus(handlers, uow, publisher)
|
||||
@@ -0,0 +1,78 @@
|
||||
from messenger.attachments.domain.events import (
|
||||
AttachmentDiscarded,
|
||||
AttachmentQueued,
|
||||
AttachmentReplayRequested,
|
||||
JobSettled,
|
||||
)
|
||||
from messenger.shared.application.messagebus import EventBus
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
LOG_FIELDS = frozenset(
|
||||
{
|
||||
"attachment_id",
|
||||
"chat_id",
|
||||
"actor_id",
|
||||
"size_bytes",
|
||||
"count",
|
||||
"job_id",
|
||||
"attempt",
|
||||
"pipeline_version",
|
||||
"outcome",
|
||||
"error_code",
|
||||
"delay_seconds",
|
||||
"operator",
|
||||
"result",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class AttachmentsJournal:
|
||||
__slots__ = ("_logger",)
|
||||
|
||||
def __init__(self, logger: Logger) -> None:
|
||||
self._logger = logger
|
||||
|
||||
async def on_attachment_queued(self, event: AttachmentQueued) -> None:
|
||||
self._logger.info(
|
||||
"audit.attachment_queued",
|
||||
attachment_id=str(event.attachment_id),
|
||||
chat_id=str(event.chat_id),
|
||||
actor_id=str(event.owner_id),
|
||||
size_bytes=event.size_bytes,
|
||||
)
|
||||
|
||||
async def on_attachment_discarded(self, event: AttachmentDiscarded) -> None:
|
||||
self._logger.info(
|
||||
"audit.attachment_discarded",
|
||||
attachment_id=str(event.attachment_id),
|
||||
chat_id=str(event.chat_id),
|
||||
reason=event.reason,
|
||||
)
|
||||
|
||||
async def on_job_settled(self, event: JobSettled) -> None:
|
||||
self._logger.info(
|
||||
"audit.job_settled",
|
||||
job_id=str(event.job_id),
|
||||
attachment_id=str(event.attachment_id),
|
||||
pipeline_version=event.pipeline_version,
|
||||
attempt=event.attempt,
|
||||
outcome=event.outcome,
|
||||
error_code=event.error_code,
|
||||
delay_seconds=event.delay_seconds,
|
||||
)
|
||||
|
||||
async def on_replay_requested(self, event: AttachmentReplayRequested) -> None:
|
||||
self._logger.info(
|
||||
"audit.attachment_replay",
|
||||
attachment_id=str(event.attachment_id),
|
||||
operator=event.operator,
|
||||
result=event.result,
|
||||
)
|
||||
|
||||
|
||||
def subscribe_journal(bus: EventBus, logger: Logger) -> None:
|
||||
journal = AttachmentsJournal(logger)
|
||||
bus.subscribe(AttachmentQueued, journal.on_attachment_queued)
|
||||
bus.subscribe(AttachmentDiscarded, journal.on_attachment_discarded)
|
||||
bus.subscribe(JobSettled, journal.on_job_settled)
|
||||
bus.subscribe(AttachmentReplayRequested, journal.on_replay_requested)
|
||||
@@ -0,0 +1,73 @@
|
||||
import asyncio
|
||||
from collections.abc import Sequence
|
||||
from contextlib import suppress
|
||||
from datetime import timedelta
|
||||
|
||||
from dishka import AsyncContainer
|
||||
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import (
|
||||
CleanStaging,
|
||||
PublishOutbox,
|
||||
RecoverExpiredLeases,
|
||||
)
|
||||
from messenger.attachments.config import PipelineSettings
|
||||
from messenger.shared.application.commands import Command
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
|
||||
class Relay:
|
||||
__slots__ = ("_container", "_logger", "_settings", "_tasks")
|
||||
|
||||
def __init__(
|
||||
self, container: AsyncContainer, settings: PipelineSettings, logger: Logger
|
||||
) -> None:
|
||||
self._container = container
|
||||
self._settings = settings
|
||||
self._logger = logger
|
||||
self._tasks: list[asyncio.Task[None]] = []
|
||||
|
||||
def start(self) -> None:
|
||||
settings = self._settings
|
||||
loops: tuple[tuple[float, Sequence[Command]], ...] = (
|
||||
(settings.outbox_poll_seconds, (PublishOutbox(settings.outbox_batch),)),
|
||||
(
|
||||
settings.sweep_interval_seconds,
|
||||
(
|
||||
RecoverExpiredLeases(settings.sweep_batch),
|
||||
CleanStaging(
|
||||
settings.sweep_batch, timedelta(seconds=settings.staging_retention_seconds)
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
self._tasks = [asyncio.create_task(self._every(*loop)) for loop in loops]
|
||||
|
||||
async def stop(self) -> None:
|
||||
for task in self._tasks:
|
||||
task.cancel()
|
||||
for task in self._tasks:
|
||||
with suppress(asyncio.CancelledError):
|
||||
await task
|
||||
self._tasks = []
|
||||
|
||||
async def run(self, command: Command) -> int:
|
||||
async with self._container() as scope:
|
||||
bus = await scope.get(AttachmentsCommandBus)
|
||||
return await bus.execute(command)
|
||||
|
||||
async def _every(self, interval: float, commands: Sequence[Command]) -> None:
|
||||
while True:
|
||||
for command in commands:
|
||||
try:
|
||||
done = await self.run(command)
|
||||
except Exception as error:
|
||||
self._logger.warning(
|
||||
"relay.pass_failed",
|
||||
reason=type(command).__name__,
|
||||
error=type(error).__name__,
|
||||
)
|
||||
continue
|
||||
if done:
|
||||
self._logger.info("relay.pass", reason=type(command).__name__, count=done)
|
||||
await asyncio.sleep(interval)
|
||||
@@ -0,0 +1,84 @@
|
||||
from datetime import datetime
|
||||
from typing import Annotated, Literal
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import AwareDatetime, BaseModel, ConfigDict, Field
|
||||
|
||||
from messenger.attachments.domain.jobs import Job
|
||||
from messenger.attachments.domain.models import Attachment
|
||||
from messenger.attachments.domain.variants import Variant
|
||||
|
||||
type VariantName = Literal["original", "thumbnail", "crop", "optimized"]
|
||||
|
||||
|
||||
class VariantOut(BaseModel):
|
||||
name: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
|
||||
@classmethod
|
||||
def of(cls, variant: Variant) -> VariantOut:
|
||||
return cls(
|
||||
name=variant.name,
|
||||
content_type=variant.content_type,
|
||||
size_bytes=variant.size_bytes,
|
||||
width=variant.width,
|
||||
height=variant.height,
|
||||
sha256=variant.sha256,
|
||||
)
|
||||
|
||||
|
||||
class AttachmentOut(BaseModel):
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str
|
||||
variants: list[VariantOut]
|
||||
error_code: str | None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@classmethod
|
||||
def of(cls, attachment: Attachment) -> AttachmentOut:
|
||||
return cls(
|
||||
id=attachment.id,
|
||||
chat_id=attachment.chat_id,
|
||||
owner_id=attachment.owner_id,
|
||||
filename=attachment.filename.value,
|
||||
content_type=attachment.content_type,
|
||||
size_bytes=attachment.size_bytes,
|
||||
sha256=attachment.sha256,
|
||||
status=attachment.status.value,
|
||||
variants=[VariantOut.of(variant) for variant in attachment.variants],
|
||||
error_code=attachment.error_code,
|
||||
created_at=attachment.created_at,
|
||||
updated_at=attachment.updated_at,
|
||||
)
|
||||
|
||||
|
||||
class JobMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", frozen=True)
|
||||
|
||||
schema_version: Literal[1]
|
||||
job_id: UUID
|
||||
type: Literal["attachment.process.v1"]
|
||||
attachment_id: UUID
|
||||
pipeline_version: Annotated[int, Field(ge=1)]
|
||||
attempt: Annotated[int, Field(ge=1)]
|
||||
created_at: AwareDatetime
|
||||
traceparent: Annotated[
|
||||
str | None, Field(pattern=r"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$")
|
||||
] = None
|
||||
tracestate: Annotated[str | None, Field(max_length=512)] = None
|
||||
|
||||
def job(self) -> Job:
|
||||
return Job(
|
||||
self.job_id, self.attachment_id, self.pipeline_version, self.attempt, self.created_at
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
import asyncio
|
||||
from contextlib import suppress
|
||||
from datetime import timedelta
|
||||
|
||||
from dishka import AsyncContainer
|
||||
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import SweepAbandonedUploads
|
||||
from messenger.attachments.config import AttachmentsSettings
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
|
||||
class UploadSweeper:
|
||||
__slots__ = ("_command", "_container", "_interval", "_logger", "_task")
|
||||
|
||||
def __init__(
|
||||
self, container: AsyncContainer, settings: AttachmentsSettings, logger: Logger
|
||||
) -> None:
|
||||
self._container = container
|
||||
self._logger = logger
|
||||
self._interval = settings.upload_sweep_interval_seconds
|
||||
self._command = SweepAbandonedUploads(
|
||||
grace=timedelta(seconds=settings.upload_grace_seconds),
|
||||
limit=settings.upload_sweep_batch,
|
||||
)
|
||||
self._task: asyncio.Task[None] | None = None
|
||||
|
||||
def start(self) -> None:
|
||||
self._task = asyncio.create_task(self._run())
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._task is None:
|
||||
return
|
||||
self._task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await self._task
|
||||
self._task = None
|
||||
|
||||
async def sweep(self) -> int:
|
||||
async with self._container() as scope:
|
||||
bus = await scope.get(AttachmentsCommandBus)
|
||||
return await bus.execute(self._command)
|
||||
|
||||
async def _run(self) -> None:
|
||||
while True:
|
||||
await asyncio.sleep(self._interval)
|
||||
try:
|
||||
swept = await self.sweep()
|
||||
except Exception as error:
|
||||
self._logger.warning("attachments.sweep_failed", error=type(error).__name__)
|
||||
continue
|
||||
if swept:
|
||||
self._logger.info("attachments.swept", count=swept)
|
||||
@@ -0,0 +1,50 @@
|
||||
import asyncio
|
||||
|
||||
from dishka import FromDishka
|
||||
from faststream import AckPolicy
|
||||
from faststream.rabbit import Channel, QueueType, RabbitBroker, RabbitQueue
|
||||
from faststream.rabbit.annotations import RabbitMessage
|
||||
from pydantic import ValidationError
|
||||
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import ProcessJob
|
||||
from messenger.attachments.entrypoints.schemas import JobMessage
|
||||
from messenger.attachments.infrastructure.rabbitmq import QUEUE
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
REQUEUE_DELAY_SECONDS = 1.0
|
||||
JOBS = RabbitQueue(QUEUE, queue_type=QueueType.QUORUM, declare=False)
|
||||
|
||||
|
||||
async def raw(message: RabbitMessage) -> bytes:
|
||||
return message.body
|
||||
|
||||
|
||||
async def handle_job(
|
||||
message: RabbitMessage,
|
||||
bus: FromDishka[AttachmentsCommandBus],
|
||||
logger: FromDishka[Logger],
|
||||
) -> None:
|
||||
try:
|
||||
job = JobMessage.model_validate_json(message.body).job()
|
||||
except ValidationError:
|
||||
logger.warning("job.rejected", reason="message does not match jobs.schema.json")
|
||||
await message.reject(requeue=False)
|
||||
return
|
||||
try:
|
||||
await bus.execute(ProcessJob(job))
|
||||
except Exception as error:
|
||||
logger.warning("job.requeued", job_id=str(job.id), error=type(error).__name__)
|
||||
await asyncio.sleep(REQUEUE_DELAY_SECONDS)
|
||||
await message.nack(requeue=True)
|
||||
return
|
||||
await message.ack()
|
||||
|
||||
|
||||
def subscribe(broker: RabbitBroker, concurrency: int) -> None:
|
||||
broker.subscriber(
|
||||
JOBS,
|
||||
channel=Channel(prefetch_count=concurrency),
|
||||
ack_policy=AckPolicy.MANUAL,
|
||||
decoder=raw,
|
||||
)(handle_job)
|
||||
@@ -0,0 +1,32 @@
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
|
||||
from messenger.attachments.application.pipeline import STALL_AFTER_CLAIM, TRANSIENT_ERROR
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
CRASH_EXIT_CODE = 137
|
||||
|
||||
|
||||
class EnvironmentFaults:
|
||||
__slots__ = ("_logger", "_point", "_stall_seconds")
|
||||
|
||||
def __init__(self, point: str, logger: Logger, stall_seconds: float = 0.0) -> None:
|
||||
self._point = point
|
||||
self._logger = logger
|
||||
self._stall_seconds = stall_seconds
|
||||
|
||||
async def reach(self, point: str) -> None:
|
||||
if not self._point or point != self._point:
|
||||
return
|
||||
self._logger.warning("fault.injected", reason=point)
|
||||
if point == TRANSIENT_ERROR:
|
||||
raise Unavailable("внедрённая временная ошибка")
|
||||
if point == STALL_AFTER_CLAIM:
|
||||
self._point = ""
|
||||
await asyncio.sleep(self._stall_seconds)
|
||||
return
|
||||
sys.stdout.flush()
|
||||
sys.stderr.flush()
|
||||
os._exit(CRASH_EXIT_CODE)
|
||||
@@ -0,0 +1,206 @@
|
||||
import asyncio
|
||||
import resource
|
||||
import sys
|
||||
import warnings
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from concurrent.futures.process import BrokenProcessPool
|
||||
from dataclasses import dataclass
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from messenger.attachments.application.ports import Rendition
|
||||
from messenger.attachments.domain.errors import (
|
||||
ImageTooDemanding,
|
||||
PayloadTooLarge,
|
||||
UnreadableImage,
|
||||
UnsupportedImage,
|
||||
)
|
||||
from messenger.attachments.domain.values import ImageInfo, ImageKind
|
||||
from messenger.attachments.domain.variants import (
|
||||
CROP,
|
||||
CROP_SIDE,
|
||||
OPTIMIZED,
|
||||
OPTIMIZED_BOX,
|
||||
THUMBNAIL,
|
||||
THUMBNAIL_BOX,
|
||||
fit,
|
||||
)
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
|
||||
KINDS = {"PNG": ImageKind.PNG, "JPEG": ImageKind.JPEG}
|
||||
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}
|
||||
ENCODINGS = {"JPEG": (ImageKind.JPEG.value, "jpg"), "WEBP": ("image/webp", "webp")}
|
||||
REDUCING_GAP = 3.0
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RenderLimits:
|
||||
max_bytes: int
|
||||
max_pixels: int
|
||||
|
||||
|
||||
class PillowImageInspector:
|
||||
__slots__ = ("_max_pixels", "_slots")
|
||||
|
||||
def __init__(self, max_pixels: int, concurrency: int) -> None:
|
||||
self._max_pixels = max_pixels
|
||||
self._slots = asyncio.Semaphore(concurrency)
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
|
||||
async def inspect(self, data: bytes, declared: ImageKind) -> ImageInfo:
|
||||
async with self._slots:
|
||||
return await asyncio.to_thread(self._inspect, data, declared)
|
||||
|
||||
def _inspect(self, data: bytes, declared: ImageKind) -> ImageInfo:
|
||||
try:
|
||||
image = Image.open(BytesIO(data), formats=tuple(KINDS))
|
||||
except BOMBS as error:
|
||||
raise PayloadTooLarge("изображение больше допустимого числа пикселей") from error
|
||||
except Exception as error:
|
||||
raise UnsupportedImage("содержимое не является изображением PNG или JPEG") from error
|
||||
with image:
|
||||
kind = KINDS[str(image.format)]
|
||||
width, height = image.size
|
||||
if kind is not declared:
|
||||
raise UnsupportedImage("содержимое не совпадает с заявленным Content-Type")
|
||||
if width * height > self._max_pixels:
|
||||
raise PayloadTooLarge("изображение больше допустимого числа пикселей")
|
||||
try:
|
||||
if kind is ImageKind.JPEG:
|
||||
image.draft("RGB", (width // JPEG_SCALE or 1, height // JPEG_SCALE or 1))
|
||||
image.load()
|
||||
else:
|
||||
image.verify()
|
||||
except Exception as error:
|
||||
raise UnsupportedImage("изображение повреждено или обрезано") from error
|
||||
return ImageInfo(kind, width, height)
|
||||
|
||||
|
||||
def flatten(image: Image.Image) -> Image.Image:
|
||||
if image.mode in WIDE_MODES:
|
||||
image = image.convert("I").point(lambda value: value / 256, "L")
|
||||
if image.mode == "P":
|
||||
image = image.convert("RGBA" if "transparency" in image.info else "RGB")
|
||||
if image.mode in ALPHA_MODES:
|
||||
image = image.convert("RGBA")
|
||||
if image.mode == "RGBA":
|
||||
background = Image.new("RGB", image.size, "white")
|
||||
background.paste(image, mask=image.getchannel("A"))
|
||||
return background
|
||||
return image if image.mode == "RGB" else image.convert("RGB")
|
||||
|
||||
|
||||
def scaled(image: Image.Image, size: tuple[int, int]) -> Image.Image:
|
||||
if size == image.size:
|
||||
return image
|
||||
return image.resize(size, Image.Resampling.LANCZOS, reducing_gap=REDUCING_GAP)
|
||||
|
||||
|
||||
def encoded(name: str, image: Image.Image, kind: str, **options: object) -> Rendition:
|
||||
buffer = BytesIO()
|
||||
image.save(buffer, kind, **options)
|
||||
content_type, extension = ENCODINGS[kind]
|
||||
return Rendition(name, content_type, extension, buffer.getvalue(), *image.size)
|
||||
|
||||
|
||||
def decoded(data: bytes, max_pixels: int) -> tuple[Image.Image, int, int]:
|
||||
try:
|
||||
image = Image.open(BytesIO(data), formats=tuple(KINDS))
|
||||
width, height = image.size
|
||||
if width * height > max_pixels:
|
||||
raise UnreadableImage("изображение больше допустимого числа пикселей")
|
||||
image.draft(None, fit(width, height, OPTIMIZED_BOX))
|
||||
stored = image.size
|
||||
ImageOps.exif_transpose(image, in_place=True)
|
||||
if image.size != stored:
|
||||
width, height = height, width
|
||||
return flatten(image), width, height
|
||||
except UnreadableImage, MemoryError:
|
||||
raise
|
||||
except Exception as error:
|
||||
raise UnreadableImage("изображение не декодируется") from error
|
||||
|
||||
|
||||
def render_variants(data: bytes, limits: RenderLimits) -> 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),
|
||||
]
|
||||
|
||||
|
||||
def limit_memory(limit_bytes: int) -> None:
|
||||
if limit_bytes and sys.platform == "linux":
|
||||
resource.setrlimit(resource.RLIMIT_AS, (limit_bytes, limit_bytes))
|
||||
|
||||
|
||||
type Render = Callable[[bytes, RenderLimits], list[Rendition]]
|
||||
|
||||
|
||||
class ProcessVariantRenderer:
|
||||
__slots__ = ("_idle", "_limits", "_memory", "_render", "_tasks", "_timeout")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
limits: RenderLimits,
|
||||
*,
|
||||
concurrency: int,
|
||||
timeout: float,
|
||||
memory_bytes: int,
|
||||
tasks_per_child: int,
|
||||
render: Render = render_variants,
|
||||
) -> None:
|
||||
self._limits = limits
|
||||
self._timeout = timeout
|
||||
self._memory = memory_bytes
|
||||
self._tasks = tasks_per_child
|
||||
self._render = render
|
||||
self._idle: asyncio.Queue[ProcessPoolExecutor] = asyncio.Queue()
|
||||
for _ in range(concurrency):
|
||||
self._idle.put_nowait(self._spawn())
|
||||
|
||||
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))
|
||||
return await asyncio.wait_for(future, self._timeout)
|
||||
except TimeoutError as error:
|
||||
pool = self._replace(pool)
|
||||
raise ImageTooDemanding("рендер дольше допустимого времени") from error
|
||||
except MemoryError as error:
|
||||
raise ImageTooDemanding("рендер больше допустимой памяти") from error
|
||||
except BrokenProcessPool as error:
|
||||
pool = self._replace(pool)
|
||||
raise Unavailable("процесс рендера завершился аварийно") from error
|
||||
except asyncio.CancelledError:
|
||||
pool = self._replace(pool)
|
||||
raise
|
||||
finally:
|
||||
self._idle.put_nowait(pool)
|
||||
|
||||
def close(self) -> None:
|
||||
while not self._idle.empty():
|
||||
self._idle.get_nowait().kill_workers()
|
||||
|
||||
def _replace(self, pool: ProcessPoolExecutor) -> ProcessPoolExecutor:
|
||||
pool.kill_workers()
|
||||
return self._spawn()
|
||||
|
||||
def _spawn(self) -> ProcessPoolExecutor:
|
||||
return ProcessPoolExecutor(
|
||||
1,
|
||||
max_tasks_per_child=self._tasks,
|
||||
initializer=limit_memory,
|
||||
initargs=(self._memory,),
|
||||
)
|
||||
@@ -0,0 +1,10 @@
|
||||
from secrets import SystemRandom
|
||||
|
||||
SOURCE = SystemRandom()
|
||||
|
||||
|
||||
class RandomJitter:
|
||||
__slots__ = ()
|
||||
|
||||
def spread(self) -> float:
|
||||
return SOURCE.random()
|
||||
@@ -0,0 +1,461 @@
|
||||
import json
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime, timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from asyncpg import ForeignKeyViolationError, Record
|
||||
|
||||
from messenger.attachments.application.ports import OutboxEntry, StagedObject
|
||||
from messenger.attachments.domain.errors import ChatNotFound
|
||||
from messenger.attachments.domain.jobs import Claim, FailedJob, FailureCode, Job, Lease, Outcome
|
||||
from messenger.attachments.domain.models import Attachment, AttachmentStatus
|
||||
from messenger.attachments.domain.values import Filename, ImageInfo, ImageKind
|
||||
from messenger.attachments.domain.variants import Variant
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.infrastructure.postgres import (
|
||||
Connection,
|
||||
Database,
|
||||
EventSource,
|
||||
PostgresUnitOfWork,
|
||||
)
|
||||
|
||||
INSERT = """
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
width, height, staging_key, status, created_at, updated_at)
|
||||
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 a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.width,
|
||||
a.height, a.status, a.staging_key, a.original_key, a.published_version, a.error_code,
|
||||
a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
"""
|
||||
VISIBLE = """
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.width,
|
||||
a.height, a.status, a.staging_key, a.original_key, a.published_version, a.error_code,
|
||||
a.created_at, a.updated_at,
|
||||
(SELECT coalesce(jsonb_agg(jsonb_build_array(v.name, v.content_type, v.size_bytes, v.width,
|
||||
v.height, v.sha256, v.object_key)
|
||||
ORDER BY v.name), '[]')
|
||||
FROM attachment_variants v
|
||||
WHERE v.attachment_id = a.id AND v.pipeline_version = a.published_version) AS variants
|
||||
FROM attachments a
|
||||
WHERE a.id = $1 AND a.status <> 'pending'
|
||||
"""
|
||||
FAILED_AMONG = """
|
||||
SELECT EXISTS (SELECT 1 FROM attachments
|
||||
WHERE id = ANY($1::uuid[]) AND chat_id = $2 AND status = 'failed')
|
||||
"""
|
||||
LOCK = COLUMNS + "WHERE a.id = $1 FOR UPDATE"
|
||||
ABANDONED = (
|
||||
COLUMNS
|
||||
+ """WHERE a.status = 'pending' AND a.created_at < $1
|
||||
ORDER BY a.created_at LIMIT 1 FOR UPDATE SKIP LOCKED"""
|
||||
)
|
||||
REMOVE = "DELETE FROM attachments WHERE id = $1 AND status = 'pending'"
|
||||
STAGED = """
|
||||
SELECT id, staging_key FROM attachments
|
||||
WHERE staging_key IS NOT NULL
|
||||
AND (status = 'ready' OR (status = 'failed' AND updated_at < now() - make_interval(secs => $2)))
|
||||
ORDER BY updated_at LIMIT $1 FOR UPDATE SKIP LOCKED
|
||||
"""
|
||||
FAILED_JOBS = """
|
||||
SELECT j.job_id, j.attachment_id, j.pipeline_version, j.attempt, a.error_code, j.last_error,
|
||||
j.updated_at AS failed_at
|
||||
FROM jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.status = 'failed'
|
||||
ORDER BY j.updated_at DESC LIMIT $1
|
||||
"""
|
||||
UNSTAGE = "UPDATE attachments SET staging_key = NULL WHERE id = ANY($1::uuid[])"
|
||||
|
||||
ADD_JOB = """
|
||||
WITH job AS (
|
||||
INSERT INTO jobs (job_id, attachment_id, pipeline_version, status, attempt,
|
||||
created_at, updated_at)
|
||||
VALUES ($1, $2, $3, 'queued', $4, $5, $5)
|
||||
RETURNING job_id
|
||||
), box AS (
|
||||
INSERT INTO outbox (job_id, payload, available_at)
|
||||
SELECT job_id, $6::jsonb, now() FROM job
|
||||
)
|
||||
INSERT INTO job_events (job_id, attachment_id, kind, attempt)
|
||||
SELECT job_id, $2, 'enqueued', $4 FROM job
|
||||
"""
|
||||
CLAIM = """
|
||||
WITH claimed AS (
|
||||
UPDATE jobs
|
||||
SET status = 'processing', lease_token = $4, claims = claims + 1, updated_at = now(),
|
||||
lease_until = now() + make_interval(secs => $5)
|
||||
WHERE job_id = $1 AND attachment_id = $2 AND pipeline_version = $3
|
||||
AND ((status = 'queued' AND coalesce(next_attempt_at, '-infinity') <= now())
|
||||
OR (status = 'processing' AND lease_until < now()))
|
||||
RETURNING job_id, attachment_id, attempt, created_at
|
||||
), moved AS (
|
||||
UPDATE attachments a SET status = 'processing', updated_at = greatest(now(), a.created_at)
|
||||
FROM claimed c WHERE a.id = c.attachment_id AND a.status = 'queued'
|
||||
), audit AS (
|
||||
INSERT INTO job_events (job_id, attachment_id, kind, attempt)
|
||||
SELECT job_id, attachment_id, 'claimed', attempt FROM claimed
|
||||
)
|
||||
SELECT c.attempt, c.created_at, a.staging_key, a.original_key
|
||||
FROM claimed c JOIN attachments a ON a.id = c.attachment_id
|
||||
"""
|
||||
FINISH = """
|
||||
UPDATE jobs SET status = 'done', lease_token = NULL, lease_until = NULL, next_attempt_at = NULL,
|
||||
last_error = NULL, updated_at = now()
|
||||
WHERE job_id = $1 AND status = 'processing' AND lease_token = $2
|
||||
"""
|
||||
ADD_VARIANTS = """
|
||||
INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type,
|
||||
size_bytes, width, height, sha256, created_at)
|
||||
SELECT $1, $2, v.name, v.object_key, v.content_type, v.size_bytes, v.width, v.height, v.sha256,
|
||||
now()
|
||||
FROM unnest($3::text[], $4::text[], $5::text[], $6::bigint[], $7::int[], $8::int[], $9::text[])
|
||||
AS v (name, object_key, content_type, size_bytes, width, height, sha256)
|
||||
ON CONFLICT DO NOTHING
|
||||
"""
|
||||
PUBLISH = """
|
||||
UPDATE attachments
|
||||
SET status = 'ready', published_version = $2, error_code = NULL, original_key = $3,
|
||||
updated_at = greatest(now(), created_at)
|
||||
WHERE id = $1 AND published_version < $2
|
||||
"""
|
||||
SUPERSEDE = "UPDATE jobs SET status = 'superseded', updated_at = now() WHERE job_id = $1"
|
||||
RESCHEDULE = """
|
||||
WITH job AS (
|
||||
UPDATE jobs
|
||||
SET status = 'queued', attempt = attempt + 1, lease_token = NULL, lease_until = NULL,
|
||||
next_attempt_at = now() + make_interval(secs => $3), last_error = $4, updated_at = now()
|
||||
WHERE job_id = $1 AND status = 'processing' AND lease_token = $2
|
||||
RETURNING job_id, attachment_id, attempt, next_attempt_at
|
||||
), moved AS (
|
||||
UPDATE attachments a SET status = 'queued', updated_at = greatest(now(), a.created_at)
|
||||
FROM job WHERE a.id = job.attachment_id AND a.status = 'processing'
|
||||
), audit AS (
|
||||
INSERT INTO job_events (job_id, attachment_id, kind, attempt, detail)
|
||||
SELECT job_id, attachment_id, $5, attempt,
|
||||
jsonb_build_object('error', $4::text, 'next_attempt_at', next_attempt_at,
|
||||
'delay_seconds', $3::float8)
|
||||
FROM job
|
||||
)
|
||||
SELECT attempt, next_attempt_at FROM job
|
||||
"""
|
||||
RENEW = """
|
||||
UPDATE jobs SET lease_until = now() + make_interval(secs => $3), updated_at = now()
|
||||
WHERE job_id = $1 AND lease_token = $2 AND status = 'processing'
|
||||
"""
|
||||
ENQUEUE = "INSERT INTO outbox (job_id, payload, available_at) VALUES ($1, $2::jsonb, $3)"
|
||||
FAIL = """
|
||||
WITH job AS (
|
||||
UPDATE jobs SET status = 'failed', lease_token = NULL, lease_until = NULL, last_error = $4,
|
||||
updated_at = now()
|
||||
WHERE job_id = $1 AND status = 'processing' AND lease_token = $2
|
||||
RETURNING job_id, attachment_id, attempt
|
||||
), moved AS (
|
||||
UPDATE attachments a SET status = 'failed', error_code = $3,
|
||||
updated_at = greatest(now(), a.created_at)
|
||||
FROM job WHERE a.id = job.attachment_id AND a.status IN ('queued', 'processing')
|
||||
), audit AS (
|
||||
INSERT INTO job_events (job_id, attachment_id, kind, attempt, detail)
|
||||
SELECT job_id, attachment_id, 'failed', attempt,
|
||||
jsonb_build_object('error_code', $3::text, 'error', $4::text)
|
||||
FROM job
|
||||
)
|
||||
SELECT attempt FROM job
|
||||
"""
|
||||
NOTE = "INSERT INTO job_events (job_id, attachment_id, kind, attempt) VALUES ($1, $2, $3, $4)"
|
||||
EXPIRED = """
|
||||
SELECT job_id, attachment_id, pipeline_version, attempt, created_at, lease_token FROM jobs
|
||||
WHERE status = 'processing' AND lease_until < now()
|
||||
ORDER BY lease_until LIMIT $1 FOR UPDATE SKIP LOCKED
|
||||
"""
|
||||
REPLAY = """
|
||||
WITH job AS (
|
||||
UPDATE jobs
|
||||
SET status = 'queued', attempt = 1, lease_token = NULL, lease_until = NULL,
|
||||
next_attempt_at = NULL, last_error = NULL, updated_at = now()
|
||||
WHERE job_id = (SELECT job_id FROM jobs WHERE attachment_id = $1 AND status = 'failed'
|
||||
ORDER BY pipeline_version DESC LIMIT 1)
|
||||
RETURNING job_id, attachment_id, pipeline_version, created_at, updated_at
|
||||
), moved AS (
|
||||
UPDATE attachments a SET status = 'queued', error_code = NULL,
|
||||
updated_at = greatest(now(), a.created_at)
|
||||
FROM job WHERE a.id = job.attachment_id AND a.status = 'failed'
|
||||
), audit AS (
|
||||
INSERT INTO job_events (job_id, attachment_id, kind, attempt, detail)
|
||||
SELECT job_id, attachment_id, 'replayed', 1,
|
||||
jsonb_build_object('operator', $2::text, 'error_code', $3::text)
|
||||
FROM job
|
||||
)
|
||||
SELECT job_id, pipeline_version, created_at, updated_at FROM job
|
||||
"""
|
||||
NOTE_REPLAY = """
|
||||
INSERT INTO job_events (job_id, attachment_id, kind, attempt, detail)
|
||||
SELECT job_id, attachment_id, 'replay_noop', attempt,
|
||||
jsonb_build_object('operator', $2::text, 'result', $3::text)
|
||||
FROM jobs WHERE attachment_id = $1
|
||||
ORDER BY pipeline_version DESC LIMIT 1
|
||||
"""
|
||||
PENDING = """
|
||||
SELECT id, job_id, payload::text AS body FROM outbox
|
||||
WHERE published_at IS NULL AND available_at <= now()
|
||||
ORDER BY available_at, id LIMIT $1 FOR UPDATE SKIP LOCKED
|
||||
"""
|
||||
PUBLISHED = "UPDATE outbox SET published_at = now() WHERE id = ANY($1::bigint[])"
|
||||
|
||||
|
||||
def attachment_of(row: Record, variants: tuple[Variant, ...] = ()) -> Attachment:
|
||||
return Attachment(
|
||||
id=row["id"],
|
||||
chat_id=row["chat_id"],
|
||||
owner_id=row["owner_id"],
|
||||
filename=Filename(row["filename"]),
|
||||
image=ImageInfo(ImageKind(row["content_type"]), row["width"], row["height"]),
|
||||
size_bytes=row["size_bytes"],
|
||||
sha256=row["sha256"],
|
||||
status=AttachmentStatus(row["status"]),
|
||||
created_at=row["created_at"],
|
||||
updated_at=row["updated_at"],
|
||||
staging_key=row["staging_key"],
|
||||
original_key=row["original_key"],
|
||||
published_version=row["published_version"],
|
||||
error_code=row["error_code"],
|
||||
variants=variants,
|
||||
)
|
||||
|
||||
|
||||
def payload(job: Job) -> str:
|
||||
return json.dumps(job.payload(), separators=(",", ":"))
|
||||
|
||||
|
||||
class PostgresAttachmentRepository:
|
||||
__slots__ = ("_connection", "_seen")
|
||||
|
||||
def __init__(self, connection: Connection, seen: list[EventSource]) -> None:
|
||||
self._connection = connection
|
||||
self._seen = seen
|
||||
|
||||
async def add(self, attachment: Attachment) -> None:
|
||||
try:
|
||||
await self._connection.execute(
|
||||
INSERT,
|
||||
attachment.id,
|
||||
attachment.chat_id,
|
||||
attachment.owner_id,
|
||||
attachment.filename.value,
|
||||
attachment.content_type,
|
||||
attachment.size_bytes,
|
||||
attachment.sha256,
|
||||
attachment.image.width,
|
||||
attachment.image.height,
|
||||
attachment.staging_key,
|
||||
attachment.status.value,
|
||||
attachment.created_at,
|
||||
attachment.updated_at,
|
||||
)
|
||||
except ForeignKeyViolationError as error:
|
||||
raise ChatNotFound("чат не найден") from error
|
||||
self._seen.append(attachment)
|
||||
|
||||
async def save(self, attachment: Attachment) -> None:
|
||||
done = await self._connection.execute(
|
||||
MARK, attachment.id, attachment.status.value, attachment.updated_at
|
||||
)
|
||||
if done == "UPDATE 0":
|
||||
raise Unavailable("намерение загрузки уже снято уборкой")
|
||||
self._seen.append(attachment)
|
||||
|
||||
async def lock(self, attachment_id: UUID) -> Attachment | None:
|
||||
row = await self._connection.fetchrow(LOCK, attachment_id)
|
||||
return None if row is None else attachment_of(row)
|
||||
|
||||
async def next_abandoned(self, before: datetime) -> Attachment | None:
|
||||
row = await self._connection.fetchrow(ABANDONED, before)
|
||||
return None if row is None else attachment_of(row)
|
||||
|
||||
async def remove(self, attachment: Attachment) -> None:
|
||||
await self._connection.execute(REMOVE, attachment.id)
|
||||
self._seen.append(attachment)
|
||||
|
||||
async def staged(self, limit: int, retention: timedelta) -> list[StagedObject]:
|
||||
rows = await self._connection.fetch(STAGED, limit, retention.total_seconds())
|
||||
return [StagedObject(row["id"], row["staging_key"]) for row in rows]
|
||||
|
||||
async def unstage(self, attachment_ids: Sequence[UUID]) -> None:
|
||||
if attachment_ids:
|
||||
await self._connection.execute(UNSTAGE, list(attachment_ids))
|
||||
|
||||
|
||||
class PostgresJobRepository:
|
||||
__slots__ = ("_connection",)
|
||||
|
||||
def __init__(self, connection: Connection) -> None:
|
||||
self._connection = connection
|
||||
|
||||
async def add(self, job: Job) -> None:
|
||||
await self._connection.execute(
|
||||
ADD_JOB,
|
||||
job.id,
|
||||
job.attachment_id,
|
||||
job.pipeline_version,
|
||||
job.attempt,
|
||||
job.created_at,
|
||||
payload(job),
|
||||
)
|
||||
|
||||
async def claim(self, job: Job, token: UUID, lease: timedelta) -> Claim | None:
|
||||
row = await self._connection.fetchrow(
|
||||
CLAIM,
|
||||
job.id,
|
||||
job.attachment_id,
|
||||
job.pipeline_version,
|
||||
token,
|
||||
lease.total_seconds(),
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
claimed = Job(
|
||||
job.id, job.attachment_id, job.pipeline_version, row["attempt"], row["created_at"]
|
||||
)
|
||||
staged = row["staging_key"] is not None
|
||||
source = row["staging_key"] if staged else row["original_key"]
|
||||
return Claim(Lease(claimed, token), source, staged)
|
||||
|
||||
async def complete(
|
||||
self, lease: Lease, variants: Sequence[Variant], original_key: str
|
||||
) -> Outcome:
|
||||
job = lease.job
|
||||
if await self._connection.execute(FINISH, job.id, lease.token) == "UPDATE 0":
|
||||
await self.note(job, Outcome.FENCED)
|
||||
return Outcome.FENCED
|
||||
await self._connection.execute(
|
||||
ADD_VARIANTS,
|
||||
job.attachment_id,
|
||||
job.pipeline_version,
|
||||
[v.name for v in variants],
|
||||
[v.object_key for v in variants],
|
||||
[v.content_type for v in variants],
|
||||
[v.size_bytes for v in variants],
|
||||
[v.width for v in variants],
|
||||
[v.height for v in variants],
|
||||
[v.sha256 for v in variants],
|
||||
)
|
||||
published = await self._connection.execute(
|
||||
PUBLISH, job.attachment_id, job.pipeline_version, original_key
|
||||
)
|
||||
outcome = Outcome.SUPERSEDED if published == "UPDATE 0" else Outcome.DONE
|
||||
if outcome is Outcome.SUPERSEDED:
|
||||
await self._connection.execute(SUPERSEDE, job.id)
|
||||
await self.note(job, outcome)
|
||||
return outcome
|
||||
|
||||
async def reschedule(
|
||||
self, lease: Lease, delay: timedelta, kind: Outcome, error: str
|
||||
) -> Job | None:
|
||||
row = await self._connection.fetchrow(
|
||||
RESCHEDULE, lease.job.id, lease.token, delay.total_seconds(), error, kind.value
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
job = lease.job.retried(row["attempt"])
|
||||
await self._connection.execute(ENQUEUE, job.id, payload(job), row["next_attempt_at"])
|
||||
return job
|
||||
|
||||
async def renew(self, lease: Lease, duration: timedelta) -> bool:
|
||||
done = await self._connection.execute(
|
||||
RENEW, lease.job.id, lease.token, duration.total_seconds()
|
||||
)
|
||||
return done == "UPDATE 1"
|
||||
|
||||
async def fail(self, lease: Lease, code: FailureCode, error: str) -> bool:
|
||||
attempt = await self._connection.fetchval(
|
||||
FAIL, lease.job.id, lease.token, code.value, error
|
||||
)
|
||||
return attempt is not None
|
||||
|
||||
async def note(self, job: Job, kind: Outcome) -> None:
|
||||
await self._connection.execute(NOTE, job.id, job.attachment_id, kind.value, job.attempt)
|
||||
|
||||
async def expired(self, limit: int) -> list[Lease]:
|
||||
rows = await self._connection.fetch(EXPIRED, limit)
|
||||
return [
|
||||
Lease(
|
||||
Job(
|
||||
row["job_id"],
|
||||
row["attachment_id"],
|
||||
row["pipeline_version"],
|
||||
row["attempt"],
|
||||
row["created_at"],
|
||||
),
|
||||
row["lease_token"],
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
async def replay(self, attachment: Attachment, operator: str) -> Job | None:
|
||||
row = await self._connection.fetchrow(
|
||||
REPLAY, attachment.id, operator, attachment.error_code
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
job = Job(row["job_id"], attachment.id, row["pipeline_version"], 1, row["created_at"])
|
||||
await self._connection.execute(ENQUEUE, job.id, payload(job), row["updated_at"])
|
||||
return job
|
||||
|
||||
async def note_replay(self, attachment_id: UUID, operator: str, result: str) -> None:
|
||||
await self._connection.execute(NOTE_REPLAY, attachment_id, operator, result)
|
||||
|
||||
|
||||
class PostgresOutboxRepository:
|
||||
__slots__ = ("_connection",)
|
||||
|
||||
def __init__(self, connection: Connection) -> None:
|
||||
self._connection = connection
|
||||
|
||||
async def pending(self, limit: int) -> list[OutboxEntry]:
|
||||
rows = await self._connection.fetch(PENDING, limit)
|
||||
return [OutboxEntry(row["id"], row["job_id"], row["body"].encode()) for row in rows]
|
||||
|
||||
async def published(self, entry_ids: Sequence[int]) -> None:
|
||||
await self._connection.execute(PUBLISHED, list(entry_ids))
|
||||
|
||||
|
||||
class PostgresAttachmentsUnitOfWork(PostgresUnitOfWork):
|
||||
__slots__ = ()
|
||||
|
||||
@property
|
||||
def attachments(self) -> PostgresAttachmentRepository:
|
||||
return PostgresAttachmentRepository(self.connection, self.seen)
|
||||
|
||||
@property
|
||||
def jobs(self) -> PostgresJobRepository:
|
||||
return PostgresJobRepository(self.connection)
|
||||
|
||||
@property
|
||||
def outbox(self) -> PostgresOutboxRepository:
|
||||
return PostgresOutboxRepository(self.connection)
|
||||
|
||||
|
||||
def variants_of(raw: str) -> tuple[Variant, ...]:
|
||||
return tuple(Variant(*item) for item in json.loads(raw))
|
||||
|
||||
|
||||
class PostgresAttachmentDirectory:
|
||||
__slots__ = ("_database",)
|
||||
|
||||
def __init__(self, database: Database) -> None:
|
||||
self._database = database
|
||||
|
||||
async def visible(self, attachment_id: UUID) -> Attachment | None:
|
||||
async with self._database.connection() as connection:
|
||||
row = await connection.fetchrow(VISIBLE, attachment_id)
|
||||
return None if row is None else attachment_of(row, variants_of(row["variants"]))
|
||||
|
||||
async def failed_among(self, chat_id: UUID, attachment_ids: Sequence[UUID]) -> bool:
|
||||
async with self._database.connection() as connection:
|
||||
return bool(await connection.fetchval(FAILED_AMONG, list(attachment_ids), chat_id))
|
||||
|
||||
async def failed_jobs(self, limit: int) -> list[FailedJob]:
|
||||
async with self._database.connection() as connection:
|
||||
return [FailedJob(**row) for row in await connection.fetch(FAILED_JOBS, limit)]
|
||||
@@ -0,0 +1,37 @@
|
||||
from uuid import UUID
|
||||
|
||||
from faststream.rabbit import RabbitBroker, RabbitExchange
|
||||
from pamqp.commands import Basic
|
||||
|
||||
from messenger.attachments.domain.jobs import JOB_TYPE
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
|
||||
EXCHANGE = RabbitExchange("attachments", declare=False)
|
||||
QUEUE = "attachments.process"
|
||||
DEAD_LETTERS = "attachments.process.dlq"
|
||||
|
||||
|
||||
class RabbitJobPublisher:
|
||||
__slots__ = ("_broker", "_timeout")
|
||||
|
||||
def __init__(self, broker: RabbitBroker, timeout: float) -> None:
|
||||
self._broker = broker
|
||||
self._timeout = timeout
|
||||
|
||||
async def publish(self, job_id: UUID, body: bytes) -> None:
|
||||
try:
|
||||
confirmation = await self._broker.publish(
|
||||
body,
|
||||
exchange=EXCHANGE,
|
||||
routing_key=JOB_TYPE,
|
||||
mandatory=True,
|
||||
persist=True,
|
||||
message_id=str(job_id),
|
||||
message_type=JOB_TYPE,
|
||||
content_type="application/json",
|
||||
timeout=self._timeout,
|
||||
)
|
||||
except Exception as error:
|
||||
raise Unavailable("брокер не принял задание") from error
|
||||
if not isinstance(confirmation, Basic.Ack):
|
||||
raise Unavailable("брокер не подтвердил задание")
|
||||
@@ -0,0 +1,104 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any
|
||||
|
||||
from aiobotocore.session import get_session
|
||||
from botocore.config import Config
|
||||
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.shared.application.errors import Unavailable
|
||||
|
||||
CHUNK_BYTES = 64 * 1024
|
||||
MISSING = frozenset({"NoSuchKey", "404", "NotFound"})
|
||||
FAILURES = (BotoCoreError, ClientError, OSError, TimeoutError)
|
||||
|
||||
|
||||
def missing(error: Exception) -> bool:
|
||||
return isinstance(error, ClientError) and error.response.get("Error", {}).get("Code") in MISSING
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def s3_client(
|
||||
*,
|
||||
endpoint: str,
|
||||
region: str,
|
||||
access_key_id: str,
|
||||
secret_access_key: str,
|
||||
connect_timeout: float,
|
||||
read_timeout: float,
|
||||
max_attempts: int,
|
||||
) -> AsyncIterator[Any]:
|
||||
config = Config(
|
||||
region_name=region,
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=connect_timeout,
|
||||
read_timeout=read_timeout,
|
||||
retries={"mode": "standard", "max_attempts": max_attempts},
|
||||
max_pool_connections=32,
|
||||
request_checksum_calculation="when_required",
|
||||
response_checksum_validation="when_required",
|
||||
)
|
||||
async with get_session().create_client(
|
||||
"s3",
|
||||
endpoint_url=endpoint,
|
||||
aws_access_key_id=access_key_id,
|
||||
aws_secret_access_key=secret_access_key,
|
||||
config=config,
|
||||
) as client:
|
||||
client.meta.events.unregister("before-call.s3", add_expect_header)
|
||||
yield client
|
||||
|
||||
|
||||
class S3ObjectStorage:
|
||||
__slots__ = ("_bucket", "_client")
|
||||
|
||||
def __init__(self, client: Any, bucket: str) -> None:
|
||||
self._client = client
|
||||
self._bucket = bucket
|
||||
|
||||
async def put(self, key: str, data: bytes, content_type: str) -> None:
|
||||
try:
|
||||
await self._client.put_object(
|
||||
Bucket=self._bucket, Key=key, Body=data, ContentType=content_type
|
||||
)
|
||||
except FAILURES as error:
|
||||
raise Unavailable("S3 недоступно") from error
|
||||
|
||||
async def open(self, key: str) -> ObjectContent:
|
||||
try:
|
||||
response = await self._client.get_object(Bucket=self._bucket, Key=key)
|
||||
except FAILURES as error:
|
||||
if missing(error):
|
||||
raise ObjectMissingError(key) from error
|
||||
raise Unavailable("S3 недоступно") from error
|
||||
return ObjectContent(size=response["ContentLength"], chunks=self._chunks(response["Body"]))
|
||||
|
||||
async def read(self, key: str) -> bytes:
|
||||
content = await self.open(key)
|
||||
try:
|
||||
return b"".join([chunk async for chunk in content.chunks])
|
||||
except Exception as error:
|
||||
raise Unavailable("S3 оборвал чтение объекта") from error
|
||||
|
||||
async def copy(self, source: str, target: str) -> None:
|
||||
try:
|
||||
await self._client.copy_object(
|
||||
Bucket=self._bucket, Key=target, CopySource={"Bucket": self._bucket, "Key": source}
|
||||
)
|
||||
except FAILURES as error:
|
||||
raise Unavailable("S3 недоступно") from error
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
try:
|
||||
await self._client.delete_object(Bucket=self._bucket, Key=key)
|
||||
except FAILURES as error:
|
||||
raise Unavailable("S3 недоступно") from error
|
||||
|
||||
async def _chunks(self, body: Any) -> AsyncIterator[bytes]:
|
||||
async with body as stream:
|
||||
async for chunk in stream.iter_chunks(CHUNK_BYTES):
|
||||
yield chunk
|
||||
Reference in New Issue
Block a user