"""Явный операторский replay failed-заданий (failed -> queued) и просмотр реестра failed/DLQ. docker compose --env-file .env run --rm --no-deps worker python -m app.replay list docker compose --env-file .env run --rm --no-deps worker python -m app.replay replay --attachment --reason "..." [--dry-run] docker compose --env-file .env run --rm --no-deps worker python -m app.replay replay --all-failed --reason "..." [--dry-run] Безопасность: переводится только задание в статусе failed (строка блокируется FOR UPDATE). Для ready/done replay — отказ: "повторить" не означает исполнить дубль успешной работы. Каждое действие пишется в job_audit (прежний статус и ошибка, actor, причина), счётчик попыток начинается заново, job_id тот же — логический эффект (attachment_id, pipeline_version, variant) защищён от дубля так же, как при redelivery. """ import argparse import asyncio import getpass import os import sys from uuid import UUID from . import config, jobs from .db import Database async def list_failed(db: Database) -> None: async with db.connection() as conn: rows = await conn.fetch( "SELECT j.job_id, j.attachment_id, j.attempt, j.max_attempts, j.error_code, j.last_error, j.finished_at " "FROM attachment_jobs j WHERE j.status = 'failed' ORDER BY j.finished_at") print(f'failed jobs: {len(rows)}') for r in rows: print(f" attachment={r['attachment_id']} job={r['job_id']} attempts={r['attempt']}/{r['max_attempts']} " f"code={r['error_code']} reason={r['last_error']!r} at={r['finished_at']:%Y-%m-%dT%H:%M:%SZ}") async def replay(db: Database, attachment: UUID | None, all_failed: bool, reason: str, dry_run: bool) -> int: actor = os.environ.get('REPLAY_ACTOR') or getpass.getuser() done = 0 async with db.connection() as conn: async with conn.transaction(): if all_failed: targets = await conn.fetch("SELECT job_id, attachment_id, status, error_code FROM attachment_jobs " "WHERE status = 'failed' ORDER BY finished_at FOR UPDATE") else: targets = await conn.fetch('SELECT job_id, attachment_id, status, error_code FROM attachment_jobs ' 'WHERE attachment_id = $1 FOR UPDATE', attachment) if not targets: print('no such job') return 1 for t in targets: if t['status'] != 'failed': print(f"skip attachment={t['attachment_id']}: status={t['status']} — replay only for failed") continue print(f"{'would replay' if dry_run else 'replay'} attachment={t['attachment_id']} " f"job={t['job_id']} previous={t['error_code']}") if dry_run: continue await conn.execute( 'INSERT INTO job_audit (job_id, action, previous_status, previous_error, actor, reason) ' "VALUES ($1, 'replay', $2, $3, $4, $5)", t['job_id'], t['status'], t['error_code'], actor, reason) await conn.execute( "UPDATE attachment_jobs SET status = 'queued', attempt = 0, error_code = NULL, last_error = NULL, " "next_attempt_at = clock_timestamp(), finished_at = NULL, worker_id = NULL, " "updated_at = clock_timestamp() WHERE job_id = $1 AND status = 'failed'", t['job_id']) await conn.execute( "UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = clock_timestamp() " "WHERE id = $1 AND status = 'failed'", t['attachment_id']) await jobs.enqueue(conn, t['job_id'], t['attachment_id'], attempt=1) done += 1 print(f'replayed: {done}' + (' (dry run, nothing changed)' if dry_run else '')) return 0 async def main_async(args) -> int: db = Database(config.load()) await db.start() try: if args.command == 'list': await list_failed(db) return 0 return await replay(db, args.attachment, args.all_failed, args.reason, args.dry_run) finally: await db.close() def main() -> None: p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) sub = p.add_subparsers(dest='command', required=True) sub.add_parser('list') r = sub.add_parser('replay') target = r.add_mutually_exclusive_group(required=True) target.add_argument('--attachment', type=UUID) target.add_argument('--all-failed', action='store_true') r.add_argument('--reason', required=True) r.add_argument('--dry-run', action='store_true') sys.exit(asyncio.run(main_async(p.parse_args()))) if __name__ == '__main__': main()