"""DB-backed delivery intent, periodically republished until a terminal state. Publishing and DB commit are deliberately repeatable: confirmed publish followed by a crash may duplicate a job, never lose an acknowledged upload. """ import json import time import pika from app.broker import connect, QUEUE from app.storage import db from app.models.time_format import utc_z def publish_due(channel): with db() as conn: jobs = conn.execute('''SELECT j.* FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.status IN ('queued','processing') AND j.next_publish<=now() ORDER BY j.next_publish LIMIT 20 FOR UPDATE OF j SKIP LOCKED''').fetchall() for job in jobs: body = dict(schema_version=1, job_id=str(job['job_id']), type='attachment.process.v1', attachment_id=str(job['attachment_id']), pipeline_version=job['pipeline_version'], attempt=job['attempts']+1, created_at=utc_z(job['created_at'])) channel.basic_publish(exchange='', routing_key=QUEUE, body=json.dumps(body), properties=pika.BasicProperties(delivery_mode=2, content_type='application/json', message_id=str(job['job_id'])), mandatory=True) conn.execute("UPDATE attachment_jobs SET next_publish=now()+interval '10 seconds' WHERE job_id=%s", (job['job_id'],)) def main(): while True: connection = None try: connection, channel = connect() while True: publish_due(channel) connection.process_data_events(time_limit=1) except Exception as exc: print('dispatcher reconnect:', type(exc).__name__, flush=True) time.sleep(2) finally: if connection and connection.is_open: connection.close() if __name__ == '__main__': main()