from __future__ import annotations import os from pathlib import Path import pika QUEUE_NAME = "attachment.process.v1" DLX_NAME = "attachment.process.dlx" DLQ_NAME = "attachment.process.v1.dlq" def connect_broker(): url = Path(os.environ["BROKER_URL_FILE"]).read_text().strip() if not url: raise ValueError("Empty broker URL file") parameters = pika.URLParameters(url) parameters.heartbeat = 15 parameters.blocked_connection_timeout = 5 parameters.socket_timeout = 5 parameters.stack_timeout = 10 parameters.connection_attempts = 1 connection = pika.BlockingConnection(parameters) try: channel = connection.channel() channel.exchange_declare( exchange=DLX_NAME, exchange_type="direct", durable=True, ) channel.queue_declare(queue=DLQ_NAME, durable=True) channel.queue_bind( queue=DLQ_NAME, exchange=DLX_NAME, routing_key=QUEUE_NAME, ) channel.queue_declare( queue=QUEUE_NAME, durable=True, exclusive=False, auto_delete=False, arguments={ "x-dead-letter-exchange": DLX_NAME, "x-dead-letter-routing-key": QUEUE_NAME, }, ) return connection, channel except Exception: connection.close() raise