"""PostgreSQL outbox, Redis Streams at-least-once transport and fenced effects.""" import asyncio import hashlib import json import os from pathlib import Path import random import sys import tempfile from uuid import uuid4, UUID from psycopg.types.json import Jsonb from redis.asyncio import Redis from redis.exceptions import ResponseError from .attachments import Attachments, BUCKET from .config import Settings from .store import Store STREAM='images.v1' GROUP='workers' MAX_ATTEMPTS=int(os.getenv('MAX_ATTEMPTS','5')) def broker(): return Redis.from_url(Path('/run/secrets/cache_url').read_text().strip().replace('@redis:', '@broker:'), decode_responses=True) async def publish(store, queue, attachments): async with store.pool.connection() as conn: # Row locks fence stale workers; recovery waits until their connection is gone. expired=await conn.execute("""SELECT id,attachment_id,attempts FROM jobs WHERE state='processing' AND lease_until=MAX_ATTEMPTS: await conn.execute("UPDATE jobs SET state='failed',lease_until=NULL WHERE id=%s",(row['id'],)) await conn.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=clock_timestamp() WHERE id=%s",(row['attachment_id'],)) continue await conn.execute("UPDATE jobs SET state='queued', available_at=clock_timestamp(),last_published=NULL WHERE id=%s",(row['id'],)) await conn.execute("UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=%s",(row['attachment_id'],)) cur=await conn.execute("""SELECT * FROM jobs WHERE state='queued' AND available_at<=clock_timestamp() AND (last_published IS NULL OR last_publishedMAX_ATTEMPTS: code='retry_exhausted' else: with tempfile.TemporaryDirectory() as directory: source=Path(directory)/'source' await asyncio.to_thread(attachments.s3.download_file,BUCKET,'staging/'+row['id'].hex,str(source)) if source.stat().st_size!=row['size_bytes'] or hashlib.sha256(source.read_bytes()).hexdigest()!=row['sha256']: code='invalid_image' else: child=await asyncio.create_subprocess_exec(sys.executable,'-m','app.transform',str(source),row['content_type'],directory, stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.DEVNULL) try: stdout,_=await asyncio.wait_for(child.communicate(),30) except BaseException: child.kill() await child.wait() raise if child.returncode: code='invalid_image' else: variants=json.loads(stdout) await asyncio.to_thread(attachments.s3.copy_object,Bucket=BUCKET,Key=row['object_key'], CopySource={'Bucket':BUCKET,'Key':'staging/'+row['id'].hex}) # Test-only one-shot crash marker on the disposable container filesystem. if Path('/tmp/crash_after_object').exists(): Path('/tmp/crash_after_object').unlink() os._exit(86) for variant in variants: body=(Path(directory)/variant['name']).read_bytes() variant.update(size_bytes=len(body),sha256=hashlib.sha256(body).hexdigest()) await asyncio.to_thread(attachments.s3.put_object,Bucket=BUCKET, Key='variants/'+row['id'].hex+'/v1/'+variant['name'],Body=body,ContentType=variant['content_type']) await conn.execute("UPDATE attachments SET status='ready',variants=%s,error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",(Jsonb(variants),row['id'])) await conn.execute("UPDATE jobs SET state='ready',lease_until=NULL WHERE id=%s",(job_id,)) return except TimeoutError: code='processing_timeout' except Exception: code='storage_unavailable' terminal=code=='invalid_image' or job['attempts']>=MAX_ATTEMPTS if terminal and code!='invalid_image': code='retry_exhausted' delay=min(60,2**min(job['attempts'],6))+random.uniform(0,1) state='failed' if terminal else 'queued' await conn.execute("UPDATE jobs SET state=%s,available_at=clock_timestamp()+(%s*interval '1 second'),lease_until=NULL,last_published=NULL WHERE id=%s",(state,delay,job_id)) await conn.execute('UPDATE attachments SET status=%s,error_code=%s,updated_at=clock_timestamp() WHERE id=%s',(state,code if terminal else None,row['id'])) async def replay(store, job_id, reason): if not reason.strip(): raise ValueError('Replay reason required') async with store.pool.connection() as conn: cur=await conn.execute('SELECT * FROM jobs WHERE id=%s FOR UPDATE',(UUID(job_id),)) job=await cur.fetchone() if not job or job['state']!='failed': raise ValueError('Only failed jobs can be replayed') cur=await conn.execute('SELECT staging_cleaned FROM attachments WHERE id=%s',(job['attachment_id'],)) if (await cur.fetchone())['staging_cleaned']: raise ValueError('Replay retention expired') await conn.execute('INSERT INTO replay_audit(job_id,reason) VALUES (%s,%s)',(job['id'],reason)) await conn.execute("UPDATE jobs SET state='queued',attempts=0,available_at=clock_timestamp(),last_published=NULL WHERE id=%s",(job['id'],)) await conn.execute("UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",(job['attachment_id'],)) async def main(role): store=Store(Settings.load()); await store.open() queue=broker(); attachments=Attachments(store) try: if role=='replay': await replay(store,*sys.argv[2:]); return if role=='worker': try: await queue.xgroup_create(STREAM,GROUP,id='0',mkstream=True) except ResponseError as error: if 'BUSYGROUP' not in str(error): raise consumer=uuid4().hex while True: try: Path('/tmp/pipeline_alive').touch() if role=='publisher': await publish(store,queue,attachments); await asyncio.sleep(.5) else: claimed=await queue.xautoclaim(STREAM,GROUP,consumer,5000,'0-0',count=1) entries=claimed[1] if not entries: batches=await queue.xreadgroup(GROUP,consumer,{STREAM:'>'},count=1,block=1000) entries=batches[0][1] if batches else [] for message_id, fields in entries: await process(store,attachments,json.loads(fields['payload'])) await queue.xack(STREAM,GROUP,message_id) await queue.xdel(STREAM,message_id) except Exception: print(role+': operation deferred',flush=True) await asyncio.sleep(1) finally: await queue.aclose(); await store.close() if __name__=='__main__': asyncio.run(main(sys.argv[1]))