forked from mtusi2026/mtusi2026lab5
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>
105 lines
3.7 KiB
Python
105 lines
3.7 KiB
Python
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
|