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`.
|
Безопасная остановка: `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)
|
error_code: Mapped[str] = mapped_column(String(50), nullable=True)
|
||||||
s3_key: Mapped[str] = mapped_column(String(500), nullable=False)
|
s3_key: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
variants: Mapped[list] = mapped_column(JSONB, default=list, 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)
|
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)
|
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)
|
id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4)
|
||||||
payload: Mapped[str] = mapped_column(Text, nullable=False)
|
payload: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
status: Mapped[str] = mapped_column(String(20), default="pending", nullable=False, index=True)
|
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)
|
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)
|
await asyncio.sleep(5)
|
||||||
try:
|
try:
|
||||||
async with async_session() as db:
|
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:
|
for job in jobs:
|
||||||
try:
|
try:
|
||||||
# публикуем в rabbitmq в отдельном потоке, чтобы не блокировать event loop
|
# публикуем в rabbitmq в отдельном потоке, чтобы не блокировать event loop
|
||||||
@@ -57,10 +65,44 @@ async def outbox_publisher():
|
|||||||
job.status = "sent"
|
job.status = "sent"
|
||||||
await db.commit()
|
await db.commit()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
await db.rollback()
|
||||||
print(f"Outbox failed to publish {job.id}: {e}", flush=True)
|
print(f"Outbox failed to publish {job.id}: {e}", flush=True)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
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:
|
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 = JSONResponse(status_code=status, content={"error": {"code": code, "message": message, "request_id": request_id_var.get()}})
|
||||||
resp.headers["X-Instance-Id"] = INSTANCE_ID
|
resp.headers["X-Instance-Id"] = INSTANCE_ID
|
||||||
@@ -78,12 +120,13 @@ class RequestIdMiddleware(BaseHTTPMiddleware):
|
|||||||
app = FastAPI(title="MTUSI Messenger — lab5")
|
app = FastAPI(title="MTUSI Messenger — lab5")
|
||||||
app.add_middleware(RequestIdMiddleware)
|
app.add_middleware(RequestIdMiddleware)
|
||||||
security = HTTPBasic(auto_error=False)
|
security = HTTPBasic(auto_error=False)
|
||||||
|
#паблишер
|
||||||
@app.on_event("startup")
|
@app.on_event("startup")
|
||||||
async def startup_event():
|
async def startup_event():
|
||||||
ensure_bucket()
|
ensure_bucket()
|
||||||
# Запускаем фоновую задачу для отправки сообщений из БД в RabbitMQ
|
# Запускаем фоновую задачу для отправки сообщений из БД в RabbitMQ
|
||||||
asyncio.create_task(outbox_publisher())
|
asyncio.create_task(outbox_publisher())
|
||||||
|
asyncio.create_task(processing_reaper())
|
||||||
|
|
||||||
@app.exception_handler(RequestValidationError)
|
@app.exception_handler(RequestValidationError)
|
||||||
async def _validation(request: Request, exc: 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]
|
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
|
nxt = f"{next_cursor[0].isoformat()}|{next_cursor[1]}" if next_cursor else None
|
||||||
return {"items": items, "next_cursor": nxt}
|
return {"items": items, "next_cursor": nxt}
|
||||||
|
#загрузка в s3
|
||||||
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
|
@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)):
|
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)
|
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 вложения без коммита
|
# Получаем ID вложения без коммита
|
||||||
await db.flush()
|
await db.flush()
|
||||||
|
|
||||||
# Создаем задачу в Outbox
|
# Создаем задачу в Outbox в одной транзакции
|
||||||
task = {"attachment_id": str(att.id), "chat_id": str(chat_id), "s3_key": s3_key, "mime": mime}
|
# payload по jobs.schema.json + scheduled_at
|
||||||
db.add(Outbox(payload=json.dumps(task), status="pending"))
|
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.commit()
|
||||||
await db.refresh(att)
|
await db.refresh(att)
|
||||||
except Exception:
|
except Exception:
|
||||||
|
#Saga удаление из с3 при ошибке
|
||||||
await db.rollback()
|
await db.rollback()
|
||||||
try: s3.delete_object(Bucket=BUCKET, Key=s3_key)
|
try: s3.delete_object(Bucket=BUCKET, Key=s3_key)
|
||||||
except Exception: pass
|
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)
|
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__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("APP_PORT", "8080")))
|
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):
|
def publish_task(task: dict):
|
||||||
connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL))
|
connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL))
|
||||||
channel = connection.channel()
|
try:
|
||||||
setup_rabbitmq(channel)
|
channel.confirm_delivery()
|
||||||
channel.basic_publish(
|
channel = connection.channel()
|
||||||
exchange="",
|
setup_rabbitmq(channel)
|
||||||
routing_key=QUEUE_NAME,
|
channel.basic_publish(
|
||||||
body=json.dumps(task),
|
exchange="",
|
||||||
properties=pika.BasicProperties(delivery_mode=2),
|
routing_key=QUEUE_NAME,
|
||||||
)
|
body=json.dumps(task),
|
||||||
connection.close()
|
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 json
|
||||||
import os
|
import os
|
||||||
import io
|
import io
|
||||||
|
import uuid
|
||||||
|
import time
|
||||||
import hashlib
|
import hashlib
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone, timedelta
|
||||||
import pika
|
import pika
|
||||||
from PIL import Image, ImageOps
|
from PIL import Image, ImageOps
|
||||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
||||||
from sqlalchemy.pool import NullPool
|
from sqlalchemy.pool import NullPool
|
||||||
from .db.models import Attachment
|
from .db.models import Attachment, Outbox
|
||||||
from .s3_client import s3, BUCKET
|
from .s3_client import s3, BUCKET
|
||||||
from .queue import RABBITMQ_URL, QUEUE_NAME, setup_rabbitmq
|
from .queue import RABBITMQ_URL, QUEUE_NAME, setup_rabbitmq
|
||||||
|
|
||||||
DATABASE_URL = os.getenv("DATABASE_URL")
|
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):
|
async def process_attachment(task: dict):
|
||||||
att_id = task["attachment_id"]
|
att_id = task["attachment_id"]
|
||||||
s3_key = task["s3_key"]
|
s3_key = task["s3_key"]
|
||||||
|
attempt = int(task.get("attempt", 0))
|
||||||
engine = create_async_engine(DATABASE_URL, poolclass=NullPool)
|
engine = create_async_engine(DATABASE_URL, poolclass=NullPool)
|
||||||
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
|
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
|
||||||
|
|
||||||
@@ -24,7 +38,13 @@ async def process_attachment(task: dict):
|
|||||||
async with AsyncSessionLocal() as session:
|
async with AsyncSessionLocal() as session:
|
||||||
att = await session.get(Attachment, att_id)
|
att = await session.get(Attachment, att_id)
|
||||||
if not att: return
|
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)
|
obj = s3.get_object(Bucket=BUCKET, Key=s3_key)
|
||||||
content = obj["Body"].read()
|
content = obj["Body"].read()
|
||||||
@@ -38,6 +58,7 @@ async def process_attachment(task: dict):
|
|||||||
elif img.mode != "RGB":
|
elif img.mode != "RGB":
|
||||||
img = img.convert("RGB")
|
img = img.convert("RGB")
|
||||||
|
|
||||||
|
#варианты
|
||||||
variants_meta = []
|
variants_meta = []
|
||||||
thumb = img.copy()
|
thumb = img.copy()
|
||||||
thumb.thumbnail((256, 256), Image.Resampling.LANCZOS)
|
thumb.thumbnail((256, 256), Image.Resampling.LANCZOS)
|
||||||
@@ -71,14 +92,46 @@ async def process_attachment(task: dict):
|
|||||||
att.variants = variants_meta
|
att.variants = variants_meta
|
||||||
att.updated_at = datetime.now(timezone.utc)
|
att.updated_at = datetime.now(timezone.utc)
|
||||||
await session.commit()
|
await session.commit()
|
||||||
|
return "ready"
|
||||||
except Exception as e:
|
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:
|
async with AsyncSessionLocal() as session:
|
||||||
att = await session.get(Attachment, att_id)
|
att = await session.get(Attachment, att_id)
|
||||||
if att:
|
if att:
|
||||||
att.status = "failed"
|
if can_retry:
|
||||||
att.error_code = "processing_failed"
|
att.status = "queued"
|
||||||
att.updated_at = datetime.now(timezone.utc)
|
att.error_code = "retry_scheduled"
|
||||||
await session.commit()
|
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)
|
print(f"Error processing {att_id}: {e}", flush=True)
|
||||||
raise e
|
raise e
|
||||||
finally:
|
finally:
|
||||||
@@ -88,21 +141,36 @@ def callback(ch, method, properties, body):
|
|||||||
task = json.loads(body)
|
task = json.loads(body)
|
||||||
try:
|
try:
|
||||||
# Таймаут 30 секунд
|
# Таймаут 30 секунд
|
||||||
asyncio.run(asyncio.wait_for(process_attachment(task), timeout=30.0))
|
result = asyncio.run(asyncio.wait_for(process_attachment(task), timeout=30.0)) # ловим result
|
||||||
ch.basic_ack(delivery_tag=method.delivery_tag)
|
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:
|
except Exception as e:
|
||||||
print(f"Task failed, routing to DLQ. Error: {e}", flush=True)
|
print(f"Task failed, routing to DLQ. Error: {e}", flush=True)
|
||||||
# requeue=False отправляет в DLQ
|
# requeue=False отправляет в DLQ
|
||||||
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False)
|
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False)
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL))
|
# цикл реконнекта — переживаем перезапуск брокера
|
||||||
channel = connection.channel()
|
while True:
|
||||||
setup_rabbitmq(channel)
|
try:
|
||||||
channel.basic_qos(prefetch_count=1)
|
connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL))
|
||||||
channel.basic_consume(queue=QUEUE_NAME, on_message_callback=callback)
|
channel = connection.channel()
|
||||||
print("Worker started...", flush=True)
|
setup_rabbitmq(channel)
|
||||||
channel.start_consuming()
|
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__":
|
if __name__ == "__main__":
|
||||||
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