Files
mtusi2026lab5/src/messenger/pipeline.py
T
Alexey Bodanyuk a633949919 lab5: схема 0005 (jobs, outbox, попытки, варианты, аудит) и модули pipeline
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Миграция только добавляет: статусы pending/queued/processing/ready/failed, staging-ключ,
published_version, jobs с lease и токеном попытки, job_attempts с заранее известными
ключами, attachment_variants (PK = ключ эффекта), outbox, job_events, view failed_jobs,
post_message_v3. CHECK attachments_active_has_source: у queued/processing всегда есть источник.
pipeline.py — версии 1/2/3 и геометрия по контракту; imaging.py — варианты в дочернем
процессе (RLIMIT_AS, таймаут, лимит пикселей); jobs.py — все переходы заданий одной
транзакцией с fencing по токену; broker.py — топология и строгая схема сообщения.
Зависимости: aio-pika 9.6.2, pillow 12.3.0 (lock с хешами).
2026-10-31 16:12:51 +03:00

64 lines
2.9 KiB
Python

"""Versioned image pipeline (lab 5): WHAT the worker builds for one attachment. Pure definitions,
no I/O; the pixels are produced by imaging.py in a child process.
Every pipeline version builds the same three variants with the geometry of the contract; versions
differ only in encoder parameters, so the published version is visible in the bytes (sha256):
thumbnail JPEG, fits into 256x256, keeps the aspect ratio, never upscales, floor rounding
(minimum 1 px), EXIF orientation applied, alpha composited onto white;
crop JPEG, centred square 128x128 (small images ARE upscaled, the contract allows it);
optimized WebP, fits into 1280x1280, never upscales, alpha kept.
Metadata: nothing of the source is copied into a variant - no EXIF (orientation is applied to
the pixels instead), no XMP, no ICC profile, no comments (the pixels are treated as sRGB).
The original is published byte for byte and keeps everything.
Track 2: the version of a job is fixed when the job is created (PIPELINE_VERSION for uploads,
`jobctl reprocess --pipeline N` later). A result is published only if its version is greater
than the published one, so an old job can never overwrite a newer result.
"""
from __future__ import annotations
from dataclasses import dataclass
THUMBNAIL_BOX = 256
CROP_SIDE = 128
OPTIMIZED_BOX = 1280
VARIANT_NAMES = ("thumbnail", "crop", "optimized")
CONTENT_TYPES = {"thumbnail": "image/jpeg", "crop": "image/jpeg", "optimized": "image/webp"}
@dataclass(frozen=True, slots=True)
class Pipeline:
version: int
jpeg_quality: int # thumbnail and crop: baseline JPEG, 4:2:0, optimized Huffman tables
webp_quality: int # optimized: lossy WebP
webp_method: int # 0 (fast) .. 6 (slow, smaller)
PIPELINES = {
1: Pipeline(1, jpeg_quality=85, webp_quality=80, webp_method=4),
# Versions 2 and 3 exist for the track 2 experiments (reprocess, reorder, stale jobs):
# different encoder settings -> different bytes, identical geometry.
2: Pipeline(2, jpeg_quality=80, webp_quality=75, webp_method=4),
3: Pipeline(3, jpeg_quality=90, webp_quality=85, webp_method=5),
}
def fit(width: int, height: int, box: int) -> tuple[int, int]:
"""Size inside box x box keeping the aspect ratio, never upscaling, rounded DOWN, >= 1 px.
Integer arithmetic: 320x200 -> 256x160 exactly, 1x1000 -> 1x256 (0.256 -> 1 px minimum)."""
if width <= box and height <= box:
return width, height
if width >= height:
return box, max(1, height * box // width)
return max(1, width * box // height), box
def center_square(width: int, height: int) -> tuple[int, int, int, int]:
"""Crop box (left, top, right, bottom) of the centred square with side min(width, height)."""
side = min(width, height)
left = (width - side) // 2
top = (height - side) // 2
return left, top, left + side, top + side