"""RabbitMQ topology, job message format (contracts/jobs.schema.json) and publishing with publisher confirms. Topology (declared idempotently by every producer/consumer): exchange attachments (direct, durable) --attachment.process.v1--> queue attachments.process (quorum, durable) queue attachments.process: x-dead-letter-exchange=attachments.dlx, x-delivery-limit (poison message guard) exchange attachments.dlx (fanout, durable) --> queue attachments.dlq (quorum, durable) Quorum queues replicate/fsync messages before the publisher confirm, persistent delivery mode is used anyway. The message carries only IDs and service fields, never image bytes, URLs or credentials. """ from __future__ import annotations import json import re import uuid from datetime import datetime, timezone from typing import Optional import aio_pika from aio_pika import DeliveryMode, ExchangeType, Message from app import config JOB_TYPE = "attachment.process.v1" JOB_FIELDS = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at", "traceparent", "tracestate"} REQUIRED = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"} _TRACEPARENT = re.compile(r"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$") class InvalidJob(ValueError): pass def job_payload(job_id: uuid.UUID, attachment_id: uuid.UUID, pipeline_version: int, attempt: int) -> dict: return { "schema_version": 1, "job_id": str(job_id), "type": JOB_TYPE, "attachment_id": str(attachment_id), "pipeline_version": int(pipeline_version), "attempt": int(attempt), "created_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ"), } def _int(value, minimum: int) -> int: if not isinstance(value, int) or isinstance(value, bool) or value < minimum: raise InvalidJob("integer field out of range") return value def parse_job(body: bytes) -> dict: """Strict validation against jobs.schema.json (additionalProperties=false).""" try: data = json.loads(body.decode("utf-8")) except (UnicodeDecodeError, ValueError): raise InvalidJob("not JSON") from None if not isinstance(data, dict): raise InvalidJob("not an object") keys = set(data) if not REQUIRED <= keys or keys - JOB_FIELDS: raise InvalidJob("unexpected or missing fields") if data["schema_version"] != 1 or isinstance(data["schema_version"], bool) or data["type"] != JOB_TYPE: raise InvalidJob("unsupported schema_version/type") try: job_id = uuid.UUID(data["job_id"]) attachment_id = uuid.UUID(data["attachment_id"]) created = datetime.fromisoformat(str(data["created_at"]).replace("Z", "+00:00")) except (ValueError, TypeError, AttributeError): raise InvalidJob("bad uuid/date-time") from None if created.tzinfo is None: raise InvalidJob("created_at without timezone") if "traceparent" in data and not (isinstance(data["traceparent"], str) and _TRACEPARENT.match(data["traceparent"])): raise InvalidJob("bad traceparent") if "tracestate" in data and not (isinstance(data["tracestate"], str) and len(data["tracestate"]) <= 512): raise InvalidJob("bad tracestate") return { "job_id": job_id, "attachment_id": attachment_id, "pipeline_version": _int(data["pipeline_version"], 1), "attempt": _int(data["attempt"], 1), } class Broker: def __init__(self, url: Optional[str] = None): self.url = url or config.BROKER_URL self.connection: Optional[aio_pika.abc.AbstractRobustConnection] = None self.channel: Optional[aio_pika.abc.AbstractChannel] = None self.exchange = None self.queue = None async def connect(self, prefetch: int = 0) -> None: if not self.url: raise RuntimeError("BROKER_URL or BROKER_URL_FILE is required") self.connection = await aio_pika.connect_robust(self.url, timeout=5, client_properties={"connection_name": "messenger"}) # publisher_confirms=True: publish() returns only after the broker took responsibility for the message. self.channel = await self.connection.channel(publisher_confirms=True) if prefetch: await self.channel.set_qos(prefetch_count=prefetch) await self.declare() async def declare(self) -> None: ch = self.channel dlx = await ch.declare_exchange(config.BROKER_DLX, ExchangeType.FANOUT, durable=True) dlq = await ch.declare_queue(config.BROKER_DLQ, durable=True, arguments={"x-queue-type": "quorum"}) await dlq.bind(dlx) self.exchange = await ch.declare_exchange(config.BROKER_EXCHANGE, ExchangeType.DIRECT, durable=True) self.queue = await ch.declare_queue(config.BROKER_QUEUE, durable=True, arguments={ "x-queue-type": "quorum", "x-dead-letter-exchange": config.BROKER_DLX, "x-delivery-limit": config.BROKER_DELIVERY_LIMIT, }) await self.queue.bind(self.exchange, routing_key=config.BROKER_ROUTING_KEY) async def publish(self, payload: dict) -> None: """Returns after the publisher confirm (basic.ack); raises on nack/return/connection loss.""" body = json.dumps(payload, separators=(",", ":")).encode("utf-8") await self.exchange.publish( Message( body, content_type="application/json", delivery_mode=DeliveryMode.PERSISTENT, message_id=payload["job_id"] + ":" + str(payload["attempt"]), type=payload["type"], ), routing_key=config.BROKER_ROUTING_KEY, mandatory=True, timeout=10, ) async def close(self) -> None: if self.connection is not None: await self.connection.close()