chore: port lab 6 solution into the lab 7 skeleton
Source: mtusi2026lab6-safronov, solution/bvt2301-safronov, 6c6a065. Files follow AGENTS.md, "Переход в следующую лабу". Contracts, public tests, README, REPORT and evidence of lab 6 are not carried over; infra and scripts of the lab 7 skeleton stay as they are. Makefile is the lab 6 one with the lab 7 skeleton part restored (HTTPS BASE_URL on 8443, test-security); .gitignore and .dockerignore are taken from lab 6 because both skeletons have the same files; .env.example is the lab 6 one without changes. The compose project, image and CI prefix are renamed to lab7, and references to the previous lab now name lab6. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
from .client import ImageRenderer
|
||||
|
||||
__all__ = ["ImageRenderer"]
|
||||
@@ -0,0 +1,202 @@
|
||||
"""Клиент процесса обработки изображения: граница worker и декодера.
|
||||
|
||||
Design change `pipeline-reliability`, решение 7. На задание — новый процесс
|
||||
`python -m src.worker.render`: окружение без секретов, вход в stdin, срок по стене
|
||||
на стороне родителя. `finally` всегда убивает процесс и дожидается его: отмена
|
||||
попытки при остановке или по сроку процесс не оставит. Коды выхода переводятся в
|
||||
исключения: постоянные — `ImageRejected`, временные — `RenderInterrupted`, срок —
|
||||
`TimeoutError`, как у остальных шагов попытки.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.trace import Span, SpanKind
|
||||
|
||||
from src.config.settings import Worker as WorkerSettings
|
||||
from src.core.exceptions import ImageRejected, RenderInterrupted
|
||||
from src.infra import telemetry
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.schemas.dataclasses import RenderedVariantDTO, RenderedVariantsDTO
|
||||
from src.schemas.enums import AttachmentJobReason, AttachmentVariantName
|
||||
from src.utils.constants import (
|
||||
ATTACHMENT_MAX_PIXELS,
|
||||
ATTR_RENDER_EXIT_CODE,
|
||||
ATTR_RENDER_INPUT_SIZE,
|
||||
ATTR_RENDER_OUTCOME,
|
||||
ATTR_RENDER_PEAK_KIB,
|
||||
)
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="image_renderer")
|
||||
|
||||
# исход процесса обработки в span (`messenger.render.outcome`)
|
||||
RENDER_OK = "ok"
|
||||
RENDER_REJECTED = "rejected"
|
||||
RENDER_INTERRUPTED = "interrupted"
|
||||
RENDER_TIMEOUT = "timeout"
|
||||
|
||||
_RENDER_MODULE = "src.worker.render"
|
||||
# корень приложения: `-m src.worker.render` ищет пакет от рабочего каталога
|
||||
_APP_ROOT = Path(__file__).resolve().parent.parent.parent.parent
|
||||
# только это из окружения родителя: секретов у процесса нет
|
||||
_INHERITED_ENV = ("PATH", "MALLOC_MMAP_THRESHOLD_")
|
||||
# секунды на ожидание убитого процесса: SIGKILL не перехватить
|
||||
_REAP_TIMEOUT_SECONDS = 1
|
||||
|
||||
_EXIT_REASONS = {
|
||||
3: AttachmentJobReason.UNDECODABLE,
|
||||
4: AttachmentJobReason.LIMIT_MEMORY,
|
||||
5: AttachmentJobReason.LIMIT_PIXELS,
|
||||
-signal.SIGXCPU: AttachmentJobReason.LIMIT_CPU,
|
||||
}
|
||||
|
||||
|
||||
def _child_env() -> dict[str, str]:
|
||||
env = {
|
||||
name: os.environ[name] for name in _INHERITED_ENV if name in os.environ
|
||||
}
|
||||
env["PYTHONDONTWRITEBYTECODE"] = "1"
|
||||
env["PYTHONUNBUFFERED"] = "1"
|
||||
return env
|
||||
|
||||
|
||||
class ImageRenderer:
|
||||
"""Запуск процесса обработки со значениями `[worker]`."""
|
||||
|
||||
def __init__(self, worker: WorkerSettings) -> None:
|
||||
self._timeout = worker.render_timeout_seconds
|
||||
self._arguments = (
|
||||
"--max-pixels",
|
||||
str(ATTACHMENT_MAX_PIXELS),
|
||||
"--memory-limit-mib",
|
||||
str(worker.render_memory_limit_mib),
|
||||
"--cpu-limit-seconds",
|
||||
str(worker.render_cpu_limit_seconds),
|
||||
)
|
||||
|
||||
async def render(self, data: bytes) -> RenderedVariantsDTO:
|
||||
"""Варианты из байтов оригинала. Изображение не прошло —
|
||||
`ImageRejected`, процесс убит или упал — `RenderInterrupted`, срок —
|
||||
`TimeoutError`.
|
||||
|
||||
Span процесса (design change `otel-telemetry`, решение 12) — в
|
||||
worker: процесс SDK не запускает, его окружение прежнее."""
|
||||
with telemetry.child_span(
|
||||
"render attachment variants",
|
||||
kind=SpanKind.INTERNAL,
|
||||
attributes={ATTR_RENDER_INPUT_SIZE: len(data)},
|
||||
# отказ изображения — исход задания, а не сбой процесса
|
||||
expected=(ImageRejected,),
|
||||
) as span:
|
||||
try:
|
||||
rendered = await self._run(data)
|
||||
except ImageRejected:
|
||||
_outcome(span, RENDER_REJECTED)
|
||||
raise
|
||||
except RenderInterrupted:
|
||||
_outcome(span, RENDER_INTERRUPTED)
|
||||
raise
|
||||
except TimeoutError:
|
||||
_outcome(span, RENDER_TIMEOUT)
|
||||
raise
|
||||
_outcome(span, RENDER_OK)
|
||||
if span is not None:
|
||||
span.set_attribute(ATTR_RENDER_PEAK_KIB, rendered.peak_kib)
|
||||
return rendered
|
||||
|
||||
async def _run(self, data: bytes) -> RenderedVariantsDTO:
|
||||
started = time.monotonic()
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
sys.executable,
|
||||
"-m",
|
||||
_RENDER_MODULE,
|
||||
*self._arguments,
|
||||
stdin=asyncio.subprocess.PIPE,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.DEVNULL,
|
||||
env=_child_env(),
|
||||
cwd=_APP_ROOT,
|
||||
)
|
||||
try:
|
||||
async with asyncio.timeout(self._timeout):
|
||||
stdout, _ = await process.communicate(data)
|
||||
finally:
|
||||
await _reap(process)
|
||||
code = process.returncode
|
||||
_exit_code(code)
|
||||
if code == 0:
|
||||
return _parse(stdout, started=started)
|
||||
reason = _EXIT_REASONS.get(code or 0)
|
||||
if reason is not None:
|
||||
raise ImageRejected(reason=reason)
|
||||
logger.warning("Render process failed", exit_code=code)
|
||||
raise RenderInterrupted(
|
||||
reason=(
|
||||
AttachmentJobReason.RENDER_KILLED
|
||||
if code == -signal.SIGKILL
|
||||
else AttachmentJobReason.RENDER_CRASHED
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _outcome(span: Span | None, outcome: str) -> None:
|
||||
if span is not None:
|
||||
span.set_attribute(ATTR_RENDER_OUTCOME, outcome)
|
||||
|
||||
|
||||
def _exit_code(code: int | None) -> None:
|
||||
"""Код выхода процесса — в текущий span (span процесса обработки)."""
|
||||
span = trace.get_current_span()
|
||||
if code is not None and span.is_recording():
|
||||
span.set_attribute(ATTR_RENDER_EXIT_CODE, code)
|
||||
|
||||
|
||||
async def _reap(process: asyncio.subprocess.Process) -> None:
|
||||
if process.returncode is not None:
|
||||
return
|
||||
with suppress(ProcessLookupError):
|
||||
process.kill()
|
||||
with suppress(TimeoutError):
|
||||
async with asyncio.timeout(_REAP_TIMEOUT_SECONDS):
|
||||
await process.wait()
|
||||
|
||||
|
||||
def _parse(stdout: bytes, *, started: float) -> RenderedVariantsDTO:
|
||||
"""Строка JSON и байты подряд. Испорченный вывод — `render_crashed`."""
|
||||
try:
|
||||
line, _, body = stdout.partition(b"\n")
|
||||
head = json.loads(line)
|
||||
variants = []
|
||||
offset = 0
|
||||
for item in head["variants"]:
|
||||
size = item["size"]
|
||||
variants.append(
|
||||
RenderedVariantDTO(
|
||||
name=AttachmentVariantName(item["name"]),
|
||||
content_type=item["content_type"],
|
||||
width=item["width"],
|
||||
height=item["height"],
|
||||
data=body[offset : offset + size],
|
||||
),
|
||||
)
|
||||
offset += size
|
||||
if offset != len(body) or not variants:
|
||||
raise ValueError("render output size differs")
|
||||
return RenderedVariantsDTO(
|
||||
variants=tuple(variants),
|
||||
peak_kib=head["peak_kib"],
|
||||
memory_limit_applied=head["memory_limit_applied"],
|
||||
render_ms=round((time.monotonic() - started) * 1000),
|
||||
)
|
||||
except (ValueError, KeyError, TypeError) as e:
|
||||
logger.warning("Render process output is damaged")
|
||||
raise RenderInterrupted(
|
||||
reason=AttachmentJobReason.RENDER_CRASHED,
|
||||
) from e
|
||||
Reference in New Issue
Block a user