"""Durable PostgreSQL outbox, Redis Streams relay and leased image processing.""" import io import json import os import random import signal import subprocess import sys import tempfile import threading import time from datetime import timezone from pathlib import Path from uuid import UUID, uuid4 import psycopg from botocore.exceptions import BotoCoreError, ClientError from psycopg.types.json import Jsonb from psycopg_pool import PoolTimeout from redis import Redis from redis.exceptions import RedisError, ResponseError from attachments import Objects from db import Store, setting STREAM = "messenger:images" GROUP = "image-workers" MAX_ATTEMPTS = int(os.environ.get("JOB_MAX_ATTEMPTS", "5")) LEASE_SECONDS = 45 CHILD_TIMEOUT = 15 JOB_TYPE = "attachment.process.v1" class PermanentImageError(Exception): pass def connect_broker(): return Redis.from_url(setting("BROKER_URL"), socket_timeout=3, socket_connect_timeout=2, decode_responses=True) def record(event, **fields): print(json.dumps({"event": event, **fields}), flush=True) def settle(connection, job, outcome, code=None): waiting = outcome == "waiting" delay = min(20, 2 ** job["attempt"]) * random.uniform(0.8, 1.2) if waiting else 0 connection.execute(""" UPDATE image_jobs SET state = %s, leased_until = NULL, published_at = NULL, next_run = clock_timestamp() + %s * interval '1 second' WHERE id = %s """, (outcome, delay, job["id"])) if outcome != "done": connection.execute(""" UPDATE attachments SET status = %s, error_code = %s, updated_at = clock_timestamp() WHERE id = %s AND pipeline_version = %s """, ("queued" if waiting else "failed", None if waiting else code, job["attachment_id"], job["pipeline_version"])) def relay_once(store, broker): with store.pool.connection() as connection: row = connection.execute(""" SELECT * FROM image_jobs WHERE ((state = 'waiting' AND next_run <= clock_timestamp()) OR (state = 'leased' AND leased_until <= clock_timestamp())) AND (published_at IS NULL OR published_at <= clock_timestamp() - interval '50 seconds') ORDER BY next_run, id FOR UPDATE SKIP LOCKED LIMIT 1 """).fetchone() if row is None: return False message = { "schema_version": 1, "job_id": str(row["id"]), "type": JOB_TYPE, "attachment_id": str(row["attachment_id"]), "pipeline_version": row["pipeline_version"], "attempt": row["attempt"] + 1, "created_at": row["created_at"].astimezone(timezone.utc).isoformat().replace("+00:00", "Z"), **row["trace_context"], } broker.xadd(STREAM, {"job": json.dumps(message, separators=(",", ":"))}) connection.execute("UPDATE image_jobs SET published_at = clock_timestamp() WHERE id = %s", (row["id"],)) return True def claim(store, message): with store.pool.connection() as connection: job = connection.execute(""" SELECT j.*, a.content_type, a.sha256, a.size_bytes, a.pipeline_version AS active_version, j.leased_until > clock_timestamp() AS lease_active, j.next_run > clock_timestamp() AS too_early FROM image_jobs j JOIN attachments a ON a.id = j.attachment_id WHERE j.id = %s FOR UPDATE OF j, a """, (UUID(message["job_id"]),)).fetchone() if not job or job["state"] in ("done", "failed"): return None if job["pipeline_version"] != job["active_version"]: settle(connection, job, "done") return None if job["lease_active"] or job["too_early"]: return None if job["attempt"] >= MAX_ATTEMPTS: settle(connection, job, "failed", "retry_exhausted") return None job["attempt"] += 1 connection.execute(""" UPDATE image_jobs SET state = 'leased', attempt = %s, leased_until = clock_timestamp() + %s * interval '1 second' WHERE id = %s """, (job["attempt"], LEASE_SECONDS, job["id"])) connection.execute(""" UPDATE attachments SET status='processing', updated_at = clock_timestamp() WHERE id=%s """, (job["attachment_id"],)) return job def encode_images(original, version): with tempfile.TemporaryDirectory(prefix="messenger-image-") as name: root = Path(name) (root / "source").write_bytes(original) result = subprocess.run( [sys.executable, "-m", "variants", str(root), str(version)], check=False, timeout=CHILD_TIMEOUT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) if result.returncode == 2: raise PermanentImageError() if result.returncode != 0: raise OSError("image subprocess failed") descriptors = json.loads((root / "variants.json").read_text(encoding="utf-8")) return [(descriptor, (root / descriptor["name"]).read_bytes()) for descriptor in descriptors] def try_publish(store, objects, job): attachment_id, version = job["attachment_id"], job["pipeline_version"] original = objects.get(objects.key(attachment_id, "staging")) processed = encode_images(original, version) with store.pool.connection() as connection: current = connection.execute(""" SELECT j.attempt, j.state, a.pipeline_version, j.leased_until > clock_timestamp() AS lease_active FROM image_jobs j JOIN attachments a ON a.id = j.attachment_id WHERE j.id = %s FOR UPDATE OF j,a """, (job["id"],)).fetchone() if not current or current["state"] != "leased" or current["attempt"] != job["attempt"]: return "stale" if current["pipeline_version"] != version or not current["lease_active"]: return "stale" digest = objects.put(objects.result_key(attachment_id, version, "original"), io.BytesIO(original), job["content_type"], len(original)) if digest != job["sha256"] or len(original) != job["size_bytes"]: raise PermanentImageError() variants = [] for descriptor, data in processed: name, mime = descriptor["name"], descriptor["content_type"] digest = objects.put(objects.result_key(attachment_id, version, name), io.BytesIO(data), mime, len(data)) variants.append({**descriptor, "size_bytes": len(data), "sha256": digest}) connection.execute(""" UPDATE attachments SET status = 'ready', error_code = NULL, variants = %s, updated_at = clock_timestamp() WHERE id = %s AND pipeline_version = %s """, (Jsonb(variants), attachment_id, version)) settle(connection, job, "done") return "ready" def fail(store, job, permanent): with store.pool.connection() as connection: current = connection.execute(""" SELECT state, attempt FROM image_jobs WHERE id = %s FOR UPDATE """, (job["id"],)).fetchone() if current != {"state": "leased", "attempt": job["attempt"]}: return "stale" if permanent or job["attempt"] >= MAX_ATTEMPTS: settle(connection, job, "failed", "invalid_image" if permanent else "retry_exhausted") return "failed" settle(connection, job, "waiting") return "retry" def process(store, objects, message): job = claim(store, message) if job is None: return "ignored" try: return try_publish(store, objects, job) except PermanentImageError: return fail(store, job, permanent=True) except (OSError, subprocess.TimeoutExpired, BotoCoreError, ClientError): return fail(store, job, permanent=False) def operate_worker(store, broker, stop): try: broker.xgroup_create(STREAM, GROUP, id="0-0", mkstream=True) except ResponseError as exc: if not str(exc).startswith("BUSYGROUP"): raise consumer = uuid4().hex objects = Objects() reclaim_cursor = "0-0" while not stop.is_set(): reclaim_cursor, entries, _ = broker.xautoclaim( STREAM, GROUP, consumer, LEASE_SECONDS * 1000, reclaim_cursor, count=1 ) if not entries: streams = broker.xreadgroup(GROUP, consumer, {STREAM: ">"}, block=500, count=1) entries = streams[0][1] if streams else [] for entry_id, fields in entries: started = time.monotonic() try: message = json.loads(fields["job"]) if message.get("schema_version") != 1 or message.get("type") != JOB_TYPE: raise ValueError UUID(message["job_id"]) except (ValueError, KeyError, TypeError, AttributeError): record("job_invalid") else: outcome = process(store, objects, message) record("job_processed", outcome=outcome, duration_s=round(time.monotonic() - started, 4)) # XACK plus XDEL atomically. There is one consumer group on this stream. with broker.pipeline(transaction=True) as pipe: pipe.xack(STREAM, GROUP, entry_id).xdel(STREAM, entry_id).execute() def main(): role = sys.argv[1] stop = threading.Event() signal.signal(signal.SIGTERM, lambda *_: stop.set()) signal.signal(signal.SIGINT, lambda *_: stop.set()) store, broker = Store(), connect_broker() try: while not stop.is_set(): try: if role == "worker": operate_worker(store, broker, stop) elif role == "relay": if not relay_once(store, broker): stop.wait(0.25) else: raise ValueError("Expected worker or relay") except (RedisError, psycopg.OperationalError, psycopg.errors.LockNotAvailable, psycopg.errors.QueryCanceled, PoolTimeout) as exc: record("worker_dependency_unavailable", error_type=type(exc).__name__) stop.wait(1) finally: broker.close() store.pool.close() if __name__ == "__main__": main()