"""Explicit operator replay for one failed attachment job.""" import argparse import json import os import uuid import psycopg def main(): parser = argparse.ArgumentParser() parser.add_argument('attachment_id', type=uuid.UUID) args = parser.parse_args() database_url = os.getenv('DATABASE_URL', 'postgresql://messenger:messenger@postgres:5432/messenger') with psycopg.connect(database_url) as connection: with connection.transaction(): row = connection.execute( "SELECT a.status, j.job_id FROM attachments a " "JOIN attachment_jobs j ON j.attachment_id=a.id " "WHERE a.id=%s FOR UPDATE", (args.attachment_id,), ).fetchone() if row is None: raise SystemExit('attachment not found') if row[0] != 'failed': raise SystemExit('attachment is not failed') replay_id = uuid.uuid4() connection.execute( 'INSERT INTO attachment_replays (replay_id,job_id) VALUES (%s,%s)', (replay_id, row[1]), ) connection.execute( "UPDATE attachments SET status='queued', attempt=0, error_code=NULL, lease_until=NULL, updated_at=now() WHERE id=%s", (args.attachment_id,), ) connection.execute( "UPDATE attachment_jobs SET attempt=1, published_at=NULL, next_attempt_at=now(), last_error=NULL WHERE job_id=%s", (row[1],), ) print(json.dumps({'attachment_id': str(args.attachment_id), 'job_id': str(row[1]), 'replay_id': str(replay_id)})) if __name__ == '__main__': main()