|
| 1 | +"""Direct reply-to: RabbitMQ's request/reply pseudo-queue (step_060_consumer_strategy.md §7). |
| 2 | +
|
| 3 | +Run against a local broker:: |
| 4 | +
|
| 5 | + PYTHONPATH=. .venv/bin/python docs/examples/direct_reply_to_example.py |
| 6 | +
|
| 7 | +``consumer_builder().settle_strategy(ConsumerSettleStrategy.DIRECT_REPLY_TO)`` |
| 8 | +attaches a receiver link to no caller-supplied queue at all: the broker |
| 9 | +dynamically generates a private, per-attach pseudo-queue address |
| 10 | +(``/queues/amq.rabbitmq.reply-to.<opaque-suffix>``) and returns it in the |
| 11 | +``attach`` reply, read back here as ``consumer.queue``. A caller who wants a |
| 12 | +reply puts that address in an outgoing request's ``properties.reply_to``; |
| 13 | +whoever answers just needs to publish to it — no dedicated, exclusive reply |
| 14 | +queue to declare and clean up per requester. Like a presettled consumer, its |
| 15 | +``Context`` methods all raise :class:`~src.ConsumerError`: the broker considers |
| 16 | +every delivery on this link already settled the instant it sends it. |
| 17 | +
|
| 18 | +This script plays both roles, on two separate connections: |
| 19 | +
|
| 20 | +* the **requester** (``requester_connection``) builds one ``DIRECT_REPLY_TO`` |
| 21 | + consumer and never declares a queue of its own; |
| 22 | +* the **responder** (``responder_connection``) declares an ordinary request |
| 23 | + queue, consumes it with a normal ``ExplicitSettle`` consumer, and replies to |
| 24 | + whatever address arrived in the request's ``reply_to`` — an ordinary |
| 25 | + anonymous :class:`~src.Publisher` (step_020_publishers.md §3.3) also sends |
| 26 | + the request itself, targeting the request queue. |
| 27 | +
|
| 28 | +Because the pseudo-queue is scoped to the exact connection and session that |
| 29 | +attached it (§3.3 point 5), it does not survive a reconnect: the second half of |
| 30 | +this script forces the requester's socket down, lets auto-reconnection redial |
| 31 | +and re-attach, and shows ``consumer.queue`` reading back a *different* |
| 32 | +broker-generated address afterward — a caller must always re-read it after |
| 33 | +recovery, never cache it. Tearing down the live socket |
| 34 | +(``connection._socket.shutdown``) reaches into the client on purpose; |
| 35 | +application code never does this. |
| 36 | +""" |
| 37 | + |
| 38 | +from __future__ import annotations |
| 39 | + |
| 40 | +import logging |
| 41 | +import queue |
| 42 | +import socket |
| 43 | +import time |
| 44 | +import uuid |
| 45 | + |
| 46 | +from src import ( |
| 47 | + Connection, |
| 48 | + ConnectionParameters, |
| 49 | + ConnectionState, |
| 50 | + Consumer, |
| 51 | + ConsumerSettleStrategy, |
| 52 | + Context, |
| 53 | + Message, |
| 54 | + Publisher, |
| 55 | + RecoveryConfiguration, |
| 56 | + queue_address, |
| 57 | +) |
| 58 | +from src.wire import Properties |
| 59 | + |
| 60 | +#: How long the example waits for a reply it expects. |
| 61 | +TIMEOUT_SECONDS = 15.0 |
| 62 | + |
| 63 | +#: How long it waits for auto-reconnection to finish. |
| 64 | +RECOVERY_TIMEOUT_SECONDS = 60.0 |
| 65 | + |
| 66 | +POLL_INTERVAL_SECONDS = 0.05 |
| 67 | + |
| 68 | +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)-7s %(name)s: %(message)s") |
| 69 | +logger = logging.getLogger("example") |
| 70 | + |
| 71 | + |
| 72 | +class ReplyBox: |
| 73 | + """Records every reply the requester's direct-reply-to consumer receives.""" |
| 74 | + |
| 75 | + def __init__(self) -> None: |
| 76 | + """Start with nothing received.""" |
| 77 | + self.replies: queue.Queue[str] = queue.Queue() |
| 78 | + |
| 79 | + def on_message(self, context: Context, message: Message) -> None: |
| 80 | + """Log and record one reply, without touching ``context`` — it is presettled.""" |
| 81 | + body = message.body_as_string() |
| 82 | + logger.info("requester received reply %r (presettled=%s)", body, context.is_presettled) |
| 83 | + self.replies.put(body) |
| 84 | + |
| 85 | + def drain_one(self) -> str: |
| 86 | + """Return the next reply body, or raise once the wait times out.""" |
| 87 | + return self.replies.get(timeout=TIMEOUT_SECONDS) |
| 88 | + |
| 89 | + |
| 90 | +def wait_for(connection: Connection, state: ConnectionState, timeout: float) -> bool: |
| 91 | + """Whether ``connection`` is seen in ``state`` within ``timeout`` seconds.""" |
| 92 | + deadline = time.monotonic() + timeout |
| 93 | + while time.monotonic() < deadline: |
| 94 | + if connection.state is state: |
| 95 | + return True |
| 96 | + time.sleep(POLL_INTERVAL_SECONDS) |
| 97 | + return False |
| 98 | + |
| 99 | + |
| 100 | +def build_responder(connection: Connection, request_queue: str) -> Consumer: |
| 101 | + """Attach the queue-bound consumer that answers every request with a reply.""" |
| 102 | + |
| 103 | + def on_request(context: Context, message: Message) -> None: |
| 104 | + reply_to = message.properties.reply_to if message.properties else None |
| 105 | + if not reply_to: |
| 106 | + logger.warning("a request with no reply_to arrived; discarding it") |
| 107 | + context.discard() |
| 108 | + return |
| 109 | + logger.info("responder received request %r, replying to %r", message.body_as_string(), reply_to) |
| 110 | + reply_publisher = connection.publisher_builder().build() # anonymous: reply_to is per-request |
| 111 | + try: |
| 112 | + reply_publisher.publish( |
| 113 | + Message( |
| 114 | + f"pong-for-{message.body_as_string()}", |
| 115 | + properties=Properties( |
| 116 | + to=reply_to, |
| 117 | + correlation_id=message.properties.message_id if message.properties else None, |
| 118 | + ), |
| 119 | + ), |
| 120 | + timeout=TIMEOUT_SECONDS, |
| 121 | + ) |
| 122 | + finally: |
| 123 | + reply_publisher.close() |
| 124 | + context.accept() |
| 125 | + |
| 126 | + return connection.consumer_builder().queue(request_queue).message_handler(on_request).build() |
| 127 | + |
| 128 | + |
| 129 | +def send_request(connection: Connection, request_queue: str, reply_to: str, body: str) -> None: |
| 130 | + """Publish one request naming ``reply_to``, from a fresh anonymous publisher. |
| 131 | +
|
| 132 | + Anonymous (step_020_publishers.md §3.3) so each request can carry its own |
| 133 | + ``to`` alongside its ``reply_to`` — a queue-bound publisher could not set |
| 134 | + the former, since its target is fixed at ``build()`` time. |
| 135 | + """ |
| 136 | + publisher: Publisher = connection.publisher_builder().build() |
| 137 | + try: |
| 138 | + publisher.publish( |
| 139 | + Message( |
| 140 | + body, |
| 141 | + properties=Properties( |
| 142 | + message_id=str(uuid.uuid4()), |
| 143 | + to=queue_address(request_queue), |
| 144 | + reply_to=reply_to, |
| 145 | + ), |
| 146 | + ), |
| 147 | + timeout=TIMEOUT_SECONDS, |
| 148 | + ) |
| 149 | + finally: |
| 150 | + publisher.close() |
| 151 | + logger.info("requester sent %r to %r with reply_to=%r", body, request_queue, reply_to) |
| 152 | + |
| 153 | + |
| 154 | +def direct_reply_to() -> None: |
| 155 | + """Round-trip a request/reply exchange over direct-reply-to, across a forced disconnect.""" |
| 156 | + requester_connection = Connection( |
| 157 | + ConnectionParameters( |
| 158 | + container_id=f"example-direct-reply-to-requester-{uuid.uuid4().hex[:8]}", |
| 159 | + on_unexpected_close=lambda error: logger.error("the requester connection died for good: %s", error), |
| 160 | + recovery_configuration=RecoveryConfiguration(), # activated=True, topology=False |
| 161 | + ) |
| 162 | + ) |
| 163 | + responder_connection = Connection( |
| 164 | + ConnectionParameters(container_id=f"example-direct-reply-to-responder-{uuid.uuid4().hex[:8]}") |
| 165 | + ) |
| 166 | + request_queue = f"example-direct-reply-to-{uuid.uuid4().hex[:8]}" |
| 167 | + reply_box = ReplyBox() |
| 168 | + try: |
| 169 | + responder_connection.management().queue(request_queue).declare() |
| 170 | + logger.info("declared the request queue %r", request_queue) |
| 171 | + |
| 172 | + responder = build_responder(responder_connection, request_queue) |
| 173 | + requester = ( |
| 174 | + requester_connection.consumer_builder() |
| 175 | + .message_handler(reply_box.on_message) |
| 176 | + .settle_strategy(ConsumerSettleStrategy.DIRECT_REPLY_TO) |
| 177 | + .build() |
| 178 | + ) |
| 179 | + try: |
| 180 | + first_address = requester.queue |
| 181 | + assert first_address is not None, "build() only returns once DIRECT_REPLY_TO's address is resolved" |
| 182 | + logger.info("requester attached to the broker-generated pseudo-queue %r", first_address) |
| 183 | + send_request(responder_connection, request_queue, first_address, "hello") |
| 184 | + logger.info("requester received %r", reply_box.drain_one()) |
| 185 | + |
| 186 | + logger.info("simulating a network failure on the requester connection") |
| 187 | + requester_connection._socket.shutdown(socket.SHUT_RDWR) |
| 188 | + if not wait_for(requester_connection, ConnectionState.RECONNECTING, timeout=10.0): |
| 189 | + logger.warning("never observed RECONNECTING — detection and recovery both landed inside one poll") |
| 190 | + if not wait_for(requester_connection, ConnectionState.OPEN, RECOVERY_TIMEOUT_SECONDS): |
| 191 | + logger.error("the requester connection never recovered") |
| 192 | + return |
| 193 | + logger.info( |
| 194 | + "state is back to %s, the receiver link re-attached underneath the same Consumer object", |
| 195 | + requester_connection.state.value, |
| 196 | + ) |
| 197 | + |
| 198 | + second_address = requester.queue |
| 199 | + assert second_address is not None, "the re-attach must have resolved a fresh address" |
| 200 | + logger.info("requester re-attached to a fresh pseudo-queue %r", second_address) |
| 201 | + assert second_address != first_address, ( |
| 202 | + "a direct-reply-to pseudo-queue is session-scoped and must not survive a reconnect" |
| 203 | + ) |
| 204 | + send_request(responder_connection, request_queue, second_address, "hello-again") |
| 205 | + logger.info("requester received %r", reply_box.drain_one()) |
| 206 | + finally: |
| 207 | + requester.close() |
| 208 | + responder.close() |
| 209 | + logger.info("closed the requester and the responder") |
| 210 | + |
| 211 | + responder_connection.management().queue(request_queue).delete() |
| 212 | + logger.info("deleted the request queue %r", request_queue) |
| 213 | + finally: |
| 214 | + requester_connection.close() |
| 215 | + responder_connection.close() |
| 216 | + |
| 217 | + |
| 218 | +if __name__ == "__main__": |
| 219 | + direct_reply_to() |
0 commit comments