Files
mtusi2026lab2/src/messenger/attachments/infrastructure/images.py
T
ArtyomandClaude Opus 5.5 5ae3d77152 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>
2026-10-29 03:51:58 +03:00

207 lines
7.8 KiB
Python

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,),
)