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
+4
View File
@@ -69,6 +69,7 @@ class Attachment(Base):
error_code: Mapped[str] = mapped_column(String(50), nullable=True)
s3_key: Mapped[str] = mapped_column(String(500), nullable=False)
variants: Mapped[list] = mapped_column(JSONB, default=list, nullable=False)
attempts: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, onupdate=_now, nullable=False)
@@ -82,4 +83,7 @@ class Outbox(Base):
id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4)
payload: Mapped[str] = mapped_column(Text, nullable=False)
status: Mapped[str] = mapped_column(String(20), default="pending", nullable=False, index=True)
scheduled_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=_now, nullable=False, index=True
)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, nullable=False)
+89 -6
View File
@@ -49,7 +49,15 @@ async def outbox_publisher():
await asyncio.sleep(5)
try:
async with async_session() as db:
jobs = (await db.execute(select(Outbox).where(Outbox.status == "pending").limit(10))).scalars().all()
now = datetime.now(timezone.utc)
stmt = (
select(Outbox)
.where(Outbox.status == "pending", Outbox.scheduled_at <= now)
.order_by(Outbox.scheduled_at)
.limit(10)
.with_for_update(skip_locked=True)
)
jobs = (await db.execute(stmt)).scalars().all()
for job in jobs:
try:
# публикуем в rabbitmq в отдельном потоке, чтобы не блокировать event loop
@@ -57,10 +65,44 @@ async def outbox_publisher():
job.status = "sent"
await db.commit()
except Exception as e:
await db.rollback()
print(f"Outbox failed to publish {job.id}: {e}", flush=True)
except Exception:
pass
# reaper для зависших processing
async def processing_reaper():
while True:
await asyncio.sleep(60)
try:
async with async_session() as db:
cutoff = datetime.now(timezone.utc) - timedelta(seconds=300)
stmt = (
select(Attachment)
.where(Attachment.status == "processing", Attachment.updated_at < cutoff)
.with_for_update(skip_locked=True)
)
stale = (await db.execute(stmt)).scalars().all()
for att in stale:
att.status = "queued"
att.error_code = "lease_expired"
att.updated_at = datetime.now(timezone.utc)
task = {
"job_id": str(uuid.uuid4()),
"attachment_id": str(att.id),
"chat_id": str(att.chat_id),
"s3_key": att.s3_key,
"mime": att.content_type,
"attempt": att.attempts or 0,
"created_at": datetime.now(timezone.utc).isoformat(),
}
db.add(Outbox(payload=json.dumps(task), status="pending",
scheduled_at=datetime.now(timezone.utc)))
if stale:
await db.commit()
except Exception:
pass
def err_json(status: int, code: str, message: str) -> JSONResponse:
resp = JSONResponse(status_code=status, content={"error": {"code": code, "message": message, "request_id": request_id_var.get()}})
resp.headers["X-Instance-Id"] = INSTANCE_ID
@@ -78,12 +120,13 @@ class RequestIdMiddleware(BaseHTTPMiddleware):
app = FastAPI(title="MTUSI Messenger — lab5")
app.add_middleware(RequestIdMiddleware)
security = HTTPBasic(auto_error=False)
#паблишер
@app.on_event("startup")
async def startup_event():
ensure_bucket()
# Запускаем фоновую задачу для отправки сообщений из БД в RabbitMQ
asyncio.create_task(outbox_publisher())
asyncio.create_task(processing_reaper())
@app.exception_handler(RequestValidationError)
async def _validation(request: Request, exc: RequestValidationError):
@@ -261,7 +304,7 @@ async def list_messages(chat_id: UUID, user: User = Depends(get_current_user), l
items = [_msg_json(m, att_map.get(m.id, [])) for m in rows]
nxt = f"{next_cursor[0].isoformat()}|{next_cursor[1]}" if next_cursor else None
return {"items": items, "next_cursor": nxt}
#загрузка в s3
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
async def upload_attachment(chat_id: UUID, request: Request, filename: str = Query(..., min_length=1, max_length=255), user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
chat = await chats_repo.get_if_member(db, chat_id, user.id)
@@ -290,14 +333,25 @@ async def upload_attachment(chat_id: UUID, request: Request, filename: str = Que
# Получаем ID вложения без коммита
await db.flush()
# Создаем задачу в Outbox
task = {"attachment_id": str(att.id), "chat_id": str(chat_id), "s3_key": s3_key, "mime": mime}
db.add(Outbox(payload=json.dumps(task), status="pending"))
# Создаем задачу в Outbox в одной транзакции
# payload по jobs.schema.json + scheduled_at
task = {
"job_id": str(uuid.uuid4()),
"attachment_id": str(att.id),
"chat_id": str(chat_id),
"s3_key": s3_key,
"mime": mime,
"attempt": 0,
"created_at": datetime.now(timezone.utc).isoformat(),
}
db.add(Outbox(payload=json.dumps(task), status="pending",
scheduled_at=datetime.now(timezone.utc)))
# Коммитим ОБЕ записи атомарно
await db.commit()
await db.refresh(att)
except Exception:
#Saga удаление из с3 при ошибке
await db.rollback()
try: s3.delete_object(Bucket=BUCKET, Key=s3_key)
except Exception: pass
@@ -344,6 +398,35 @@ async def download_attachment(attachment_id: UUID, variant: str = Query("origina
return Response(content=content, media_type=mime)
# ручной replay из failed
@app.post("/api/v1/attachments/{attachment_id}/retry", status_code=202)
async def retry_attachment(attachment_id: UUID, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
att = await db.get(Attachment, attachment_id)
if not att: raise HTTPException(404, "Attachment not found")
chat = await chats_repo.get_if_member(db, att.chat_id, user.id)
if not chat: raise HTTPException(404, "Attachment not found")
if att.status != "failed":
raise HTTPException(409, f"Cannot retry attachment in status '{att.status}'")
att.status = "queued"
att.error_code = None
att.attempts = 0
att.updated_at = datetime.now(timezone.utc)
task = {
"job_id": str(uuid.uuid4()),
"attachment_id": str(att.id),
"chat_id": str(att.chat_id),
"s3_key": att.s3_key,
"mime": att.content_type,
"attempt": 0,
"created_at": datetime.now(timezone.utc).isoformat(),
}
db.add(Outbox(payload=json.dumps(task), status="pending",
scheduled_at=datetime.now(timezone.utc)))
await db.commit()
await db.refresh(att)
return _attachment_json(att)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("APP_PORT", "8080")))
+16 -9
View File
@@ -24,12 +24,19 @@ def setup_rabbitmq(channel):
def publish_task(task: dict):
connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL))
channel = connection.channel()
setup_rabbitmq(channel)
channel.basic_publish(
exchange="",
routing_key=QUEUE_NAME,
body=json.dumps(task),
properties=pika.BasicProperties(delivery_mode=2),
)
connection.close()
try:
channel.confirm_delivery()
channel = connection.channel()
setup_rabbitmq(channel)
channel.basic_publish(
exchange="",
routing_key=QUEUE_NAME,
body=json.dumps(task),
properties=pika.BasicProperties(
delivery_mode=2,
content_type="application/json",
message_id=task.get("job_id"),
),
)
finally:
connection.close()
+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()