forked from mtusi2026/mtusi2026lab5
121 lines
3.7 KiB
Python
121 lines
3.7 KiB
Python
from __future__ import annotations
|
|
|
|
import argparse
|
|
import asyncio
|
|
import json
|
|
import logging
|
|
import sys
|
|
import uuid
|
|
|
|
import asyncpg
|
|
|
|
from app.broker import publisher
|
|
from app.config import DATABASE_URL
|
|
from app.schemas import now_utc_iso
|
|
|
|
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
|
|
logger = logging.getLogger("messenger.cli")
|
|
|
|
|
|
async def replay_attachment(attachment_id_str: str) -> None:
|
|
"""Безопасный операторский replay задачи из failed в queued."""
|
|
try:
|
|
att_id = uuid.UUID(attachment_id_str)
|
|
except ValueError:
|
|
logger.error("Invalid UUID: %s", attachment_id_str)
|
|
sys.exit(1)
|
|
|
|
pool = await asyncpg.create_pool(dsn=DATABASE_URL)
|
|
assert pool is not None
|
|
|
|
async with pool.acquire() as conn:
|
|
row = await conn.fetchrow(
|
|
"SELECT id, status, chat_id, filename FROM attachments WHERE id = $1",
|
|
att_id,
|
|
)
|
|
if not row:
|
|
logger.error("Attachment %s not found in DB", att_id)
|
|
await pool.close()
|
|
sys.exit(1)
|
|
|
|
if row["status"] == "ready":
|
|
logger.warning(
|
|
"Attachment %s is already 'ready'. Replay will not re-execute successful job.",
|
|
att_id,
|
|
)
|
|
await pool.close()
|
|
return
|
|
|
|
# Переводим в queued и создаем новое задание
|
|
new_job_id = uuid.uuid4()
|
|
now_iso = now_utc_iso()
|
|
job_payload = {
|
|
"schema_version": 1,
|
|
"job_id": str(new_job_id),
|
|
"type": "attachment.process.v1",
|
|
"attachment_id": str(att_id),
|
|
"pipeline_version": 1,
|
|
"attempt": 1,
|
|
"created_at": now_iso,
|
|
}
|
|
|
|
async with conn.transaction():
|
|
await conn.execute(
|
|
"""
|
|
UPDATE attachments
|
|
SET status = 'queued',
|
|
error_code = NULL,
|
|
processing_started_at = NULL,
|
|
processing_worker_id = NULL,
|
|
updated_at = NOW()
|
|
WHERE id = $1
|
|
""",
|
|
att_id,
|
|
)
|
|
await conn.execute(
|
|
"""
|
|
INSERT INTO outbox_jobs (
|
|
job_id, attachment_id, event_type, payload, status, attempt, created_at, updated_at
|
|
)
|
|
VALUES ($1, $2, 'attachment.process.v1', $3::jsonb, 'pending', 1, NOW(), NOW())
|
|
""",
|
|
new_job_id,
|
|
att_id,
|
|
json.dumps(job_payload),
|
|
)
|
|
|
|
# Публикуем напрямую в брокер
|
|
published = await publisher.publish_job(job_payload)
|
|
if published:
|
|
await conn.execute(
|
|
"UPDATE outbox_jobs SET status = 'published' WHERE job_id = $1",
|
|
new_job_id,
|
|
)
|
|
logger.info("Attachment %s successfully replayed with new job %s", att_id, new_job_id)
|
|
else:
|
|
logger.warning(
|
|
"Attachment %s queued in outbox_jobs, will be dispatched by outbox relay",
|
|
att_id,
|
|
)
|
|
|
|
await publisher.close()
|
|
await pool.close()
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description="Operator CLI for messenger")
|
|
subparsers = parser.add_subparsers(dest="command")
|
|
|
|
replay_parser = subparsers.add_parser("replay", help="Replay a failed attachment")
|
|
replay_parser.add_argument("attachment_id", help="UUID of the attachment to replay")
|
|
|
|
args = parser.parse_args()
|
|
if args.command == "replay":
|
|
asyncio.run(replay_attachment(args.attachment_id))
|
|
else:
|
|
parser.print_help()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|