Files
mtusi2026lab5/src/infrastructure/services/image_pipeline/pipeline.py
T

101 lines
3.7 KiB
Python

import asyncio
import hashlib
import json
import sys
import tempfile
from pathlib import Path
from domain.jobs import ClaimedJobSchema, ProcessedVariantSchema, ProcessingError
from interfaces import ObjectStorage
from interfaces.job_repository import JobRepository
TRANSFORM_SCRIPT = Path(__file__).resolve().parents[2] / "media" / "image_transform.py"
class ImagePipeline:
"""Worker side effect: неизменный original + детерминированные ключи вариантов"""
def __init__(
self,
repository: JobRepository,
storage: ObjectStorage,
max_bytes: int,
max_pixels: int,
memory_mb: int,
timeout: int,
) -> None:
self._jobs = repository
self._storage = storage
self._max_bytes = max_bytes
self._max_pixels = max_pixels
self._memory_mb = memory_mb
self._timeout = timeout
async def process(self, job: ClaimedJobSchema) -> bool:
with tempfile.TemporaryDirectory(prefix="attachment-") as directory:
target = Path(directory)
original = target / "original"
content = await self._storage.open(job.staging_key)
if content is None:
raise ProcessingError("staging_missing")
digest = hashlib.sha256()
size = 0
try:
with original.open("wb") as file:
async for chunk in content.iter_chunks():
size += len(chunk)
if size > self._max_bytes:
raise ProcessingError("image_resource_limit")
digest.update(chunk)
file.write(chunk)
finally:
await content.close()
if size != job.size_bytes or digest.hexdigest() != job.sha256:
raise ProcessingError("checksum_mismatch")
process = await asyncio.create_subprocess_exec(
sys.executable,
str(TRANSFORM_SCRIPT),
str(original),
str(target),
str(self._max_pixels),
str(self._memory_mb),
str(self._timeout),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
try:
output, _ = await process.communicate()
except BaseException:
if process.returncode is None:
process.kill()
await process.wait()
raise
if process.returncode == 2:
raise ProcessingError(output.decode().strip())
if process.returncode != 0:
raise ProcessingError("image_resource_limit")
variants = [
ProcessedVariantSchema(**v, object_key=job.object_key + "/" + v["name"])
for v in json.loads(output)
]
with original.open("rb") as file:
await self._storage.put(
job.object_key, file, size, job.content_type, digest.digest()
)
for variant in variants:
with (target / variant.name).open("rb") as file:
await self._storage.put(
variant.object_key,
file,
variant.size_bytes,
variant.content_type,
bytes.fromhex(variant.sha256),
)
from infrastructure.utils.faults import crash_once
crash_once("after-objects")
completed = await self._jobs.complete(job, variants)
if completed:
crash_once("after-result")
return completed