"""AMQP carrier and durable publishing, shared by API and worker.""" import json import logging import os from contextlib import contextmanager from datetime import datetime from typing import Literal from uuid import UUID import pika from pydantic import AwareDatetime, BaseModel, ConfigDict, Field from src.config import secret QUEUE = "attachment.process.v1" PIPELINE_VERSION = 1 MAX_ATTEMPTS = int(os.getenv("JOB_MAX_ATTEMPTS", "5")) if not 1 <= MAX_ATTEMPTS <= 20: raise RuntimeError("JOB_MAX_ATTEMPTS must be 1..20") # Report dependency failures at the call site without logging connection details. logging.getLogger("pika").setLevel(logging.CRITICAL) class Job(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) schema_version: Literal[1] type: Literal["attachment.process.v1"] job_id: UUID attachment_id: UUID pipeline_version: int = Field(ge=1) attempt: int = Field(ge=1) created_at: AwareDatetime traceparent: str = Field(default="", pattern=r"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$") tracestate: str = Field(default="", max_length=512) def carrier(job_id: UUID, attachment_id: UUID, created_at: datetime, attempt: int = 1): return Job( schema_version=1, type=QUEUE, job_id=job_id, attachment_id=attachment_id, pipeline_version=PIPELINE_VERSION, attempt=attempt, created_at=created_at, ) def parse(body): # Validate JSON primitive types before Pydantic's UUID/time parsing. values = json.loads(body) if not isinstance(values, dict) or any( type(values.get(k)) is not int for k in ("schema_version", "pipeline_version", "attempt") ) or any(type(values.get(k)) is not str for k in ("job_id", "attachment_id", "created_at")): raise ValueError("Bad job carrier") return Job.model_validate_json(body) @contextmanager def broker(): params = pika.URLParameters(secret("BROKER_URL")) params.socket_timeout = 2 params.stack_timeout = 4 params.blocked_connection_timeout = 4 params.heartbeat = 30 conn = pika.BlockingConnection(params) try: channel = conn.channel() channel.queue_declare(queue=QUEUE, durable=True, arguments={"x-queue-type": "classic"}) channel.confirm_delivery() yield channel finally: if conn.is_open: conn.close() def publish(channel, job): channel.basic_publish( exchange="", routing_key=QUEUE, body=job.model_dump_json(exclude_unset=True).encode(), properties=pika.BasicProperties(delivery_mode=2, content_type="application/json", message_id=str(job.job_id)), mandatory=True, )