fix: jobs schema payload, publisher confirms, worker reconnect, retry with backoff, replay endpoint

This commit is contained in:
2026-11-27 13:40:30 +03:00
parent 8760ec186a
commit 8c141c2866
6 changed files with 238 additions and 31 deletions
+84 -16
View File
@@ -2,21 +2,35 @@ import asyncio
import json
import os
import io
import uuid
import time
import hashlib
from datetime import datetime, timezone
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
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)
@@ -24,7 +38,13 @@ async def process_attachment(task: dict):
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
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()
@@ -38,6 +58,7 @@ async def process_attachment(task: dict):
elif img.mode != "RGB":
img = img.convert("RGB")
#варианты
variants_meta = []
thumb = img.copy()
thumb.thumbnail((256, 256), Image.Resampling.LANCZOS)
@@ -71,14 +92,46 @@ async def process_attachment(task: dict):
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:
att.status = "failed"
att.error_code = "processing_failed"
att.updated_at = datetime.now(timezone.utc)
await session.commit()
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:
@@ -88,21 +141,36 @@ def callback(ch, method, properties, body):
task = json.loads(body)
try:
# Таймаут 30 секунд
asyncio.run(asyncio.wait_for(process_attachment(task), timeout=30.0))
ch.basic_ack(delivery_tag=method.delivery_tag)
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():
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()
# цикл реконнекта — переживаем перезапуск брокера
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()