"""RabbitMQ (AMQP 0-9-1) for the attachment jobs: topology names and the message format. Topology (declared by the broker itself from its definitions file at boot, infra/rabbitmq and scripts/init_secrets.py; the relay and the worker have NO configure permission and declare nothing): exchange messenger.jobs direct, durable queue messenger.attachment-jobs quorum (Raft log on disk), bound with routing key attachment.process.v1; x-delivery-limit and dead-lettering to exchange messenger.jobs.dlx fanout -> queue messenger.attachment-jobs.dlq (quorum) Publisher side (relay): persistent message, `mandatory` (an unroutable message is returned, not silently dropped), channel in confirm mode - `publish()` returns only after the broker has written the message to the quorum log (publisher confirm). Consumer side (worker): manual ack after the durable effect, prefetch = WORKER_CONCURRENCY. The message carries IDs and service fields only (contracts/jobs.schema.json): no bytes, no URL, no S3 key, no filename, no credentials. The worker takes every trusted detail from PostgreSQL. """ from __future__ import annotations import datetime as dt import json import re import uuid EXCHANGE = "messenger.jobs" QUEUE = "messenger.attachment-jobs" DLX = "messenger.jobs.dlx" DLQ = "messenger.attachment-jobs.dlq" ROUTING_KEY = "attachment.process.v1" JOB_TYPE = "attachment.process.v1" MAX_MESSAGE_BYTES = 4096 REQUIRED = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"} OPTIONAL = {"traceparent", "tracestate"} TRACEPARENT_RE = re.compile(r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}") DATETIME_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z") class BadMessage(ValueError): """Not a valid job message (schema v1): dead-lettered, never processed.""" def rfc3339(value: dt.datetime) -> str: return value.astimezone(dt.timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z") def encode(job_id: str, attachment_id: str, pipeline_version: int, attempt: int, created_at: dt.datetime) -> bytes: body = {"schema_version": 1, "job_id": job_id, "type": JOB_TYPE, "attachment_id": attachment_id, "pipeline_version": pipeline_version, "attempt": attempt, "created_at": rfc3339(created_at)} return json.dumps(body, separators=(",", ":")).encode() def decode(raw: bytes) -> dict: """Strict check against contracts/jobs.schema.json (additionalProperties: false).""" if len(raw) > MAX_MESSAGE_BYTES: raise BadMessage("too large") try: body = json.loads(raw) except (ValueError, UnicodeError): raise BadMessage("not JSON") from None if not isinstance(body, dict): raise BadMessage("not an object") keys = set(body) if not REQUIRED <= keys or keys - REQUIRED - OPTIONAL: raise BadMessage("wrong fields") if body["schema_version"] != 1 or isinstance(body["schema_version"], bool) or body["type"] != JOB_TYPE: raise BadMessage("unsupported schema/type") for name in ("job_id", "attachment_id"): if not isinstance(body[name], str): raise BadMessage(name) try: uuid.UUID(body[name]) except ValueError: raise BadMessage(name) from None for name in ("pipeline_version", "attempt"): value = body[name] if not isinstance(value, int) or isinstance(value, bool) or value < 1: raise BadMessage(name) if not isinstance(body["created_at"], str) or not DATETIME_RE.fullmatch(body["created_at"]): raise BadMessage("created_at") if "traceparent" in body and not (isinstance(body["traceparent"], str) and TRACEPARENT_RE.fullmatch(body["traceparent"])): raise BadMessage("traceparent") if "tracestate" in body and not (isinstance(body["tracestate"], str) and len(body["tracestate"]) <= 512): raise BadMessage("tracestate") return body