ЛР5: брокер Redis Streams, worker, outbox, retry/DLQ/replay, варианты

This commit is contained in:
LOSYASH
2026-11-12 15:14:48 +01:00
parent 276dbdad8a
commit b4804ac5c1
98 changed files with 9131 additions and 38 deletions
+153
View File
@@ -0,0 +1,153 @@
"""
Построение вариантов изображения (lab5). Выполняется в ДОЧЕРНЕМ процессе worker
(app/worker.py → run_isolated), чтобы ограничить память и время одной задачи:
- RLIMIT_AS (IMAGE_MEMORY_MB): нехватка памяти → MemoryError в ребёнке, а не OOM всего worker;
- RLIMIT_CPU и wall-clock таймаут родителя (JOB_TIMEOUT_SECONDS): зависшее
декодирование убивается, worker живёт дальше;
- пиксели проверяются по заголовку ДО распаковки (MAX_IMAGE_PIXELS = 40 млн).
Варианты (контракт, contracts/README.md «Фоновая обработка»):
thumbnail — JPEG, вписан в 256×256, пропорции сохраняются, маленькие НЕ увеличиваются,
размеры округляются вниз, минимум 1 px (320×200 → 256×160);
crop — JPEG, центрированный квадрат 128×128 (маленькие исходники увеличиваются);
optimized — WebP, вписан в 1280×1280 без увеличения, quality 80, method 4.
Во всех вариантах: EXIF orientation применяется; EXIF/XMP/ICC в результат НЕ пишутся
(Pillow пишет метаданные только если их явно передать в save()). Прозрачность в JPEG
компонуется на белый фон; в WebP альфа-канал сохраняется.
"""
from __future__ import annotations
import json
import os
import resource
import traceback
import warnings
from PIL import Image, ImageFile, ImageOps
ImageFile.LOAD_TRUNCATED_IMAGES = False
warnings.simplefilter("error", Image.DecompressionBombWarning)
THUMB_BOX = 256
CROP_SIDE = 128
OPTIMIZED_BOX = 1280
JPEG_QUALITY = 85
WEBP_QUALITY = 80
WEBP_METHOD = 4
# Порядок вариантов в ответе API и набор, который обещает уровень «4».
VARIANTS = ("thumbnail", "crop", "optimized")
VARIANT_TYPES = {"thumbnail": "image/jpeg", "crop": "image/jpeg", "optimized": "image/webp"}
VARIANT_EXT = {"thumbnail": "jpg", "crop": "jpg", "optimized": "webp"}
class PermanentImageError(Exception):
"""Изображение не обработать никогда (битое, слишком большое) → failed invalid_image."""
def fit_size(w: int, h: int, box: int) -> tuple[int, int]:
"""Вписать в box×box без увеличения, округление вниз, минимум 1 px."""
if w <= box and h <= box:
return w, h
if w >= h:
return box, max(1, h * box // w)
return max(1, w * box // h), box
def _oriented_size(img: Image.Image) -> tuple[int, int]:
w, h = img.size
try:
orientation = img.getexif().get(0x0112, 1)
except Exception: # noqa: BLE001 — битый EXIF не повод падать; ориентация по умолчанию
orientation = 1
return (h, w) if orientation in (5, 6, 7, 8) else (w, h)
def _on_white(img: Image.Image) -> Image.Image:
"""RGB для JPEG: прозрачность компонуется на белый."""
if img.mode in ("RGBA", "LA", "PA") or (img.mode == "P" and "transparency" in img.info):
rgba = img.convert("RGBA")
bg = Image.new("RGB", rgba.size, (255, 255, 255))
bg.paste(rgba, mask=rgba.getchannel("A"))
return bg
return img.convert("RGB")
def _has_alpha(img: Image.Image) -> bool:
return img.mode in ("RGBA", "LA", "PA") or (img.mode == "P" and "transparency" in img.info)
def render(src_path: str, out_dir: str, content_type: str, max_pixels: int) -> dict:
fmt = {"image/png": "PNG", "image/jpeg": "JPEG"}[content_type]
Image.MAX_IMAGE_PIXELS = max_pixels
try:
with Image.open(src_path, formats=[fmt]) as img:
w0, h0 = img.size
if w0 <= 0 or h0 <= 0 or w0 * h0 > max_pixels:
raise PermanentImageError("pixel limit")
ow, oh = _oriented_size(img) # размеры после поворота по EXIF
thumb = fit_size(ow, oh, THUMB_BOX)
opt = fit_size(ow, oh, OPTIMIZED_BOX)
if fmt == "JPEG":
# Декодируем сразу в уменьшенном масштабе (1/2, 1/4, 1/8), но не меньше,
# чем нужно самому большому варианту (optimized) и crop: экономия памяти и времени.
rw, rh = (opt[1], opt[0]) if (ow, oh) != (w0, h0) else opt # в осях файла
img.draft("RGB", (max(rw, min(w0, CROP_SIDE)), max(rh, min(h0, CROP_SIDE))))
img.load()
base = ImageOps.exif_transpose(img) # копия с применённой ориентацией
except PermanentImageError:
raise
except (Image.DecompressionBombError, Image.DecompressionBombWarning) as exc:
raise PermanentImageError("pixel limit") from exc
except (OSError, SyntaxError, ValueError, EOFError, IndexError, KeyError) as exc:
raise PermanentImageError(f"cannot decode: {type(exc).__name__}") from exc
out = {}
rgb = _on_white(base)
t = rgb.resize(thumb, Image.Resampling.LANCZOS, reducing_gap=3.0)
out["thumbnail"] = _save(t, out_dir, "thumbnail", "JPEG", quality=JPEG_QUALITY, optimize=True)
bw, bh = rgb.size
side = min(bw, bh)
left, top = (bw - side) // 2, (bh - side) // 2
c = rgb.crop((left, top, left + side, top + side)).resize(
(CROP_SIDE, CROP_SIDE), Image.Resampling.LANCZOS, reducing_gap=3.0)
out["crop"] = _save(c, out_dir, "crop", "JPEG", quality=JPEG_QUALITY, optimize=True)
src = base.convert("RGBA") if _has_alpha(base) else rgb
o = src if src.size == opt else src.resize(opt, Image.Resampling.LANCZOS, reducing_gap=3.0)
out["optimized"] = _save(o, out_dir, "optimized", "WEBP", quality=WEBP_QUALITY, method=WEBP_METHOD)
return out
def _save(img: Image.Image, out_dir: str, name: str, fmt: str, **opts) -> dict:
path = os.path.join(out_dir, f"{name}.{VARIANT_EXT[name]}")
img.save(path, fmt, **opts) # без exif=/icc_profile= → метаданных нет
return {"path": path, "content_type": VARIANT_TYPES[name],
"width": img.size[0], "height": img.size[1]}
def child_main(src_path: str, out_dir: str, content_type: str, max_pixels: int,
memory_mb: int, cpu_seconds: int, result_path: str,
slow_seconds: float = 0.0) -> None:
"""Точка входа дочернего процесса. Результат — JSON-файл; код выхода 0.
slow_seconds > 0 — только для теста «долгой, но живой» задачи (fault-профиль)."""
resource.setrlimit(resource.RLIMIT_AS, (memory_mb * 1024 * 1024, memory_mb * 1024 * 1024))
resource.setrlimit(resource.RLIMIT_CPU, (cpu_seconds, cpu_seconds + 1))
if slow_seconds > 0:
import time
time.sleep(slow_seconds) # sleep не тратит CPU: держит только wall-clock
try:
result = {"ok": True, "variants": render(src_path, out_dir, content_type, max_pixels)}
except PermanentImageError as exc:
result = {"ok": False, "permanent": True, "code": "invalid_image", "detail": str(exc)[:200]}
except MemoryError:
result = {"ok": False, "permanent": True, "code": "invalid_image", "detail": "memory limit"}
except Exception as exc: # noqa: BLE001 — неизвестное: временная ошибка, retry ограничен
result = {"ok": False, "permanent": False, "code": "processing_failed",
"detail": type(exc).__name__,
"trace": traceback.format_exc(limit=3)[-500:]}
with open(result_path, "w", encoding="utf-8") as f:
json.dump(result, f)