fix: jobs schema payload, publisher confirms, worker reconnect, retry with backoff, replay endpoint
This commit is contained in:
+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")))
|
||||
Reference in New Issue
Block a user