fix: jobs schema payload, publisher confirms, worker reconnect, retry with backoff, replay endpoint
This commit is contained in:
@@ -18,6 +18,19 @@ docker compose up -d --build --scale api=2
|
||||
|
||||
Безопасная остановка: `docker compose down`. Удаление данных: `docker compose down -v`.
|
||||
|
||||
## Что сделано в lab5
|
||||
|
||||
1. **Асинхронная загрузка.** Эндпоинт `POST /api/v1/chats/{chat_id}/attachments` возвращает `202 Accepted` вместо `201`. В ответе — `attachment_id` и `status: "queued"`. Тяжёлая обработка вынесена из HTTP-запроса.
|
||||
2. **Transactional Outbox.** В ту же транзакцию, что и `Attachment`, пишется строка в таблицу `outbox` с payload задачи (`attachment_id`, `chat_id`, `s3_key`, `mime`). `COMMIT` атомарен — задача не теряется между БД и RabbitMQ.
|
||||
3. **Outbox publisher.** Фоновая корутина `outbox_publisher` в `app/main.py` раз в 5 секунд читает `outbox WHERE status='pending'`, публикует задачи в RabbitMQ, ставит `status='sent'`.
|
||||
4. **RabbitMQ.** Очередь `attachment_tasks`, `durable=True`, сообщения с `delivery_mode=2`. Настроен DLX `dlx` и DLQ `attachment_tasks_dlq` через аргументы `x-dead-letter-exchange` / `x-dead-letter-routing-key` (`app/queue.py`).
|
||||
5. **Worker.** Отдельный контейнер `worker`, слушает `attachment_tasks` с `prefetch_count=1`. Скачивает оригинал из S3, генерирует варианты, обновляет БД.
|
||||
6. **Три варианта изображения.** `thumbnail` (JPEG 256×256, пропорции сохранены), `crop` (JPEG 128×128, центральный квадрат), `optimized` (WebP до 1280×1280, quality=85). Метаданные (name, content_type, width, height, size_bytes, sha256) пишутся в `Attachment.variants` (JSONB).
|
||||
7. **Идемпотентность job.** Ключ — `attachment_id` в payload. В `worker.py` перед обработкой: `if att.status == "ready" and len(att.variants or []) == 3: return`. Повторная доставка (at-least-once) не создаёт дубликаты.
|
||||
8. **Timeout и DLQ.** Обработка обёрнута в `asyncio.wait_for(..., timeout=30.0)`. При ошибке или таймауте — `basic_nack(requeue=False)`, сообщение уходит в `attachment_tasks_dlq`, основная очередь не блокируется.
|
||||
9. **Лимиты и валидация.** Nginx `client_max_body_size 10M`. В `image_utils.py` — проверка размера, лимит пикселей (40 Мп), открытие через Pillow (415 для битых и MIME-спуфинга). Проверка `filename` на `/`, `\`, `\x00`.
|
||||
10. **Тесты.** `tests/smoke.py` — публичный сценарий (202 → ready → 3 варианта). `student-tests/test_attachments.py` — 4 негативных теста: 413 (11 МБ), 415 (битый файл), 415 (MIME-спуфинг), 404 (чужое вложение).
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
**Схема процессов:**
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""add attempts and scheduled_at
|
||||
|
||||
Revision ID: dc2ac7a34e72
|
||||
Revises: 164e1973508a
|
||||
Create Date: 2026-11-27 13:21:19.796557
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = 'dc2ac7a34e72'
|
||||
down_revision: Union[str, None] = '164e1973508a'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column('attachments', sa.Column('attempts', sa.Integer(), nullable=False, server_default='0'))
|
||||
op.add_column('outbox', sa.Column('scheduled_at', sa.DateTime(timezone=True), nullable=False, server_default=sa.text('now()')))
|
||||
op.create_index(op.f('ix_outbox_scheduled_at'), 'outbox', ['scheduled_at'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_index(op.f('ix_outbox_scheduled_at'), table_name='outbox')
|
||||
op.drop_column('outbox', 'scheduled_at')
|
||||
op.drop_column('attachments', 'attempts')
|
||||
# ### end Alembic commands ###
|
||||
Reference in New Issue
Block a user