"""Small PostgreSQL outbox + Redis Streams queue; PostgreSQL owns job state.""" import argparse import json import logging import os import random import time from datetime import datetime, timedelta, timezone from uuid import UUID, uuid4 from redis import Redis from redis.exceptions import ResponseError from sqlalchemy import and_, or_, select from sqlalchemy.orm import sessionmaker from .database import create_db_engine from .models import Attachment, AttachmentJob from .object_storage import BUCKET, s3_client STREAM = 'attachment-jobs' GROUP = 'image-workers' MAX_ATTEMPTS = max(1, int(os.getenv('JOB_MAX_ATTEMPTS', '5'))) TIMEOUT = max(1, int(os.getenv('JOB_TIMEOUT_SECONDS', '60'))) LEASE_SECONDS = TIMEOUT + 15 def now(): return datetime.now(timezone.utc) def broker(): return Redis.from_url(os.getenv('BROKER_URL', 'redis://broker:6379/0'), decode_responses=True, socket_connect_timeout=2, socket_timeout=5) def ensure_group(client): try: client.xgroup_create(STREAM, GROUP, id='0', mkstream=True) except ResponseError as exc: if not str(exc).startswith('BUSYGROUP'): raise def envelope(job): return {'schema_version': 1, 'job_id': job.id, 'type': 'attachment.process.v1', 'attachment_id': job.attachment_id, 'pipeline_version': job.pipeline_version, 'attempt': job.attempt + 1, 'created_at': job.created_at.isoformat().replace('+00:00', 'Z')} def fail(session, job, attachment, code, permanent=False): job.failures += 1 job.last_error = code job.lease_token = job.lease_until = job.published_at = None attachment.updated_at = now() if permanent or job.failures >= MAX_ATTEMPTS: attachment.status = 'failed' attachment.error_code = code if permanent else 'retry_exhausted' else: attachment.status = 'queued' attachment.error_code = None delay = min(60, 2 ** min(job.failures, 6)) * random.uniform(0.5, 1.5) job.available_at = now() + timedelta(seconds=delay) logging.info('job=%s attempt=%s result=%s code=%s', job.id, job.attempt, attachment.status, code) def dispatch_once(sessions, client): # A crash after XADD but before COMMIT deliberately results in redelivery. with sessions.begin() as session: jobs = list(session.scalars(select(AttachmentJob).join(Attachment).where( or_(and_(Attachment.status == 'queued', AttachmentJob.published_at.is_(None)), and_(Attachment.status == 'processing', AttachmentJob.lease_until <= now())), AttachmentJob.available_at <= now()).order_by(AttachmentJob.available_at) .with_for_update(skip_locked=True, of=AttachmentJob).limit(50))) for job in jobs: attachment = session.get(Attachment, job.attachment_id, with_for_update=True) if attachment.status == 'processing': if job.lease_until <= now(): fail(session, job, attachment, 'lease_expired') continue if job.published_at is None: client.xadd(STREAM, {'job': json.dumps(envelope(job))}) job.published_at = now() def claim(sessions, message): if (message.get('schema_version') != 1 or message.get('type') != 'attachment.process.v1' or message.get('pipeline_version') != 1): raise ValueError('unsupported job envelope') job_id = str(UUID(message['job_id'])) with sessions.begin() as session: job = session.get(AttachmentJob, job_id, with_for_update=True) if job is None or job.attachment_id != message.get('attachment_id'): raise ValueError('unknown job') attachment = session.get(Attachment, job.attachment_id, with_for_update=True) if attachment.status != 'queued' or job.available_at > now(): return None job.attempt += 1 job.lease_token = str(uuid4()) job.lease_until = now() + timedelta(seconds=LEASE_SECONDS) attachment.status = 'processing' attachment.updated_at = now() return job.id, job.lease_token def record_failure(sessions, job_id, token, code, permanent=False): with sessions.begin() as session: job = session.get(AttachmentJob, job_id, with_for_update=True) if job.lease_token == token: attachment = session.get(Attachment, job.attachment_id, with_for_update=True) fail(session, job, attachment, code, permanent) def replay(sessions, job_id, reason): if not reason.strip() or len(reason) > 200: raise ValueError('Give a nonempty reason of at most 200 characters') with sessions.begin() as session: job = session.get(AttachmentJob, str(UUID(job_id)), with_for_update=True) if job is None: raise ValueError('Job not found') attachment = session.get(Attachment, job.attachment_id, with_for_update=True) if attachment.status != 'failed': raise ValueError('Replay is allowed only for failed jobs') if not attachment.staging_key: raise ValueError('Staging retention expired; upload the file again') s3_client().head_object(Bucket=BUCKET, Key=attachment.staging_key) job.replay_audit = job.replay_audit + [{'at': now().isoformat(), 'reason': reason, 'after_attempt': job.attempt, 'last_error': job.last_error}] job.failures = 0 job.available_at = now() job.published_at = job.lease_until = job.lease_token = None attachment.status, attachment.error_code = 'queued', None attachment.updated_at = now() def main(): parser = argparse.ArgumentParser(description=__doc__) sub = parser.add_subparsers(dest='command', required=True) sub.add_parser('dispatch') sub.add_parser('failed') retry = sub.add_parser('replay') retry.add_argument('job_id') retry.add_argument('--reason', required=True) args = parser.parse_args() logging.basicConfig(level=logging.INFO) engine = create_db_engine() sessions = sessionmaker(engine, expire_on_commit=False) try: if args.command == 'failed': with sessions() as session: for job, att in session.execute(select(AttachmentJob, Attachment).join( Attachment, Attachment.id == AttachmentJob.attachment_id) .where(Attachment.status == 'failed')): print(json.dumps({'job_id': job.id, 'attachment_id': att.id, 'attempt': job.attempt, 'error_code': att.error_code, 'last_error': job.last_error, 'replay_available': bool(att.staging_key)})) elif args.command == 'replay': replay(sessions, args.job_id, args.reason) print('Job queued for replay') else: client = broker() while True: try: ensure_group(client) dispatch_once(sessions, client) except Exception as exc: logging.warning('Dispatch deferred: %s', type(exc).__name__) time.sleep(1) finally: engine.dispose() if __name__ == '__main__': main()