Files
mtusi2026lab5/app/imaging.py
T
RainakandClaude Opus 5.5 0a221b0675 ЛР5 БВТ2304 Запорожец на 5
RabbitMQ (quorum queue, publisher confirms, manual ack, DLX) + отдельный worker:
staging в S3 + вложение/job/outbox одной транзакцией -> 202 queued; relay outbox,
lease с heartbeat и fencing (worker_id, attempt), retry с backoff+jitter, failed-реестр,
безопасный replay с audit; thumbnail/crop/WebP в изолированном процессе с лимитами.
Тесты окон отказа (fault injection), трек 1 «Очередь под перегрузкой» с backpressure.
Перенесено исправление замечания lab3 PR #99 (U+0000 в тексте).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:33:52 +03:00

185 lines
9.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Построение вариантов изображения (выполняется worker-ом в отдельном дочернем процессе).
Контракт (contracts/README.md, «Фоновая обработка»):
- thumbnail: JPEG, вписан в 256x256 с сохранением пропорций, без увеличения, EXIF orientation применяется,
alpha компонуется на белый, размеры округляются вниз, минимум 1 px (320x200 -> 256x160);
- crop: JPEG, центрированный квадрат 128x128 (маленький исходник увеличивается);
- optimized: WebP, вписан в 1280x1280 без увеличения.
Параметры: JPEG quality=85 (thumbnail, crop), optimize=True, progressive=False; WebP quality=80, method=4.
Метаданные удаляются: EXIF/ICC/XMP не передаются в save() (Pillow не копирует их без явного exif=/icc_profile=),
ориентация EXIF уже применена к пикселям. Все варианты — 8-bit sRGB без alpha.
Ограничения ресурсов: лимит пикселей проверяется по заголовку ДО декодирования; JPEG декодируется в draft-
режиме с уменьшением до ближайшего масштаба >= 1280 (меньше памяти и CPU); процесс запускается с RLIMIT_AS
(память) и убивается по таймауту (время) — см. run_isolated().
"""
import asyncio
import hashlib
import io
import multiprocessing
import resource
import warnings
from PIL import Image, ImageOps
THUMB = 256
CROP = 128
OPTIMIZED = 1280
class PermanentImageError(Exception):
def __init__(self, code: str):
super().__init__(code)
self.code = code
class TransientImageError(Exception):
def __init__(self, code: str):
super().__init__(code)
self.code = code
def fit(width: int, height: int, box: int) -> tuple[int, int]:
"""Вписать в box x box без увеличения; целочисленно, округление вниз, минимум 1 px."""
m = max(width, height)
if m <= box:
return width, height
return max(1, width * box // m), max(1, height * box // m)
def flatten(img: Image.Image) -> Image.Image:
"""Alpha (RGBA/LA/P с прозрачностью) компонуется на белый фон; результат RGB."""
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
rgba = img.convert('RGBA')
background = Image.new('RGB', rgba.size, (255, 255, 255))
background.paste(rgba, mask=rgba.getchannel('A'))
return background
if img.mode in ('I;16', 'I;16B', 'I;16L', 'I'):
img = img.point(lambda v: v / 256).convert('L') # 16-bit серый -> 8-bit
return img.convert('RGB')
def encode(name: str, img: Image.Image, fmt: str, content_type: str, **params) -> dict:
buf = io.BytesIO()
img.save(buf, fmt, **params)
data = buf.getvalue()
return {'name': name, 'content_type': content_type, 'width': img.width, 'height': img.height,
'size_bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest(), 'data': data}
def build_variants(data: bytes, max_pixels: int) -> list[dict]:
with warnings.catch_warnings():
warnings.simplefilter('error', Image.DecompressionBombWarning)
Image.MAX_IMAGE_PIXELS = max_pixels
try:
img = Image.open(io.BytesIO(data))
width, height = img.size
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
raise PermanentImageError('image_too_large') from None
except Exception:
raise PermanentImageError('invalid_image') from None
if img.format not in ('PNG', 'JPEG'):
raise PermanentImageError('invalid_image')
if width * height > max_pixels:
raise PermanentImageError('image_too_large')
try:
if img.format == 'JPEG':
img.draft('RGB', (OPTIMIZED, OPTIMIZED)) # декодер сам уменьшает в 2/4/8 раз, если можно
img.load()
img = ImageOps.exif_transpose(img)
rgb = flatten(img)
except MemoryError:
raise
except Exception:
raise PermanentImageError('invalid_image') from None
# Размеры считаются от ориентированного ОРИГИНАЛА (не от draft-копии), иначе draft менял бы результат.
ow, oh = _oriented_size(data, width, height)
variants = []
tw, th = fit(ow, oh, THUMB)
variants.append(encode('thumbnail', rgb.resize((tw, th), Image.LANCZOS) if (tw, th) != rgb.size else rgb,
'JPEG', 'image/jpeg', quality=85, optimize=True))
side = min(rgb.size)
left, top = (rgb.width - side) // 2, (rgb.height - side) // 2
square = rgb.crop((left, top, left + side, top + side))
variants.append(encode('crop', square.resize((CROP, CROP), Image.LANCZOS), 'JPEG', 'image/jpeg',
quality=85, optimize=True))
pw, ph = fit(ow, oh, OPTIMIZED)
variants.append(encode('optimized', rgb.resize((pw, ph), Image.LANCZOS) if (pw, ph) != rgb.size else rgb,
'WEBP', 'image/webp', quality=80, method=4))
return variants
def _orientation(data: bytes) -> int:
try:
return Image.open(io.BytesIO(data)).getexif().get(0x0112, 1)
except Exception:
return 1
def _rotated(data: bytes) -> bool:
return _orientation(data) in (5, 6, 7, 8)
def _oriented_size(data: bytes, width: int, height: int) -> tuple[int, int]:
"""Размер оригинала после применения EXIF orientation (5–8 меняют местами ширину и высоту)."""
return (height, width) if _rotated(data) else (width, height)
# ---------- изоляция: отдельный процесс с лимитом памяти и времени ----------
def _child(conn, data: bytes, max_pixels: int, memory_mb: int) -> None:
limit = memory_mb * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
try:
conn.send(('ok', build_variants(data, max_pixels)))
except PermanentImageError as exc:
conn.send(('permanent', exc.code))
except MemoryError:
conn.send(('permanent', 'resource_limit'))
except Exception:
conn.send(('permanent', 'processing_failed'))
finally:
conn.close()
_ctx = multiprocessing.get_context('forkserver')
# Preload app.worker: forkserver один раз импортирует главный модуль worker со всеми зависимостями
# (aio-pika, jsonschema, minio, asyncpg, Pillow), дочерние процессы получают их готовыми через fork.
# Без этого каждый запуск обработки заново импортировал app.worker (при `python -m` multiprocessing
# восстанавливает __main__ по имени модуля): 0.7–2.3 с накладных расходов на задание при 0.07 с полезной
# работы для 320x200 — найдено в эксперименте трека 1 (evidence/track1/, раздел «Итерация 1» в REPORT.md).
# '__main__' по пути здесь не работает: при запуске через -m пути к главному модулю нет.
_ctx.set_forkserver_preload(['app.worker', 'app.imaging'])
async def run_isolated(data: bytes, max_pixels: int, memory_mb: int, timeout: float) -> list[dict]:
"""Варианты строятся в дочернем процессе: зависание/бомба памяти не роняют и не блокируют worker.
Таймаут -> процесс убивается, TransientImageError('processing_timeout') (мог помешать перегруз CPU —
повтор с backoff; при исчерпании попыток — failed retry_exhausted).
RLIMIT_AS/смерть процесса -> PermanentImageError('resource_limit').
"""
parent, child = _ctx.Pipe(duplex=False)
proc = _ctx.Process(target=_child, args=(child, data, max_pixels, memory_mb), daemon=True)
proc.start()
child.close()
loop = asyncio.get_running_loop()
try:
ready = await loop.run_in_executor(None, parent.poll, timeout)
if not ready:
raise TransientImageError('processing_timeout')
try:
status, value = await loop.run_in_executor(None, parent.recv)
except EOFError:
raise PermanentImageError('resource_limit') from None
finally:
if proc.is_alive():
proc.kill()
await loop.run_in_executor(None, proc.join, 5)
parent.close()
if status == 'ok':
return value
raise PermanentImageError(value)