"""Durable Redis Streams + transactional PostgreSQL outbox.""" import json import os import random import time import uuid import redis import db import telemetry as ot from opentelemetry.trace import SpanKind from opentelemetry import propagate STREAM = 'attachment:jobs' GROUP = 'workers' MAX_ATTEMPTS = int(os.getenv('JOB_MAX_ATTEMPTS','5')) BROKER = redis.Redis.from_url(os.environ['BROKER_URL'],decode_responses=True,socket_timeout=3,socket_connect_timeout=2, ssl_ca_certs='/ca/ca.crt',ssl_certfile='/identity/tls.crt',ssl_keyfile='/identity/tls.key',ssl_check_hostname=True) def ensure_group(): try: BROKER.xgroup_create(STREAM,GROUP,id='0',mkstream=True) except redis.ResponseError as exc: if 'BUSYGROUP' not in str(exc): raise def dispatch_once(): with db.pool.connection() as conn: q=conn.execute("SELECT count(*) AS depth,coalesce(extract(epoch FROM now()-min(j.created_at)),0) AS age FROM attachment_jobs j JOIN attachments a ON j.id=a.id WHERE a.status IN ('queued','processing')").fetchone() ot.state['queue_depth']=q['depth'] ot.state['oldest_seconds']=float(q['age']) expired = conn.execute("""SELECT j.id,j.attempt FROM attachment_jobs j JOIN attachments a ON a.id=j.id WHERE a.status='processing' AND j.lease_until= MAX_ATTEMPTS: conn.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=now() WHERE id=%s",(row['id'],)) else: conn.execute("UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s",(row['id'],)) conn.execute("UPDATE attachment_jobs SET published_at=NULL,lease_until=NULL,available_at=now() WHERE id=%s",(row['id'],)) jobs = conn.execute("""SELECT j.* FROM attachment_jobs j JOIN attachments a ON a.id=j.id WHERE a.status='queued' AND j.available_at<=now() AND (j.published_at IS NULL OR j.published_at=MAX_ATTEMPTS: conn.execute("UPDATE attachments SET status='failed',error_code=%s,updated_at=now() WHERE id=%s AND status='processing'", ('invalid_image' if permanent else 'retry_exhausted',job_id)) else: delay = min(60,2**row['attempt'])+random.random() conn.execute("UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s AND status='processing'",(job_id,)) conn.execute("UPDATE attachment_jobs SET published_at=NULL,lease_until=NULL,available_at=now()+%s*interval '1 second' WHERE id=%s",(delay,job_id)) def replay(job_id): with db.pool.connection() as conn: changed=conn.execute("UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=%s AND status='failed' AND NOT staging_cleaned RETURNING id",(job_id,)).fetchone() if not changed: raise SystemExit('Only failed jobs may be replayed') conn.execute("UPDATE attachment_jobs SET attempt=0,published_at=NULL,lease_until=NULL,available_at=now(),replay_count=replay_count+1 WHERE id=%s",(job_id,)) conn.execute("INSERT INTO attachment_replays(job_id) VALUES (%s)",(job_id,)) if __name__ == '__main__': import sys db.pool.open(wait=True,timeout=30) if len(sys.argv)==3 and sys.argv[1]=='replay': replay(str(uuid.UUID(sys.argv[2]))) else: while True: try: ensure_group() dispatch_once() except Exception: print('dispatcher will retry',flush=True) time.sleep(1)