forked from mtusi2026/mtusi2026lab5
92 lines
2.6 KiB
Python
92 lines
2.6 KiB
Python
|
|
import asyncio
|
|
import sys
|
|
import uuid
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
|
|
|
from app.config import DATABASE_URL
|
|
from app.models.attachment import Attachment
|
|
from app.models.outbox import OutboxEvent
|
|
from app.models.user import User
|
|
from app.models.chat import Chat, ChatMember
|
|
|
|
|
|
RETRYABLE_ERROR_CODES = {
|
|
"s3_download_error",
|
|
"s3_upload_error",
|
|
"image_processing_timeout",
|
|
"image_processor_start_error",
|
|
"image_processor_error",
|
|
"image_processor_output_error",
|
|
"worker_error",
|
|
}
|
|
|
|
|
|
async def replay_failed(attachment_id: uuid.UUID):
|
|
engine = create_async_engine(DATABASE_URL)
|
|
session_maker = async_sessionmaker(engine, expire_on_commit=False)
|
|
|
|
try:
|
|
async with session_maker() as session:
|
|
async with session.begin():
|
|
att = await session.get(
|
|
Attachment,
|
|
attachment_id,
|
|
with_for_update=True,
|
|
)
|
|
|
|
if att is None:
|
|
print("Файл не найден")
|
|
return
|
|
|
|
if att.status != "failed":
|
|
print(f"Replay запрещён: status={att.status}")
|
|
return
|
|
|
|
if att.error_code not in RETRYABLE_ERROR_CODES:
|
|
print(
|
|
f"Replay запрещён: error_code={att.error_code}"
|
|
)
|
|
return
|
|
|
|
pending = await session.scalar(
|
|
select(OutboxEvent.id)
|
|
.where(
|
|
OutboxEvent.attachment_id == attachment_id,
|
|
OutboxEvent.published_at.is_(None),
|
|
)
|
|
.limit(1)
|
|
)
|
|
|
|
if pending is not None:
|
|
print("Задание уже ожидает публикации")
|
|
return
|
|
|
|
att.status = "queued"
|
|
att.error_code = None
|
|
|
|
session.add(
|
|
OutboxEvent(attachment_id=attachment_id)
|
|
)
|
|
|
|
print(f"Задание {attachment_id} отправлено на повторную обработку")
|
|
|
|
finally:
|
|
await engine.dispose()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) != 2:
|
|
print("Использование: python -m app.replay_failed UUID")
|
|
sys.exit(1)
|
|
|
|
try:
|
|
attachment_id = uuid.UUID(sys.argv[1])
|
|
except ValueError:
|
|
print("Некорректный UUID")
|
|
sys.exit(1)
|
|
|
|
asyncio.run(replay_failed(attachment_id))
|