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>
103 lines
4.5 KiB
Python
103 lines
4.5 KiB
Python
import asyncio
|
|
import warnings
|
|
from io import BytesIO
|
|
|
|
from PIL import Image, ImageOps
|
|
|
|
from messenger.attachments.application.ports import Rendition
|
|
from messenger.attachments.domain.errors import PayloadTooLarge, UnreadableImage, UnsupportedImage
|
|
from messenger.attachments.domain.values import ImageInfo, ImageKind
|
|
from messenger.attachments.domain.variants import THUMBNAIL, THUMBNAIL_BOX, fit
|
|
|
|
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
|
|
|
|
|
|
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 jpeg(name: str, image: Image.Image, box: int) -> Rendition:
|
|
size = fit(image.width, image.height, box)
|
|
scaled = image if size == image.size else image.resize(size, Image.Resampling.LANCZOS)
|
|
buffer = BytesIO()
|
|
scaled.save(buffer, "JPEG", quality=JPEG_QUALITY, optimize=True)
|
|
return Rendition(name, ImageKind.JPEG.value, "jpg", buffer.getvalue(), *size)
|
|
|
|
|
|
def render_variants(data: bytes, max_pixels: int) -> list[Rendition]:
|
|
try:
|
|
with Image.open(BytesIO(data), formats=tuple(KINDS)) as image:
|
|
if image.width * image.height > max_pixels:
|
|
raise UnreadableImage("изображение больше допустимого числа пикселей")
|
|
image.load()
|
|
upright = flatten(ImageOps.exif_transpose(image))
|
|
except UnreadableImage:
|
|
raise
|
|
except Exception as error:
|
|
raise UnreadableImage("изображение не декодируется") from error
|
|
return [jpeg(THUMBNAIL, upright, THUMBNAIL_BOX)]
|
|
|
|
|
|
class PillowVariantRenderer:
|
|
__slots__ = ("_max_pixels", "_slots")
|
|
|
|
def __init__(self, max_pixels: int, concurrency: int) -> None:
|
|
self._max_pixels = max_pixels
|
|
self._slots = asyncio.Semaphore(concurrency)
|
|
|
|
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
|
|
async with self._slots:
|
|
return await asyncio.to_thread(render_variants, data, self._max_pixels)
|