import asyncio import json import os import io import uuid import time import hashlib from datetime import datetime, timezone, timedelta import pika from PIL import Image, ImageOps from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker from sqlalchemy.pool import NullPool from .db.models import Attachment, Outbox from .s3_client import s3, BUCKET from .queue import RABBITMQ_URL, QUEUE_NAME, setup_rabbitmq DATABASE_URL = os.getenv("DATABASE_URL") # параметры retry MAX_ATTEMPTS = 3 RETRY_BACKOFF_SECONDS = 10 RETRYABLE_ERRORS = ( ConnectionError, TimeoutError, OSError, pika.exceptions.AMQPError, ) #обработка задачи async def process_attachment(task: dict): att_id = task["attachment_id"] s3_key = task["s3_key"] attempt = int(task.get("attempt", 0)) engine = create_async_engine(DATABASE_URL, poolclass=NullPool) AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False) try: async with AsyncSessionLocal() as session: att = await session.get(Attachment, att_id) if not att: return if att.status == "ready" and len(att.variants or []) == 3: return #пропуск дублей # помечаем processing перед тяжёлой работой att.status = "processing" att.attempts = attempt att.updated_at = datetime.now(timezone.utc) await session.commit() obj = s3.get_object(Bucket=BUCKET, Key=s3_key) content = obj["Body"].read() img = Image.open(io.BytesIO(content)) img = ImageOps.exif_transpose(img) if img.mode in ("RGBA", "LA"): background = Image.new("RGB", img.size, (255, 255, 255)) background.paste(img, mask=img.split()[-1]) img = background elif img.mode != "RGB": img = img.convert("RGB") #варианты variants_meta = [] thumb = img.copy() thumb.thumbnail((256, 256), Image.Resampling.LANCZOS) thumb_bytes = io.BytesIO() thumb.save(thumb_bytes, format="JPEG") thumb_data = thumb_bytes.getvalue() s3.put_object(Bucket=BUCKET, Key=f"{s3_key}_thumb.jpg", Body=thumb_data, ContentType="image/jpeg") variants_meta.append({"name": "thumbnail", "content_type": "image/jpeg", "width": thumb.width, "height": thumb.height, "size_bytes": len(thumb_data), "sha256": hashlib.sha256(thumb_data).hexdigest()}) crop_img = img.copy() width, height = crop_img.size min_dim = min(width, height) crop_img = crop_img.crop(((width - min_dim) / 2, (height - min_dim) / 2, (width + min_dim) / 2, (height + min_dim) / 2)) crop_img = crop_img.resize((128, 128), Image.Resampling.LANCZOS) crop_bytes = io.BytesIO() crop_img.save(crop_bytes, format="JPEG") crop_data = crop_bytes.getvalue() s3.put_object(Bucket=BUCKET, Key=f"{s3_key}_crop.jpg", Body=crop_data, ContentType="image/jpeg") variants_meta.append({"name": "crop", "content_type": "image/jpeg", "width": 128, "height": 128, "size_bytes": len(crop_data), "sha256": hashlib.sha256(crop_data).hexdigest()}) opt_img = img.copy() opt_img.thumbnail((1280, 1280), Image.Resampling.LANCZOS) opt_bytes = io.BytesIO() opt_img.save(opt_bytes, format="WEBP", quality=85) opt_data = opt_bytes.getvalue() s3.put_object(Bucket=BUCKET, Key=f"{s3_key}_opt.webp", Body=opt_data, ContentType="image/webp") variants_meta.append({"name": "optimized", "content_type": "image/webp", "width": opt_img.width, "height": opt_img.height, "size_bytes": len(opt_data), "sha256": hashlib.sha256(opt_data).hexdigest()}) att.status = "ready" att.error_code = None att.variants = variants_meta att.updated_at = datetime.now(timezone.utc) await session.commit() return "ready" except Exception as e: # вместо мгновенного failed — retry с backoff через Outbox retryable = isinstance(e, RETRYABLE_ERRORS) next_attempt = attempt + 1 can_retry = retryable and next_attempt < MAX_ATTEMPTS async with AsyncSessionLocal() as session: att = await session.get(Attachment, att_id) if att: if can_retry: att.status = "queued" att.error_code = "retry_scheduled" att.attempts = next_attempt att.updated_at = datetime.now(timezone.utc) next_task = { "job_id": str(uuid.uuid4()), "attachment_id": att_id, "chat_id": task["chat_id"], "s3_key": s3_key, "mime": task.get("mime"), "attempt": next_attempt, "created_at": datetime.now(timezone.utc).isoformat(), } backoff = RETRY_BACKOFF_SECONDS * (2 ** attempt) session.add(Outbox( payload=json.dumps(next_task), status="pending", scheduled_at=datetime.now(timezone.utc) + timedelta(seconds=backoff), )) await session.commit() print(f"Retry scheduled for {att_id}, attempt {next_attempt}, backoff {backoff}s", flush=True) return "retry" else: att.status = "failed" att.error_code = "processing_failed" if not retryable else "max_attempts_exceeded" att.attempts = next_attempt att.updated_at = datetime.now(timezone.utc) await session.commit() return "failed" print(f"Error processing {att_id}: {e}", flush=True) raise e finally: await engine.dispose() def callback(ch, method, properties, body): task = json.loads(body) try: # Таймаут 30 секунд result = asyncio.run(asyncio.wait_for(process_attachment(task), timeout=30.0)) # ловим result if result == "failed": ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False) #failed → DLQ else: ch.basic_ack(delivery_tag=method.delivery_tag) # ready/skip/retry → ack (retry уже в outbox) except Exception as e: print(f"Task failed, routing to DLQ. Error: {e}", flush=True) # requeue=False отправляет в DLQ ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False) def main(): # цикл реконнекта — переживаем перезапуск брокера while True: try: connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL)) channel = connection.channel() setup_rabbitmq(channel) channel.basic_qos(prefetch_count=1) channel.basic_consume(queue=QUEUE_NAME, on_message_callback=callback) print("Worker started...", flush=True) channel.start_consuming() except KeyboardInterrupt: print("Worker stopped.", flush=True) break except (pika.exceptions.AMQPConnectionError, pika.exceptions.AMQPChannelError) as e: print(f"RabbitMQ connection lost: {e}. Reconnecting in 5s...", flush=True) time.sleep(5) except Exception as e: print(f"Unexpected worker error: {e}. Reconnecting in 5s...", flush=True) time.sleep(5) if __name__ == "__main__": main()