|
| 1 | +"""RabbitMQ transport over AMQP 0-9-1. Requires the ``amqp`` extra: |
| 2 | +
|
| 3 | + pip install "babelqueue[amqp]" |
| 4 | +
|
| 5 | +Producing publishes the envelope to a durable queue with persistent delivery and |
| 6 | +the AMQP properties that are part of the cross-language contract (``type`` = URN, |
| 7 | +``correlation_id`` = trace_id, ``message_id`` = meta.id, ``x-schema-version`` / |
| 8 | +``x-source-lang`` / ``x-attempts`` headers) — so a Go/PHP consumer can route on |
| 9 | +``properties.type`` without parsing the body. Consuming uses ``basic_get`` + manual |
| 10 | +ack (at-least-once), matching the PHP RabbitMQ driver. |
| 11 | +
|
| 12 | +Connection is lazy; it (re)connects on first use and after a drop. |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import json |
| 18 | +from typing import Any, Dict, Optional |
| 19 | + |
| 20 | +from .transport import ReceivedMessage, Transport |
| 21 | + |
| 22 | + |
| 23 | +class PikaTransport(Transport): |
| 24 | + def __init__(self, url: str) -> None: |
| 25 | + try: |
| 26 | + import pika |
| 27 | + except ImportError as exc: # pragma: no cover - import guard |
| 28 | + raise ImportError( |
| 29 | + "PikaTransport requires the 'pika' package. Install with " |
| 30 | + 'pip install "babelqueue[amqp]".' |
| 31 | + ) from exc |
| 32 | + |
| 33 | + self._pika = pika |
| 34 | + self._url = url |
| 35 | + self._connection: Any = None |
| 36 | + self._channel: Any = None |
| 37 | + self._declared: set[str] = set() |
| 38 | + |
| 39 | + # -- connection / topology --------------------------------------------- |
| 40 | + |
| 41 | + def _chan(self) -> Any: |
| 42 | + if self._connection is None or self._connection.is_closed: |
| 43 | + self._connection = self._pika.BlockingConnection(self._pika.URLParameters(self._url)) |
| 44 | + self._channel = None |
| 45 | + self._declared.clear() |
| 46 | + if self._channel is None or self._channel.is_closed: |
| 47 | + self._channel = self._connection.channel() |
| 48 | + return self._channel |
| 49 | + |
| 50 | + def _declare(self, queue: str) -> None: |
| 51 | + if queue not in self._declared: |
| 52 | + self._chan().queue_declare(queue=queue, durable=True) |
| 53 | + self._declared.add(queue) |
| 54 | + |
| 55 | + def _properties(self, body: str) -> Any: |
| 56 | + """AMQP properties derived from the envelope (part of the wire contract).""" |
| 57 | + try: |
| 58 | + envelope: Dict[str, Any] = json.loads(body) |
| 59 | + except (ValueError, TypeError): |
| 60 | + return self._pika.BasicProperties(content_type="application/json", delivery_mode=2) |
| 61 | + |
| 62 | + meta = envelope.get("meta") or {} |
| 63 | + headers = { |
| 64 | + "x-schema-version": meta.get("schema_version"), |
| 65 | + "x-source-lang": meta.get("lang"), |
| 66 | + "x-attempts": envelope.get("attempts", 0), |
| 67 | + } |
| 68 | + return self._pika.BasicProperties( |
| 69 | + content_type="application/json", |
| 70 | + content_encoding="utf-8", |
| 71 | + delivery_mode=2, # persistent |
| 72 | + message_id=meta.get("id"), |
| 73 | + correlation_id=envelope.get("trace_id"), |
| 74 | + type=envelope.get("job"), |
| 75 | + app_id="babelqueue", |
| 76 | + headers={k: v for k, v in headers.items() if v is not None}, |
| 77 | + ) |
| 78 | + |
| 79 | + # -- Transport ---------------------------------------------------------- |
| 80 | + |
| 81 | + def publish(self, queue: str, body: str) -> None: |
| 82 | + self._declare(queue) |
| 83 | + self._chan().basic_publish( |
| 84 | + exchange="", |
| 85 | + routing_key=queue, |
| 86 | + body=body.encode("utf-8"), |
| 87 | + properties=self._properties(body), |
| 88 | + ) |
| 89 | + |
| 90 | + def pop(self, queue: str, timeout: float = 1.0) -> Optional[ReceivedMessage]: |
| 91 | + self._declare(queue) |
| 92 | + method, _props, body = self._chan().basic_get(queue=queue, auto_ack=False) |
| 93 | + if method is None: |
| 94 | + # Nothing ready — sleep (heartbeat-safe) so the caller doesn't busy-loop. |
| 95 | + if timeout and timeout > 0: |
| 96 | + self._connection.sleep(timeout) |
| 97 | + return None |
| 98 | + text = body.decode("utf-8") if isinstance(body, (bytes, bytearray)) else str(body) |
| 99 | + return ReceivedMessage(body=text, queue=queue, handle=method.delivery_tag) |
| 100 | + |
| 101 | + def ack(self, message: ReceivedMessage) -> None: |
| 102 | + self._chan().basic_ack(delivery_tag=message.handle) |
| 103 | + |
| 104 | + def close(self) -> None: # pragma: no cover |
| 105 | + try: |
| 106 | + if self._connection is not None and self._connection.is_open: |
| 107 | + self._connection.close() |
| 108 | + except Exception: |
| 109 | + pass |
0 commit comments