Upload now stages the checked original under staging/, and one transaction moves the intent to queued, inserts the job (pipeline version 1, attempt 1), its outbox row and an audit event; the 202 is the in-memory snapshot, never a reread. Content answers 409 until the attachment is ready, the thumbnail variant is served from the published version and absent variants are 404. The relay publishes outbox rows through FastStream with publisher confirms, mandatory routing and persistent delivery, marks a row only after the broker acked it, returns jobs whose lease expired and deletes the staging object of ready attachments. The worker consumes the quorum queue through a FastStream subscriber that declares nothing, takes prefetch from WORKER_CONCURRENCY and acks manually after the result commit, rejects messages off jobs.schema.json to the dead letter exchange and requeues after an infrastructure error. A job is claimed under a lease token; the original is copied to originals/ and a 256 px JPEG thumbnail is written under a content-addressed key; the commit is fenced by the token, inserts variants with ON CONFLICT DO NOTHING and publishes only a newer pipeline version. A transient error reschedules the same job with an exponential delay and a new outbox row, the last attempt fails with retry_exhausted, an undecodable image fails at once with invalid_image, and a redelivered finished job is a recorded no-op. The worker and the relay are assembled in worker.py and relay.py with the dishka FastStream integration and the platform providers of the API; the shared core imports neither FastStream nor aio-pika. Tests cover the thumbnail geometry and rendering, the job message against the contract, the pipeline against PostgreSQL (duplicates, parallel copies, retries, the attempt bound, leases and fencing) and the broker adapters against a throwaway RabbitMQ with the stand's topology and permissions. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
82 lines
2.6 KiB
Python
82 lines
2.6 KiB
Python
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
from datetime import datetime, timedelta
|
|
from typing import Any
|
|
|
|
from dishka import Provider, Scope, provide
|
|
|
|
from messenger.attachments.application.errors import ObjectMissingError
|
|
from messenger.attachments.application.ports import ObjectContent, ObjectStorage
|
|
from messenger.shared.application.errors import Unavailable
|
|
|
|
|
|
class NullLogger:
|
|
__slots__ = ()
|
|
|
|
def info(self, event: str, /, **fields: Any) -> None: ...
|
|
|
|
def warning(self, event: str, /, **fields: Any) -> None: ...
|
|
|
|
def error(self, event: str, /, **fields: Any) -> None: ...
|
|
|
|
|
|
class FrozenClock:
|
|
__slots__ = ("_current",)
|
|
|
|
def __init__(self, start: datetime) -> None:
|
|
self._current = start
|
|
|
|
def now(self) -> datetime:
|
|
self._current += timedelta(microseconds=1)
|
|
return self._current
|
|
|
|
|
|
async def pieces(data: bytes, size: int = 65_536) -> AsyncIterator[bytes]:
|
|
for start in range(0, len(data), size):
|
|
yield data[start : start + size]
|
|
|
|
|
|
class MemoryObjectStorage:
|
|
__slots__ = ("after_put", "failing", "objects")
|
|
|
|
def __init__(self) -> None:
|
|
self.objects: dict[str, tuple[bytes, str]] = {}
|
|
self.failing = False
|
|
self.after_put: Callable[[str], Awaitable[None]] | None = None
|
|
|
|
async def put(self, key: str, data: bytes, content_type: str) -> None:
|
|
if self.failing:
|
|
raise Unavailable("S3 недоступно")
|
|
self.objects[key] = (bytes(data), content_type)
|
|
if self.after_put is not None:
|
|
await self.after_put(key)
|
|
|
|
async def open(self, key: str) -> ObjectContent:
|
|
if self.failing:
|
|
raise Unavailable("S3 недоступно")
|
|
if key not in self.objects:
|
|
raise ObjectMissingError(key)
|
|
data = self.objects[key][0]
|
|
return ObjectContent(size=len(data), chunks=pieces(data))
|
|
|
|
async def read(self, key: str) -> bytes:
|
|
content = await self.open(key)
|
|
return b"".join([chunk async for chunk in content.chunks])
|
|
|
|
async def copy(self, source: str, target: str) -> None:
|
|
if self.failing:
|
|
raise Unavailable("S3 недоступно")
|
|
if source not in self.objects:
|
|
raise ObjectMissingError(source)
|
|
self.objects[target] = self.objects[source]
|
|
|
|
async def delete(self, key: str) -> None:
|
|
if self.failing:
|
|
raise Unavailable("S3 недоступно")
|
|
self.objects.pop(key, None)
|
|
|
|
|
|
class MemoryStorageProvider(Provider):
|
|
@provide(scope=Scope.APP)
|
|
def storage(self) -> ObjectStorage:
|
|
return MemoryObjectStorage()
|