This commit is contained in:
Матвей
2026-10-26 15:49:31 +03:00
parent 4f6e69cfac
commit a1bb6f8bde
18 changed files with 820 additions and 195 deletions
+94 -26
View File
@@ -6,8 +6,13 @@ import json
import logging
import os
import random
import pickle
import subprocess
import sys
import time
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
from uuid import UUID
from uuid import UUID, uuid4
from PIL import Image, ImageOps
@@ -19,6 +24,32 @@ from .storage.s3 import S3Settings, S3Store
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s worker %(message)s")
class PermanentFailure(Exception):
pass
def fit(image, bound):
longest = max(image.size)
if longest <= bound:
return image.copy()
return image.resize((max(1, image.width * bound // longest),
max(1, image.height * bound // longest)), Image.Resampling.LANCZOS)
def render_isolated(data, timeout):
try:
result = subprocess.run([sys.executable, '-m', 'src.render'], input=data,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout)
except subprocess.TimeoutExpired as error:
raise TimeoutError('render deadline exceeded') from error
if result.returncode in (20, 21):
raise PermanentFailure('invalid_image' if result.returncode == 20 else 'image_resource_limit')
if result.returncode:
raise RuntimeError('renderer exited')
# Only our own child process produces this payload; no external pickle input.
return pickle.loads(result.stdout)
def thumbnail(data: bytes) -> tuple[bytes, int, int]:
with Image.open(BytesIO(data), formats=("PNG", "JPEG")) as source:
image = ImageOps.exif_transpose(source)
@@ -28,7 +59,7 @@ def thumbnail(data: bytes) -> tuple[bytes, int, int]:
image = background.convert("RGB")
else:
image = image.convert("RGB")
image.thumbnail((256, 256), Image.Resampling.LANCZOS)
image = fit(image, 256)
output = BytesIO()
image.save(output, format="JPEG", quality=85, optimize=True)
return output.getvalue(), image.width, image.height
@@ -44,8 +75,7 @@ def variants(data: bytes, max_pixels: int = 40_000_000) -> list[tuple[str, bytes
white.alpha_composite(image)
rgb = white.convert("RGB")
thumb = rgb.copy()
thumb.thumbnail((256, 256), Image.Resampling.LANCZOS)
thumb = fit(rgb, 256)
thumbnail_out = BytesIO(); thumb.save(thumbnail_out, "JPEG", quality=85, optimize=True)
side = min(rgb.width, rgb.height)
@@ -53,8 +83,7 @@ def variants(data: bytes, max_pixels: int = 40_000_000) -> list[tuple[str, bytes
crop = rgb.crop((left, top, left + side, top + side)).resize((128, 128), Image.Resampling.LANCZOS)
crop_out = BytesIO(); crop.save(crop_out, "JPEG", quality=85, optimize=True)
optimized = rgb.copy()
optimized.thumbnail((1280, 1280), Image.Resampling.LANCZOS)
optimized = fit(rgb, 1280)
optimized_out = BytesIO(); optimized.save(optimized_out, "WEBP", quality=80, method=4)
return [
("thumbnail", thumbnail_out.getvalue(), "image/jpeg", thumb.width, thumb.height),
@@ -64,26 +93,50 @@ def variants(data: bytes, max_pixels: int = 40_000_000) -> list[tuple[str, bytes
async def process(store: PostgresStore, s3: S3Store, payload: dict, lease_seconds: int) -> None:
# Excludes cleanup for the whole lifetime of S3 effects, including stale attempts.
async with store.attachment_transaction():
await process_locked(store, s3, payload, lease_seconds)
async def process_locked(store: PostgresStore, s3: S3Store, payload: dict, lease_seconds: int) -> None:
attachment_id = UUID(payload["attachment_id"])
attachment = await store.claim_attachment_job(attachment_id, lease_seconds)
if attachment is None:
return
original_key = f"originals/{attachment_id}"
payload['_claim_time'] = attachment['claim_time']
payload['attempt'] = attachment.get('attempt', payload.get('attempt', 1))
attempt_key = uuid4().hex
original_key = f"originals/{attachment_id}/{attempt_key}"
await s3.copy(attachment["staging_key"], original_key, attachment["content_type"])
original = await s3.download_key(attachment["staging_key"], attachment["size_bytes"], attachment["sha256"])
rendered = await asyncio.wait_for(
asyncio.to_thread(variants, original, s3.settings.max_pixels), timeout=lease_seconds
)
rendered = await asyncio.to_thread(render_isolated, original, lease_seconds)
metadata = []
for name, content, content_type, width, height in rendered:
extension = "webp" if name == "optimized" else "jpg"
object_key = f"variants/{attachment_id}/{name}.{extension}"
object_key = f"variants/{attachment_id}/{attempt_key}/{name}.{extension}"
await s3.put(object_key, BytesIO(content), len(content), content_type)
metadata.append({"name": name, "object_key": object_key, "content_type": content_type,
"size_bytes": len(content), "width": width, "height": height,
"sha256": sha256(content).hexdigest()})
await store.complete_attachment_job(attachment_id, original_key, metadata)
await s3.delete(attachment["staging_key"])
committed = await store.complete_attachment_job(attachment_id, original_key, metadata, attachment['claim_time'])
if committed:
try:
await s3.delete(attachment["staging_key"])
except Exception:
logging.warning('staging cleanup deferred attachment_id=%s', attachment_id)
def settle_delivery(channel, delivery_tag, future):
"""Only a successful durable disposition permits acknowledgement."""
try:
success = future.result() is True
except Exception:
success = False
if channel.is_open:
if success:
channel.basic_ack(delivery_tag)
else:
channel.basic_nack(delivery_tag, requeue=True)
def main() -> None:
@@ -104,46 +157,61 @@ def main() -> None:
s3.client.close()
await store.close()
async def schedule_retry(attachment_id, delay):
async def schedule_retry(attachment_id, delay, claim_time, permanent_code=None):
retry_store = PostgresStore(settings.database_url)
await retry_store.connect()
try:
return await retry_store.retry_attachment_job(
attachment_id, max(1, int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))), delay
attachment_id, max(1, int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))), delay, claim_time, permanent_code
)
finally:
await retry_store.close()
def handle(body):
payload = None
try:
payload = json.loads(body)
if not isinstance(payload, dict):
raise ValueError('job must be an object')
if payload["type"] != "attachment.process.v1" or payload["schema_version"] != 1:
raise ValueError("unexpected broker payload")
UUID(payload['attachment_id'])
UUID(payload['job_id'])
except (ValueError, KeyError, TypeError):
try:
asyncio.run(publish_dlq({'failure': 'invalid_job'}))
return True
except Exception:
return False
try:
asyncio.run(handle_async(payload))
except Exception:
logging.exception("job failed")
except Exception as error:
logging.warning("job failed attachment_id=%s", payload['attachment_id'])
if '_claim_time' not in payload:
return False
try:
attachment_id = UUID(payload["attachment_id"])
attempt = int(payload.get("attempt", 1))
delay = min(60.0, float(2 ** min(attempt, 6))) * random.uniform(0.5, 1.5)
retry = asyncio.run(schedule_retry(attachment_id, delay))
asyncio.run(schedule_retry(attachment_id, delay, payload['_claim_time'],
str(error) if isinstance(error, PermanentFailure) else None))
except Exception:
retry = False
if not retry:
try:
asyncio.run(publish_dlq(payload))
except Exception:
logging.exception("could not publish failed job to DLQ")
return None
return False
return True
def consume(ch, method, properties, body):
del properties
future = executor.submit(handle, body)
def acknowledged(_future):
connection.add_callback_threadsafe(lambda: ch.basic_ack(method.delivery_tag))
if connection.is_open:
connection.add_callback_threadsafe(lambda: settle_delivery(ch, method.delivery_tag, _future))
future.add_done_callback(acknowledged)
try:
def heartbeat():
Path('/tmp/worker-heartbeat').write_text(str(time.time()))
connection.call_later(2, heartbeat)
heartbeat()
with ThreadPoolExecutor(max_workers=workers, thread_name_prefix="attachment-worker") as executor:
channel.basic_consume(queue=QUEUE, on_message_callback=consume, auto_ack=False)
channel.start_consuming()